From 4ec06781478bbd01301ea05f2f8457a8aaee429f Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Thu, 23 Nov 2023 14:55:54 +0100 Subject: [PATCH 01/59] Initial metrics integration test --- .../metrics-v4.2.19-expected-changes.patch | 6660 +++++++++++++++++ .../metrics-v4.2.19-expected-warnings.txt | 8 + integration-tests/metrics-v4.2.19-init.patch | 219 + integration-tests/metrics-v4.2.19.sh | 180 + 4 files changed, 7067 insertions(+) create mode 100644 integration-tests/metrics-v4.2.19-expected-changes.patch create mode 100644 integration-tests/metrics-v4.2.19-expected-warnings.txt create mode 100644 integration-tests/metrics-v4.2.19-init.patch create mode 100755 integration-tests/metrics-v4.2.19.sh diff --git a/integration-tests/metrics-v4.2.19-expected-changes.patch b/integration-tests/metrics-v4.2.19-expected-changes.patch new file mode 100644 index 0000000000..5d6d51f6b8 --- /dev/null +++ b/integration-tests/metrics-v4.2.19-expected-changes.patch @@ -0,0 +1,6660 @@ +--- a/metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java ++++ b/metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java +@@ -2,7 +2,6 @@ package com.codahale.metrics.benchmarks; + + import com.codahale.metrics.SlidingTimeWindowArrayReservoir; + import com.codahale.metrics.SlidingTimeWindowReservoir; +-import com.codahale.metrics.Snapshot; + import java.util.concurrent.TimeUnit; + import org.openjdk.jmh.annotations.Benchmark; + import org.openjdk.jmh.annotations.Group; +@@ -42,8 +41,7 @@ public class SlidingTimeWindowReservoirsBenchmark { + @Group("slidingTime") + @GroupThreads(1) + public Object slidingTimeRead() { +- Snapshot snapshot = slidingTime.getSnapshot(); +- return snapshot; ++ return slidingTime.getSnapshot(); + } + + @Benchmark +@@ -58,8 +56,7 @@ public class SlidingTimeWindowReservoirsBenchmark { + @Group("arrTime") + @GroupThreads(1) + public Object arrTimeRead() { +- Snapshot snapshot = arrTime.getSnapshot(); +- return snapshot; ++ return arrTime.getSnapshot(); + } + + public static void main(String[] args) throws RunnerException { +--- a/metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java ++++ b/metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java +@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; + import static com.codahale.metrics.MetricAttribute.M15_RATE; + import static com.codahale.metrics.MetricAttribute.M1_RATE; + import static com.codahale.metrics.MetricAttribute.M5_RATE; +-import static com.codahale.metrics.MetricAttribute.MAX; + import static com.codahale.metrics.MetricAttribute.MEAN; + import static com.codahale.metrics.MetricAttribute.MEAN_RATE; +-import static com.codahale.metrics.MetricAttribute.MIN; + import static com.codahale.metrics.MetricAttribute.P50; + import static com.codahale.metrics.MetricAttribute.P75; + import static com.codahale.metrics.MetricAttribute.P95; +@@ -15,6 +13,7 @@ import static com.codahale.metrics.MetricAttribute.P98; + import static com.codahale.metrics.MetricAttribute.P99; + import static com.codahale.metrics.MetricAttribute.P999; + import static com.codahale.metrics.MetricAttribute.STDDEV; ++import static java.util.Collections.emptySet; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.Counter; +@@ -29,7 +28,6 @@ import com.codahale.metrics.Snapshot; + import com.codahale.metrics.Timer; + import java.io.IOException; + import java.net.InetAddress; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -80,7 +78,7 @@ public class CollectdReporter extends ScheduledReporter { + private SecurityLevel securityLevel = SecurityLevel.NONE; + private String username = ""; + private String password = ""; +- private Set disabledMetricAttributes = Collections.emptySet(); ++ private Set disabledMetricAttributes = emptySet(); + private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; + + private Builder(MetricRegistry registry) { +@@ -302,7 +300,7 @@ public class CollectdReporter extends ScheduledReporter { + try { + writer.write(metaData, value); + } catch (RuntimeException e) { +- LOG.warn("Failed to process metric '" + metaData.getPlugin() + "': " + e.getMessage()); ++ LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage()); + } catch (IOException e) { + LOG.error("Failed to send metric to collectd", e); + } +@@ -337,9 +335,9 @@ public class CollectdReporter extends ScheduledReporter { + private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { + final Snapshot snapshot = metric.getSnapshot(); + writeValue(metaData, COUNT, (double) metric.getCount()); +- writeValue(metaData, MAX, (double) snapshot.getMax()); ++ writeValue(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); + writeValue(metaData, MEAN, snapshot.getMean()); +- writeValue(metaData, MIN, (double) snapshot.getMin()); ++ writeValue(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); + writeValue(metaData, STDDEV, snapshot.getStdDev()); + writeValue(metaData, P50, snapshot.getMedian()); + writeValue(metaData, P75, snapshot.get75thPercentile()); +@@ -352,9 +350,9 @@ public class CollectdReporter extends ScheduledReporter { + private void serializeTimer(MetaData.Builder metaData, Timer metric) { + final Snapshot snapshot = metric.getSnapshot(); + writeValue(metaData, COUNT, (double) metric.getCount()); +- writeDuration(metaData, MAX, (double) snapshot.getMax()); ++ writeDuration(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); + writeDuration(metaData, MEAN, snapshot.getMean()); +- writeDuration(metaData, MIN, (double) snapshot.getMin()); ++ writeDuration(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); + writeDuration(metaData, STDDEV, snapshot.getStdDev()); + writeDuration(metaData, P50, snapshot.getMedian()); + writeDuration(metaData, P75, snapshot.get75thPercentile()); +--- a/metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java ++++ b/metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java +@@ -1,10 +1,12 @@ + package com.codahale.metrics.collectd; + ++import static java.nio.charset.StandardCharsets.US_ASCII; ++import static java.nio.charset.StandardCharsets.UTF_8; ++ + import java.io.IOException; + import java.nio.BufferOverflowException; + import java.nio.ByteBuffer; + import java.nio.ByteOrder; +-import java.nio.charset.StandardCharsets; + import java.security.InvalidKeyException; + import java.security.MessageDigest; + import java.security.NoSuchAlgorithmException; +@@ -64,8 +66,8 @@ class PacketWriter { + PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { + this.sender = sender; + this.securityLevel = securityLevel; +- this.username = username != null ? username.getBytes(StandardCharsets.UTF_8) : null; +- this.password = password != null ? password.getBytes(StandardCharsets.UTF_8) : null; ++ this.username = username != null ? username.getBytes(UTF_8) : null; ++ this.password = password != null ? password.getBytes(UTF_8) : null; + } + + void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { +@@ -119,12 +121,12 @@ class PacketWriter { + } + + private void writeString(ByteBuffer buffer, int type, String val) { +- if (val == null || val.length() == 0) { ++ if (val == null || val.isEmpty()) { + return; + } + int len = HEADER_LEN + val.length() + 1; + writeHeader(buffer, type, len); +- buffer.put(val.getBytes(StandardCharsets.US_ASCII)).put(NULL); ++ buffer.put(val.getBytes(US_ASCII)).put(NULL); + } + + private void writeNumber(ByteBuffer buffer, int type, long val) { +--- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterSecurityTest.java ++++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterSecurityTest.java +@@ -1,6 +1,6 @@ + package com.codahale.metrics.collectd; + +-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + + import com.codahale.metrics.MetricRegistry; + import org.junit.Test; +@@ -11,27 +11,27 @@ public class CollectdReporterSecurityTest { + + @Test + public void testUnableSetSecurityLevelToSignWithoutUsername() { +- assertThatIllegalArgumentException() +- .isThrownBy( ++ assertThatThrownBy( + () -> + CollectdReporter.forRegistry(registry) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withPassword("t1_g3r") + .build(new Sender("localhost", 25826))) +- .withMessage("username is required for securityLevel: SIGN"); ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("username is required for securityLevel: SIGN"); + } + + @Test + public void testUnableSetSecurityLevelToSignWithoutPassword() { +- assertThatIllegalArgumentException() +- .isThrownBy( ++ assertThatThrownBy( + () -> + CollectdReporter.forRegistry(registry) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withUsername("scott") + .build(new Sender("localhost", 25826))) +- .withMessage("password is required for securityLevel: SIGN"); ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("password is required for securityLevel: SIGN"); + } + } +--- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java ++++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java +@@ -1,5 +1,8 @@ + package com.codahale.metrics.collectd; + ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptySortedMap; ++import static java.util.Collections.singletonMap; + import static java.util.concurrent.TimeUnit.MILLISECONDS; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; +@@ -12,7 +15,6 @@ import com.codahale.metrics.MetricAttribute; + import com.codahale.metrics.MetricRegistry; + import com.codahale.metrics.Snapshot; + import com.codahale.metrics.Timer; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -94,7 +96,7 @@ public class CollectdReporterTest { + + @Test + public void reportsCounters() throws Exception { +- Counter counter = mock(Counter.class); ++ Counter counter = mock(); + when(counter.getCount()).thenReturn(42L); + + reporter.report(map(), map("api.rest.requests.count", counter), map(), map(), map()); +@@ -104,7 +106,7 @@ public class CollectdReporterTest { + + @Test + public void reportsMeters() throws Exception { +- Meter meter = mock(Meter.class); ++ Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); +@@ -122,8 +124,8 @@ public class CollectdReporterTest { + + @Test + public void reportsHistograms() throws Exception { +- Histogram histogram = mock(Histogram.class); +- Snapshot snapshot = mock(Snapshot.class); ++ Histogram histogram = mock(); ++ Snapshot snapshot = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSnapshot()).thenReturn(snapshot); + when(snapshot.getMax()).thenReturn(2L); +@@ -146,8 +148,8 @@ public class CollectdReporterTest { + + @Test + public void reportsTimers() throws Exception { +- Timer timer = mock(Timer.class); +- Snapshot snapshot = mock(Snapshot.class); ++ Timer timer = mock(); ++ Snapshot snapshot = mock(); + when(timer.getSnapshot()).thenReturn(snapshot); + when(timer.getCount()).thenReturn(1L); + when(timer.getSnapshot()).thenReturn(snapshot); +@@ -187,14 +189,14 @@ public class CollectdReporterTest { + + @Test + public void doesNotReportDisabledMetricAttributes() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(11L); + + CollectdReporter reporter = +@@ -240,16 +242,16 @@ public class CollectdReporterTest { + } + + private SortedMap map() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + private SortedMap map(String name, T metric) { +- final Map map = Collections.singletonMap(name, metric); ++ final Map map = singletonMap(name, metric); + return new TreeMap<>(map); + } + + private List nextValues(Receiver receiver) throws Exception { + final ValueList valueList = receiver.next(); +- return valueList == null ? Collections.emptyList() : valueList.getValues(); ++ return valueList == null ? emptyList() : valueList.getValues(); + } + } +--- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/PacketWriterTest.java ++++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/PacketWriterTest.java +@@ -190,6 +190,6 @@ public class PacketWriterTest { + assertThat(amountOfValues).isEqualTo((short) 1); + byte dataType = packet.get(); + assertThat(dataType).isEqualTo((byte) 1); +- assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isEqualTo(42.0, offset(0.01)); ++ assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01)); + } + } +--- a/metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java +@@ -1,8 +1,9 @@ + package com.codahale.metrics; + ++import static java.util.Collections.emptySet; ++ + import java.io.PrintStream; + import java.text.DateFormat; +-import java.util.Collections; + import java.util.Date; + import java.util.Locale; + import java.util.Map; +@@ -53,7 +54,7 @@ public class ConsoleReporter extends ScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- disabledMetricAttributes = Collections.emptySet(); ++ disabledMetricAttributes = emptySet(); + } + + /** +--- a/metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java +@@ -1,8 +1,9 @@ + package com.codahale.metrics; + ++import static java.util.Objects.requireNonNull; ++ + import com.codahale.metrics.WeightedSnapshot.WeightedSample; + import java.time.Duration; +-import java.util.Objects; + import java.util.concurrent.ConcurrentSkipListMap; + import java.util.concurrent.ThreadLocalRandom; + import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +@@ -127,7 +128,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + // It's possible that more values were added while the map was scanned, those with the + // minimum priorities are removed. + while (newCount > size) { +- Objects.requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); ++ requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); + newCount--; + } + return new State(alphaNanos, size, newTick, newCount, newValues); +@@ -255,13 +256,13 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + + /** Interval at which this reservoir is rescaled. */ + public Builder rescaleThreshold(Duration value) { +- this.rescaleThreshold = Objects.requireNonNull(value, "rescaleThreshold is required"); ++ this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required"); + return this; + } + + /** Clock instance used for decay. */ + public Builder clock(Clock value) { +- this.clock = Objects.requireNonNull(value, "clock is required"); ++ this.clock = requireNonNull(value, "clock is required"); + return this; + } + +--- a/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java +@@ -1,6 +1,9 @@ + package com.codahale.metrics; + +-import java.util.Collections; ++import static java.util.Collections.unmodifiableMap; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; ++ + import java.util.List; + import java.util.Map; + import java.util.SortedMap; +@@ -207,7 +210,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); ++ return metric instanceof Counter; + } + }); + } +@@ -242,7 +245,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); ++ return metric instanceof Histogram; + } + }); + } +@@ -277,7 +280,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); ++ return metric instanceof Meter; + } + }); + } +@@ -312,7 +315,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); ++ return metric instanceof Timer; + } + }); + } +@@ -350,7 +353,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Gauge.class.isInstance(metric); ++ return metric instanceof Gauge; + } + }); + } +@@ -414,7 +417,7 @@ public class MetricRegistry implements MetricSet { + * @return the names of all the metrics + */ + public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); ++ return unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); + } + + /** +@@ -541,7 +544,7 @@ public class MetricRegistry implements MetricSet { + timers.put(entry.getKey(), (T) entry.getValue()); + } + } +- return Collections.unmodifiableSortedMap(timers); ++ return unmodifiableSortedMap(timers); + } + + private void onMetricAdded(String name, Metric metric) { +@@ -609,7 +612,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public Map getMetrics() { +- return Collections.unmodifiableMap(metrics); ++ return unmodifiableMap(metrics); + } + + @FunctionalInterface +@@ -628,7 +631,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); ++ return metric instanceof Counter; + } + }; + +@@ -641,7 +644,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); ++ return metric instanceof Histogram; + } + }; + +@@ -654,7 +657,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); ++ return metric instanceof Meter; + } + }; + +@@ -667,7 +670,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); ++ return metric instanceof Timer; + } + }; + +@@ -681,7 +684,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Gauge.class.isInstance(metric); ++ return metric instanceof Gauge; + } + }; + +--- a/metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java +@@ -1,9 +1,13 @@ + package com.codahale.metrics; + ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.emptySet; ++import static java.util.Collections.emptySortedMap; ++import static java.util.Collections.emptySortedSet; ++ + import java.io.OutputStream; + import java.time.Duration; + import java.util.Collection; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -137,69 +141,69 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public SortedSet getNames() { +- return Collections.emptySortedSet(); ++ return emptySortedSet(); + } + + /** {@inheritDoc} */ + @Override + @SuppressWarnings("rawtypes") + public SortedMap getGauges() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + @SuppressWarnings("rawtypes") + public SortedMap getGauges(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getCounters() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getCounters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getHistograms() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getHistograms(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getMeters() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getMeters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getTimers() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getTimers(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ +@@ -211,7 +215,7 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public Map getMetrics() { +- return Collections.emptyMap(); ++ return emptyMap(); + } + + static final class NoopGauge implements Gauge { +@@ -601,19 +605,19 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public Set keySet() { +- return Collections.emptySet(); ++ return emptySet(); + } + + /** {@inheritDoc} */ + @Override + public Collection values() { +- return Collections.emptySet(); ++ return emptySet(); + } + + /** {@inheritDoc} */ + @Override + public Set> entrySet() { +- return Collections.emptySet(); ++ return emptySet(); + } + } + } +--- a/metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java +@@ -1,7 +1,8 @@ + package com.codahale.metrics; + ++import static java.util.Collections.emptySet; ++ + import java.io.Closeable; +-import java.util.Collections; + import java.util.Locale; + import java.util.Set; + import java.util.SortedMap; +@@ -128,7 +129,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + durationUnit, + executor, + shutdownExecutorOnStop, +- Collections.emptySet()); ++ emptySet()); + } + + protected ScheduledReporter( +@@ -154,7 +155,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + this.durationFactor = durationUnit.toNanos(1); + this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); + this.disabledMetricAttributes = +- disabledMetricAttributes != null ? disabledMetricAttributes : Collections.emptySet(); ++ disabledMetricAttributes != null ? disabledMetricAttributes : emptySet(); + } + + /** +@@ -185,8 +186,8 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, + * ScheduledExecutorService)} instead. + */ +- @SuppressWarnings("DeprecatedIsStillUsed") + @Deprecated ++ @SuppressWarnings("DeprecatedIsStillUsed") + protected ScheduledFuture getScheduledFuture( + long initialDelay, long period, TimeUnit unit, Runnable runnable) { + return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); +--- a/metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java +@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; + import static com.codahale.metrics.MetricAttribute.M15_RATE; + import static com.codahale.metrics.MetricAttribute.M1_RATE; + import static com.codahale.metrics.MetricAttribute.M5_RATE; +-import static com.codahale.metrics.MetricAttribute.MAX; + import static com.codahale.metrics.MetricAttribute.MEAN; + import static com.codahale.metrics.MetricAttribute.MEAN_RATE; +-import static com.codahale.metrics.MetricAttribute.MIN; + import static com.codahale.metrics.MetricAttribute.P50; + import static com.codahale.metrics.MetricAttribute.P75; + import static com.codahale.metrics.MetricAttribute.P95; +@@ -15,8 +13,8 @@ import static com.codahale.metrics.MetricAttribute.P98; + import static com.codahale.metrics.MetricAttribute.P99; + import static com.codahale.metrics.MetricAttribute.P999; + import static com.codahale.metrics.MetricAttribute.STDDEV; ++import static java.util.Collections.emptySet; + +-import java.util.Collections; + import java.util.Map.Entry; + import java.util.Set; + import java.util.SortedMap; +@@ -81,7 +79,7 @@ public class Slf4jReporter extends ScheduledReporter { + this.loggingLevel = LoggingLevel.INFO; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = emptySet(); + } + + /** +@@ -306,8 +304,8 @@ public class Slf4jReporter extends ScheduledReporter { + b.append("type=TIMER"); + append(b, "name", prefix(name)); + appendCountIfEnabled(b, timer); +- appendLongDurationIfEnabled(b, MIN, snapshot::getMin); +- appendLongDurationIfEnabled(b, MAX, snapshot::getMax); ++ appendLongDurationIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongDurationIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); + appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); + appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); + appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); +@@ -338,8 +336,8 @@ public class Slf4jReporter extends ScheduledReporter { + b.append("type=HISTOGRAM"); + append(b, "name", prefix(name)); + appendCountIfEnabled(b, histogram); +- appendLongIfEnabled(b, MIN, snapshot::getMin); +- appendLongIfEnabled(b, MAX, snapshot::getMax); ++ appendLongIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); + appendDoubleIfEnabled(b, MEAN, snapshot::getMean); + appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); + appendDoubleIfEnabled(b, P50, snapshot::getMedian); +--- a/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowMovingAverages.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowMovingAverages.java +@@ -184,7 +184,6 @@ public class SlidingTimeWindowMovingAverages implements MovingAverages { + buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); + buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); + } +- long retval = adder.longValue(); +- return retval; ++ return adder.longValue(); + } + } +--- a/metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java +@@ -1,13 +1,13 @@ + package com.codahale.metrics; + + import static java.nio.charset.StandardCharsets.UTF_8; ++import static java.util.Comparator.comparingLong; + + import java.io.OutputStream; + import java.io.OutputStreamWriter; + import java.io.PrintWriter; + import java.util.Arrays; + import java.util.Collection; +-import java.util.Comparator; + + /** A statistical snapshot of a {@link WeightedSnapshot}. */ + public class WeightedSnapshot extends Snapshot { +@@ -35,7 +35,7 @@ public class WeightedSnapshot extends Snapshot { + public WeightedSnapshot(Collection values) { + final WeightedSample[] copy = values.toArray(new WeightedSample[] {}); + +- Arrays.sort(copy, Comparator.comparingLong(w -> w.value)); ++ Arrays.sort(copy, comparingLong(w -> w.value)); + + this.values = new long[copy.length]; + this.normWeights = new double[copy.length]; +--- a/metrics-core/src/test/java/com/codahale/metrics/ClockTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/ClockTest.java +@@ -11,9 +11,9 @@ public class ClockTest { + public void userTimeClock() { + final Clock.UserTimeClock clock = new Clock.UserTimeClock(); + +- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(100.0)); ++ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0)); + +- assertThat((double) clock.getTick()).isEqualTo(System.nanoTime(), offset(1000000.0)); ++ assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0)); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/ConsoleReporterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/ConsoleReporterTest.java +@@ -21,8 +21,8 @@ public class ConsoleReporterTest { + private final Locale locale = Locale.US; + private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); + +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); + private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + private final PrintStream output = new PrintStream(bytes); + private final ConsoleReporter reporter = +@@ -68,7 +68,7 @@ public class ConsoleReporterTest { + + @Test + public void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map("test.counter", counter), map(), map(), map()); +@@ -87,10 +87,10 @@ public class ConsoleReporterTest { + + @Test + public void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -130,7 +130,7 @@ public class ConsoleReporterTest { + + @Test + public void reportsMeterValues() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -157,14 +157,14 @@ public class ConsoleReporterTest { + + @Test + public void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -223,7 +223,7 @@ public class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); + +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -266,14 +266,14 @@ public class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); + +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -329,10 +329,10 @@ public class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); + +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +--- a/metrics-core/src/test/java/com/codahale/metrics/CounterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/CounterTest.java +@@ -9,7 +9,7 @@ public class CounterTest { + + @Test + public void startsAtZero() { +- assertThat(counter.getCount()).isZero(); ++ assertThat(counter.getCount()).isEqualTo(0); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/CsvReporterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/CsvReporterTest.java +@@ -7,7 +7,6 @@ import static org.mockito.Mockito.when; + + import java.io.File; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.nio.file.Files; + import java.util.Locale; + import java.util.SortedMap; +@@ -21,8 +20,8 @@ import org.junit.rules.TemporaryFolder; + public class CsvReporterTest { + @Rule public final TemporaryFolder folder = new TemporaryFolder(); + +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); + + private File dataDirectory; + private CsvReporter reporter; +@@ -54,7 +53,7 @@ public class CsvReporterTest { + + @Test + public void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map("test.counter", counter), map(), map(), map()); +@@ -64,10 +63,10 @@ public class CsvReporterTest { + + @Test + public void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -105,14 +104,14 @@ public class CsvReporterTest { + + @Test + public void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -137,7 +136,7 @@ public class CsvReporterTest { + + @Test + public void testCsvFileProviderIsUsed() { +- CsvFileProvider fileProvider = mock(CsvFileProvider.class); ++ CsvFileProvider fileProvider = mock(); + when(fileProvider.getFile(dataDirectory, "gauge")) + .thenReturn(new File(dataDirectory, "guage.csv")); + +@@ -175,7 +174,7 @@ public class CsvReporterTest { + } + + private Meter mockMeter() { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -194,8 +193,7 @@ public class CsvReporterTest { + } + + private String fileContents(String filename) throws IOException { +- return new String( +- Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); ++ return Files.readString(new File(dataDirectory, filename).toPath()); + } + + private SortedMap map() { +--- a/metrics-core/src/test/java/com/codahale/metrics/EWMATest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/EWMATest.java +@@ -13,67 +13,67 @@ public class EWMATest { + ewma.update(3); + ewma.tick(); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.01098938, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00404277, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00148725, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00054713, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00020128, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00007405, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00002724, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00001002, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000369, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000136, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000050, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000018, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001)); + } + + @Test +@@ -82,67 +82,67 @@ public class EWMATest { + ewma.update(3); + ewma.tick(); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.18071653, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.14795818, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.12113791, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.09917933, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.06648190, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.05443077, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.04456415, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.03648604, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); + } + + @Test +@@ -151,67 +151,67 @@ public class EWMATest { + ewma.update(3); + ewma.tick(); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.56130419, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.52510399, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.45955700, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.42991879, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.37625345, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.35198773, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.30805027, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.28818318, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.25221023, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.23594443, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + } + + private void elapseMinute(EWMA ewma) { +--- a/metrics-core/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java +@@ -1,5 +1,6 @@ + package com.codahale.metrics; + ++import static java.util.stream.Collectors.toList; + import static org.assertj.core.api.Assertions.assertThat; + + import com.codahale.metrics.Timer.Context; +@@ -8,7 +9,6 @@ import java.util.Collection; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicBoolean; + import java.util.concurrent.atomic.AtomicInteger; +-import java.util.stream.Collectors; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.junit.runners.Parameterized; +@@ -46,7 +46,7 @@ public class ExponentiallyDecayingReservoirTest { + public static Collection reservoirs() { + return Arrays.stream(ReservoirFactory.values()) + .map(value -> new Object[] {value}) +- .collect(Collectors.toList()); ++ .collect(toList()); + } + + private final ReservoirFactory reservoirFactory; +--- a/metrics-core/src/test/java/com/codahale/metrics/HistogramTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/HistogramTest.java +@@ -8,12 +8,12 @@ import static org.mockito.Mockito.when; + import org.junit.Test; + + public class HistogramTest { +- private final Reservoir reservoir = mock(Reservoir.class); ++ private final Reservoir reservoir = mock(); + private final Histogram histogram = new Histogram(reservoir); + + @Test + public void updatesTheCountOnUpdates() { +- assertThat(histogram.getCount()).isZero(); ++ assertThat(histogram.getCount()).isEqualTo(0); + + histogram.update(1); + +@@ -22,7 +22,7 @@ public class HistogramTest { + + @Test + public void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(reservoir.getSnapshot()).thenReturn(snapshot); + + assertThat(histogram.getSnapshot()).isEqualTo(snapshot); +--- a/metrics-core/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java +@@ -112,8 +112,8 @@ public class InstrumentedExecutorServiceTest { + assertThat(idle.getSnapshot().size()).isEqualTo(1); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void reportsTasksInformationForThreadPoolExecutor() throws Exception { + executor = + new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); +@@ -170,8 +170,8 @@ public class InstrumentedExecutorServiceTest { + assertThat(poolSize.getValue()).isEqualTo(1); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void reportsTasksInformationForForkJoinPool() throws Exception { + executor = Executors.newWorkStealingPool(4); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); +--- a/metrics-core/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java +@@ -36,16 +36,16 @@ public class InstrumentedScheduledExecutorServiceTest { + + @Test + public void testSubmitRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + Future theFuture = + instrumentedScheduledExecutor.submit( +@@ -53,87 +53,87 @@ public class InstrumentedScheduledExecutorServiceTest { + assertThat(submitted.getCount()).isEqualTo(1); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + }); + + theFuture.get(); + + assertThat(submitted.getCount()).isEqualTo(1); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test + public void testScheduleRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + ScheduledFuture theFuture = + instrumentedScheduledExecutor.schedule( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + }, + 10L, + TimeUnit.MILLISECONDS); + + theFuture.get(); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test + public void testSubmitCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + final Object obj = new Object(); + +@@ -143,13 +143,13 @@ public class InstrumentedScheduledExecutorServiceTest { + assertThat(submitted.getCount()).isEqualTo(1); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + return obj; + }); +@@ -158,45 +158,45 @@ public class InstrumentedScheduledExecutorServiceTest { + + assertThat(submitted.getCount()).isEqualTo(1); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test + public void testScheduleCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + final Object obj = new Object(); + + ScheduledFuture theFuture = + instrumentedScheduledExecutor.schedule( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + return obj; + }, +@@ -205,37 +205,37 @@ public class InstrumentedScheduledExecutorServiceTest { + + assertThat(theFuture.get()).isEqualTo(obj); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test + public void testScheduleFixedRateCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + CountDownLatch countDownLatch = new CountDownLatch(1); + ScheduledFuture theFuture = + instrumentedScheduledExecutor.scheduleAtFixedRate( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); + +@@ -257,14 +257,14 @@ public class InstrumentedScheduledExecutorServiceTest { + theFuture.cancel(true); + TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isNotEqualTo(0); + assertThat(duration.getCount()).isNotEqualTo(0); + assertThat(duration.getSnapshot().size()).isNotEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); + assertThat(scheduledRepetitively.getCount()).isEqualTo(1); + assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); + assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); +@@ -272,22 +272,22 @@ public class InstrumentedScheduledExecutorServiceTest { + + @Test + public void testScheduleFixedDelayCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + CountDownLatch countDownLatch = new CountDownLatch(1); + ScheduledFuture theFuture = + instrumentedScheduledExecutor.scheduleWithFixedDelay( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); + +@@ -310,9 +310,9 @@ public class InstrumentedScheduledExecutorServiceTest { + theFuture.cancel(true); + TimeUnit.MILLISECONDS.sleep(200); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isNotEqualTo(0); + assertThat(duration.getCount()).isNotEqualTo(0); + assertThat(duration.getSnapshot().size()).isNotEqualTo(0); +--- a/metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java +@@ -11,7 +11,7 @@ import org.junit.runner.RunWith; + import org.junit.runners.Parameterized; + import org.junit.runners.Parameterized.Parameters; + +-@RunWith(value = Parameterized.class) ++@RunWith(Parameterized.class) + public class MeterApproximationTest { + + @Parameters +@@ -34,7 +34,7 @@ public class MeterApproximationTest { + 3, TimeUnit.MINUTES); + + assertThat(meter.getOneMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } + + @Test +@@ -45,7 +45,7 @@ public class MeterApproximationTest { + 13, TimeUnit.MINUTES); + + assertThat(meter.getFiveMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } + + @Test +@@ -56,7 +56,7 @@ public class MeterApproximationTest { + 38, TimeUnit.MINUTES); + + assertThat(meter.getFifteenMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } + + private Meter simulateMetronome( +--- a/metrics-core/src/test/java/com/codahale/metrics/MeterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/MeterTest.java +@@ -10,7 +10,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MeterTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final Meter meter = new Meter(clock); + + @Before +@@ -20,15 +20,15 @@ public class MeterTest { + + @Test + public void startsOutWithNoRatesOrCount() { +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + +- assertThat(meter.getMeanRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); + } + + @Test +@@ -36,12 +36,12 @@ public class MeterTest { + meter.mark(); + meter.mark(2); + +- assertThat(meter.getMeanRate()).isEqualTo(0.3, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001)); + +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.1840, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001)); + +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.1966, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001)); + +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.1988, offset(0.001)); ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001)); + } + } +--- a/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryListenerTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryListenerTest.java +@@ -6,10 +6,10 @@ import static org.mockito.Mockito.verifyNoInteractions; + import org.junit.Test; + + public class MetricRegistryListenerTest { +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + private final MetricRegistryListener listener = new MetricRegistryListener.Base() {}; + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryTest.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.stream.Collectors.toSet; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.mockito.Mockito.mock; +@@ -10,20 +11,19 @@ import static org.mockito.Mockito.verify; + import java.util.HashMap; + import java.util.Map; + import java.util.Set; +-import java.util.stream.Collectors; + import org.junit.Assert; + import org.junit.Before; + import org.junit.Test; + + public class MetricRegistryTest { +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); ++ private final MetricRegistryListener listener = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final Gauge gauge = () -> ""; + private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + + @Before + public void setUp() { +@@ -230,8 +230,8 @@ public class MetricRegistryTest { + verify(listener).onGaugeAdded("thing", gauge1); + } + +- @Test + @SuppressWarnings("rawtypes") ++ @Test + public void accessingACustomGaugeRegistersAndReusesIt() { + final MetricRegistry.MetricSupplier supplier = () -> gauge; + final Gauge gauge1 = registry.gauge("thing", supplier); +@@ -261,7 +261,7 @@ public class MetricRegistryTest { + registry.register("meter", meter); + registry.register("timer", timer); + +- final MetricRegistryListener other = mock(MetricRegistryListener.class); ++ final MetricRegistryListener other = mock(); + registry.addListener(other); + + verify(other).onGaugeAdded("gauge", gauge); +@@ -383,7 +383,7 @@ public class MetricRegistryTest { + MetricRegistry other = new MetricRegistry(); + other.register("gauge", gauge); + registry.register("nested", other); +- assertThat(registry.getNames()).containsOnly("nested.gauge"); ++ assertThat(registry.getNames()).containsExactly("nested.gauge"); + } + + @Test +@@ -391,8 +391,8 @@ public class MetricRegistryTest { + assertThat(name("one", "two", "three")).isEqualTo("one.two.three"); + } + +- @Test + @SuppressWarnings("NullArgumentToVariableArgMethod") ++ @Test + public void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { + assertThat(name("one", (String) null)).isEqualTo("one"); + } +@@ -456,7 +456,7 @@ public class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + } + + @Test +@@ -474,7 +474,7 @@ public class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + } + + @Test +@@ -498,14 +498,13 @@ public class MetricRegistryTest { + Set deepChildMetrics = deepChild.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + + assertThat(childMetrics) +- .containsAll( +- deepChildMetrics.stream().map(m -> "deep-child." + m).collect(Collectors.toSet())); ++ .containsAll(deepChildMetrics.stream().map(m -> "deep-child." + m).collect(toSet())); + +- assertThat(deepChildMetrics.size()).isEqualTo(3); +- assertThat(childMetrics.size()).isEqualTo(5); ++ assertThat(deepChildMetrics).hasSize(3); ++ assertThat(childMetrics).hasSize(5); + } + + @Test +@@ -523,7 +522,7 @@ public class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + + assertThat(childMetrics).doesNotContain("test-1"); + } +@@ -546,7 +545,7 @@ public class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + + assertThat(childMetrics).doesNotContain("test-1", "test-3"); + } +@@ -572,16 +571,15 @@ public class MetricRegistryTest { + Set deepChildMetrics = deepChild.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + + assertThat(childMetrics) +- .containsAll( +- deepChildMetrics.stream().map(m -> "deep-child." + m).collect(Collectors.toSet())); ++ .containsAll(deepChildMetrics.stream().map(m -> "deep-child." + m).collect(toSet())); + + assertThat(deepChildMetrics).doesNotContain("test-2"); + +- assertThat(deepChildMetrics.size()).isEqualTo(1); +- assertThat(childMetrics.size()).isEqualTo(3); ++ assertThat(deepChildMetrics).hasSize(1); ++ assertThat(childMetrics).hasSize(3); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/NoopMetricRegistryTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/NoopMetricRegistryTest.java +@@ -1,7 +1,7 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatNullPointerException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; + import static org.mockito.Mockito.verify; +@@ -13,13 +13,13 @@ import org.junit.Before; + import org.junit.Test; + + public class NoopMetricRegistryTest { +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); ++ private final MetricRegistryListener listener = mock(); + private final NoopMetricRegistry registry = new NoopMetricRegistry(); + private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + + @Before + public void setUp() { +@@ -218,8 +218,8 @@ public class NoopMetricRegistryTest { + verify(listener, never()).onGaugeAdded("thing", gauge1); + } + +- @Test + @SuppressWarnings("rawtypes") ++ @Test + public void accessingACustomGaugeRegistersAndReusesIt() { + final MetricRegistry.MetricSupplier supplier = () -> gauge; + final Gauge gauge1 = registry.gauge("thing", supplier); +@@ -240,7 +240,7 @@ public class NoopMetricRegistryTest { + registry.register("meter", meter); + registry.register("timer", timer); + +- final MetricRegistryListener other = mock(MetricRegistryListener.class); ++ final MetricRegistryListener other = mock(); + registry.addListener(other); + + verify(other, never()).onGaugeAdded("gauge", gauge); +@@ -488,8 +488,8 @@ public class NoopMetricRegistryTest { + @Test + public void registerNullMetric() { + MetricRegistry registry = new NoopMetricRegistry(); +- assertThatNullPointerException() +- .isThrownBy(() -> registry.register("any_name", null)) +- .withMessage("metric == null"); ++ assertThatThrownBy(() -> registry.register("any_name", null)) ++ .isInstanceOf(NullPointerException.class) ++ .hasMessage("metric == null"); + } + } +--- a/metrics-core/src/test/java/com/codahale/metrics/RatioGaugeTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/RatioGaugeTest.java +@@ -9,7 +9,7 @@ public class RatioGaugeTest { + public void ratiosAreHumanReadable() { + final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); + +- assertThat(ratio.toString()).isEqualTo("100.0:200.0"); ++ assertThat(ratio).hasToString("100.0:200.0"); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java +@@ -26,12 +26,12 @@ import org.junit.Test; + + public class ScheduledReporterTest { + private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + +- private final ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); ++ private final ScheduledExecutorService mockExecutor = mock(); + private final ScheduledExecutorService customExecutor = + Executors.newSingleThreadScheduledExecutor(); + private final ScheduledExecutorService externalExecutor = +@@ -145,7 +145,7 @@ public class ScheduledReporterTest { + public void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { + reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); + +- verify(mockExecutor, times(1)) ++ verify(mockExecutor) + .scheduleWithFixedDelay(any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS)); + } + +@@ -295,7 +295,7 @@ public class ScheduledReporterTest { + + Thread.sleep(1_000); + +- verify(reporter, times(1)) ++ verify(reporter) + .report( + map("gauge", gauge), + map("counter", counter), +--- a/metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java +@@ -29,7 +29,7 @@ public class SharedMetricRegistriesTest { + public void hasASetOfNames() { + SharedMetricRegistries.getOrCreate("one"); + +- assertThat(SharedMetricRegistries.names()).containsOnly("one"); ++ assertThat(SharedMetricRegistries.names()).containsExactly("one"); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/Slf4jReporterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/Slf4jReporterTest.java +@@ -3,7 +3,6 @@ package com.codahale.metrics; + import static com.codahale.metrics.MetricAttribute.COUNT; + import static com.codahale.metrics.MetricAttribute.M1_RATE; + import static com.codahale.metrics.MetricAttribute.MEAN_RATE; +-import static com.codahale.metrics.MetricAttribute.MIN; + import static com.codahale.metrics.MetricAttribute.P50; + import static com.codahale.metrics.MetricAttribute.P999; + import static com.codahale.metrics.MetricAttribute.STDDEV; +@@ -22,9 +21,9 @@ import org.slf4j.Marker; + + public class Slf4jReporterTest { + +- private final Logger logger = mock(Logger.class); +- private final Marker marker = mock(Marker.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final Logger logger = mock(); ++ private final Marker marker = mock(); ++ private final MetricRegistry registry = mock(); + + /** + * The set of disabled metric attributes to pass to the Slf4jReporter builder in the default +@@ -79,7 +78,7 @@ public class Slf4jReporterTest { + } + + private Timer timer() { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + + when(timer.getMeanRate()).thenReturn(2.0); +@@ -87,7 +86,7 @@ public class Slf4jReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -104,10 +103,10 @@ public class Slf4jReporterTest { + } + + private Histogram histogram() { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -124,7 +123,7 @@ public class Slf4jReporterTest { + } + + private Meter meter() { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -134,7 +133,7 @@ public class Slf4jReporterTest { + } + + private Counter counter() { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + return counter; + } +@@ -168,7 +167,7 @@ public class Slf4jReporterTest { + + @Test + public void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); ++ disabledMetricAttributes = EnumSet.of(COUNT, MetricAttribute.MIN, P50); + reportsHistogramValuesAtError( + "type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " + + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); +@@ -192,7 +191,7 @@ public class Slf4jReporterTest { + + @Test + public void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, P50, M1_RATE); + reportsMeterValuesAtError( + "type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " + + "mean_rate=2.0, rate_unit=events/second"); +@@ -218,7 +217,7 @@ public class Slf4jReporterTest { + + @Test + public void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, STDDEV, P999, MEAN_RATE); + reportsTimerValuesAtError( + "type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " + + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " +--- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java +@@ -16,7 +16,7 @@ public class SlidingTimeWindowArrayReservoirTest { + + @Test + public void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); + +@@ -30,7 +30,7 @@ public class SlidingTimeWindowArrayReservoirTest { + + @Test + public void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); + +@@ -99,7 +99,7 @@ public class SlidingTimeWindowArrayReservoirTest { + // Set the clock to overflow in (2*window+1)ns + final ManualClock clock = new ManualClock(); + clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); ++ assertThat(clock.getTick() * 256).isPositive(); + + // Create the reservoir + final SlidingTimeWindowArrayReservoir reservoir = +--- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowMovingAveragesTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowMovingAveragesTest.java +@@ -44,7 +44,7 @@ public class SlidingTimeWindowMovingAveragesTest { + + SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); + +- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(0L)), is(0)); ++ assertThat(stwm.calculateIndexOfTick(Instant.EPOCH), is(0)); + assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L)), is(1)); + } + +@@ -62,7 +62,7 @@ public class SlidingTimeWindowMovingAveragesTest { + } + + // verify that no cleanup happened yet +- assertThat(movingAverages.oldestBucketTime, is(Instant.ofEpochSecond(0L))); ++ assertThat(movingAverages.oldestBucketTime, is(Instant.EPOCH)); + + assertThat(meter.getOneMinuteRate(), is(60.0)); + assertThat(meter.getFiveMinuteRate(), is(300.0)); +@@ -83,7 +83,7 @@ public class SlidingTimeWindowMovingAveragesTest { + } + + // verify that at least one cleanup happened +- assertThat(movingAverages.oldestBucketTime, not(is(Instant.ofEpochSecond(0L)))); ++ assertThat(movingAverages.oldestBucketTime, not(is(Instant.EPOCH))); + + assertThat(meter.getOneMinuteRate(), is(60.0)); + assertThat(meter.getFiveMinuteRate(), is(300.0)); +--- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java +@@ -12,7 +12,7 @@ import org.junit.Test; + public class SlidingTimeWindowReservoirTest { + @Test + public void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowReservoir reservoir = + new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); + +@@ -26,7 +26,7 @@ public class SlidingTimeWindowReservoirTest { + + @Test + public void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + when(clock.getTick()).thenReturn(0L); + + final SlidingTimeWindowReservoir reservoir = +@@ -72,7 +72,7 @@ public class SlidingTimeWindowReservoirTest { + + // Set the clock to overflow in (2*window+1)ns + clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); ++ assertThat(clock.getTick() * 256).isPositive(); + + int updatesAfterThreshold = 0; + while (true) { +--- a/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java +@@ -13,7 +13,7 @@ import java.util.concurrent.atomic.AtomicBoolean; + import org.junit.Test; + + public class TimerTest { +- private final Reservoir reservoir = mock(Reservoir.class); ++ private final Reservoir reservoir = mock(); + private final Clock clock = + new Clock() { + // a mock clock that increments its ticker by 50msec per call +@@ -28,20 +28,20 @@ public class TimerTest { + + @Test + public void hasRates() { +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + +- assertThat(timer.getMeanRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); + } + + @Test + public void updatesTheCountOnUpdates() { +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + timer.update(1, TimeUnit.SECONDS); + +@@ -93,7 +93,7 @@ public class TimerTest { + + @Test + public void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(reservoir.getSnapshot()).thenReturn(snapshot); + + assertThat(timer.getSnapshot()).isEqualTo(snapshot); +@@ -103,7 +103,7 @@ public class TimerTest { + public void ignoresNegativeValues() { + timer.update(-1, TimeUnit.SECONDS); + +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + verifyNoInteractions(reservoir); + } +@@ -121,14 +121,14 @@ public class TimerTest { + public void java8NegativeDuration() { + timer.update(Duration.ofMillis(-5678)); + +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + verifyNoInteractions(reservoir); + } + + @Test + public void tryWithResourcesWork() { +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + int dummy = 0; + try (Timer.Context context = timer.time()) { +--- a/metrics-core/src/test/java/com/codahale/metrics/UniformReservoirTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/UniformReservoirTest.java +@@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; + + public class UniformReservoirTest { +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void aReservoirOf100OutOf1000Elements() { + final UniformReservoir reservoir = new UniformReservoir(100); + for (int i = 0; i < 1000; i++) { +@@ -20,7 +20,7 @@ public class UniformReservoirTest { + assertThat(snapshot.size()).isEqualTo(100); + + for (double i : snapshot.getValues()) { +- assertThat(i).isLessThan(1000).isGreaterThanOrEqualTo(0); ++ assertThat(i).isLessThan(1000).isNotNegative(); + } + } + } +--- a/metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java +@@ -16,12 +16,12 @@ public class UniformSnapshotTest { + + @Test + public void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)).isEqualTo(1, offset(0.1)); ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1)); + } + + @Test + public void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)).isEqualTo(5, offset(0.1)); ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1)); + } + + @Test(expected = IllegalArgumentException.class) +@@ -41,32 +41,32 @@ public class UniformSnapshotTest { + + @Test + public void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); ++ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1)); + } + + @Test + public void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1)); + } + + @Test + public void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test +@@ -125,7 +125,7 @@ public class UniformSnapshotTest { + + snapshot.dump(output); + +- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); + } + + @Test +@@ -145,41 +145,41 @@ public class UniformSnapshotTest { + + @Test + public void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()).isEqualTo(1.5811, offset(0.0001)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001)); + } + + @Test + public void calculatesAMinOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMin()).isZero(); ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); + } + + @Test + public void calculatesAMaxOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMax()).isZero(); ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); + } + + @Test + public void calculatesAMeanOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMean()).isZero(); ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); + } + + @Test + public void calculatesAStdDevOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getStdDev()).isZero(); ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); + } + + @Test + public void calculatesAStdDevOfZeroForASingletonSnapshot() { + final Snapshot singleItemSnapshot = new UniformSnapshot(new long[] {1}); + +- assertThat(singleItemSnapshot.getStdDev()).isZero(); ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); + } + } +--- a/metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java +@@ -2,6 +2,7 @@ package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.offset; ++import static org.mockito.ArgumentMatchers.any; + import static org.mockito.Mockito.doReturn; + import static org.mockito.Mockito.spy; + import static org.mockito.Mockito.when; +@@ -11,7 +12,6 @@ import java.io.ByteArrayOutputStream; + import java.util.ArrayList; + import java.util.List; + import org.junit.Test; +-import org.mockito.ArgumentMatchers; + + public class WeightedSnapshotTest { + +@@ -34,12 +34,12 @@ public class WeightedSnapshotTest { + + @Test + public void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)).isEqualTo(1.0, offset(0.1)); ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1)); + } + + @Test + public void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1)); + } + + @Test(expected = IllegalArgumentException.class) +@@ -59,32 +59,32 @@ public class WeightedSnapshotTest { + + @Test + public void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); ++ assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1)); + } + + @Test + public void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1)); + } + + @Test + public void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test +@@ -104,7 +104,7 @@ public class WeightedSnapshotTest { + final List spyItems = spy(originalItems); + doReturn(originalItems.toArray(new WeightedSample[] {})) + .when(spyItems) +- .toArray(ArgumentMatchers.any(WeightedSample[].class)); ++ .toArray(any(WeightedSample[].class)); + when(spyItems.size()).thenReturn(4, 5); + + final Snapshot other = new WeightedSnapshot(spyItems); +@@ -119,7 +119,7 @@ public class WeightedSnapshotTest { + final List spyItems = spy(originalItems); + doReturn(originalItems.toArray(new WeightedSample[] {})) + .when(spyItems) +- .toArray(ArgumentMatchers.any(WeightedSample[].class)); ++ .toArray(any(WeightedSample[].class)); + when(spyItems.size()).thenReturn(6, 5); + + final Snapshot other = new WeightedSnapshot(spyItems); +@@ -133,7 +133,7 @@ public class WeightedSnapshotTest { + + snapshot.dump(output); + +- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); + } + + @Test +@@ -153,7 +153,7 @@ public class WeightedSnapshotTest { + + @Test + public void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()).isEqualTo(1.2688, offset(0.0001)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001)); + } + + @Test +@@ -161,7 +161,7 @@ public class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getMin()).isZero(); ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); + } + + @Test +@@ -169,7 +169,7 @@ public class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getMax()).isZero(); ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); + } + + @Test +@@ -177,7 +177,7 @@ public class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getMean()).isZero(); ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); + } + + @Test +@@ -185,7 +185,7 @@ public class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getStdDev()).isZero(); ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); + } + + @Test +@@ -193,7 +193,7 @@ public class WeightedSnapshotTest { + final Snapshot singleItemSnapshot = + new WeightedSnapshot(weightedArray(new long[] {1}, new double[] {1.0})); + +- assertThat(singleItemSnapshot.getStdDev()).isZero(); ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); + } + + @Test +--- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java ++++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java +@@ -132,8 +132,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { + final String sanitizedName = sanitize(name); + final String sanitizedValue = sanitize(value); + +- final String message = +- sanitizedName + ' ' + sanitizedValue + ' ' + Long.toString(timestamp) + '\n'; ++ final String message = sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n'; + channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); + } catch (IOException e) { + failures++; +--- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java ++++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java +@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; + import static com.codahale.metrics.MetricAttribute.M15_RATE; + import static com.codahale.metrics.MetricAttribute.M1_RATE; + import static com.codahale.metrics.MetricAttribute.M5_RATE; +-import static com.codahale.metrics.MetricAttribute.MAX; + import static com.codahale.metrics.MetricAttribute.MEAN; + import static com.codahale.metrics.MetricAttribute.MEAN_RATE; +-import static com.codahale.metrics.MetricAttribute.MIN; + import static com.codahale.metrics.MetricAttribute.P50; + import static com.codahale.metrics.MetricAttribute.P75; + import static com.codahale.metrics.MetricAttribute.P95; +@@ -15,6 +13,7 @@ import static com.codahale.metrics.MetricAttribute.P98; + import static com.codahale.metrics.MetricAttribute.P99; + import static com.codahale.metrics.MetricAttribute.P999; + import static com.codahale.metrics.MetricAttribute.STDDEV; ++import static java.util.Collections.emptySet; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.Counter; +@@ -29,7 +28,6 @@ import com.codahale.metrics.ScheduledReporter; + import com.codahale.metrics.Snapshot; + import com.codahale.metrics.Timer; + import java.io.IOException; +-import java.util.Collections; + import java.util.Locale; + import java.util.Map; + import java.util.Set; +@@ -83,7 +81,7 @@ public class GraphiteReporter extends ScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = emptySet(); + this.addMetricAttributesAsTags = false; + this.floatingPointFormatter = DEFAULT_FP_FORMATTER; + } +@@ -453,9 +451,9 @@ public class GraphiteReporter extends ScheduledReporter { + + private void reportTimer(String name, Timer timer, long timestamp) throws IOException { + final Snapshot snapshot = timer.getSnapshot(); +- sendIfEnabled(MAX, name, convertDuration(snapshot.getMax()), timestamp); ++ sendIfEnabled(MetricAttribute.MAX, name, convertDuration(snapshot.getMax()), timestamp); + sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); +- sendIfEnabled(MIN, name, convertDuration(snapshot.getMin()), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, convertDuration(snapshot.getMin()), timestamp); + sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); + sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); + sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); +@@ -478,9 +476,9 @@ public class GraphiteReporter extends ScheduledReporter { + throws IOException { + final Snapshot snapshot = histogram.getSnapshot(); + sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); +- sendIfEnabled(MAX, name, snapshot.getMax(), timestamp); ++ sendIfEnabled(MetricAttribute.MAX, name, snapshot.getMax(), timestamp); + sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); +- sendIfEnabled(MIN, name, snapshot.getMin(), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, snapshot.getMin(), timestamp); + sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); + sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); + sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); +--- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java ++++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java +@@ -63,7 +63,7 @@ public class GraphiteUDP implements GraphiteSender { + @Override + public void send(String name, String value, long timestamp) throws IOException { + try { +- String str = sanitize(name) + ' ' + sanitize(value) + ' ' + Long.toString(timestamp) + '\n'; ++ String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n'; + ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); + datagramChannel.send(byteBuffer, address); + this.failures = 0; +--- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java ++++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java +@@ -249,7 +249,7 @@ public class PickledGraphite implements GraphiteSender { + * message to graphite 3. Clear out the list of metrics + */ + private void writeMetrics() throws IOException { +- if (metrics.size() > 0) { ++ if (!metrics.isEmpty()) { + try { + byte[] payload = pickleMetrics(metrics); + byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteRabbitMQTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteRabbitMQTest.java +@@ -8,7 +8,6 @@ import static org.mockito.Mockito.anyString; + import static org.mockito.Mockito.atMost; + import static org.mockito.Mockito.doThrow; + import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -21,13 +20,13 @@ import org.junit.Before; + import org.junit.Test; + + public class GraphiteRabbitMQTest { +- private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); +- private final Connection connection = mock(Connection.class); +- private final Channel channel = mock(Channel.class); ++ private final ConnectionFactory connectionFactory = mock(); ++ private final Connection connection = mock(); ++ private final Channel channel = mock(); + +- private final ConnectionFactory bogusConnectionFactory = mock(ConnectionFactory.class); +- private final Connection bogusConnection = mock(Connection.class); +- private final Channel bogusChannel = mock(Channel.class); ++ private final ConnectionFactory bogusConnectionFactory = mock(); ++ private final Connection bogusConnection = mock(); ++ private final Channel bogusChannel = mock(); + + private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); + +@@ -92,10 +91,9 @@ public class GraphiteRabbitMQTest { + + String expectedMessage = "name value 100\n"; + +- verify(channel, times(1)) +- .basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); ++ verify(channel).basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); + +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } + + @Test +@@ -105,10 +103,10 @@ public class GraphiteRabbitMQTest { + + String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; + +- verify(channel, times(1)) ++ verify(channel) + .basicPublish("graphite", "name-to-sanitize", null, expectedMessage.getBytes(UTF_8)); + +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } + + @Test +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java +@@ -1,5 +1,6 @@ + package com.codahale.metrics.graphite; + ++import static java.util.Collections.emptySet; + import static org.mockito.Mockito.doThrow; + import static org.mockito.Mockito.inOrder; + import static org.mockito.Mockito.mock; +@@ -21,7 +22,6 @@ import com.codahale.metrics.Timer; + import java.net.UnknownHostException; + import java.text.DecimalFormat; + import java.text.DecimalFormatSymbols; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.Locale; + import java.util.Set; +@@ -34,9 +34,9 @@ import org.mockito.InOrder; + + public class GraphiteReporterTest { + private final long timestamp = 1000198; +- private final Clock clock = mock(Clock.class); +- private final Graphite graphite = mock(Graphite.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final Clock clock = mock(); ++ private final Graphite graphite = mock(); ++ private final MetricRegistry registry = mock(); + private final GraphiteReporter reporter = + GraphiteReporter.forRegistry(registry) + .withClock(clock) +@@ -44,7 +44,7 @@ public class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(emptySet()) + .build(graphite); + + private final GraphiteReporter minuteRateReporter = +@@ -54,7 +54,7 @@ public class GraphiteReporterTest { + .convertRatesTo(TimeUnit.MINUTES) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(emptySet()) + .build(graphite); + + @Before +@@ -174,7 +174,7 @@ public class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(emptySet()) + .withFloatingPointFormatter(formatter::format) + .build(graphite)) { + reportGaugeValue(graphiteReporter, 0.000045322); +@@ -216,7 +216,7 @@ public class GraphiteReporterTest { + + @Test + public void reportsCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map("counter", counter), map(), map(), map()); +@@ -232,10 +232,10 @@ public class GraphiteReporterTest { + + @Test + public void reportsHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -272,7 +272,7 @@ public class GraphiteReporterTest { + + @Test + public void reportsMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); +@@ -296,7 +296,7 @@ public class GraphiteReporterTest { + + @Test + public void reportsMetersInMinutes() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); +@@ -321,14 +321,14 @@ public class GraphiteReporterTest { + + @Test + public void reportsTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -395,14 +395,14 @@ public class GraphiteReporterTest { + + @Test + public void disabledMetricsAttribute() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(11L); + + Set disabledMetricAttributes = +@@ -433,7 +433,7 @@ public class GraphiteReporterTest { + + @Test + public void sendsMetricAttributesAsTagsIfEnabled() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + getReporterThatSendsMetricAttributesAsTags() +@@ -459,7 +459,7 @@ public class GraphiteReporterTest { + MetricFilter.ALL, + null, + false, +- Collections.emptySet(), ++ emptySet(), + false) { + @Override + protected String format(double v) { +@@ -475,7 +475,7 @@ public class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(emptySet()) + .addMetricAttributesAsTags(true) + .build(graphite); + } +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java +@@ -26,11 +26,11 @@ import org.junit.Test; + public class GraphiteTest { + private final String host = "example.com"; + private final int port = 1234; +- private final SocketFactory socketFactory = mock(SocketFactory.class); ++ private final SocketFactory socketFactory = mock(); + private final InetSocketAddress address = new InetSocketAddress(host, port); + +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); + + @Before + public void setUp() throws Exception { +@@ -84,7 +84,7 @@ public class GraphiteTest { + @Test + public void measuresFailures() throws IOException { + try (Graphite graphite = new Graphite(address, socketFactory)) { +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } + } + +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java +@@ -1,13 +1,13 @@ + package com.codahale.metrics.graphite; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; + + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; + import java.nio.channels.DatagramChannel; + import org.junit.Test; +-import org.mockito.Mockito; + + public class GraphiteUDPTest { + +@@ -30,7 +30,7 @@ public class GraphiteUDPTest { + @Test + public void writesValue() throws Exception { + graphiteUDP = new GraphiteUDP(host, port); +- DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); ++ DatagramChannel mockDatagramChannel = mock(); + graphiteUDP.setDatagramChannel(mockDatagramChannel); + graphiteUDP.setAddress(new InetSocketAddress(host, port)); + +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java +@@ -32,12 +32,12 @@ import org.python.core.PyList; + import org.python.core.PyTuple; + + public class PickledGraphiteTest { +- private final SocketFactory socketFactory = mock(SocketFactory.class); ++ private final SocketFactory socketFactory = mock(); + private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); + private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); + +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); + + private CompiledScript unpickleScript; + +--- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java ++++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java +@@ -29,10 +29,10 @@ public class AsyncHealthCheckDecorator extends HealthCheck implements Runnable { + this.healthyTtl = + async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); + result = +- Async.InitialState.HEALTHY.equals(async.initialState()) ++ Async.InitialState.HEALTHY == async.initialState() + ? Result.healthy(NO_RESULT_YET_MESSAGE) + : Result.unhealthy(NO_RESULT_YET_MESSAGE); +- if (Async.ScheduleType.FIXED_RATE.equals(async.scheduleType())) { ++ if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) { + future = + executorService.scheduleAtFixedRate( + this, async.initialDelay(), async.period(), async.unit()); +--- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java ++++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java +@@ -1,11 +1,12 @@ + package com.codahale.metrics.health; + ++import static java.util.Collections.unmodifiableMap; ++ + import com.codahale.metrics.Clock; + import java.time.Instant; + import java.time.ZoneId; + import java.time.ZonedDateTime; + import java.time.format.DateTimeFormatter; +-import java.util.Collections; + import java.util.LinkedHashMap; + import java.util.Map; + import java.util.concurrent.TimeUnit; +@@ -124,7 +125,7 @@ public abstract class HealthCheck { + this.healthy = isHealthy; + this.message = message; + this.error = error; +- this.details = details == null ? null : Collections.unmodifiableMap(details); ++ this.details = details == null ? null : unmodifiableMap(details); + this.time = clock.getTime(); + } + +@@ -163,7 +164,7 @@ public abstract class HealthCheck { + */ + public String getTimestamp() { + Instant currentInstant = Instant.ofEpochMilli(time); +- ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(currentInstant, ZoneId.systemDefault()); ++ ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault()); + return DATE_FORMAT_PATTERN.format(zonedDateTime); + } + +@@ -219,8 +220,7 @@ public abstract class HealthCheck { + int result = healthy ? 1 : 0; + result = PRIME * result + (message != null ? message.hashCode() : 0); + result = PRIME * result + (error != null ? error.hashCode() : 0); +- result = PRIME * result + (Long.hashCode(time)); +- return result; ++ return PRIME * result + (Long.hashCode(time)); + } + + @Override +@@ -238,7 +238,7 @@ public abstract class HealthCheck { + if (details != null) { + for (Map.Entry e : details.entrySet()) { + builder.append(", "); +- builder.append(e.getKey()).append("=").append(String.valueOf(e.getValue())); ++ builder.append(e.getKey()).append("=").append(e.getValue()); + } + } + builder.append('}'); +--- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java ++++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java +@@ -1,9 +1,10 @@ + package com.codahale.metrics.health; + + import static com.codahale.metrics.health.HealthCheck.Result; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; + + import com.codahale.metrics.health.annotation.Async; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -128,7 +129,7 @@ public class HealthCheckRegistry { + * @return the names of all registered health checks + */ + public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); ++ return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); + } + + /** +@@ -180,7 +181,7 @@ public class HealthCheckRegistry { + results.put(entry.getKey(), result); + } + } +- return Collections.unmodifiableSortedMap(results); ++ return unmodifiableSortedMap(results); + } + + /** +@@ -208,7 +209,7 @@ public class HealthCheckRegistry { + final String name = entry.getKey(); + final HealthCheck healthCheck = entry.getValue(); + if (filter.matches(name, healthCheck)) { +- futures.put(name, executor.submit(() -> healthCheck.execute())); ++ futures.put(name, executor.submit(healthCheck::execute)); + } + } + +@@ -222,7 +223,7 @@ public class HealthCheckRegistry { + } + } + +- return Collections.unmodifiableSortedMap(results); ++ return unmodifiableSortedMap(results); + } + + private void onHealthCheckAdded(String name, HealthCheck healthCheck) { +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/AsyncHealthCheckDecoratorTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/AsyncHealthCheckDecoratorTest.java +@@ -5,7 +5,6 @@ import static org.mockito.ArgumentCaptor.forClass; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -31,11 +30,11 @@ public class AsyncHealthCheckDecoratorTest { + .withMessage("Result was healthy but it expired 1 milliseconds ago") + .build(); + +- private final HealthCheck mockHealthCheck = mock(HealthCheck.class); +- private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); ++ private final HealthCheck mockHealthCheck = mock(); ++ private final ScheduledExecutorService mockExecutorService = mock(); + + @SuppressWarnings("rawtypes") +- private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); ++ private final ScheduledFuture mockFuture = mock(); + + @Test(expected = IllegalArgumentException.class) + public void nullHealthCheckTriggersInstantiationFailure() { +@@ -74,7 +73,7 @@ public class AsyncHealthCheckDecoratorTest { + AsyncHealthCheckDecorator asyncDecorator = + new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); + assertThat(asyncDecorator.check().isHealthy()).isTrue(); +@@ -87,7 +86,7 @@ public class AsyncHealthCheckDecoratorTest { + AsyncHealthCheckDecorator asyncDecorator = + new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); + } +@@ -102,8 +101,8 @@ public class AsyncHealthCheckDecoratorTest { + assertThat(asyncDecorator.check().isHealthy()).isFalse(); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void tearDownTriggersCancellation() throws Exception { + when(mockExecutorService.scheduleAtFixedRate( + any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) +@@ -114,13 +113,13 @@ public class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); + asyncDecorator.tearDown(); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); +- verify(mockFuture, times(1)).cancel(eq(true)); ++ verify(mockFuture).cancel(true); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { + HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); + when(mockExecutorService.scheduleAtFixedRate( +@@ -133,7 +132,7 @@ public class AsyncHealthCheckDecoratorTest { + HealthCheck.Result initialResult = asyncDecorator.check(); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +@@ -143,8 +142,8 @@ public class AsyncHealthCheckDecoratorTest { + assertThat(actualResult).isNotEqualTo(initialResult); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { + Exception exception = new Exception("TestException"); + when(mockExecutorService.scheduleAtFixedRate( +@@ -156,7 +155,7 @@ public class AsyncHealthCheckDecoratorTest { + new ConfigurableAsyncHealthCheck(exception), mockExecutorService); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +@@ -173,7 +172,7 @@ public class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate( + runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); +@@ -192,7 +191,7 @@ public class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate( + runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); +@@ -210,7 +209,7 @@ public class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckRegistryTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckRegistryTest.java +@@ -23,21 +23,21 @@ import org.junit.Test; + import org.mockito.ArgumentCaptor; + + public class HealthCheckRegistryTest { +- private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); ++ private final ScheduledExecutorService executorService = mock(); + private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); +- private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ private final HealthCheckRegistryListener listener = mock(); + +- private final HealthCheck hc1 = mock(HealthCheck.class); +- private final HealthCheck hc2 = mock(HealthCheck.class); ++ private final HealthCheck hc1 = mock(); ++ private final HealthCheck hc2 = mock(); + +- private final HealthCheck.Result r1 = mock(HealthCheck.Result.class); +- private final HealthCheck.Result r2 = mock(HealthCheck.Result.class); ++ private final HealthCheck.Result r1 = mock(); ++ private final HealthCheck.Result r2 = mock(); + +- private final HealthCheck.Result ar = mock(HealthCheck.Result.class); ++ private final HealthCheck.Result ar = mock(); + private final HealthCheck ahc = new TestAsyncHealthCheck(ar); + + @SuppressWarnings("rawtypes") +- private final ScheduledFuture af = mock(ScheduledFuture.class); ++ private final ScheduledFuture af = mock(); + + @Before + @SuppressWarnings("unchecked") +@@ -96,7 +96,7 @@ public class HealthCheckRegistryTest { + + @Test + public void addingListenerCatchesExistingHealthChecks() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ HealthCheckRegistryListener listener = mock(); + HealthCheckRegistry registry = new HealthCheckRegistry(); + registry.register("hc1", hc1); + registry.register("hc2", hc2); +@@ -110,7 +110,7 @@ public class HealthCheckRegistryTest { + + @Test + public void removedListenerDoesNotReceiveUpdates() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ HealthCheckRegistryListener listener = mock(); + HealthCheckRegistry registry = new HealthCheckRegistry(); + registry.addListener(listener); + registry.register("hc1", hc1); +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java +@@ -29,7 +29,7 @@ public class HealthCheckTest { + } + } + +- private final HealthCheck underlying = mock(HealthCheck.class); ++ private final HealthCheck underlying = mock(); + private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); + + @Test +@@ -89,7 +89,7 @@ public class HealthCheckTest { + + @Test + public void canHaveUnhealthyResultsWithExceptions() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); +@@ -144,7 +144,7 @@ public class HealthCheckTest { + + @Test + public void canHaveUnHealthyBuilderWithDetailAndError() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + final HealthCheck.Result result = +@@ -161,7 +161,7 @@ public class HealthCheckTest { + + @Test + public void returnsResultsWhenExecuted() { +- final HealthCheck.Result result = mock(HealthCheck.Result.class); ++ final HealthCheck.Result result = mock(); + when(underlying.execute()).thenReturn(result); + + assertThat(healthCheck.execute()).isEqualTo(result); +@@ -171,7 +171,7 @@ public class HealthCheckTest { + + @Test + public void wrapsExceptionsWhenExecuted() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + when(underlying.execute()).thenThrow(e); +@@ -181,7 +181,7 @@ public class HealthCheckTest { + assertThat(actual.getMessage()).isEqualTo("oh noes"); + assertThat(actual.getError()).isEqualTo(e); + assertThat(actual.getDetails()).isNull(); +- assertThat(actual.getDuration()).isGreaterThanOrEqualTo(0); ++ assertThat(actual.getDuration()).isNotNegative(); + } + + @Test +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java +@@ -30,7 +30,7 @@ public class SharedHealthCheckRegistriesTest { + public void returnsSetOfCreatedRegistries() { + SharedHealthCheckRegistries.getOrCreate("db"); + +- assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); ++ assertThat(SharedHealthCheckRegistries.names()).containsExactly("db"); + } + + @Test +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java +@@ -1,12 +1,12 @@ + package com.codahale.metrics.health.jvm; + ++import static java.util.Collections.emptySet; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + + import com.codahale.metrics.health.HealthCheck; + import com.codahale.metrics.jvm.ThreadDeadlockDetector; +-import java.util.Collections; + import java.util.Set; + import java.util.TreeSet; + import org.junit.Test; +@@ -14,10 +14,10 @@ import org.junit.Test; + public class ThreadDeadlockHealthCheckTest { + @Test + public void isHealthyIfNoThreadsAreDeadlocked() { +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ final ThreadDeadlockDetector detector = mock(); + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); + +- when(detector.getDeadlockedThreads()).thenReturn(Collections.emptySet()); ++ when(detector.getDeadlockedThreads()).thenReturn(emptySet()); + + assertThat(healthCheck.execute().isHealthy()).isTrue(); + } +@@ -28,7 +28,7 @@ public class ThreadDeadlockHealthCheckTest { + threads.add("one"); + threads.add("two"); + +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ final ThreadDeadlockDetector detector = mock(); + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); + + when(detector.getDeadlockedThreads()).thenReturn(threads); +--- a/metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/InstrumentedHttpClientsTimerTest.java ++++ b/metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/InstrumentedHttpClientsTimerTest.java +@@ -45,7 +45,7 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + chac.start(); + asyncHttpClient = chac; + +- Timer timer = mock(Timer.class); ++ Timer timer = mock(); + when(timer.time()).thenReturn(context); + when(metricRegistry.timer(any())).thenReturn(timer); + } +@@ -71,13 +71,13 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + verify(context, timeout(200).times(1)).stop(); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { + HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); + HttpGet get = new HttpGet("/?q=something"); + +- FutureCallback futureCallback = mock(FutureCallback.class); ++ FutureCallback futureCallback = mock(); + + // Timer hasn't been stopped prior to executing the request + verify(context, never()).stop(); +@@ -98,14 +98,14 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + verify(context, timeout(200).times(1)).stop(); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { + // There should be nothing listening on this port + HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); + HttpGet get = new HttpGet("/?q=something"); + +- FutureCallback futureCallback = mock(FutureCallback.class); ++ FutureCallback futureCallback = mock(); + + // Timer hasn't been stopped prior to executing the request + verify(context, never()).stop(); +--- a/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientConnectionManagerTest.java +@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import com.codahale.metrics.MetricRegistry; + import org.junit.Assert; + import org.junit.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; + + public class InstrumentedHttpClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); +@@ -36,7 +38,7 @@ public class InstrumentedHttpClientConnectionManagerTest { + + @Test + public void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); + + InstrumentedHttpClientConnectionManager.builder(registry) + .name("some-name") +@@ -45,7 +47,7 @@ public class InstrumentedHttpClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); + assertTrue(argumentCaptor.getValue().contains("some-other-name")); + } + } +--- a/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientsTest.java +@@ -22,9 +22,8 @@ import org.junit.Before; + import org.junit.Test; + + public class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); + private final MetricRegistry metricRegistry = new MetricRegistry(); + private final HttpClient client = + InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) +--- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java +@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import com.codahale.metrics.MetricRegistry; + import org.junit.Assert; + import org.junit.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; + + public class InstrumentedAsyncClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); +@@ -43,7 +45,7 @@ public class InstrumentedAsyncClientConnectionManagerTest { + + @Test + public void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); + + InstrumentedAsyncClientConnectionManager.builder(registry) + .name("some-name") +@@ -52,7 +54,7 @@ public class InstrumentedAsyncClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); + assertTrue(argumentCaptor.getValue().contains("some-other-name")); + } + } +--- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java ++++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java +@@ -1,5 +1,6 @@ + package com.codahale.metrics.httpclient5; + ++import static java.nio.charset.StandardCharsets.US_ASCII; + import static org.assertj.core.api.Assertions.assertThat; + import static org.awaitility.Awaitility.await; + import static org.junit.Assert.fail; +@@ -17,7 +18,6 @@ import com.sun.net.httpserver.HttpExchange; + import com.sun.net.httpserver.HttpServer; + import java.io.IOException; + import java.net.InetSocketAddress; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.ExecutionException; + import java.util.concurrent.Future; +@@ -82,7 +82,7 @@ public class InstrumentedHttpAsyncClientsTest { + exchange -> { + exchange.sendResponseHeaders(200, 0L); + exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); + exchange.close(); + }); + httpServer.start(); +@@ -187,7 +187,7 @@ public class InstrumentedHttpAsyncClientsTest { + exchange -> { + exchange.sendResponseHeaders(200, 0L); + exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); + exchange.close(); + }); + httpServer.start(); +--- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientConnectionManagerTest.java +@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import com.codahale.metrics.MetricRegistry; + import org.junit.Assert; + import org.junit.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; + + public class InstrumentedHttpClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); +@@ -41,7 +43,7 @@ public class InstrumentedHttpClientConnectionManagerTest { + + @Test + public void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); + + InstrumentedHttpClientConnectionManager.builder(registry) + .name("some-name") +@@ -50,7 +52,7 @@ public class InstrumentedHttpClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); + assertTrue(argumentCaptor.getValue().contains("some-other-name")); + } + } +--- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java +@@ -22,9 +22,8 @@ import org.junit.Before; + import org.junit.Test; + + public class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); + private final MetricRegistry metricRegistry = new MetricRegistry(); + private final HttpClient client = + InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) +--- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListenerTest.java +@@ -10,7 +10,7 @@ import jakarta.servlet.ServletContextEvent; + import org.junit.Test; + + public class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ public class InstrumentedFilterContextListenerTest { + + @Test + public void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); + + listener.contextInitialized(event); +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java +@@ -83,7 +83,7 @@ public class HealthCheckServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); + if (registryAttr instanceof HealthCheckRegistry) { + this.registry = (HealthCheckRegistry) registryAttr; +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java +@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(METRICS_REGISTRY); + if (registryAttr instanceof MetricRegistry) { + this.registry = (MetricRegistry) registryAttr; +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java +@@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -102,9 +101,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -143,9 +141,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -217,15 +214,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getContent()) + .isEqualTo( + String.format( +- "{%n" +- + " \"fun\" : {%n" +- + " \"healthy\" : true,%n" +- + " \"message\" : \"foo bar 123\",%n" +- + " \"duration\" : 0,%n" +- + " \"timestamp\" : \"" +- + EXPECTED_TIMESTAMP +- + "\"" +- + "%n }%n}")); ++ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", ++ EXPECTED_TIMESTAMP)); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -240,25 +230,25 @@ public class HealthCheckServletTest extends AbstractServletTest { + @Test + public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() + throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final io.dropwizard.metrics.servlets.HealthCheckServlet healthCheckServlet = + new io.dropwizard.metrics.servlets.HealthCheckServlet(healthCheckRegistry); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()) + .getAttribute(eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY)); + } + + @Test + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute( + eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY))) +@@ -268,16 +258,16 @@ public class HealthCheckServletTest extends AbstractServletTest { + new io.dropwizard.metrics.servlets.HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)) ++ verify(servletConfig).getServletContext(); ++ verify(servletContext) + .getAttribute(eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY)); + } + + @Test(expected = ServletException.class) + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute( + eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY))) +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletContextListenerTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletContextListenerTest.java +@@ -17,7 +17,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MetricsServletContextListenerTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final String allowedOrigin = "some.other.origin"; + +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java +@@ -1,10 +1,8 @@ + package io.dropwizard.metrics.servlets; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -24,7 +22,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MetricsServletTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private ServletTester tester; + +@@ -128,22 +126,8 @@ public class MetricsServletTest extends AbstractServletTest { + assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); + assertThat(response.getContent()) + .isEqualTo( +- callbackParamVal +- + "({" +- + "\"version\":\"4.0.0\"," +- + "\"gauges\":{" +- + "\"g1\":{\"value\":100}" +- + "}," +- + "\"counters\":{" +- + "\"c\":{\"count\":1}" +- + "}," +- + "\"histograms\":{" +- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" +- + "}," +- + "\"meters\":{" +- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" +- + "}" +- + "})"); ++ "%s({\"version\":\"4.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", ++ callbackParamVal); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -223,47 +207,47 @@ public class MetricsServletTest extends AbstractServletTest { + @Test + public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() + throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = + new io.dropwizard.metrics.servlets.MetricsServlet(metricRegistry); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()) +- .getAttribute(eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)); ++ .getAttribute(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY); + } + + @Test + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute( +- eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY))) ++ io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)) + .thenReturn(metricRegistry); + + final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = + new io.dropwizard.metrics.servlets.MetricsServlet(null); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)) +- .getAttribute(eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext) ++ .getAttribute(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY); + } + + @Test(expected = ServletException.class) + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute( +- eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY))) ++ io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); + + final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = new MetricsServlet(null); +--- a/metrics-jcache/src/main/java/com/codahale/metrics/jcache/JCacheGaugeSet.java ++++ b/metrics-jcache/src/main/java/com/codahale/metrics/jcache/JCacheGaugeSet.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics.jcache; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Metric; + import com.codahale.metrics.MetricSet; +@@ -8,7 +9,6 @@ import com.codahale.metrics.jvm.JmxAttributeGauge; + import java.lang.management.ManagementFactory; + import java.lang.reflect.Method; + import java.util.ArrayList; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Locale; +@@ -51,7 +51,7 @@ public class JCacheGaugeSet implements MetricSet { + } + } + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + + private Set getCacheBeans() { +--- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java ++++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java +@@ -71,18 +71,18 @@ public class JCacheGaugeSetTest { + assertThat( + (Float) + registry.getGauges().get("jcache.statistics.myCache.average-get-time").getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + assertThat( + (Float) + registry.getGauges().get("jcache.statistics.myCache.average-put-time").getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + assertThat( + (Float) + registry + .getGauges() + .get("jcache.statistics.myCache.average-remove-time") + .getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + } + + @After +--- a/metrics-jdbi/src/main/java/com/codahale/metrics/jdbi/strategies/NameStrategies.java ++++ b/metrics-jdbi/src/main/java/com/codahale/metrics/jdbi/strategies/NameStrategies.java +@@ -45,7 +45,7 @@ public final class NameStrategies { + public String getStatementName(StatementContext statementContext) { + final String rawSql = statementContext.getRawSql(); + +- if (rawSql == null || rawSql.length() == 0) { ++ if (rawSql == null || rawSql.isEmpty()) { + return EMPTY_SQL; + } + return null; +--- a/metrics-jdbi/src/test/java/com/codahale/metrics/jdbi/InstrumentedTimingCollectorTest.java ++++ b/metrics-jdbi/src/test/java/com/codahale/metrics/jdbi/InstrumentedTimingCollectorTest.java +@@ -23,7 +23,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass()).when(ctx).getSqlObjectType(); + doReturn(getClass().getMethod("updatesTimerForSqlObjects")).when(ctx).getSqlObjectMethod(); +@@ -42,7 +42,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass()).when(ctx).getSqlObjectType(); + +@@ -60,7 +60,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + + collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); +@@ -77,7 +77,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + + collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); + +@@ -93,7 +93,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("don't know what it is but it's not SQL").when(ctx).getRawSql(); + + collector.collect(TimeUnit.SECONDS.toNanos(3), ctx); +@@ -110,7 +110,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass().getName()).when(ctx).getAttribute(NameStrategies.STATEMENT_CLASS); + doReturn("updatesTimerForContextClass").when(ctx).getAttribute(NameStrategies.STATEMENT_NAME); +@@ -129,7 +129,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn("foo/bar.stg").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); + doReturn("updatesTimerForTemplateFile").when(ctx).getAttribute(NameStrategies.STATEMENT_NAME); +@@ -148,7 +148,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn("my-group").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); + doReturn("updatesTimerForContextGroupAndName") +@@ -169,7 +169,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn("my-group").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); + doReturn("my-type").when(ctx).getAttribute(NameStrategies.STATEMENT_TYPE); +@@ -192,7 +192,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new ShortNameStrategy("jdbi"); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass()).when(ctx).getSqlObjectType(); + doReturn(getClass().getMethod("updatesTimerForShortSqlObjectStrategy")) +@@ -215,7 +215,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new ShortNameStrategy("jdbi"); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass().getName()).when(ctx).getAttribute(NameStrategies.STATEMENT_CLASS); + doReturn("updatesTimerForShortContextClassStrategy") +--- a/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/InstrumentedSqlLoggerTest.java ++++ b/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/InstrumentedSqlLoggerTest.java +@@ -16,12 +16,12 @@ import org.junit.Test; + public class InstrumentedSqlLoggerTest { + @Test + public void logsExecutionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); + final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); + +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); + + final String statementName = "my-fake-name"; + final long fakeElapsed = 1234L; +@@ -38,12 +38,12 @@ public class InstrumentedSqlLoggerTest { + + @Test + public void logsExceptionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); + final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); + +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); + + final String statementName = "my-fake-name"; + final long fakeElapsed = 1234L; +--- a/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/AbstractStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/AbstractStrategyTest.java +@@ -10,7 +10,7 @@ import org.junit.Before; + public class AbstractStrategyTest { + + MetricRegistry registry = new MetricRegistry(); +- StatementContext ctx = mock(StatementContext.class); ++ StatementContext ctx = mock(); + + @Before + public void setUp() throws Exception { +--- a/metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.ExponentiallyDecayingReservoir; +@@ -19,7 +22,6 @@ import com.codahale.metrics.annotation.Timed; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(metricName, "1xx-responses")), // 1xx + registry.meter(name(metricName, "2xx-responses")), // 2xx +@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(name(metricName, "4xx-responses")), // 4xx + registry.meter(name(metricName, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); + this.metricRegistry = registry; + } + +@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); + } + } + } +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonFilterMetricsJerseyTest.java +@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @Before +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } + + @Test +@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsJerseyTest.java +@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -87,12 +85,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(0); + } + + @Test +@@ -107,9 +105,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -119,9 +117,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } + + @Test +@@ -131,12 +129,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + + @Test +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsTimedPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } + + @Test +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } + + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } + + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedResource.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import javax.ws.rs.core.Response; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,24 +46,24 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedSubResource.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import javax.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +--- a/metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.ExponentiallyDecayingReservoir; +@@ -21,7 +24,6 @@ import jakarta.ws.rs.ext.Provider; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(metricName, "1xx-responses")), // 1xx + registry.meter(name(metricName, "2xx-responses")), // 2xx +@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(name(metricName, "4xx-responses")), // 4xx + registry.meter(name(metricName, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); + this.metricRegistry = registry; + } + +@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); + } + } + } +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonFilterMetricsJerseyTest.java +@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @Before +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } + + @Test +@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsJerseyTest.java +@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -92,9 +90,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -104,9 +102,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } + + @Test +@@ -116,12 +114,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + + @Test +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsTimedPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } + + @Test +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } + + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } + + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedResource.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,24 +46,24 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedSubResource.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +--- a/metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.ExponentiallyDecayingReservoir; +@@ -21,7 +24,6 @@ import jakarta.ws.rs.ext.Provider; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(metricName, "1xx-responses")), // 1xx + registry.meter(name(metricName, "2xx-responses")), // 2xx +@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(name(metricName, "4xx-responses")), // 4xx + registry.meter(name(metricName, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); + this.metricRegistry = registry; + } + +@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); + } + } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonFilterMetricsJerseyTest.java +@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @Before +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } + + @Test +@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsJerseyTest.java +@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -87,12 +85,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(0); + } + + @Test +@@ -107,9 +105,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -119,9 +117,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } + + @Test +@@ -131,12 +129,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + + @Test +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsTimedPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } + + @Test +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } + + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } + + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,24 +46,24 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedSubResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -13,7 +16,6 @@ import com.codahale.metrics.Timer; + import com.codahale.metrics.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -172,10 +174,10 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx +@@ -183,7 +185,7 @@ public class InstrumentedHandler extends HandlerWrapper { + metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx + metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -14,7 +17,6 @@ import com.codahale.metrics.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(prefix, "1xx-responses")), // 1xx + registry.meter(name(prefix, "2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(name(prefix, "4xx-responses")), // 4xx + registry.meter(name(prefix, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); + this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java +@@ -1,12 +1,12 @@ + package io.dropwizard.metrics.jetty10; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatCode; + + import com.codahale.metrics.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import javax.servlet.AsyncContext; + import javax.servlet.ServletException; +@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { + assertThatCode(handler::doStop).doesNotThrowAnyException(); + } + +- @Test + @Ignore("flaky on virtual machines") ++ @Test + public void responseTimesAreRecordedForAsyncResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/async")); +@@ -126,15 +126,14 @@ public class InstrumentedHandlerTest { + } + + private void assertResponseTimesValid() { +- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) +- .isGreaterThan(0L); ++ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); + + assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -197,7 +196,7 @@ public class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListenerTest.java +@@ -1,11 +1,11 @@ + package io.dropwizard.metrics.jetty10; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import com.codahale.metrics.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import javax.servlet.AsyncContext; + import javax.servlet.ServletOutputStream; + import javax.servlet.WriteListener; +@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -172,10 +174,10 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx +@@ -183,7 +185,7 @@ public class InstrumentedHandler extends HandlerWrapper { + metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx + metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(prefix, "1xx-responses")), // 1xx + registry.meter(name(prefix, "2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(name(prefix, "4xx-responses")), // 4xx + registry.meter(name(prefix, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); + this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics.jetty11; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatCode; + +@@ -12,7 +13,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; +@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { + assertThatCode(handler::doStop).doesNotThrowAnyException(); + } + +- @Test + @Ignore("flaky on virtual machines") ++ @Test + public void responseTimesAreRecordedForAsyncResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/async")); +@@ -126,17 +126,15 @@ public class InstrumentedHandlerTest { + } + + private void assertResponseTimesValid() { +- assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()) +- .isGreaterThan(0L); +- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) +- .isGreaterThan(0L); ++ assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()).isPositive(); ++ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); + + assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -199,7 +197,7 @@ public class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListenerTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics.jetty11; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import com.codahale.metrics.MetricRegistry; +@@ -10,7 +11,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.Request; +@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java ++++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -13,7 +16,6 @@ import com.codahale.metrics.Timer; + import com.codahale.metrics.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -180,10 +182,10 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx +@@ -191,7 +193,7 @@ public class InstrumentedHandler extends HandlerWrapper { + metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx + metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); +--- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -14,7 +17,6 @@ import com.codahale.metrics.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(prefix, "1xx-responses")), // 1xx + registry.meter(name(prefix, "2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(name(prefix, "4xx-responses")), // 4xx + registry.meter(name(prefix, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); + this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); +--- a/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java ++++ b/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java +@@ -1,12 +1,12 @@ + package com.codahale.metrics.jetty9; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatCode; + + import com.codahale.metrics.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import javax.servlet.AsyncContext; + import javax.servlet.ServletException; +@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { + assertThatCode(handler::doStop).doesNotThrowAnyException(); + } + +- @Test + @Ignore("flaky on virtual machines") ++ @Test + public void responseTimesAreRecordedForAsyncResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/async")); +@@ -126,17 +126,15 @@ public class InstrumentedHandlerTest { + } + + private void assertResponseTimesValid() { +- assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()) +- .isGreaterThan(0L); +- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) +- .isGreaterThan(0L); ++ assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()).isPositive(); ++ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); + + assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -199,7 +197,7 @@ public class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListenerTest.java +@@ -1,11 +1,11 @@ + package com.codahale.metrics.jetty9; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import com.codahale.metrics.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import javax.servlet.AsyncContext; + import javax.servlet.ServletOutputStream; + import javax.servlet.WriteListener; +@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java ++++ b/metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java +@@ -36,9 +36,8 @@ public class DefaultObjectNameFactory implements ObjectNameFactory { + || shouldQuote(objectName.getKeyProperty("type"))) { + properties.put("type", ObjectName.quote(type)); + } +- objectName = new ObjectName(domain, properties); ++ return new ObjectName(domain, properties); + +- return objectName; + } catch (MalformedObjectNameException e) { + try { + return new ObjectName(domain, "name", ObjectName.quote(name)); +--- a/metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java ++++ b/metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java +@@ -1,5 +1,8 @@ + package com.codahale.metrics.jmx; + ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableMap; ++ + import com.codahale.metrics.Counter; + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Histogram; +@@ -12,7 +15,6 @@ import com.codahale.metrics.Reporter; + import com.codahale.metrics.Timer; + import java.io.Closeable; + import java.lang.management.ManagementFactory; +-import java.util.Collections; + import java.util.Locale; + import java.util.Map; + import java.util.concurrent.ConcurrentHashMap; +@@ -60,8 +62,8 @@ public class JmxReporter implements Reporter, Closeable { + this.durationUnit = TimeUnit.MILLISECONDS; + this.domain = "metrics"; + this.objectNameFactory = new DefaultObjectNameFactory(); +- this.specificDurationUnits = Collections.emptyMap(); +- this.specificRateUnits = Collections.emptyMap(); ++ this.specificDurationUnits = emptyMap(); ++ this.specificRateUnits = emptyMap(); + } + + /** +@@ -128,7 +130,7 @@ public class JmxReporter implements Reporter, Closeable { + * @return {@code this} + */ + public Builder specificDurationUnits(Map specificDurationUnits) { +- this.specificDurationUnits = Collections.unmodifiableMap(specificDurationUnits); ++ this.specificDurationUnits = unmodifiableMap(specificDurationUnits); + return this; + } + +@@ -139,7 +141,7 @@ public class JmxReporter implements Reporter, Closeable { + * @return {@code this} + */ + public Builder specificRateUnits(Map specificRateUnits) { +- this.specificRateUnits = Collections.unmodifiableMap(specificRateUnits); ++ this.specificRateUnits = unmodifiableMap(specificRateUnits); + return this; + } + +--- a/metrics-jmx/src/test/java/com/codahale/metrics/jmx/JmxReporterTest.java ++++ b/metrics-jmx/src/test/java/com/codahale/metrics/jmx/JmxReporterTest.java +@@ -1,5 +1,6 @@ + package com.codahale.metrics.jmx; + ++import static java.util.UUID.randomUUID; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +@@ -20,7 +21,6 @@ import com.codahale.metrics.Timer; + import java.lang.management.ManagementFactory; + import java.util.SortedMap; + import java.util.TreeMap; +-import java.util.UUID; + import java.util.concurrent.TimeUnit; + import javax.management.Attribute; + import javax.management.AttributeList; +@@ -36,7 +36,7 @@ import org.junit.Test; + @SuppressWarnings("rawtypes") + public class JmxReporterTest { + private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); +- private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); ++ private final String name = randomUUID().toString().replaceAll("[{\\-}]", ""); + private final MetricRegistry registry = new MetricRegistry(); + + private final JmxReporter reporter = +@@ -48,12 +48,12 @@ public class JmxReporterTest { + .filter(MetricFilter.ALL) + .build(); + +- private final Gauge gauge = mock(Gauge.class); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); +- private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); ++ private final Gauge gauge = mock(); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); ++ private final ObjectNameFactory mockObjectNameFactory = mock(); + private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); + + @Before +@@ -64,7 +64,7 @@ public class JmxReporterTest { + + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot hSnapshot = mock(Snapshot.class); ++ final Snapshot hSnapshot = mock(); + when(hSnapshot.getMax()).thenReturn(2L); + when(hSnapshot.getMean()).thenReturn(3.0); + when(hSnapshot.getMin()).thenReturn(4L); +@@ -91,7 +91,7 @@ public class JmxReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot tSnapshot = mock(Snapshot.class); ++ final Snapshot tSnapshot = mock(); + when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -274,7 +274,7 @@ public class JmxReporterTest { + + @Test + public void objectNameModifyingMBeanServer() throws Exception { +- MBeanServer mockedMBeanServer = mock(MBeanServer.class); ++ MBeanServer mockedMBeanServer = mock(); + + // overwrite the objectName + when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))) +--- a/metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java ++++ b/metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java +@@ -1,5 +1,7 @@ + package com.codahale.metrics.json; + ++import static java.util.Collections.singletonList; ++ + import com.codahale.metrics.health.HealthCheck; + import com.fasterxml.jackson.core.JsonGenerator; + import com.fasterxml.jackson.core.Version; +@@ -8,7 +10,6 @@ import com.fasterxml.jackson.databind.SerializerProvider; + import com.fasterxml.jackson.databind.module.SimpleSerializers; + import com.fasterxml.jackson.databind.ser.std.StdSerializer; + import java.io.IOException; +-import java.util.Collections; + import java.util.Map; + + public class HealthCheckModule extends Module { +@@ -79,7 +80,6 @@ public class HealthCheckModule extends Module { + + @Override + public void setupModule(SetupContext context) { +- context.addSerializers( +- new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer()))); ++ context.addSerializers(new SimpleSerializers(singletonList(new HealthCheckResultSerializer()))); + } + } +--- a/metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java ++++ b/metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java +@@ -17,8 +17,7 @@ public class HealthCheckModuleTest { + public void serializesAHealthyResult() throws Exception { + HealthCheck.Result result = HealthCheck.Result.healthy(); + assertThat(mapper.writeValueAsString(result)) +- .isEqualTo( +- "{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); ++ .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp()); + } + + @Test +@@ -26,14 +25,8 @@ public class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":true," +- + "\"message\":\"yay for me\"," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -41,14 +34,8 @@ public class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"boo\"," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -60,19 +47,8 @@ public class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy(e); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"oh no\"," +- + "\"error\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh no\"," +- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" +- + "}," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -88,24 +64,8 @@ public class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy(b); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"oh well\"," +- + "\"error\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh well\"," +- + "\"stack\":[\"Blah.blee(Blah.java:150)\"]," +- + "\"cause\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh no\"," +- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" +- + "}" +- + "}," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -129,23 +89,7 @@ public class HealthCheckModuleTest { + + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":true," +- + "\"duration\":0," +- + "\"boolean\":true," +- + "\"integer\":1," +- + "\"long\":2," +- + "\"float\":3.546," +- + "\"double\":4.567," +- + "\"BigInteger\":12345," +- + "\"BigDecimal\":12345.56789," +- + "\"String\":\"string\"," +- + "\"complex\":{" +- + "\"field\":\"value\"" +- + "}," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + } +--- a/metrics-json/src/test/java/com/codahale/metrics/json/MetricsModuleTest.java ++++ b/metrics-json/src/test/java/com/codahale/metrics/json/MetricsModuleTest.java +@@ -42,7 +42,7 @@ public class MetricsModuleTest { + + @Test + public void serializesCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + assertThat(mapper.writeValueAsString(counter)).isEqualTo("{\"count\":100}"); +@@ -50,10 +50,10 @@ public class MetricsModuleTest { + + @Test + public void serializesHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -107,7 +107,7 @@ public class MetricsModuleTest { + + @Test + public void serializesMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(5.0); +@@ -127,14 +127,14 @@ public class MetricsModuleTest { + + @Test + public void serializesTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/BufferPoolMetricSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/BufferPoolMetricSet.java +@@ -1,10 +1,10 @@ + package com.codahale.metrics.jvm; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Metric; + import com.codahale.metrics.MetricSet; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + import javax.management.JMException; +@@ -46,6 +46,6 @@ public class BufferPoolMetricSet implements MetricSet { + } + } + } +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/GarbageCollectorMetricSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/GarbageCollectorMetricSet.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics.jvm; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Metric; +@@ -9,7 +10,6 @@ import java.lang.management.GarbageCollectorMXBean; + import java.lang.management.ManagementFactory; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -43,6 +43,6 @@ public class GarbageCollectorMetricSet implements MetricSet { + gauges.put(name(name, "count"), (Gauge) gc::getCollectionCount); + gauges.put(name(name, "time"), (Gauge) gc::getCollectionTime); + } +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/JvmAttributeGaugeSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/JvmAttributeGaugeSet.java +@@ -1,11 +1,12 @@ + package com.codahale.metrics.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Metric; + import com.codahale.metrics.MetricSet; + import java.lang.management.ManagementFactory; + import java.lang.management.RuntimeMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Locale; + import java.util.Map; +@@ -46,6 +47,6 @@ public class JvmAttributeGaugeSet implements MetricSet { + runtime.getSpecVersion())); + gauges.put("uptime", (Gauge) runtime::getUptime); + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics.jvm; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Metric; +@@ -12,7 +13,6 @@ import java.lang.management.MemoryPoolMXBean; + import java.lang.management.MemoryUsage; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -122,6 +122,6 @@ public class MemoryUsageGaugeSet implements MetricSet { + gauges.put(name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); + } + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java +@@ -1,9 +1,11 @@ + package com.codahale.metrics.jvm; + ++import static java.util.Collections.emptySet; ++import static java.util.Collections.unmodifiableSet; ++ + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashSet; + import java.util.Set; + +@@ -40,19 +42,16 @@ public class ThreadDeadlockDetector { + for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { + final StringBuilder stackTrace = new StringBuilder(); + for (StackTraceElement element : info.getStackTrace()) { +- stackTrace.append("\t at ").append(element.toString()).append(String.format("%n")); ++ stackTrace.append("\t at ").append(element).append(String.format("%n")); + } + + deadlocks.add( + String.format( + "%s locked on %s (owned by %s):%n%s", +- info.getThreadName(), +- info.getLockName(), +- info.getLockOwnerName(), +- stackTrace.toString())); ++ info.getThreadName(), info.getLockName(), info.getLockOwnerName(), stackTrace)); + } +- return Collections.unmodifiableSet(deadlocks); ++ return unmodifiableSet(deadlocks); + } +- return Collections.emptySet(); ++ return emptySet(); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics.jvm; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Metric; +@@ -8,7 +9,6 @@ import com.codahale.metrics.MetricSet; + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + import java.util.Set; +@@ -56,7 +56,7 @@ public class ThreadStatesGaugeSet implements MetricSet { + "deadlock.count", (Gauge) () -> deadlockDetector.getDeadlockedThreads().size()); + gauges.put("deadlocks", (Gauge>) deadlockDetector::getDeadlockedThreads); + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + + private int getThreadCount(Thread.State state) { +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/BufferPoolMetricSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/BufferPoolMetricSetTest.java +@@ -13,7 +13,7 @@ import org.junit.Test; + + @SuppressWarnings("rawtypes") + public class BufferPoolMetricSetTest { +- private final MBeanServer mBeanServer = mock(MBeanServer.class); ++ private final MBeanServer mBeanServer = mock(); + private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); + + private ObjectName mapped; +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ClassLoadingGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ClassLoadingGaugeSetTest.java +@@ -12,7 +12,7 @@ import org.junit.Test; + @SuppressWarnings("rawtypes") + public class ClassLoadingGaugeSetTest { + +- private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); ++ private final ClassLoadingMXBean cl = mock(); + private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); + + @Before +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java +@@ -12,10 +12,10 @@ public class CpuTimeClockTest { + public void cpuTimeClock() { + final CpuTimeClock clock = new CpuTimeClock(); + +- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(250D)); ++ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(250D)); + + assertThat((double) clock.getTick()) +- .isEqualTo( ++ .isCloseTo( + ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(), offset(1000000.0)); + } + } +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeTest.java +@@ -13,7 +13,7 @@ import org.junit.Test; + + @SuppressWarnings("UnusedDeclaration") + public class FileDescriptorRatioGaugeTest { +- private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); ++ private final UnixOperatingSystemMXBean os = mock(); + + private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); + +@@ -33,9 +33,7 @@ public class FileDescriptorRatioGaugeTest { + OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); + assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); + +- assertThat(new FileDescriptorRatioGauge().getValue()) +- .isGreaterThanOrEqualTo(0.0) +- .isLessThanOrEqualTo(1.0); ++ assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative().isLessThanOrEqualTo(1.0); + } + + @Test +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java +@@ -1,20 +1,20 @@ + package com.codahale.metrics.jvm; + ++import static java.util.Collections.singletonList; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + + import com.codahale.metrics.Gauge; + import java.lang.management.GarbageCollectorMXBean; +-import java.util.Collections; + import org.junit.Before; + import org.junit.Test; + + @SuppressWarnings("unchecked") + public class GarbageCollectorMetricSetTest { +- private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); ++ private final GarbageCollectorMXBean gc = mock(); + private final GarbageCollectorMetricSet metrics = +- new GarbageCollectorMetricSet(Collections.singletonList(gc)); ++ new GarbageCollectorMetricSet(singletonList(gc)); + + @Before + public void setUp() { +@@ -42,6 +42,6 @@ public class GarbageCollectorMetricSetTest { + + @Test + public void autoDiscoversGCs() { +- assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()).isNotEmpty(); ++ assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty(); + } + } +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JmxAttributeGaugeTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JmxAttributeGaugeTest.java +@@ -53,7 +53,7 @@ public class JmxAttributeGaugeTest { + JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); + + assertThat(gauge.getValue()).isInstanceOf(Integer.class); +- assertThat((Integer) gauge.getValue()).isGreaterThan(0); ++ assertThat((Integer) gauge.getValue()).isPositive(); + } + + @Test +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JvmAttributeGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JvmAttributeGaugeSetTest.java +@@ -11,7 +11,7 @@ import org.junit.Test; + + @SuppressWarnings("unchecked") + public class JvmAttributeGaugeSetTest { +- private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); ++ private final RuntimeMXBean runtime = mock(); + private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); + + @Before +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/MemoryUsageGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/MemoryUsageGaugeSetTest.java +@@ -14,14 +14,14 @@ import org.junit.Test; + + @SuppressWarnings("rawtypes") + public class MemoryUsageGaugeSetTest { +- private final MemoryUsage heap = mock(MemoryUsage.class); +- private final MemoryUsage nonHeap = mock(MemoryUsage.class); +- private final MemoryUsage pool = mock(MemoryUsage.class); +- private final MemoryUsage weirdPool = mock(MemoryUsage.class); +- private final MemoryUsage weirdCollection = mock(MemoryUsage.class); +- private final MemoryMXBean mxBean = mock(MemoryMXBean.class); +- private final MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); +- private final MemoryPoolMXBean weirdMemoryPool = mock(MemoryPoolMXBean.class); ++ private final MemoryUsage heap = mock(); ++ private final MemoryUsage nonHeap = mock(); ++ private final MemoryUsage pool = mock(); ++ private final MemoryUsage weirdPool = mock(); ++ private final MemoryUsage weirdCollection = mock(); ++ private final MemoryMXBean mxBean = mock(); ++ private final MemoryPoolMXBean memoryPool = mock(); ++ private final MemoryPoolMXBean weirdMemoryPool = mock(); + + private final MemoryUsageGaugeSet gauges = + new MemoryUsageGaugeSet(mxBean, Arrays.asList(memoryPool, weirdMemoryPool)); +@@ -262,6 +262,6 @@ public class MemoryUsageGaugeSetTest { + + @Test + public void autoDetectsMemoryUsageBeanAndMemoryPools() { +- assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()).isNotEmpty(); ++ assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty(); + } + } +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDeadlockDetectorTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDeadlockDetectorTest.java +@@ -12,7 +12,7 @@ import java.util.Locale; + import org.junit.Test; + + public class ThreadDeadlockDetectorTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); ++ private final ThreadMXBean threads = mock(); + private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); + + @Test +@@ -24,7 +24,7 @@ public class ThreadDeadlockDetectorTest { + + @Test + public void returnsASetOfThreadsIfAnyAreDeadlocked() { +- final ThreadInfo thread1 = mock(ThreadInfo.class); ++ final ThreadInfo thread1 = mock(); + when(thread1.getThreadName()).thenReturn("thread1"); + when(thread1.getLockName()).thenReturn("lock2"); + when(thread1.getLockOwnerName()).thenReturn("thread2"); +@@ -35,7 +35,7 @@ public class ThreadDeadlockDetectorTest { + new StackTraceElement("Blah", "blee", "Blah.java", 100) + }); + +- final ThreadInfo thread2 = mock(ThreadInfo.class); ++ final ThreadInfo thread2 = mock(); + when(thread2.getThreadName()).thenReturn("thread2"); + when(thread2.getLockName()).thenReturn("lock1"); + when(thread2.getLockOwnerName()).thenReturn("thread1"); +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java +@@ -15,10 +15,10 @@ import org.junit.Test; + // TODO: 3/12/13 -- improve test coverage for ThreadDump + + public class ThreadDumpTest { +- private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); ++ private final ThreadMXBean threadMXBean = mock(); + private final ThreadDump threadDump = new ThreadDump(threadMXBean); + +- private final ThreadInfo runnable = mock(ThreadInfo.class); ++ private final ThreadInfo runnable = mock(); + + @Before + public void setUp() { +@@ -39,8 +39,8 @@ public class ThreadDumpTest { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + threadDump.dump(output); + +- assertThat(output.toString()) +- .isEqualTo( ++ assertThat(output) ++ .hasToString( + String.format( + "\"runnable\" id=100 state=RUNNABLE%n" + + " at Blah.blee(Blah.java:100)%n" +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadStatesGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadStatesGaugeSetTest.java +@@ -13,17 +13,17 @@ import org.junit.Before; + import org.junit.Test; + + public class ThreadStatesGaugeSetTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); +- private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ private final ThreadMXBean threads = mock(); ++ private final ThreadDeadlockDetector detector = mock(); + private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); + private final long[] ids = new long[] {1, 2, 3}; + +- private final ThreadInfo newThread = mock(ThreadInfo.class); +- private final ThreadInfo runnableThread = mock(ThreadInfo.class); +- private final ThreadInfo blockedThread = mock(ThreadInfo.class); +- private final ThreadInfo waitingThread = mock(ThreadInfo.class); +- private final ThreadInfo timedWaitingThread = mock(ThreadInfo.class); +- private final ThreadInfo terminatedThread = mock(ThreadInfo.class); ++ private final ThreadInfo newThread = mock(); ++ private final ThreadInfo runnableThread = mock(); ++ private final ThreadInfo blockedThread = mock(); ++ private final ThreadInfo waitingThread = mock(); ++ private final ThreadInfo timedWaitingThread = mock(); ++ private final ThreadInfo terminatedThread = mock(); + + private final Set deadlocks = new HashSet<>(); + +--- a/metrics-log4j2/src/test/java/com/codahale/metrics/log4j2/InstrumentedAppenderTest.java ++++ b/metrics-log4j2/src/test/java/com/codahale/metrics/log4j2/InstrumentedAppenderTest.java +@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final LogEvent event = mock(LogEvent.class); ++ private final LogEvent event = mock(); + + @Before + public void setUp() { +--- a/metrics-logback/src/test/java/com/codahale/metrics/logback/InstrumentedAppenderTest.java ++++ b/metrics-logback/src/test/java/com/codahale/metrics/logback/InstrumentedAppenderTest.java +@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); + + @Before + public void setUp() { +--- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java ++++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java +@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); + + @Before + public void setUp() { +--- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java ++++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java +@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); + + @Before + public void setUp() { +--- a/metrics-servlet/src/test/java/com/codahale/metrics/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-servlet/src/test/java/com/codahale/metrics/servlet/InstrumentedFilterContextListenerTest.java +@@ -10,7 +10,7 @@ import javax.servlet.ServletContextEvent; + import org.junit.Test; + + public class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ public class InstrumentedFilterContextListenerTest { + + @Test + public void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); + + listener.contextInitialized(event); +--- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java ++++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java +@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); + if (registryAttr instanceof HealthCheckRegistry) { + this.registry = (HealthCheckRegistry) registryAttr; +--- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java ++++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java +@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(METRICS_REGISTRY); + if (registryAttr instanceof MetricRegistry) { + this.registry = (MetricRegistry) registryAttr; +--- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java ++++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java +@@ -3,7 +3,6 @@ package com.codahale.metrics.servlets; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -94,9 +93,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } + + @Test +@@ -110,9 +108,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } + + @Test +@@ -168,15 +165,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getContent()) + .isEqualTo( + String.format( +- "{%n" +- + " \"fun\" : {%n" +- + " \"healthy\" : true,%n" +- + " \"message\" : \"foo bar 123\",%n" +- + " \"duration\" : 0,%n" +- + " \"timestamp\" : \"" +- + EXPECTED_TIMESTAMP +- + "\"" +- + "%n }%n}")); ++ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", ++ EXPECTED_TIMESTAMP)); + } + + private static HealthCheck.Result healthyResultWithMessage(String message) { +@@ -198,23 +188,23 @@ public class HealthCheckServletTest extends AbstractServletTest { + @Test + public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() + throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(healthCheckRegistry); +@@ -222,15 +212,15 @@ public class HealthCheckServletTest extends AbstractServletTest { + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test(expected = ServletException.class) + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); +@@ -242,8 +232,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + @Test + public void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(registry); +--- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletContextListenerTest.java ++++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletContextListenerTest.java +@@ -17,7 +17,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MetricsServletContextListenerTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final String allowedOrigin = "some.other.origin"; + +--- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java ++++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java +@@ -1,10 +1,8 @@ + package com.codahale.metrics.servlets; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -24,7 +22,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MetricsServletTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private ServletTester tester; + +@@ -128,22 +126,8 @@ public class MetricsServletTest extends AbstractServletTest { + assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); + assertThat(response.getContent()) + .isEqualTo( +- callbackParamVal +- + "({" +- + "\"version\":\"4.0.0\"," +- + "\"gauges\":{" +- + "\"g1\":{\"value\":100}" +- + "}," +- + "\"counters\":{" +- + "\"c\":{\"count\":1}" +- + "}," +- + "\"histograms\":{" +- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" +- + "}," +- + "\"meters\":{" +- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" +- + "}" +- + "})"); ++ "%s({\"version\":\"4.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", ++ callbackParamVal); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -223,41 +207,40 @@ public class MetricsServletTest extends AbstractServletTest { + @Test + public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() + throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); + } + + @Test + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn(metricRegistry); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); + + final MetricsServlet metricsServlet = new MetricsServlet(null); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); + } + + @Test(expected = ServletException.class) + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); + + final MetricsServlet metricsServlet = new MetricsServlet(null); diff --git a/integration-tests/metrics-v4.2.19-expected-warnings.txt b/integration-tests/metrics-v4.2.19-expected-warnings.txt new file mode 100644 index 0000000000..972ecad639 --- /dev/null +++ b/integration-tests/metrics-v4.2.19-expected-warnings.txt @@ -0,0 +1,8 @@ +metrics-core/src/main/java/com/codahale/metrics/CsvReporter.java:[382,36] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[429,18] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[434,20] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[447,21] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[189,47] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[203,47] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[29,68] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[30,68] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone diff --git a/integration-tests/metrics-v4.2.19-init.patch b/integration-tests/metrics-v4.2.19-init.patch new file mode 100644 index 0000000000..8ce1957ec7 --- /dev/null +++ b/integration-tests/metrics-v4.2.19-init.patch @@ -0,0 +1,219 @@ +diff --git a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java +index a248dd8..4e7f053 100644 +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java +@@ -188,6 +188,7 @@ public class MetricsServlet extends HttpServlet { + return mapper.writer(); + } + ++ @SuppressWarnings("IdentityConversion") + protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { + try { + return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); +diff --git a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java +index 0bd1297..7c69a08 100644 +--- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java ++++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java +@@ -189,6 +189,7 @@ public class MetricsServlet extends HttpServlet { + return mapper.writer(); + } + ++ @SuppressWarnings("IdentityConversion") + protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { + try { + return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); +diff --git a/pom.xml b/pom.xml +index 6192b52..f1eebbe 100644 +--- a/pom.xml ++++ b/pom.xml +@@ -66,7 +66,7 @@ + 4.13.1 + 1.3 + 3.11.0 +- 2.19.1 ++ -Xplugin:ErrorProne ${error-prone.flags} -Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\$StringIsNullOrEmpty)).*) + 9+181-r4173-1 + + dropwizard_metrics +@@ -137,60 +137,110 @@ + + + +- jdk8 +- +- 1.8 +- ++ error-prone-compile + + +- +- org.apache.maven.plugins +- maven-compiler-plugin ++ ++ org.apache.maven.plugins ++ maven-compiler-plugin ++ ${maven-compiler-plugin.version} ++ ++ ++ error-prone-compile ++ compile ++ ++ compile ++ + +- +- -J-Xbootclasspath/p:${settings.localRepository}/com/google/errorprone/javac/${errorprone.javac.version}/javac-${errorprone.javac.version}.jar +- ++ false ++ 1.8 ++ 1.8 ++ ++ -Xpkginfo:always ++ -XDcompilePolicy=simple ++ ${error-prone-support.flags} ++ ++ ++ ++ com.google.errorprone ++ error_prone_core ++ ${error-prone.version} ++ ++ ++ tech.picnic.error-prone-support ++ error-prone-contrib ++ ${error-prone-support.version} ++ ++ ++ tech.picnic.error-prone-support ++ refaster-runner ++ ${error-prone-support.version} ++ ++ + +- ++ ++ ++ + +- ++ + + +- jdk17 +- +- [17,) +- ++ error-prone-test-compile + +- +- +- org.apache.maven.plugins +- maven-compiler-plugin +- +- +- -Xlint:all +- -XDcompilePolicy=simple +- -Xplugin:ErrorProne -XepExcludedPaths:.*/target/generated-sources/.* +- -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED +- -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED +- -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED +- -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED +- -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED +- -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED +- -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED +- -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED +- -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED +- -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED +- +- +- +- com.google.errorprone +- error_prone_core +- ${errorprone.version} +- +- +- +- +- ++ ++ ++ org.apache.maven.plugins ++ maven-compiler-plugin ++ ${maven-compiler-plugin.version} ++ ++ ++ ++ default-testCompile ++ test-compile ++ ++ testCompile ++ ++ ++ true ++ ++ ++ ++ error-prone-test-compile ++ test-compile ++ ++ testCompile ++ ++ ++ false ++ 1.8 ++ 1.8 ++ ++ -Xpkginfo:always ++ -XDcompilePolicy=simple ++ ${error-prone-support.flags} ++ ++ ++ ++ com.google.errorprone ++ error_prone_core ++ ${error-prone.version} ++ ++ ++ tech.picnic.error-prone-support ++ error-prone-contrib ++ ${error-prone-support.version} ++ ++ ++ tech.picnic.error-prone-support ++ refaster-runner ++ ${error-prone-support.version} ++ ++ ++ ++ ++ ++ ++ + + + +@@ -315,23 +365,13 @@ + org.apache.maven.plugins + maven-compiler-plugin + +- 1.8 +- 1.8 +- true ++ false + true + true + + -Xlint:all + -XDcompilePolicy=simple +- -Xplugin:ErrorProne -XepExcludedPaths:.*/target/generated-sources/.* + +- +- +- com.google.errorprone +- error_prone_core +- ${errorprone.version} +- +- + + + diff --git a/integration-tests/metrics-v4.2.19.sh b/integration-tests/metrics-v4.2.19.sh new file mode 100755 index 0000000000..425e075b2a --- /dev/null +++ b/integration-tests/metrics-v4.2.19.sh @@ -0,0 +1,180 @@ +#!/usr/bin/env bash + +set -e -u -o pipefail + +integration_test_root="$(readlink -f "$(dirname "${0}")")" +error_prone_support_root="${integration_test_root}/.." +repos_root="${integration_test_root}/.repos" + +test_name="$(basename "${0}" .sh)" +project=metrics +repository=https://github.com/dropwizard/metrics.git +revision=v4.2.19 + +if [ "${#}" -gt 2 ] || ([ "${#}" = 2 ] && [ "${1:---sync}" != '--sync' ]); then + echo "Usage: ${0} [--sync] []" + exit 1 +fi +do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" +report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" + +if [ -n "${report_directory}" ]; then + mkdir -p "${report_directory}" +else + report_directory="$(mktemp -d)" + trap 'rm -rf -- "${report_directory}"' INT TERM HUP EXIT +fi + +# XXX: Configure Renovate to manage the AssertJ version declared here. +shared_build_flags=" + -Perror-prone-compile,error-prone-test-compile + -Dassertj.version=3.24.2 + -Derror-prone.version=$( + mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=version.error-prone -q -DforceStdout + ) + -Derror-prone-support.version=$( + mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=project.version -q -DforceStdout + ) + -DadditionalSourceDirectories=\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java + " + +# XXX: Configure Renovate to manage the fmt-maven-plugin version declared here. +# XXX: Once GitHub actions uses Maven 3.9.2+, we can inline this variable with +# version reference `${fmt.version}`, and `-Dfmt.version=2.21.1` added to +# `shared_build_flags`. +format_goal='com.spotify.fmt:fmt-maven-plugin:2.21.1:format' + +error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' + +error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( + find "${error_prone_support_root}" -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" -print0 \ + | xargs -0 grep -hoP '[^.]+$' \ + | paste -s -d ',' +)" + +error_prone_validation_flags="${error_prone_shared_flags} -XepDisableAllChecks $( + find "${error_prone_support_root}" -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" -print0 \ + | xargs -0 grep -hoP '[^.]+$' \ + | sed -r 's,(.*),-Xep:\1:WARN,' \ + | paste -s -d ' ' +)" + +echo "Shared build flags: ${shared_build_flags}" +echo "Error Prone patch flags: ${error_prone_patch_flags}" +echo "Error Prone validation flags: ${error_prone_validation_flags}" + +mkdir -p "${repos_root}" + +# Make sure that the targeted tag of the project's Git repository is checked +# out. +project_root="${repos_root}/${project}" +if [ ! -d "${project_root}" ]; then + # The repository has not yet been cloned; create a shallow clone. + git clone --branch "${revision}" --depth 1 "${repository}" "${project_root}" +else + # The repository does already appear to exist. Try to check out the requested + # tag if possible, and fetch it otherwise. + # + # Under certain circumstances this does not cause the relevant tag to be + # created, so if necessary we manually create it. + git -C "${project_root}" checkout --force "${revision}" 2>/dev/null \ + || ( + git -C "${project_root}" fetch --depth 1 "${repository}" "${revision}" \ + && git -C "${project_root}" checkout --force FETCH_HEAD \ + && (git -C "${project_root}" tag "${revision}" || true) + ) +fi + +pushd "${project_root}" + +# Make sure that Git is sufficiently configured to enable committing to the +# project's Git repository. +git config user.email || git config user.email "integration-test@example.com" +git config user.name || git config user.name "Integration Test" + +# Prepare the code for analysis by (a) applying the minimal set of changes +# required to run Error Prone with Error Prone Support and (b) formatting the +# code using the same method by which it will be formatted after each +# compilation round. The initial formatting operation ensures that subsequent +# modifications can be rendered in a clean manner. +git clean -fdx +git apply < "${integration_test_root}/${test_name}-init.patch" +git commit -m 'dependency: Introduce Error Prone Support' . +mvn ${shared_build_flags} "${format_goal}" +git commit -m 'minor: Reformat using Google Java Format' . +diff_base="$(git rev-parse HEAD)" + +# Apply Error Prone Support-suggested changes until a fixed point is reached. +function apply_patch() { + local extra_build_args="${1}" + + mvn ${shared_build_flags} ${extra_build_args} \ + package "${format_goal}" \ + -Derror-prone.flags="${error_prone_patch_flags}" \ + -DskipTests + + if ! git diff --exit-code; then + git commit -m 'minor: Apply patches' . + + # Changes were applied, so another compilation round may apply yet more + # changes. For performance reasons we perform incremental compilation, + # enabled using a misleading flag. (See + # https://issues.apache.org/jira/browse/MCOMPILER-209 for details.) + apply_patch '-Dmaven.compiler.useIncrementalCompilation=false' + elif [ "${extra_build_args}" != 'clean' ]; then + # No changes were applied. We'll attempt one more round in which all files + # are recompiled, because there are cases in which violations are missed + # during incremental compilation. + apply_patch 'clean' + fi +} +apply_patch '' + +# Run one more full build and log the output. +# +# By also running the tests, we validate that the (majority of) applied changes +# are behavior preserving. Some tests are skipped: +# - The `metadataFilesGenerationAllFiles` test is skipped because it makes line +# number assertions that will fail when the code is formatted or patched. +# - The `allCheckSectionJavaDocs` test is skipped because is validates that +# Javadoc has certain closing tags that are removed by Google Java Format. +validation_build_log="${report_directory}/${test_name}-validation-build-log.txt" +mvn ${shared_build_flags} \ + clean package \ + -Derror-prone.flags="${error_prone_validation_flags}" \ + | tee "${validation_build_log}" \ + || failure=1 + +# Collect the applied changes. +expected_changes="${integration_test_root}/${test_name}-expected-changes.patch" +actual_changes="${report_directory}/${test_name}-changes.patch" +(git diff "${diff_base}"..HEAD | grep -vP '^(diff|index)' || true) > "${actual_changes}" + +# Collect the warnings reported by Error Prone Support checks. +expected_warnings="${integration_test_root}/${test_name}-expected-warnings.txt" +actual_warnings="${report_directory}/${test_name}-validation-build-warnings.txt" +(grep -oP "(?<=^\\Q[WARNING] ${PWD}/\\E).*" "${validation_build_log}" | grep -P '\] \[' || true) | LC_ALL=C sort > "${actual_warnings}" + +# Persist or validate the applied changes and reported warnings. +if [ -n "${do_sync}" ]; then + echo 'Saving changes...' + cp "${actual_changes}" "${expected_changes}" + cp "${actual_warnings}" "${expected_warnings}" +else + echo 'Inspecting changes...' + # XXX: This "diff of diffs" also contains vacuous sections, introduced due to + # line offset differences. Try to omit those from the final output. + if ! diff -u "${expected_changes}" "${actual_changes}"; then + echo 'There are unexpected changes.' + failure=1 + fi + echo 'Inspecting emitted warnings...' + if ! diff -u "${expected_warnings}" "${actual_warnings}"; then + echo 'Diagnostics output changed.' + failure=1 + fi +fi + +if [ -n "${failure:-}" ]; then + exit 1 +fi From 11d02d468e985750d6bef37976e421d75bd315e7 Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Thu, 23 Nov 2023 16:33:05 +0100 Subject: [PATCH 02/59] Integration test script --- integration-tests/integration-test.sh | 186 ++++++++++++++++++++++++++ integration-tests/metrics-v4.2.19.sh | 165 +---------------------- 2 files changed, 187 insertions(+), 164 deletions(-) create mode 100755 integration-tests/integration-test.sh diff --git a/integration-tests/integration-test.sh b/integration-tests/integration-test.sh new file mode 100755 index 0000000000..5e0e75f2eb --- /dev/null +++ b/integration-tests/integration-test.sh @@ -0,0 +1,186 @@ +#!/usr/bin/env bash + +set -e -u -o pipefail + +integration_test_root="$(readlink -f "$(dirname "${0}")")" +error_prone_support_root="${integration_test_root}/.." +repos_root="${integration_test_root}/.repos" + +if [ "${#}" -ne 10 ]; then + >&2 echo "Usage $(basename "${0}") " + + exit 1 +fi + +test_name="${1}" +project="${2}" +repository="${3}" +revision="${4}" +build_flags="${5}" +patch_flags="${6}" +validation_ep_flags="${7}" +validation_mvn_flags="${8}" +do_sync="${9}" +report_directory="${10}" + +if [ -n "${report_directory}" ]; then + mkdir -p "${report_directory}" +else + report_directory="$(mktemp -d)" + trap 'rm -rf -- "${report_directory}"' INT TERM HUP EXIT +fi + +# XXX: Configure Renovate to manage the AssertJ version declared here. +shared_build_flags=" + -Perror-prone-compile,error-prone-test-compile + -Derror-prone.version=$( + mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=version.error-prone -q -DforceStdout + ) + -Derror-prone-support.version=$( + mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=project.version -q -DforceStdout + ) + -DadditionalSourceDirectories=\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java + ${build_flags} + " + +# XXX: Configure Renovate to manage the fmt-maven-plugin version declared here. +# XXX: Once GitHub actions uses Maven 3.9.2+, we can inline this variable with +# version reference `${fmt.version}`, and `-Dfmt.version=2.21.1` added to +# `shared_build_flags`. +format_goal='com.spotify.fmt:fmt-maven-plugin:2.21.1:format' + +error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' + +error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( + find "${error_prone_support_root}" -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" -print0 \ + | xargs -0 grep -hoP '[^.]+$' \ + | paste -s -d ',' +) ${patch_flags}" + +error_prone_validation_flags="${error_prone_shared_flags} -XepDisableAllChecks $( + find "${error_prone_support_root}" -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" -print0 \ + | xargs -0 grep -hoP '[^.]+$' \ + | sed -r 's,(.*),-Xep:\1:WARN,' \ + | paste -s -d ' ' +) ${validation_ep_flags}" + +echo "Shared build flags: ${shared_build_flags}" +echo "Error Prone patch flags: ${error_prone_patch_flags}" +echo "Error Prone validation flags: ${error_prone_validation_flags}" + +mkdir -p "${repos_root}" + +# Make sure that the targeted tag of the project's Git repository is checked +# out. +project_root="${repos_root}/${project}" +if [ ! -d "${project_root}" ]; then + # The repository has not yet been cloned; create a shallow clone. + git clone --branch "${revision}" --depth 1 "${repository}" "${project_root}" +else + # The repository does already appear to exist. Try to check out the requested + # tag if possible, and fetch it otherwise. + # + # Under certain circumstances this does not cause the relevant tag to be + # created, so if necessary we manually create it. + git -C "${project_root}" checkout --force "${revision}" 2>/dev/null \ + || ( + git -C "${project_root}" fetch --depth 1 "${repository}" "${revision}" \ + && git -C "${project_root}" checkout --force FETCH_HEAD \ + && (git -C "${project_root}" tag "${revision}" || true) + ) +fi + +pushd "${project_root}" + +# Make sure that Git is sufficiently configured to enable committing to the +# project's Git repository. +git config user.email || git config user.email "integration-test@example.com" +git config user.name || git config user.name "Integration Test" + +# Prepare the code for analysis by (a) applying the minimal set of changes +# required to run Error Prone with Error Prone Support and (b) formatting the +# code using the same method by which it will be formatted after each +# compilation round. The initial formatting operation ensures that subsequent +# modifications can be rendered in a clean manner. +git clean -fdx +git apply < "${integration_test_root}/${test_name}-init.patch" +git commit -m 'dependency: Introduce Error Prone Support' . +mvn ${shared_build_flags} "${format_goal}" +git commit -m 'minor: Reformat using Google Java Format' . +diff_base="$(git rev-parse HEAD)" + +# Apply Error Prone Support-suggested changes until a fixed point is reached. +function apply_patch() { + local extra_build_args="${1}" + + mvn ${shared_build_flags} ${extra_build_args} \ + package "${format_goal}" \ + -Derror-prone.flags="${error_prone_patch_flags}" \ + -DskipTests + + if ! git diff --exit-code; then + git commit -m 'minor: Apply patches' . + + # Changes were applied, so another compilation round may apply yet more + # changes. For performance reasons we perform incremental compilation, + # enabled using a misleading flag. (See + # https://issues.apache.org/jira/browse/MCOMPILER-209 for details.) + apply_patch '-Dmaven.compiler.useIncrementalCompilation=false' + elif [ "${extra_build_args}" != 'clean' ]; then + # No changes were applied. We'll attempt one more round in which all files + # are recompiled, because there are cases in which violations are missed + # during incremental compilation. + apply_patch 'clean' + fi +} +apply_patch '' + +# Run one more full build and log the output. +# +# By also running the tests, we validate that the (majority of) applied changes +# are behavior preserving. Some tests are skipped: +# - The `metadataFilesGenerationAllFiles` test is skipped because it makes line +# number assertions that will fail when the code is formatted or patched. +# - The `allCheckSectionJavaDocs` test is skipped because is validates that +# Javadoc has certain closing tags that are removed by Google Java Format. +validation_build_log="${report_directory}/${test_name}-validation-build-log.txt" +mvn ${shared_build_flags} \ + clean package \ + -Derror-prone.flags="${error_prone_validation_flags}" \ + ${validation_mvn_flags} \ + | tee "${validation_build_log}" \ + || failure=1 + +# Collect the applied changes. +expected_changes="${integration_test_root}/${test_name}-expected-changes.patch" +actual_changes="${report_directory}/${test_name}-changes.patch" +(git diff "${diff_base}"..HEAD | grep -vP '^(diff|index)' || true) > "${actual_changes}" + +# Collect the warnings reported by Error Prone Support checks. +expected_warnings="${integration_test_root}/${test_name}-expected-warnings.txt" +actual_warnings="${report_directory}/${test_name}-validation-build-warnings.txt" +(grep -oP "(?<=^\\Q[WARNING] ${PWD}/\\E).*" "${validation_build_log}" | grep -P '\] \[' || true) | LC_ALL=C sort > "${actual_warnings}" + +# Persist or validate the applied changes and reported warnings. +if [ -n "${do_sync}" ]; then + echo 'Saving changes...' + cp "${actual_changes}" "${expected_changes}" + cp "${actual_warnings}" "${expected_warnings}" +else + echo 'Inspecting changes...' + # XXX: This "diff of diffs" also contains vacuous sections, introduced due to + # line offset differences. Try to omit those from the final output. + if ! diff -u "${expected_changes}" "${actual_changes}"; then + echo 'There are unexpected changes.' + failure=1 + fi + echo 'Inspecting emitted warnings...' + if ! diff -u "${expected_warnings}" "${actual_warnings}"; then + echo 'Diagnostics output changed.' + failure=1 + fi +fi + +if [ -n "${failure:-}" ]; then + exit 1 +fi diff --git a/integration-tests/metrics-v4.2.19.sh b/integration-tests/metrics-v4.2.19.sh index 425e075b2a..eb660875ef 100755 --- a/integration-tests/metrics-v4.2.19.sh +++ b/integration-tests/metrics-v4.2.19.sh @@ -2,10 +2,6 @@ set -e -u -o pipefail -integration_test_root="$(readlink -f "$(dirname "${0}")")" -error_prone_support_root="${integration_test_root}/.." -repos_root="${integration_test_root}/.repos" - test_name="$(basename "${0}" .sh)" project=metrics repository=https://github.com/dropwizard/metrics.git @@ -18,163 +14,4 @@ fi do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" -if [ -n "${report_directory}" ]; then - mkdir -p "${report_directory}" -else - report_directory="$(mktemp -d)" - trap 'rm -rf -- "${report_directory}"' INT TERM HUP EXIT -fi - -# XXX: Configure Renovate to manage the AssertJ version declared here. -shared_build_flags=" - -Perror-prone-compile,error-prone-test-compile - -Dassertj.version=3.24.2 - -Derror-prone.version=$( - mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=version.error-prone -q -DforceStdout - ) - -Derror-prone-support.version=$( - mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=project.version -q -DforceStdout - ) - -DadditionalSourceDirectories=\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java - " - -# XXX: Configure Renovate to manage the fmt-maven-plugin version declared here. -# XXX: Once GitHub actions uses Maven 3.9.2+, we can inline this variable with -# version reference `${fmt.version}`, and `-Dfmt.version=2.21.1` added to -# `shared_build_flags`. -format_goal='com.spotify.fmt:fmt-maven-plugin:2.21.1:format' - -error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' - -error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( - find "${error_prone_support_root}" -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" -print0 \ - | xargs -0 grep -hoP '[^.]+$' \ - | paste -s -d ',' -)" - -error_prone_validation_flags="${error_prone_shared_flags} -XepDisableAllChecks $( - find "${error_prone_support_root}" -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" -print0 \ - | xargs -0 grep -hoP '[^.]+$' \ - | sed -r 's,(.*),-Xep:\1:WARN,' \ - | paste -s -d ' ' -)" - -echo "Shared build flags: ${shared_build_flags}" -echo "Error Prone patch flags: ${error_prone_patch_flags}" -echo "Error Prone validation flags: ${error_prone_validation_flags}" - -mkdir -p "${repos_root}" - -# Make sure that the targeted tag of the project's Git repository is checked -# out. -project_root="${repos_root}/${project}" -if [ ! -d "${project_root}" ]; then - # The repository has not yet been cloned; create a shallow clone. - git clone --branch "${revision}" --depth 1 "${repository}" "${project_root}" -else - # The repository does already appear to exist. Try to check out the requested - # tag if possible, and fetch it otherwise. - # - # Under certain circumstances this does not cause the relevant tag to be - # created, so if necessary we manually create it. - git -C "${project_root}" checkout --force "${revision}" 2>/dev/null \ - || ( - git -C "${project_root}" fetch --depth 1 "${repository}" "${revision}" \ - && git -C "${project_root}" checkout --force FETCH_HEAD \ - && (git -C "${project_root}" tag "${revision}" || true) - ) -fi - -pushd "${project_root}" - -# Make sure that Git is sufficiently configured to enable committing to the -# project's Git repository. -git config user.email || git config user.email "integration-test@example.com" -git config user.name || git config user.name "Integration Test" - -# Prepare the code for analysis by (a) applying the minimal set of changes -# required to run Error Prone with Error Prone Support and (b) formatting the -# code using the same method by which it will be formatted after each -# compilation round. The initial formatting operation ensures that subsequent -# modifications can be rendered in a clean manner. -git clean -fdx -git apply < "${integration_test_root}/${test_name}-init.patch" -git commit -m 'dependency: Introduce Error Prone Support' . -mvn ${shared_build_flags} "${format_goal}" -git commit -m 'minor: Reformat using Google Java Format' . -diff_base="$(git rev-parse HEAD)" - -# Apply Error Prone Support-suggested changes until a fixed point is reached. -function apply_patch() { - local extra_build_args="${1}" - - mvn ${shared_build_flags} ${extra_build_args} \ - package "${format_goal}" \ - -Derror-prone.flags="${error_prone_patch_flags}" \ - -DskipTests - - if ! git diff --exit-code; then - git commit -m 'minor: Apply patches' . - - # Changes were applied, so another compilation round may apply yet more - # changes. For performance reasons we perform incremental compilation, - # enabled using a misleading flag. (See - # https://issues.apache.org/jira/browse/MCOMPILER-209 for details.) - apply_patch '-Dmaven.compiler.useIncrementalCompilation=false' - elif [ "${extra_build_args}" != 'clean' ]; then - # No changes were applied. We'll attempt one more round in which all files - # are recompiled, because there are cases in which violations are missed - # during incremental compilation. - apply_patch 'clean' - fi -} -apply_patch '' - -# Run one more full build and log the output. -# -# By also running the tests, we validate that the (majority of) applied changes -# are behavior preserving. Some tests are skipped: -# - The `metadataFilesGenerationAllFiles` test is skipped because it makes line -# number assertions that will fail when the code is formatted or patched. -# - The `allCheckSectionJavaDocs` test is skipped because is validates that -# Javadoc has certain closing tags that are removed by Google Java Format. -validation_build_log="${report_directory}/${test_name}-validation-build-log.txt" -mvn ${shared_build_flags} \ - clean package \ - -Derror-prone.flags="${error_prone_validation_flags}" \ - | tee "${validation_build_log}" \ - || failure=1 - -# Collect the applied changes. -expected_changes="${integration_test_root}/${test_name}-expected-changes.patch" -actual_changes="${report_directory}/${test_name}-changes.patch" -(git diff "${diff_base}"..HEAD | grep -vP '^(diff|index)' || true) > "${actual_changes}" - -# Collect the warnings reported by Error Prone Support checks. -expected_warnings="${integration_test_root}/${test_name}-expected-warnings.txt" -actual_warnings="${report_directory}/${test_name}-validation-build-warnings.txt" -(grep -oP "(?<=^\\Q[WARNING] ${PWD}/\\E).*" "${validation_build_log}" | grep -P '\] \[' || true) | LC_ALL=C sort > "${actual_warnings}" - -# Persist or validate the applied changes and reported warnings. -if [ -n "${do_sync}" ]; then - echo 'Saving changes...' - cp "${actual_changes}" "${expected_changes}" - cp "${actual_warnings}" "${expected_warnings}" -else - echo 'Inspecting changes...' - # XXX: This "diff of diffs" also contains vacuous sections, introduced due to - # line offset differences. Try to omit those from the final output. - if ! diff -u "${expected_changes}" "${actual_changes}"; then - echo 'There are unexpected changes.' - failure=1 - fi - echo 'Inspecting emitted warnings...' - if ! diff -u "${expected_warnings}" "${actual_warnings}"; then - echo 'Diagnostics output changed.' - failure=1 - fi -fi - -if [ -n "${failure:-}" ]; then - exit 1 -fi +./integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "" "" "" "$do_sync" "$report_directory" From d18dd8af5226c8b14a510a8c59de8e684b15290f Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Thu, 30 Nov 2023 10:23:09 +0100 Subject: [PATCH 03/59] Use integration-test.sh in checkstyle --- integration-tests/checkstyle.sh | 191 +------------------------- integration-tests/integration-test.sh | 56 +++++--- 2 files changed, 43 insertions(+), 204 deletions(-) diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index 0b1f5a5e4c..9ffdf8519c 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -2,10 +2,6 @@ set -e -u -o pipefail -integration_test_root="$(cd "$(dirname -- "${0}")" && pwd)" -error_prone_support_root="${integration_test_root}/.." -repos_root="${integration_test_root}/.repos" - test_name="$(basename "${0}" .sh)" project=checkstyle repository=https://github.com/checkstyle/checkstyle.git @@ -18,189 +14,8 @@ fi do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" -if [ -n "${report_directory}" ]; then - mkdir -p "${report_directory}" -else - report_directory="$(mktemp -d)" - trap 'rm -rf -- "${report_directory}"' INT TERM HUP EXIT -fi - -case "$(uname -s)" in - Linux*) - grep_command=grep - sed_command=sed - ;; - Darwin*) - grep_command=ggrep - sed_command=gsed - ;; - *) - echo "Unsupported distribution $(uname -s) for this script." - exit 1 - ;; -esac - # XXX: Configure Renovate to manage the AssertJ version declared here. -shared_build_flags=" - -Perror-prone-compile,error-prone-test-compile - -Dassertj.version=3.24.2 - -Derror-prone.version=$( - mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=version.error-prone -q -DforceStdout - ) - -Derror-prone-support.version=$( - mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=project.version -q -DforceStdout - ) - -DadditionalSourceDirectories=\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java - " - -# XXX: Configure Renovate to manage the fmt-maven-plugin version declared here. -# XXX: Once GitHub actions uses Maven 3.9.2+, we can inline this variable with -# version reference `${fmt.version}`, and `-Dfmt.version=2.21.1` added to -# `shared_build_flags`. -format_goal='com.spotify.fmt:fmt-maven-plugin:2.21.1:format' - -error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' - -error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( - find "${error_prone_support_root}" \ - -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" \ - -not -path "*/error-prone-experimental/*" \ - -not -path "*/error-prone-guidelines/*" \ - -print0 \ - | xargs -0 "${grep_command}" -hoP '[^.]+$' \ - | paste -s -d ',' - -)" - -error_prone_validation_flags="${error_prone_shared_flags} -XepDisableAllChecks $( - find "${error_prone_support_root}" \ - -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" \ - -not -path "*/error-prone-experimental/*" \ - -not -path "*/error-prone-guidelines/*" \ - -print0 \ - | xargs -0 "${grep_command}" -hoP '[^.]+$' \ - | "${sed_command}" -r 's,(.*),-Xep:\1:WARN,' \ - | paste -s -d ' ' - -)" - -echo "Shared build flags: ${shared_build_flags}" -echo "Error Prone patch flags: ${error_prone_patch_flags}" -echo "Error Prone validation flags: ${error_prone_validation_flags}" - -mkdir -p "${repos_root}" - -# Make sure that the targeted tag of the project's Git repository is checked -# out. -project_root="${repos_root}/${project}" -if [ ! -d "${project_root}" ]; then - # The repository has not yet been cloned; create a shallow clone. - git clone --branch "${revision}" --depth 1 "${repository}" "${project_root}" -else - # The repository does already appear to exist. Try to check out the requested - # tag if possible, and fetch it otherwise. - # - # Under certain circumstances this does not cause the relevant tag to be - # created, so if necessary we manually create it. - git -C "${project_root}" checkout --force "${revision}" 2>/dev/null \ - || ( - git -C "${project_root}" fetch --depth 1 "${repository}" "${revision}" \ - && git -C "${project_root}" checkout --force FETCH_HEAD \ - && (git -C "${project_root}" tag "${revision}" || true) - ) -fi - -pushd "${project_root}" +build_flags="-Dassertj.version=3.24.2" +validation_mvn_flags="-Dtest=!MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles,!XdocsJavaDocsTest#allCheckSectionJavaDocs" -# Make sure that Git is sufficiently configured to enable committing to the -# project's Git repository. -git config user.email || git config user.email "integration-test@example.com" -git config user.name || git config user.name "Integration Test" - -# Prepare the code for analysis by (a) applying the minimal set of changes -# required to run Error Prone with Error Prone Support and (b) formatting the -# code using the same method by which it will be formatted after each -# compilation round. The initial formatting operation ensures that subsequent -# modifications can be rendered in a clean manner. -git clean -fdx -git apply < "${integration_test_root}/${test_name}-init.patch" -git commit -m 'dependency: Introduce Error Prone Support' . -mvn ${shared_build_flags} "${format_goal}" -git commit -m 'minor: Reformat using Google Java Format' . -diff_base="$(git rev-parse HEAD)" - -# Apply Error Prone Support-suggested changes until a fixed point is reached. -function apply_patch() { - local extra_build_args="${1}" - - mvn ${shared_build_flags} ${extra_build_args} \ - package "${format_goal}" \ - -Derror-prone.configuration-args="${error_prone_patch_flags}" \ - -DskipTests - - if ! git diff --exit-code; then - git commit -m 'minor: Apply patches' . - - # Changes were applied, so another compilation round may apply yet more - # changes. For performance reasons we perform incremental compilation, - # enabled using a misleading flag. (See - # https://issues.apache.org/jira/browse/MCOMPILER-209 for details.) - apply_patch '-Dmaven.compiler.useIncrementalCompilation=false' - elif [ "${extra_build_args}" != 'clean' ]; then - # No changes were applied. We'll attempt one more round in which all files - # are recompiled, because there are cases in which violations are missed - # during incremental compilation. - apply_patch 'clean' - fi -} -apply_patch '' - -# Run one more full build and log the output. -# -# By also running the tests, we validate that the (majority of) applied changes -# are behavior preserving. Some tests are skipped: -# - The `metadataFilesGenerationAllFiles` test is skipped because it makes line -# number assertions that will fail when the code is formatted or patched. -# - The `allCheckSectionJavaDocs` test is skipped because is validates that -# Javadoc has certain closing tags that are removed by Google Java Format. -validation_build_log="${report_directory}/${test_name}-validation-build-log.txt" -mvn ${shared_build_flags} \ - clean package \ - -Derror-prone.configuration-args="${error_prone_validation_flags}" \ - -Dtest=' - !MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles, - !XdocsJavaDocsTest#allCheckSectionJavaDocs' \ - | tee "${validation_build_log}" \ - || failure=1 - -# Collect the applied changes. -expected_changes="${integration_test_root}/${test_name}-expected-changes.patch" -actual_changes="${report_directory}/${test_name}-changes.patch" -(git diff "${diff_base}"..HEAD | "${grep_command}" -vP '^(diff|index)' || true) > "${actual_changes}" - -# Collect the warnings reported by Error Prone Support checks. -expected_warnings="${integration_test_root}/${test_name}-expected-warnings.txt" -actual_warnings="${report_directory}/${test_name}-validation-build-warnings.txt" -("${grep_command}" -oP "(?<=^\\Q[WARNING] ${PWD}/\\E).*" "${validation_build_log}" | "${grep_command}" -P '\] \[' || true) | LC_ALL=C sort > "${actual_warnings}" - -# Persist or validate the applied changes and reported warnings. -if [ -n "${do_sync}" ]; then - echo 'Saving changes...' - cp "${actual_changes}" "${expected_changes}" - cp "${actual_warnings}" "${expected_warnings}" -else - echo 'Inspecting changes...' - # XXX: This "diff of diffs" also contains vacuous sections, introduced due to - # line offset differences. Try to omit those from the final output. - if ! diff -u "${expected_changes}" "${actual_changes}"; then - echo 'There are unexpected changes. Inspect the preceding output for details.' - failure=1 - fi - echo 'Inspecting emitted warnings...' - if ! diff -u "${expected_warnings}" "${actual_warnings}"; then - echo 'Diagnostics output changed. Inspect the preceding output for details.' - failure=1 - fi -fi - -if [ -n "${failure:-}" ]; then - exit 1 -fi +./integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" diff --git a/integration-tests/integration-test.sh b/integration-tests/integration-test.sh index 5e0e75f2eb..952d97273a 100755 --- a/integration-tests/integration-test.sh +++ b/integration-tests/integration-test.sh @@ -1,14 +1,15 @@ #!/usr/bin/env bash +# This script is not meant to be invoked manually, instead it should be invoked +# through one of the integration test scripts such as the metrics or checkstyle one. set -e -u -o pipefail -integration_test_root="$(readlink -f "$(dirname "${0}")")" +integration_test_root="$(cd "$(dirname -- "${0}")" && pwd)" error_prone_support_root="${integration_test_root}/.." repos_root="${integration_test_root}/.repos" if [ "${#}" -ne 10 ]; then - >&2 echo "Usage $(basename "${0}") " - + >&2 echo "Usage $(basename "${0}") [TestName] [Project] [Repository] [Revision] [BuildFlags] [PatchFlags] [ValidationEpFlags] [ValidationMvnFlags] [DoSync] [ReportDirectory]" exit 1 fi @@ -30,6 +31,21 @@ else trap 'rm -rf -- "${report_directory}"' INT TERM HUP EXIT fi +case "$(uname -s)" in + Linux*) + grep_command=grep + sed_command=sed + ;; + Darwin*) + grep_command=ggrep + sed_command=gsed + ;; + *) + echo "Unsupported distribution $(uname -s) for this script." + exit 1 + ;; +esac + # XXX: Configure Renovate to manage the AssertJ version declared here. shared_build_flags=" -Perror-prone-compile,error-prone-test-compile @@ -52,16 +68,24 @@ format_goal='com.spotify.fmt:fmt-maven-plugin:2.21.1:format' error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( - find "${error_prone_support_root}" -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" -print0 \ - | xargs -0 grep -hoP '[^.]+$' \ - | paste -s -d ',' + find "${error_prone_support_root}" \ + -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" \ + -not -path "*/error-prone-experimental/*" \ + -not -path "*/error-prone-guidelines/*" \ + -print0 \ + | xargs -0 "${grep_command}" -hoP '[^.]+$' \ + | paste -s -d ',' - ) ${patch_flags}" error_prone_validation_flags="${error_prone_shared_flags} -XepDisableAllChecks $( - find "${error_prone_support_root}" -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" -print0 \ - | xargs -0 grep -hoP '[^.]+$' \ - | sed -r 's,(.*),-Xep:\1:WARN,' \ - | paste -s -d ' ' + find "${error_prone_support_root}" \ + -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" \ + -not -path "*/error-prone-experimental/*" \ + -not -path "*/error-prone-guidelines/*" \ + -print0 \ + | xargs -0 "${grep_command}" -hoP '[^.]+$' \ + | "${sed_command}" -r 's,(.*),-Xep:\1:WARN,' \ + | paste -s -d ' ' - ) ${validation_ep_flags}" echo "Shared build flags: ${shared_build_flags}" @@ -115,7 +139,7 @@ function apply_patch() { mvn ${shared_build_flags} ${extra_build_args} \ package "${format_goal}" \ - -Derror-prone.flags="${error_prone_patch_flags}" \ + -Derror-prone.configuration-args="${error_prone_patch_flags}" \ -DskipTests if ! git diff --exit-code; then @@ -146,7 +170,7 @@ apply_patch '' validation_build_log="${report_directory}/${test_name}-validation-build-log.txt" mvn ${shared_build_flags} \ clean package \ - -Derror-prone.flags="${error_prone_validation_flags}" \ + -Derror-prone.configuration-args="${error_prone_validation_flags}" \ ${validation_mvn_flags} \ | tee "${validation_build_log}" \ || failure=1 @@ -154,12 +178,12 @@ mvn ${shared_build_flags} \ # Collect the applied changes. expected_changes="${integration_test_root}/${test_name}-expected-changes.patch" actual_changes="${report_directory}/${test_name}-changes.patch" -(git diff "${diff_base}"..HEAD | grep -vP '^(diff|index)' || true) > "${actual_changes}" +(git diff "${diff_base}"..HEAD | "${grep_command}" -vP '^(diff|index)' || true) > "${actual_changes}" # Collect the warnings reported by Error Prone Support checks. expected_warnings="${integration_test_root}/${test_name}-expected-warnings.txt" actual_warnings="${report_directory}/${test_name}-validation-build-warnings.txt" -(grep -oP "(?<=^\\Q[WARNING] ${PWD}/\\E).*" "${validation_build_log}" | grep -P '\] \[' || true) | LC_ALL=C sort > "${actual_warnings}" +("${grep_command}" -oP "(?<=^\\Q[WARNING] ${PWD}/\\E).*" "${validation_build_log}" | "${grep_command}" -P '\] \[' || true) | LC_ALL=C sort > "${actual_warnings}" # Persist or validate the applied changes and reported warnings. if [ -n "${do_sync}" ]; then @@ -171,12 +195,12 @@ else # XXX: This "diff of diffs" also contains vacuous sections, introduced due to # line offset differences. Try to omit those from the final output. if ! diff -u "${expected_changes}" "${actual_changes}"; then - echo 'There are unexpected changes.' + echo 'There are unexpected changes. Inspect the preceding output for details.' failure=1 fi echo 'Inspecting emitted warnings...' if ! diff -u "${expected_warnings}" "${actual_warnings}"; then - echo 'Diagnostics output changed.' + echo 'Diagnostics output changed. Inspect the preceding output for details.' failure=1 fi fi From d7a3fbe9afcfeafa42214cfff8fb6007a356c818 Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Thu, 30 Nov 2023 10:43:34 +0100 Subject: [PATCH 04/59] Use integration-test.sh relative to test dir --- integration-tests/checkstyle.sh | 2 +- integration-tests/metrics-v4.2.19.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index 9ffdf8519c..fc4ee882dd 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -18,4 +18,4 @@ report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ build_flags="-Dassertj.version=3.24.2" validation_mvn_flags="-Dtest=!MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles,!XdocsJavaDocsTest#allCheckSectionJavaDocs" -./integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" +"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" diff --git a/integration-tests/metrics-v4.2.19.sh b/integration-tests/metrics-v4.2.19.sh index eb660875ef..96f1488a12 100755 --- a/integration-tests/metrics-v4.2.19.sh +++ b/integration-tests/metrics-v4.2.19.sh @@ -14,4 +14,4 @@ fi do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" -./integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "" "" "" "$do_sync" "$report_directory" +"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "" "" "" "$do_sync" "$report_directory" From be6d3e555b8f576c62f1e461fa7de4c4f2a5b35f Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Thu, 30 Nov 2023 12:08:17 +0100 Subject: [PATCH 05/59] Run metrics on java 17 --- .../metrics-v4.2.19-expected-changes.patch | 6660 ----------------- .../metrics-v4.2.19-expected-warnings.txt | 14 +- integration-tests/metrics-v4.2.19-init.patch | 306 +- 3 files changed, 151 insertions(+), 6829 deletions(-) diff --git a/integration-tests/metrics-v4.2.19-expected-changes.patch b/integration-tests/metrics-v4.2.19-expected-changes.patch index 5d6d51f6b8..e69de29bb2 100644 --- a/integration-tests/metrics-v4.2.19-expected-changes.patch +++ b/integration-tests/metrics-v4.2.19-expected-changes.patch @@ -1,6660 +0,0 @@ ---- a/metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java -+++ b/metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java -@@ -2,7 +2,6 @@ package com.codahale.metrics.benchmarks; - - import com.codahale.metrics.SlidingTimeWindowArrayReservoir; - import com.codahale.metrics.SlidingTimeWindowReservoir; --import com.codahale.metrics.Snapshot; - import java.util.concurrent.TimeUnit; - import org.openjdk.jmh.annotations.Benchmark; - import org.openjdk.jmh.annotations.Group; -@@ -42,8 +41,7 @@ public class SlidingTimeWindowReservoirsBenchmark { - @Group("slidingTime") - @GroupThreads(1) - public Object slidingTimeRead() { -- Snapshot snapshot = slidingTime.getSnapshot(); -- return snapshot; -+ return slidingTime.getSnapshot(); - } - - @Benchmark -@@ -58,8 +56,7 @@ public class SlidingTimeWindowReservoirsBenchmark { - @Group("arrTime") - @GroupThreads(1) - public Object arrTimeRead() { -- Snapshot snapshot = arrTime.getSnapshot(); -- return snapshot; -+ return arrTime.getSnapshot(); - } - - public static void main(String[] args) throws RunnerException { ---- a/metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java -+++ b/metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java -@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; - import static com.codahale.metrics.MetricAttribute.M15_RATE; - import static com.codahale.metrics.MetricAttribute.M1_RATE; - import static com.codahale.metrics.MetricAttribute.M5_RATE; --import static com.codahale.metrics.MetricAttribute.MAX; - import static com.codahale.metrics.MetricAttribute.MEAN; - import static com.codahale.metrics.MetricAttribute.MEAN_RATE; --import static com.codahale.metrics.MetricAttribute.MIN; - import static com.codahale.metrics.MetricAttribute.P50; - import static com.codahale.metrics.MetricAttribute.P75; - import static com.codahale.metrics.MetricAttribute.P95; -@@ -15,6 +13,7 @@ import static com.codahale.metrics.MetricAttribute.P98; - import static com.codahale.metrics.MetricAttribute.P99; - import static com.codahale.metrics.MetricAttribute.P999; - import static com.codahale.metrics.MetricAttribute.STDDEV; -+import static java.util.Collections.emptySet; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.Counter; -@@ -29,7 +28,6 @@ import com.codahale.metrics.Snapshot; - import com.codahale.metrics.Timer; - import java.io.IOException; - import java.net.InetAddress; --import java.util.Collections; - import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -80,7 +78,7 @@ public class CollectdReporter extends ScheduledReporter { - private SecurityLevel securityLevel = SecurityLevel.NONE; - private String username = ""; - private String password = ""; -- private Set disabledMetricAttributes = Collections.emptySet(); -+ private Set disabledMetricAttributes = emptySet(); - private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; - - private Builder(MetricRegistry registry) { -@@ -302,7 +300,7 @@ public class CollectdReporter extends ScheduledReporter { - try { - writer.write(metaData, value); - } catch (RuntimeException e) { -- LOG.warn("Failed to process metric '" + metaData.getPlugin() + "': " + e.getMessage()); -+ LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage()); - } catch (IOException e) { - LOG.error("Failed to send metric to collectd", e); - } -@@ -337,9 +335,9 @@ public class CollectdReporter extends ScheduledReporter { - private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { - final Snapshot snapshot = metric.getSnapshot(); - writeValue(metaData, COUNT, (double) metric.getCount()); -- writeValue(metaData, MAX, (double) snapshot.getMax()); -+ writeValue(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); - writeValue(metaData, MEAN, snapshot.getMean()); -- writeValue(metaData, MIN, (double) snapshot.getMin()); -+ writeValue(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); - writeValue(metaData, STDDEV, snapshot.getStdDev()); - writeValue(metaData, P50, snapshot.getMedian()); - writeValue(metaData, P75, snapshot.get75thPercentile()); -@@ -352,9 +350,9 @@ public class CollectdReporter extends ScheduledReporter { - private void serializeTimer(MetaData.Builder metaData, Timer metric) { - final Snapshot snapshot = metric.getSnapshot(); - writeValue(metaData, COUNT, (double) metric.getCount()); -- writeDuration(metaData, MAX, (double) snapshot.getMax()); -+ writeDuration(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); - writeDuration(metaData, MEAN, snapshot.getMean()); -- writeDuration(metaData, MIN, (double) snapshot.getMin()); -+ writeDuration(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); - writeDuration(metaData, STDDEV, snapshot.getStdDev()); - writeDuration(metaData, P50, snapshot.getMedian()); - writeDuration(metaData, P75, snapshot.get75thPercentile()); ---- a/metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java -+++ b/metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java -@@ -1,10 +1,12 @@ - package com.codahale.metrics.collectd; - -+import static java.nio.charset.StandardCharsets.US_ASCII; -+import static java.nio.charset.StandardCharsets.UTF_8; -+ - import java.io.IOException; - import java.nio.BufferOverflowException; - import java.nio.ByteBuffer; - import java.nio.ByteOrder; --import java.nio.charset.StandardCharsets; - import java.security.InvalidKeyException; - import java.security.MessageDigest; - import java.security.NoSuchAlgorithmException; -@@ -64,8 +66,8 @@ class PacketWriter { - PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { - this.sender = sender; - this.securityLevel = securityLevel; -- this.username = username != null ? username.getBytes(StandardCharsets.UTF_8) : null; -- this.password = password != null ? password.getBytes(StandardCharsets.UTF_8) : null; -+ this.username = username != null ? username.getBytes(UTF_8) : null; -+ this.password = password != null ? password.getBytes(UTF_8) : null; - } - - void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { -@@ -119,12 +121,12 @@ class PacketWriter { - } - - private void writeString(ByteBuffer buffer, int type, String val) { -- if (val == null || val.length() == 0) { -+ if (val == null || val.isEmpty()) { - return; - } - int len = HEADER_LEN + val.length() + 1; - writeHeader(buffer, type, len); -- buffer.put(val.getBytes(StandardCharsets.US_ASCII)).put(NULL); -+ buffer.put(val.getBytes(US_ASCII)).put(NULL); - } - - private void writeNumber(ByteBuffer buffer, int type, long val) { ---- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterSecurityTest.java -+++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterSecurityTest.java -@@ -1,6 +1,6 @@ - package com.codahale.metrics.collectd; - --import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - - import com.codahale.metrics.MetricRegistry; - import org.junit.Test; -@@ -11,27 +11,27 @@ public class CollectdReporterSecurityTest { - - @Test - public void testUnableSetSecurityLevelToSignWithoutUsername() { -- assertThatIllegalArgumentException() -- .isThrownBy( -+ assertThatThrownBy( - () -> - CollectdReporter.forRegistry(registry) - .withHostName("eddie") - .withSecurityLevel(SecurityLevel.SIGN) - .withPassword("t1_g3r") - .build(new Sender("localhost", 25826))) -- .withMessage("username is required for securityLevel: SIGN"); -+ .isInstanceOf(IllegalArgumentException.class) -+ .hasMessage("username is required for securityLevel: SIGN"); - } - - @Test - public void testUnableSetSecurityLevelToSignWithoutPassword() { -- assertThatIllegalArgumentException() -- .isThrownBy( -+ assertThatThrownBy( - () -> - CollectdReporter.forRegistry(registry) - .withHostName("eddie") - .withSecurityLevel(SecurityLevel.SIGN) - .withUsername("scott") - .build(new Sender("localhost", 25826))) -- .withMessage("password is required for securityLevel: SIGN"); -+ .isInstanceOf(IllegalArgumentException.class) -+ .hasMessage("password is required for securityLevel: SIGN"); - } - } ---- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java -+++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java -@@ -1,5 +1,8 @@ - package com.codahale.metrics.collectd; - -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptySortedMap; -+import static java.util.Collections.singletonMap; - import static java.util.concurrent.TimeUnit.MILLISECONDS; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; -@@ -12,7 +15,6 @@ import com.codahale.metrics.MetricAttribute; - import com.codahale.metrics.MetricRegistry; - import com.codahale.metrics.Snapshot; - import com.codahale.metrics.Timer; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -94,7 +96,7 @@ public class CollectdReporterTest { - - @Test - public void reportsCounters() throws Exception { -- Counter counter = mock(Counter.class); -+ Counter counter = mock(); - when(counter.getCount()).thenReturn(42L); - - reporter.report(map(), map("api.rest.requests.count", counter), map(), map(), map()); -@@ -104,7 +106,7 @@ public class CollectdReporterTest { - - @Test - public void reportsMeters() throws Exception { -- Meter meter = mock(Meter.class); -+ Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); -@@ -122,8 +124,8 @@ public class CollectdReporterTest { - - @Test - public void reportsHistograms() throws Exception { -- Histogram histogram = mock(Histogram.class); -- Snapshot snapshot = mock(Snapshot.class); -+ Histogram histogram = mock(); -+ Snapshot snapshot = mock(); - when(histogram.getCount()).thenReturn(1L); - when(histogram.getSnapshot()).thenReturn(snapshot); - when(snapshot.getMax()).thenReturn(2L); -@@ -146,8 +148,8 @@ public class CollectdReporterTest { - - @Test - public void reportsTimers() throws Exception { -- Timer timer = mock(Timer.class); -- Snapshot snapshot = mock(Snapshot.class); -+ Timer timer = mock(); -+ Snapshot snapshot = mock(); - when(timer.getSnapshot()).thenReturn(snapshot); - when(timer.getCount()).thenReturn(1L); - when(timer.getSnapshot()).thenReturn(snapshot); -@@ -187,14 +189,14 @@ public class CollectdReporterTest { - - @Test - public void doesNotReportDisabledMetricAttributes() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); - when(meter.getFifteenMinuteRate()).thenReturn(4.0); - when(meter.getMeanRate()).thenReturn(5.0); - -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(11L); - - CollectdReporter reporter = -@@ -240,16 +242,16 @@ public class CollectdReporterTest { - } - - private SortedMap map() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - private SortedMap map(String name, T metric) { -- final Map map = Collections.singletonMap(name, metric); -+ final Map map = singletonMap(name, metric); - return new TreeMap<>(map); - } - - private List nextValues(Receiver receiver) throws Exception { - final ValueList valueList = receiver.next(); -- return valueList == null ? Collections.emptyList() : valueList.getValues(); -+ return valueList == null ? emptyList() : valueList.getValues(); - } - } ---- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/PacketWriterTest.java -+++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/PacketWriterTest.java -@@ -190,6 +190,6 @@ public class PacketWriterTest { - assertThat(amountOfValues).isEqualTo((short) 1); - byte dataType = packet.get(); - assertThat(dataType).isEqualTo((byte) 1); -- assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isEqualTo(42.0, offset(0.01)); -+ assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01)); - } - } ---- a/metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java -@@ -1,8 +1,9 @@ - package com.codahale.metrics; - -+import static java.util.Collections.emptySet; -+ - import java.io.PrintStream; - import java.text.DateFormat; --import java.util.Collections; - import java.util.Date; - import java.util.Locale; - import java.util.Map; -@@ -53,7 +54,7 @@ public class ConsoleReporter extends ScheduledReporter { - this.filter = MetricFilter.ALL; - this.executor = null; - this.shutdownExecutorOnStop = true; -- disabledMetricAttributes = Collections.emptySet(); -+ disabledMetricAttributes = emptySet(); - } - - /** ---- a/metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java -@@ -1,8 +1,9 @@ - package com.codahale.metrics; - -+import static java.util.Objects.requireNonNull; -+ - import com.codahale.metrics.WeightedSnapshot.WeightedSample; - import java.time.Duration; --import java.util.Objects; - import java.util.concurrent.ConcurrentSkipListMap; - import java.util.concurrent.ThreadLocalRandom; - import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -@@ -127,7 +128,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - // It's possible that more values were added while the map was scanned, those with the - // minimum priorities are removed. - while (newCount > size) { -- Objects.requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); -+ requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); - newCount--; - } - return new State(alphaNanos, size, newTick, newCount, newValues); -@@ -255,13 +256,13 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - - /** Interval at which this reservoir is rescaled. */ - public Builder rescaleThreshold(Duration value) { -- this.rescaleThreshold = Objects.requireNonNull(value, "rescaleThreshold is required"); -+ this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required"); - return this; - } - - /** Clock instance used for decay. */ - public Builder clock(Clock value) { -- this.clock = Objects.requireNonNull(value, "clock is required"); -+ this.clock = requireNonNull(value, "clock is required"); - return this; - } - ---- a/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java -@@ -1,6 +1,9 @@ - package com.codahale.metrics; - --import java.util.Collections; -+import static java.util.Collections.unmodifiableMap; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Collections.unmodifiableSortedSet; -+ - import java.util.List; - import java.util.Map; - import java.util.SortedMap; -@@ -207,7 +210,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Counter.class.isInstance(metric); -+ return metric instanceof Counter; - } - }); - } -@@ -242,7 +245,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Histogram.class.isInstance(metric); -+ return metric instanceof Histogram; - } - }); - } -@@ -277,7 +280,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Meter.class.isInstance(metric); -+ return metric instanceof Meter; - } - }); - } -@@ -312,7 +315,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Timer.class.isInstance(metric); -+ return metric instanceof Timer; - } - }); - } -@@ -350,7 +353,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Gauge.class.isInstance(metric); -+ return metric instanceof Gauge; - } - }); - } -@@ -414,7 +417,7 @@ public class MetricRegistry implements MetricSet { - * @return the names of all the metrics - */ - public SortedSet getNames() { -- return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); -+ return unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); - } - - /** -@@ -541,7 +544,7 @@ public class MetricRegistry implements MetricSet { - timers.put(entry.getKey(), (T) entry.getValue()); - } - } -- return Collections.unmodifiableSortedMap(timers); -+ return unmodifiableSortedMap(timers); - } - - private void onMetricAdded(String name, Metric metric) { -@@ -609,7 +612,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public Map getMetrics() { -- return Collections.unmodifiableMap(metrics); -+ return unmodifiableMap(metrics); - } - - @FunctionalInterface -@@ -628,7 +631,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Counter.class.isInstance(metric); -+ return metric instanceof Counter; - } - }; - -@@ -641,7 +644,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Histogram.class.isInstance(metric); -+ return metric instanceof Histogram; - } - }; - -@@ -654,7 +657,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Meter.class.isInstance(metric); -+ return metric instanceof Meter; - } - }; - -@@ -667,7 +670,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Timer.class.isInstance(metric); -+ return metric instanceof Timer; - } - }; - -@@ -681,7 +684,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Gauge.class.isInstance(metric); -+ return metric instanceof Gauge; - } - }; - ---- a/metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java -@@ -1,9 +1,13 @@ - package com.codahale.metrics; - -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.emptySet; -+import static java.util.Collections.emptySortedMap; -+import static java.util.Collections.emptySortedSet; -+ - import java.io.OutputStream; - import java.time.Duration; - import java.util.Collection; --import java.util.Collections; - import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -137,69 +141,69 @@ public final class NoopMetricRegistry extends MetricRegistry { - /** {@inheritDoc} */ - @Override - public SortedSet getNames() { -- return Collections.emptySortedSet(); -+ return emptySortedSet(); - } - - /** {@inheritDoc} */ - @Override - @SuppressWarnings("rawtypes") - public SortedMap getGauges() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - @SuppressWarnings("rawtypes") - public SortedMap getGauges(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getCounters() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getCounters(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getHistograms() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getHistograms(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getMeters() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getMeters(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getTimers() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getTimers(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ -@@ -211,7 +215,7 @@ public final class NoopMetricRegistry extends MetricRegistry { - /** {@inheritDoc} */ - @Override - public Map getMetrics() { -- return Collections.emptyMap(); -+ return emptyMap(); - } - - static final class NoopGauge implements Gauge { -@@ -601,19 +605,19 @@ public final class NoopMetricRegistry extends MetricRegistry { - /** {@inheritDoc} */ - @Override - public Set keySet() { -- return Collections.emptySet(); -+ return emptySet(); - } - - /** {@inheritDoc} */ - @Override - public Collection values() { -- return Collections.emptySet(); -+ return emptySet(); - } - - /** {@inheritDoc} */ - @Override - public Set> entrySet() { -- return Collections.emptySet(); -+ return emptySet(); - } - } - } ---- a/metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java -@@ -1,7 +1,8 @@ - package com.codahale.metrics; - -+import static java.util.Collections.emptySet; -+ - import java.io.Closeable; --import java.util.Collections; - import java.util.Locale; - import java.util.Set; - import java.util.SortedMap; -@@ -128,7 +129,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - durationUnit, - executor, - shutdownExecutorOnStop, -- Collections.emptySet()); -+ emptySet()); - } - - protected ScheduledReporter( -@@ -154,7 +155,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - this.durationFactor = durationUnit.toNanos(1); - this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); - this.disabledMetricAttributes = -- disabledMetricAttributes != null ? disabledMetricAttributes : Collections.emptySet(); -+ disabledMetricAttributes != null ? disabledMetricAttributes : emptySet(); - } - - /** -@@ -185,8 +186,8 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, - * ScheduledExecutorService)} instead. - */ -- @SuppressWarnings("DeprecatedIsStillUsed") - @Deprecated -+ @SuppressWarnings("DeprecatedIsStillUsed") - protected ScheduledFuture getScheduledFuture( - long initialDelay, long period, TimeUnit unit, Runnable runnable) { - return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); ---- a/metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java -@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; - import static com.codahale.metrics.MetricAttribute.M15_RATE; - import static com.codahale.metrics.MetricAttribute.M1_RATE; - import static com.codahale.metrics.MetricAttribute.M5_RATE; --import static com.codahale.metrics.MetricAttribute.MAX; - import static com.codahale.metrics.MetricAttribute.MEAN; - import static com.codahale.metrics.MetricAttribute.MEAN_RATE; --import static com.codahale.metrics.MetricAttribute.MIN; - import static com.codahale.metrics.MetricAttribute.P50; - import static com.codahale.metrics.MetricAttribute.P75; - import static com.codahale.metrics.MetricAttribute.P95; -@@ -15,8 +13,8 @@ import static com.codahale.metrics.MetricAttribute.P98; - import static com.codahale.metrics.MetricAttribute.P99; - import static com.codahale.metrics.MetricAttribute.P999; - import static com.codahale.metrics.MetricAttribute.STDDEV; -+import static java.util.Collections.emptySet; - --import java.util.Collections; - import java.util.Map.Entry; - import java.util.Set; - import java.util.SortedMap; -@@ -81,7 +79,7 @@ public class Slf4jReporter extends ScheduledReporter { - this.loggingLevel = LoggingLevel.INFO; - this.executor = null; - this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -+ this.disabledMetricAttributes = emptySet(); - } - - /** -@@ -306,8 +304,8 @@ public class Slf4jReporter extends ScheduledReporter { - b.append("type=TIMER"); - append(b, "name", prefix(name)); - appendCountIfEnabled(b, timer); -- appendLongDurationIfEnabled(b, MIN, snapshot::getMin); -- appendLongDurationIfEnabled(b, MAX, snapshot::getMax); -+ appendLongDurationIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); -+ appendLongDurationIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); - appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); - appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); - appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); -@@ -338,8 +336,8 @@ public class Slf4jReporter extends ScheduledReporter { - b.append("type=HISTOGRAM"); - append(b, "name", prefix(name)); - appendCountIfEnabled(b, histogram); -- appendLongIfEnabled(b, MIN, snapshot::getMin); -- appendLongIfEnabled(b, MAX, snapshot::getMax); -+ appendLongIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); -+ appendLongIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); - appendDoubleIfEnabled(b, MEAN, snapshot::getMean); - appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); - appendDoubleIfEnabled(b, P50, snapshot::getMedian); ---- a/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowMovingAverages.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowMovingAverages.java -@@ -184,7 +184,6 @@ public class SlidingTimeWindowMovingAverages implements MovingAverages { - buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); - buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); - } -- long retval = adder.longValue(); -- return retval; -+ return adder.longValue(); - } - } ---- a/metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java -@@ -1,13 +1,13 @@ - package com.codahale.metrics; - - import static java.nio.charset.StandardCharsets.UTF_8; -+import static java.util.Comparator.comparingLong; - - import java.io.OutputStream; - import java.io.OutputStreamWriter; - import java.io.PrintWriter; - import java.util.Arrays; - import java.util.Collection; --import java.util.Comparator; - - /** A statistical snapshot of a {@link WeightedSnapshot}. */ - public class WeightedSnapshot extends Snapshot { -@@ -35,7 +35,7 @@ public class WeightedSnapshot extends Snapshot { - public WeightedSnapshot(Collection values) { - final WeightedSample[] copy = values.toArray(new WeightedSample[] {}); - -- Arrays.sort(copy, Comparator.comparingLong(w -> w.value)); -+ Arrays.sort(copy, comparingLong(w -> w.value)); - - this.values = new long[copy.length]; - this.normWeights = new double[copy.length]; ---- a/metrics-core/src/test/java/com/codahale/metrics/ClockTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/ClockTest.java -@@ -11,9 +11,9 @@ public class ClockTest { - public void userTimeClock() { - final Clock.UserTimeClock clock = new Clock.UserTimeClock(); - -- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(100.0)); -+ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0)); - -- assertThat((double) clock.getTick()).isEqualTo(System.nanoTime(), offset(1000000.0)); -+ assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0)); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/ConsoleReporterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/ConsoleReporterTest.java -@@ -21,8 +21,8 @@ public class ConsoleReporterTest { - private final Locale locale = Locale.US; - private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); - -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final Clock clock = mock(Clock.class); -+ private final MetricRegistry registry = mock(); -+ private final Clock clock = mock(); - private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - private final PrintStream output = new PrintStream(bytes); - private final ConsoleReporter reporter = -@@ -68,7 +68,7 @@ public class ConsoleReporterTest { - - @Test - public void reportsCounterValues() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map("test.counter", counter), map(), map(), map()); -@@ -87,10 +87,10 @@ public class ConsoleReporterTest { - - @Test - public void reportsHistogramValues() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -130,7 +130,7 @@ public class ConsoleReporterTest { - - @Test - public void reportsMeterValues() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(3.0); -@@ -157,14 +157,14 @@ public class ConsoleReporterTest { - - @Test - public void reportsTimerValues() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -223,7 +223,7 @@ public class ConsoleReporterTest { - .disabledMetricAttributes(disabledMetricAttributes) - .build(); - -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(3.0); -@@ -266,14 +266,14 @@ public class ConsoleReporterTest { - .disabledMetricAttributes(disabledMetricAttributes) - .build(); - -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -329,10 +329,10 @@ public class ConsoleReporterTest { - .disabledMetricAttributes(disabledMetricAttributes) - .build(); - -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); ---- a/metrics-core/src/test/java/com/codahale/metrics/CounterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/CounterTest.java -@@ -9,7 +9,7 @@ public class CounterTest { - - @Test - public void startsAtZero() { -- assertThat(counter.getCount()).isZero(); -+ assertThat(counter.getCount()).isEqualTo(0); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/CsvReporterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/CsvReporterTest.java -@@ -7,7 +7,6 @@ import static org.mockito.Mockito.when; - - import java.io.File; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.nio.file.Files; - import java.util.Locale; - import java.util.SortedMap; -@@ -21,8 +20,8 @@ import org.junit.rules.TemporaryFolder; - public class CsvReporterTest { - @Rule public final TemporaryFolder folder = new TemporaryFolder(); - -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final Clock clock = mock(Clock.class); -+ private final MetricRegistry registry = mock(); -+ private final Clock clock = mock(); - - private File dataDirectory; - private CsvReporter reporter; -@@ -54,7 +53,7 @@ public class CsvReporterTest { - - @Test - public void reportsCounterValues() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map("test.counter", counter), map(), map(), map()); -@@ -64,10 +63,10 @@ public class CsvReporterTest { - - @Test - public void reportsHistogramValues() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -105,14 +104,14 @@ public class CsvReporterTest { - - @Test - public void reportsTimerValues() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -137,7 +136,7 @@ public class CsvReporterTest { - - @Test - public void testCsvFileProviderIsUsed() { -- CsvFileProvider fileProvider = mock(CsvFileProvider.class); -+ CsvFileProvider fileProvider = mock(); - when(fileProvider.getFile(dataDirectory, "gauge")) - .thenReturn(new File(dataDirectory, "guage.csv")); - -@@ -175,7 +174,7 @@ public class CsvReporterTest { - } - - private Meter mockMeter() { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(3.0); -@@ -194,8 +193,7 @@ public class CsvReporterTest { - } - - private String fileContents(String filename) throws IOException { -- return new String( -- Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); -+ return Files.readString(new File(dataDirectory, filename).toPath()); - } - - private SortedMap map() { ---- a/metrics-core/src/test/java/com/codahale/metrics/EWMATest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/EWMATest.java -@@ -13,67 +13,67 @@ public class EWMATest { - ewma.update(3); - ewma.tick(); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.01098938, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00404277, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00148725, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00054713, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00020128, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00007405, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00002724, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00001002, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000369, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000136, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000050, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000018, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001)); - } - - @Test -@@ -82,67 +82,67 @@ public class EWMATest { - ewma.update(3); - ewma.tick(); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.18071653, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.14795818, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.12113791, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.09917933, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.06648190, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.05443077, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.04456415, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.03648604, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); - } - - @Test -@@ -151,67 +151,67 @@ public class EWMATest { - ewma.update(3); - ewma.tick(); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.56130419, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.52510399, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.45955700, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.42991879, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.37625345, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.35198773, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.30805027, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.28818318, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.25221023, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.23594443, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); - } - - private void elapseMinute(EWMA ewma) { ---- a/metrics-core/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -@@ -1,5 +1,6 @@ - package com.codahale.metrics; - -+import static java.util.stream.Collectors.toList; - import static org.assertj.core.api.Assertions.assertThat; - - import com.codahale.metrics.Timer.Context; -@@ -8,7 +9,6 @@ import java.util.Collection; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicBoolean; - import java.util.concurrent.atomic.AtomicInteger; --import java.util.stream.Collectors; - import org.junit.Test; - import org.junit.runner.RunWith; - import org.junit.runners.Parameterized; -@@ -46,7 +46,7 @@ public class ExponentiallyDecayingReservoirTest { - public static Collection reservoirs() { - return Arrays.stream(ReservoirFactory.values()) - .map(value -> new Object[] {value}) -- .collect(Collectors.toList()); -+ .collect(toList()); - } - - private final ReservoirFactory reservoirFactory; ---- a/metrics-core/src/test/java/com/codahale/metrics/HistogramTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/HistogramTest.java -@@ -8,12 +8,12 @@ import static org.mockito.Mockito.when; - import org.junit.Test; - - public class HistogramTest { -- private final Reservoir reservoir = mock(Reservoir.class); -+ private final Reservoir reservoir = mock(); - private final Histogram histogram = new Histogram(reservoir); - - @Test - public void updatesTheCountOnUpdates() { -- assertThat(histogram.getCount()).isZero(); -+ assertThat(histogram.getCount()).isEqualTo(0); - - histogram.update(1); - -@@ -22,7 +22,7 @@ public class HistogramTest { - - @Test - public void returnsTheSnapshotFromTheReservoir() { -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(reservoir.getSnapshot()).thenReturn(snapshot); - - assertThat(histogram.getSnapshot()).isEqualTo(snapshot); ---- a/metrics-core/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java -@@ -112,8 +112,8 @@ public class InstrumentedExecutorServiceTest { - assertThat(idle.getSnapshot().size()).isEqualTo(1); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void reportsTasksInformationForThreadPoolExecutor() throws Exception { - executor = - new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); -@@ -170,8 +170,8 @@ public class InstrumentedExecutorServiceTest { - assertThat(poolSize.getValue()).isEqualTo(1); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void reportsTasksInformationForForkJoinPool() throws Exception { - executor = Executors.newWorkStealingPool(4); - instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); ---- a/metrics-core/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java -@@ -36,16 +36,16 @@ public class InstrumentedScheduledExecutorServiceTest { - - @Test - public void testSubmitRunnable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - Future theFuture = - instrumentedScheduledExecutor.submit( -@@ -53,87 +53,87 @@ public class InstrumentedScheduledExecutorServiceTest { - assertThat(submitted.getCount()).isEqualTo(1); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - }); - - theFuture.get(); - - assertThat(submitted.getCount()).isEqualTo(1); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test - public void testScheduleRunnable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - ScheduledFuture theFuture = - instrumentedScheduledExecutor.schedule( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - }, - 10L, - TimeUnit.MILLISECONDS); - - theFuture.get(); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test - public void testSubmitCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - final Object obj = new Object(); - -@@ -143,13 +143,13 @@ public class InstrumentedScheduledExecutorServiceTest { - assertThat(submitted.getCount()).isEqualTo(1); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - return obj; - }); -@@ -158,45 +158,45 @@ public class InstrumentedScheduledExecutorServiceTest { - - assertThat(submitted.getCount()).isEqualTo(1); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test - public void testScheduleCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - final Object obj = new Object(); - - ScheduledFuture theFuture = - instrumentedScheduledExecutor.schedule( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - return obj; - }, -@@ -205,37 +205,37 @@ public class InstrumentedScheduledExecutorServiceTest { - - assertThat(theFuture.get()).isEqualTo(obj); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test - public void testScheduleFixedRateCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - CountDownLatch countDownLatch = new CountDownLatch(1); - ScheduledFuture theFuture = - instrumentedScheduledExecutor.scheduleAtFixedRate( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); - -@@ -257,14 +257,14 @@ public class InstrumentedScheduledExecutorServiceTest { - theFuture.cancel(true); - TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isNotEqualTo(0); - assertThat(duration.getCount()).isNotEqualTo(0); - assertThat(duration.getSnapshot().size()).isNotEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); - assertThat(scheduledRepetitively.getCount()).isEqualTo(1); - assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); - assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); -@@ -272,22 +272,22 @@ public class InstrumentedScheduledExecutorServiceTest { - - @Test - public void testScheduleFixedDelayCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - CountDownLatch countDownLatch = new CountDownLatch(1); - ScheduledFuture theFuture = - instrumentedScheduledExecutor.scheduleWithFixedDelay( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); - -@@ -310,9 +310,9 @@ public class InstrumentedScheduledExecutorServiceTest { - theFuture.cancel(true); - TimeUnit.MILLISECONDS.sleep(200); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isNotEqualTo(0); - assertThat(duration.getCount()).isNotEqualTo(0); - assertThat(duration.getSnapshot().size()).isNotEqualTo(0); ---- a/metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java -@@ -11,7 +11,7 @@ import org.junit.runner.RunWith; - import org.junit.runners.Parameterized; - import org.junit.runners.Parameterized.Parameters; - --@RunWith(value = Parameterized.class) -+@RunWith(Parameterized.class) - public class MeterApproximationTest { - - @Parameters -@@ -34,7 +34,7 @@ public class MeterApproximationTest { - 3, TimeUnit.MINUTES); - - assertThat(meter.getOneMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); - } - - @Test -@@ -45,7 +45,7 @@ public class MeterApproximationTest { - 13, TimeUnit.MINUTES); - - assertThat(meter.getFiveMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); - } - - @Test -@@ -56,7 +56,7 @@ public class MeterApproximationTest { - 38, TimeUnit.MINUTES); - - assertThat(meter.getFifteenMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); - } - - private Meter simulateMetronome( ---- a/metrics-core/src/test/java/com/codahale/metrics/MeterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/MeterTest.java -@@ -10,7 +10,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MeterTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final Meter meter = new Meter(clock); - - @Before -@@ -20,15 +20,15 @@ public class MeterTest { - - @Test - public void startsOutWithNoRatesOrCount() { -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - -- assertThat(meter.getMeanRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); - } - - @Test -@@ -36,12 +36,12 @@ public class MeterTest { - meter.mark(); - meter.mark(2); - -- assertThat(meter.getMeanRate()).isEqualTo(0.3, offset(0.001)); -+ assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001)); - -- assertThat(meter.getOneMinuteRate()).isEqualTo(0.1840, offset(0.001)); -+ assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001)); - -- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.1966, offset(0.001)); -+ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001)); - -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.1988, offset(0.001)); -+ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001)); - } - } ---- a/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryListenerTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryListenerTest.java -@@ -6,10 +6,10 @@ import static org.mockito.Mockito.verifyNoInteractions; - import org.junit.Test; - - public class MetricRegistryListenerTest { -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - private final MetricRegistryListener listener = new MetricRegistryListener.Base() {}; - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryTest.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.stream.Collectors.toSet; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.mockito.Mockito.mock; -@@ -10,20 +11,19 @@ import static org.mockito.Mockito.verify; - import java.util.HashMap; - import java.util.Map; - import java.util.Set; --import java.util.stream.Collectors; - import org.junit.Assert; - import org.junit.Before; - import org.junit.Test; - - public class MetricRegistryTest { -- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); -+ private final MetricRegistryListener listener = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private final Gauge gauge = () -> ""; - private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - - @Before - public void setUp() { -@@ -230,8 +230,8 @@ public class MetricRegistryTest { - verify(listener).onGaugeAdded("thing", gauge1); - } - -- @Test - @SuppressWarnings("rawtypes") -+ @Test - public void accessingACustomGaugeRegistersAndReusesIt() { - final MetricRegistry.MetricSupplier supplier = () -> gauge; - final Gauge gauge1 = registry.gauge("thing", supplier); -@@ -261,7 +261,7 @@ public class MetricRegistryTest { - registry.register("meter", meter); - registry.register("timer", timer); - -- final MetricRegistryListener other = mock(MetricRegistryListener.class); -+ final MetricRegistryListener other = mock(); - registry.addListener(other); - - verify(other).onGaugeAdded("gauge", gauge); -@@ -383,7 +383,7 @@ public class MetricRegistryTest { - MetricRegistry other = new MetricRegistry(); - other.register("gauge", gauge); - registry.register("nested", other); -- assertThat(registry.getNames()).containsOnly("nested.gauge"); -+ assertThat(registry.getNames()).containsExactly("nested.gauge"); - } - - @Test -@@ -391,8 +391,8 @@ public class MetricRegistryTest { - assertThat(name("one", "two", "three")).isEqualTo("one.two.three"); - } - -- @Test - @SuppressWarnings("NullArgumentToVariableArgMethod") -+ @Test - public void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { - assertThat(name("one", (String) null)).isEqualTo("one"); - } -@@ -456,7 +456,7 @@ public class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - } - - @Test -@@ -474,7 +474,7 @@ public class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - } - - @Test -@@ -498,14 +498,13 @@ public class MetricRegistryTest { - Set deepChildMetrics = deepChild.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - - assertThat(childMetrics) -- .containsAll( -- deepChildMetrics.stream().map(m -> "deep-child." + m).collect(Collectors.toSet())); -+ .containsAll(deepChildMetrics.stream().map(m -> "deep-child." + m).collect(toSet())); - -- assertThat(deepChildMetrics.size()).isEqualTo(3); -- assertThat(childMetrics.size()).isEqualTo(5); -+ assertThat(deepChildMetrics).hasSize(3); -+ assertThat(childMetrics).hasSize(5); - } - - @Test -@@ -523,7 +522,7 @@ public class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - - assertThat(childMetrics).doesNotContain("test-1"); - } -@@ -546,7 +545,7 @@ public class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - - assertThat(childMetrics).doesNotContain("test-1", "test-3"); - } -@@ -572,16 +571,15 @@ public class MetricRegistryTest { - Set deepChildMetrics = deepChild.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - - assertThat(childMetrics) -- .containsAll( -- deepChildMetrics.stream().map(m -> "deep-child." + m).collect(Collectors.toSet())); -+ .containsAll(deepChildMetrics.stream().map(m -> "deep-child." + m).collect(toSet())); - - assertThat(deepChildMetrics).doesNotContain("test-2"); - -- assertThat(deepChildMetrics.size()).isEqualTo(1); -- assertThat(childMetrics.size()).isEqualTo(3); -+ assertThat(deepChildMetrics).hasSize(1); -+ assertThat(childMetrics).hasSize(3); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/NoopMetricRegistryTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/NoopMetricRegistryTest.java -@@ -1,7 +1,7 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatNullPointerException; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; - import static org.mockito.Mockito.verify; -@@ -13,13 +13,13 @@ import org.junit.Before; - import org.junit.Test; - - public class NoopMetricRegistryTest { -- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); -+ private final MetricRegistryListener listener = mock(); - private final NoopMetricRegistry registry = new NoopMetricRegistry(); - private final Gauge gauge = () -> ""; -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - - @Before - public void setUp() { -@@ -218,8 +218,8 @@ public class NoopMetricRegistryTest { - verify(listener, never()).onGaugeAdded("thing", gauge1); - } - -- @Test - @SuppressWarnings("rawtypes") -+ @Test - public void accessingACustomGaugeRegistersAndReusesIt() { - final MetricRegistry.MetricSupplier supplier = () -> gauge; - final Gauge gauge1 = registry.gauge("thing", supplier); -@@ -240,7 +240,7 @@ public class NoopMetricRegistryTest { - registry.register("meter", meter); - registry.register("timer", timer); - -- final MetricRegistryListener other = mock(MetricRegistryListener.class); -+ final MetricRegistryListener other = mock(); - registry.addListener(other); - - verify(other, never()).onGaugeAdded("gauge", gauge); -@@ -488,8 +488,8 @@ public class NoopMetricRegistryTest { - @Test - public void registerNullMetric() { - MetricRegistry registry = new NoopMetricRegistry(); -- assertThatNullPointerException() -- .isThrownBy(() -> registry.register("any_name", null)) -- .withMessage("metric == null"); -+ assertThatThrownBy(() -> registry.register("any_name", null)) -+ .isInstanceOf(NullPointerException.class) -+ .hasMessage("metric == null"); - } - } ---- a/metrics-core/src/test/java/com/codahale/metrics/RatioGaugeTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/RatioGaugeTest.java -@@ -9,7 +9,7 @@ public class RatioGaugeTest { - public void ratiosAreHumanReadable() { - final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); - -- assertThat(ratio.toString()).isEqualTo("100.0:200.0"); -+ assertThat(ratio).hasToString("100.0:200.0"); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java -@@ -26,12 +26,12 @@ import org.junit.Test; - - public class ScheduledReporterTest { - private final Gauge gauge = () -> ""; -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - -- private final ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); -+ private final ScheduledExecutorService mockExecutor = mock(); - private final ScheduledExecutorService customExecutor = - Executors.newSingleThreadScheduledExecutor(); - private final ScheduledExecutorService externalExecutor = -@@ -145,7 +145,7 @@ public class ScheduledReporterTest { - public void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { - reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); - -- verify(mockExecutor, times(1)) -+ verify(mockExecutor) - .scheduleWithFixedDelay(any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS)); - } - -@@ -295,7 +295,7 @@ public class ScheduledReporterTest { - - Thread.sleep(1_000); - -- verify(reporter, times(1)) -+ verify(reporter) - .report( - map("gauge", gauge), - map("counter", counter), ---- a/metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java -@@ -29,7 +29,7 @@ public class SharedMetricRegistriesTest { - public void hasASetOfNames() { - SharedMetricRegistries.getOrCreate("one"); - -- assertThat(SharedMetricRegistries.names()).containsOnly("one"); -+ assertThat(SharedMetricRegistries.names()).containsExactly("one"); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/Slf4jReporterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/Slf4jReporterTest.java -@@ -3,7 +3,6 @@ package com.codahale.metrics; - import static com.codahale.metrics.MetricAttribute.COUNT; - import static com.codahale.metrics.MetricAttribute.M1_RATE; - import static com.codahale.metrics.MetricAttribute.MEAN_RATE; --import static com.codahale.metrics.MetricAttribute.MIN; - import static com.codahale.metrics.MetricAttribute.P50; - import static com.codahale.metrics.MetricAttribute.P999; - import static com.codahale.metrics.MetricAttribute.STDDEV; -@@ -22,9 +21,9 @@ import org.slf4j.Marker; - - public class Slf4jReporterTest { - -- private final Logger logger = mock(Logger.class); -- private final Marker marker = mock(Marker.class); -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final Logger logger = mock(); -+ private final Marker marker = mock(); -+ private final MetricRegistry registry = mock(); - - /** - * The set of disabled metric attributes to pass to the Slf4jReporter builder in the default -@@ -79,7 +78,7 @@ public class Slf4jReporterTest { - } - - private Timer timer() { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - - when(timer.getMeanRate()).thenReturn(2.0); -@@ -87,7 +86,7 @@ public class Slf4jReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -104,10 +103,10 @@ public class Slf4jReporterTest { - } - - private Histogram histogram() { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -124,7 +123,7 @@ public class Slf4jReporterTest { - } - - private Meter meter() { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(3.0); -@@ -134,7 +133,7 @@ public class Slf4jReporterTest { - } - - private Counter counter() { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - return counter; - } -@@ -168,7 +167,7 @@ public class Slf4jReporterTest { - - @Test - public void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); -+ disabledMetricAttributes = EnumSet.of(COUNT, MetricAttribute.MIN, P50); - reportsHistogramValuesAtError( - "type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " - + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -@@ -192,7 +191,7 @@ public class Slf4jReporterTest { - - @Test - public void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); -+ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, P50, M1_RATE); - reportsMeterValuesAtError( - "type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " - + "mean_rate=2.0, rate_unit=events/second"); -@@ -218,7 +217,7 @@ public class Slf4jReporterTest { - - @Test - public void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); -+ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, STDDEV, P999, MEAN_RATE); - reportsTimerValuesAtError( - "type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " - + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " ---- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java -@@ -16,7 +16,7 @@ public class SlidingTimeWindowArrayReservoirTest { - - @Test - public void storesMeasurementsWithDuplicateTicks() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - final SlidingTimeWindowArrayReservoir reservoir = - new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); - -@@ -30,7 +30,7 @@ public class SlidingTimeWindowArrayReservoirTest { - - @Test - public void boundsMeasurementsToATimeWindow() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - final SlidingTimeWindowArrayReservoir reservoir = - new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); - -@@ -99,7 +99,7 @@ public class SlidingTimeWindowArrayReservoirTest { - // Set the clock to overflow in (2*window+1)ns - final ManualClock clock = new ManualClock(); - clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -- assertThat(clock.getTick() * 256).isGreaterThan(0); -+ assertThat(clock.getTick() * 256).isPositive(); - - // Create the reservoir - final SlidingTimeWindowArrayReservoir reservoir = ---- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowMovingAveragesTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowMovingAveragesTest.java -@@ -44,7 +44,7 @@ public class SlidingTimeWindowMovingAveragesTest { - - SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); - -- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(0L)), is(0)); -+ assertThat(stwm.calculateIndexOfTick(Instant.EPOCH), is(0)); - assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L)), is(1)); - } - -@@ -62,7 +62,7 @@ public class SlidingTimeWindowMovingAveragesTest { - } - - // verify that no cleanup happened yet -- assertThat(movingAverages.oldestBucketTime, is(Instant.ofEpochSecond(0L))); -+ assertThat(movingAverages.oldestBucketTime, is(Instant.EPOCH)); - - assertThat(meter.getOneMinuteRate(), is(60.0)); - assertThat(meter.getFiveMinuteRate(), is(300.0)); -@@ -83,7 +83,7 @@ public class SlidingTimeWindowMovingAveragesTest { - } - - // verify that at least one cleanup happened -- assertThat(movingAverages.oldestBucketTime, not(is(Instant.ofEpochSecond(0L)))); -+ assertThat(movingAverages.oldestBucketTime, not(is(Instant.EPOCH))); - - assertThat(meter.getOneMinuteRate(), is(60.0)); - assertThat(meter.getFiveMinuteRate(), is(300.0)); ---- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java -@@ -12,7 +12,7 @@ import org.junit.Test; - public class SlidingTimeWindowReservoirTest { - @Test - public void storesMeasurementsWithDuplicateTicks() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - final SlidingTimeWindowReservoir reservoir = - new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); - -@@ -26,7 +26,7 @@ public class SlidingTimeWindowReservoirTest { - - @Test - public void boundsMeasurementsToATimeWindow() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - when(clock.getTick()).thenReturn(0L); - - final SlidingTimeWindowReservoir reservoir = -@@ -72,7 +72,7 @@ public class SlidingTimeWindowReservoirTest { - - // Set the clock to overflow in (2*window+1)ns - clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -- assertThat(clock.getTick() * 256).isGreaterThan(0); -+ assertThat(clock.getTick() * 256).isPositive(); - - int updatesAfterThreshold = 0; - while (true) { ---- a/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java -@@ -13,7 +13,7 @@ import java.util.concurrent.atomic.AtomicBoolean; - import org.junit.Test; - - public class TimerTest { -- private final Reservoir reservoir = mock(Reservoir.class); -+ private final Reservoir reservoir = mock(); - private final Clock clock = - new Clock() { - // a mock clock that increments its ticker by 50msec per call -@@ -28,20 +28,20 @@ public class TimerTest { - - @Test - public void hasRates() { -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - -- assertThat(timer.getMeanRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); - } - - @Test - public void updatesTheCountOnUpdates() { -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - - timer.update(1, TimeUnit.SECONDS); - -@@ -93,7 +93,7 @@ public class TimerTest { - - @Test - public void returnsTheSnapshotFromTheReservoir() { -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(reservoir.getSnapshot()).thenReturn(snapshot); - - assertThat(timer.getSnapshot()).isEqualTo(snapshot); -@@ -103,7 +103,7 @@ public class TimerTest { - public void ignoresNegativeValues() { - timer.update(-1, TimeUnit.SECONDS); - -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - - verifyNoInteractions(reservoir); - } -@@ -121,14 +121,14 @@ public class TimerTest { - public void java8NegativeDuration() { - timer.update(Duration.ofMillis(-5678)); - -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - - verifyNoInteractions(reservoir); - } - - @Test - public void tryWithResourcesWork() { -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - - int dummy = 0; - try (Timer.Context context = timer.time()) { ---- a/metrics-core/src/test/java/com/codahale/metrics/UniformReservoirTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/UniformReservoirTest.java -@@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; - - public class UniformReservoirTest { -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void aReservoirOf100OutOf1000Elements() { - final UniformReservoir reservoir = new UniformReservoir(100); - for (int i = 0; i < 1000; i++) { -@@ -20,7 +20,7 @@ public class UniformReservoirTest { - assertThat(snapshot.size()).isEqualTo(100); - - for (double i : snapshot.getValues()) { -- assertThat(i).isLessThan(1000).isGreaterThanOrEqualTo(0); -+ assertThat(i).isLessThan(1000).isNotNegative(); - } - } - } ---- a/metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java -@@ -16,12 +16,12 @@ public class UniformSnapshotTest { - - @Test - public void smallQuantilesAreTheFirstValue() { -- assertThat(snapshot.getValue(0.0)).isEqualTo(1, offset(0.1)); -+ assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1)); - } - - @Test - public void bigQuantilesAreTheLastValue() { -- assertThat(snapshot.getValue(1.0)).isEqualTo(5, offset(0.1)); -+ assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1)); - } - - @Test(expected = IllegalArgumentException.class) -@@ -41,32 +41,32 @@ public class UniformSnapshotTest { - - @Test - public void hasAMedian() { -- assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); -+ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1)); - } - - @Test - public void hasAp75() { -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1)); - } - - @Test - public void hasAp95() { -- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp98() { -- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp99() { -- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp999() { -- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test -@@ -125,7 +125,7 @@ public class UniformSnapshotTest { - - snapshot.dump(output); - -- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); -+ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); - } - - @Test -@@ -145,41 +145,41 @@ public class UniformSnapshotTest { - - @Test - public void calculatesTheStdDev() { -- assertThat(snapshot.getStdDev()).isEqualTo(1.5811, offset(0.0001)); -+ assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001)); - } - - @Test - public void calculatesAMinOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMin()).isZero(); -+ assertThat(emptySnapshot.getMin()).isEqualTo(0); - } - - @Test - public void calculatesAMaxOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMax()).isZero(); -+ assertThat(emptySnapshot.getMax()).isEqualTo(0); - } - - @Test - public void calculatesAMeanOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMean()).isZero(); -+ assertThat(emptySnapshot.getMean()).isEqualTo(0); - } - - @Test - public void calculatesAStdDevOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getStdDev()).isZero(); -+ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); - } - - @Test - public void calculatesAStdDevOfZeroForASingletonSnapshot() { - final Snapshot singleItemSnapshot = new UniformSnapshot(new long[] {1}); - -- assertThat(singleItemSnapshot.getStdDev()).isZero(); -+ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); - } - } ---- a/metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java -@@ -2,6 +2,7 @@ package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.offset; -+import static org.mockito.ArgumentMatchers.any; - import static org.mockito.Mockito.doReturn; - import static org.mockito.Mockito.spy; - import static org.mockito.Mockito.when; -@@ -11,7 +12,6 @@ import java.io.ByteArrayOutputStream; - import java.util.ArrayList; - import java.util.List; - import org.junit.Test; --import org.mockito.ArgumentMatchers; - - public class WeightedSnapshotTest { - -@@ -34,12 +34,12 @@ public class WeightedSnapshotTest { - - @Test - public void smallQuantilesAreTheFirstValue() { -- assertThat(snapshot.getValue(0.0)).isEqualTo(1.0, offset(0.1)); -+ assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1)); - } - - @Test - public void bigQuantilesAreTheLastValue() { -- assertThat(snapshot.getValue(1.0)).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1)); - } - - @Test(expected = IllegalArgumentException.class) -@@ -59,32 +59,32 @@ public class WeightedSnapshotTest { - - @Test - public void hasAMedian() { -- assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); -+ assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1)); - } - - @Test - public void hasAp75() { -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1)); - } - - @Test - public void hasAp95() { -- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp98() { -- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp99() { -- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp999() { -- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test -@@ -104,7 +104,7 @@ public class WeightedSnapshotTest { - final List spyItems = spy(originalItems); - doReturn(originalItems.toArray(new WeightedSample[] {})) - .when(spyItems) -- .toArray(ArgumentMatchers.any(WeightedSample[].class)); -+ .toArray(any(WeightedSample[].class)); - when(spyItems.size()).thenReturn(4, 5); - - final Snapshot other = new WeightedSnapshot(spyItems); -@@ -119,7 +119,7 @@ public class WeightedSnapshotTest { - final List spyItems = spy(originalItems); - doReturn(originalItems.toArray(new WeightedSample[] {})) - .when(spyItems) -- .toArray(ArgumentMatchers.any(WeightedSample[].class)); -+ .toArray(any(WeightedSample[].class)); - when(spyItems.size()).thenReturn(6, 5); - - final Snapshot other = new WeightedSnapshot(spyItems); -@@ -133,7 +133,7 @@ public class WeightedSnapshotTest { - - snapshot.dump(output); - -- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); -+ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); - } - - @Test -@@ -153,7 +153,7 @@ public class WeightedSnapshotTest { - - @Test - public void calculatesTheStdDev() { -- assertThat(snapshot.getStdDev()).isEqualTo(1.2688, offset(0.0001)); -+ assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001)); - } - - @Test -@@ -161,7 +161,7 @@ public class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getMin()).isZero(); -+ assertThat(emptySnapshot.getMin()).isEqualTo(0); - } - - @Test -@@ -169,7 +169,7 @@ public class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getMax()).isZero(); -+ assertThat(emptySnapshot.getMax()).isEqualTo(0); - } - - @Test -@@ -177,7 +177,7 @@ public class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getMean()).isZero(); -+ assertThat(emptySnapshot.getMean()).isEqualTo(0); - } - - @Test -@@ -185,7 +185,7 @@ public class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getStdDev()).isZero(); -+ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); - } - - @Test -@@ -193,7 +193,7 @@ public class WeightedSnapshotTest { - final Snapshot singleItemSnapshot = - new WeightedSnapshot(weightedArray(new long[] {1}, new double[] {1.0})); - -- assertThat(singleItemSnapshot.getStdDev()).isZero(); -+ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); - } - - @Test ---- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java -+++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java -@@ -132,8 +132,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { - final String sanitizedName = sanitize(name); - final String sanitizedValue = sanitize(value); - -- final String message = -- sanitizedName + ' ' + sanitizedValue + ' ' + Long.toString(timestamp) + '\n'; -+ final String message = sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n'; - channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); - } catch (IOException e) { - failures++; ---- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java -+++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java -@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; - import static com.codahale.metrics.MetricAttribute.M15_RATE; - import static com.codahale.metrics.MetricAttribute.M1_RATE; - import static com.codahale.metrics.MetricAttribute.M5_RATE; --import static com.codahale.metrics.MetricAttribute.MAX; - import static com.codahale.metrics.MetricAttribute.MEAN; - import static com.codahale.metrics.MetricAttribute.MEAN_RATE; --import static com.codahale.metrics.MetricAttribute.MIN; - import static com.codahale.metrics.MetricAttribute.P50; - import static com.codahale.metrics.MetricAttribute.P75; - import static com.codahale.metrics.MetricAttribute.P95; -@@ -15,6 +13,7 @@ import static com.codahale.metrics.MetricAttribute.P98; - import static com.codahale.metrics.MetricAttribute.P99; - import static com.codahale.metrics.MetricAttribute.P999; - import static com.codahale.metrics.MetricAttribute.STDDEV; -+import static java.util.Collections.emptySet; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.Counter; -@@ -29,7 +28,6 @@ import com.codahale.metrics.ScheduledReporter; - import com.codahale.metrics.Snapshot; - import com.codahale.metrics.Timer; - import java.io.IOException; --import java.util.Collections; - import java.util.Locale; - import java.util.Map; - import java.util.Set; -@@ -83,7 +81,7 @@ public class GraphiteReporter extends ScheduledReporter { - this.filter = MetricFilter.ALL; - this.executor = null; - this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -+ this.disabledMetricAttributes = emptySet(); - this.addMetricAttributesAsTags = false; - this.floatingPointFormatter = DEFAULT_FP_FORMATTER; - } -@@ -453,9 +451,9 @@ public class GraphiteReporter extends ScheduledReporter { - - private void reportTimer(String name, Timer timer, long timestamp) throws IOException { - final Snapshot snapshot = timer.getSnapshot(); -- sendIfEnabled(MAX, name, convertDuration(snapshot.getMax()), timestamp); -+ sendIfEnabled(MetricAttribute.MAX, name, convertDuration(snapshot.getMax()), timestamp); - sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); -- sendIfEnabled(MIN, name, convertDuration(snapshot.getMin()), timestamp); -+ sendIfEnabled(MetricAttribute.MIN, name, convertDuration(snapshot.getMin()), timestamp); - sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); - sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); - sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); -@@ -478,9 +476,9 @@ public class GraphiteReporter extends ScheduledReporter { - throws IOException { - final Snapshot snapshot = histogram.getSnapshot(); - sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); -- sendIfEnabled(MAX, name, snapshot.getMax(), timestamp); -+ sendIfEnabled(MetricAttribute.MAX, name, snapshot.getMax(), timestamp); - sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); -- sendIfEnabled(MIN, name, snapshot.getMin(), timestamp); -+ sendIfEnabled(MetricAttribute.MIN, name, snapshot.getMin(), timestamp); - sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); - sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); - sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); ---- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java -+++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java -@@ -63,7 +63,7 @@ public class GraphiteUDP implements GraphiteSender { - @Override - public void send(String name, String value, long timestamp) throws IOException { - try { -- String str = sanitize(name) + ' ' + sanitize(value) + ' ' + Long.toString(timestamp) + '\n'; -+ String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n'; - ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); - datagramChannel.send(byteBuffer, address); - this.failures = 0; ---- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java -+++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java -@@ -249,7 +249,7 @@ public class PickledGraphite implements GraphiteSender { - * message to graphite 3. Clear out the list of metrics - */ - private void writeMetrics() throws IOException { -- if (metrics.size() > 0) { -+ if (!metrics.isEmpty()) { - try { - byte[] payload = pickleMetrics(metrics); - byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteRabbitMQTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteRabbitMQTest.java -@@ -8,7 +8,6 @@ import static org.mockito.Mockito.anyString; - import static org.mockito.Mockito.atMost; - import static org.mockito.Mockito.doThrow; - import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -21,13 +20,13 @@ import org.junit.Before; - import org.junit.Test; - - public class GraphiteRabbitMQTest { -- private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); -- private final Connection connection = mock(Connection.class); -- private final Channel channel = mock(Channel.class); -+ private final ConnectionFactory connectionFactory = mock(); -+ private final Connection connection = mock(); -+ private final Channel channel = mock(); - -- private final ConnectionFactory bogusConnectionFactory = mock(ConnectionFactory.class); -- private final Connection bogusConnection = mock(Connection.class); -- private final Channel bogusChannel = mock(Channel.class); -+ private final ConnectionFactory bogusConnectionFactory = mock(); -+ private final Connection bogusConnection = mock(); -+ private final Channel bogusChannel = mock(); - - private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); - -@@ -92,10 +91,9 @@ public class GraphiteRabbitMQTest { - - String expectedMessage = "name value 100\n"; - -- verify(channel, times(1)) -- .basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); -+ verify(channel).basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); - -- assertThat(graphite.getFailures()).isZero(); -+ assertThat(graphite.getFailures()).isEqualTo(0); - } - - @Test -@@ -105,10 +103,10 @@ public class GraphiteRabbitMQTest { - - String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; - -- verify(channel, times(1)) -+ verify(channel) - .basicPublish("graphite", "name-to-sanitize", null, expectedMessage.getBytes(UTF_8)); - -- assertThat(graphite.getFailures()).isZero(); -+ assertThat(graphite.getFailures()).isEqualTo(0); - } - - @Test ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java -@@ -1,5 +1,6 @@ - package com.codahale.metrics.graphite; - -+import static java.util.Collections.emptySet; - import static org.mockito.Mockito.doThrow; - import static org.mockito.Mockito.inOrder; - import static org.mockito.Mockito.mock; -@@ -21,7 +22,6 @@ import com.codahale.metrics.Timer; - import java.net.UnknownHostException; - import java.text.DecimalFormat; - import java.text.DecimalFormatSymbols; --import java.util.Collections; - import java.util.EnumSet; - import java.util.Locale; - import java.util.Set; -@@ -34,9 +34,9 @@ import org.mockito.InOrder; - - public class GraphiteReporterTest { - private final long timestamp = 1000198; -- private final Clock clock = mock(Clock.class); -- private final Graphite graphite = mock(Graphite.class); -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final Clock clock = mock(); -+ private final Graphite graphite = mock(); -+ private final MetricRegistry registry = mock(); - private final GraphiteReporter reporter = - GraphiteReporter.forRegistry(registry) - .withClock(clock) -@@ -44,7 +44,7 @@ public class GraphiteReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(emptySet()) - .build(graphite); - - private final GraphiteReporter minuteRateReporter = -@@ -54,7 +54,7 @@ public class GraphiteReporterTest { - .convertRatesTo(TimeUnit.MINUTES) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(emptySet()) - .build(graphite); - - @Before -@@ -174,7 +174,7 @@ public class GraphiteReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(emptySet()) - .withFloatingPointFormatter(formatter::format) - .build(graphite)) { - reportGaugeValue(graphiteReporter, 0.000045322); -@@ -216,7 +216,7 @@ public class GraphiteReporterTest { - - @Test - public void reportsCounters() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map("counter", counter), map(), map(), map()); -@@ -232,10 +232,10 @@ public class GraphiteReporterTest { - - @Test - public void reportsHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -272,7 +272,7 @@ public class GraphiteReporterTest { - - @Test - public void reportsMeters() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); -@@ -296,7 +296,7 @@ public class GraphiteReporterTest { - - @Test - public void reportsMetersInMinutes() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); -@@ -321,14 +321,14 @@ public class GraphiteReporterTest { - - @Test - public void reportsTimers() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -395,14 +395,14 @@ public class GraphiteReporterTest { - - @Test - public void disabledMetricsAttribute() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); - when(meter.getFifteenMinuteRate()).thenReturn(4.0); - when(meter.getMeanRate()).thenReturn(5.0); - -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(11L); - - Set disabledMetricAttributes = -@@ -433,7 +433,7 @@ public class GraphiteReporterTest { - - @Test - public void sendsMetricAttributesAsTagsIfEnabled() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - getReporterThatSendsMetricAttributesAsTags() -@@ -459,7 +459,7 @@ public class GraphiteReporterTest { - MetricFilter.ALL, - null, - false, -- Collections.emptySet(), -+ emptySet(), - false) { - @Override - protected String format(double v) { -@@ -475,7 +475,7 @@ public class GraphiteReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(emptySet()) - .addMetricAttributesAsTags(true) - .build(graphite); - } ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java -@@ -26,11 +26,11 @@ import org.junit.Test; - public class GraphiteTest { - private final String host = "example.com"; - private final int port = 1234; -- private final SocketFactory socketFactory = mock(SocketFactory.class); -+ private final SocketFactory socketFactory = mock(); - private final InetSocketAddress address = new InetSocketAddress(host, port); - -- private final Socket socket = mock(Socket.class); -- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); -+ private final Socket socket = mock(); -+ private final ByteArrayOutputStream output = spy(); - - @Before - public void setUp() throws Exception { -@@ -84,7 +84,7 @@ public class GraphiteTest { - @Test - public void measuresFailures() throws IOException { - try (Graphite graphite = new Graphite(address, socketFactory)) { -- assertThat(graphite.getFailures()).isZero(); -+ assertThat(graphite.getFailures()).isEqualTo(0); - } - } - ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java -@@ -1,13 +1,13 @@ - package com.codahale.metrics.graphite; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; - - import java.net.InetSocketAddress; - import java.nio.ByteBuffer; - import java.nio.channels.DatagramChannel; - import org.junit.Test; --import org.mockito.Mockito; - - public class GraphiteUDPTest { - -@@ -30,7 +30,7 @@ public class GraphiteUDPTest { - @Test - public void writesValue() throws Exception { - graphiteUDP = new GraphiteUDP(host, port); -- DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); -+ DatagramChannel mockDatagramChannel = mock(); - graphiteUDP.setDatagramChannel(mockDatagramChannel); - graphiteUDP.setAddress(new InetSocketAddress(host, port)); - ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java -@@ -32,12 +32,12 @@ import org.python.core.PyList; - import org.python.core.PyTuple; - - public class PickledGraphiteTest { -- private final SocketFactory socketFactory = mock(SocketFactory.class); -+ private final SocketFactory socketFactory = mock(); - private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); - private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); - -- private final Socket socket = mock(Socket.class); -- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); -+ private final Socket socket = mock(); -+ private final ByteArrayOutputStream output = spy(); - - private CompiledScript unpickleScript; - ---- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java -+++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java -@@ -29,10 +29,10 @@ public class AsyncHealthCheckDecorator extends HealthCheck implements Runnable { - this.healthyTtl = - async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); - result = -- Async.InitialState.HEALTHY.equals(async.initialState()) -+ Async.InitialState.HEALTHY == async.initialState() - ? Result.healthy(NO_RESULT_YET_MESSAGE) - : Result.unhealthy(NO_RESULT_YET_MESSAGE); -- if (Async.ScheduleType.FIXED_RATE.equals(async.scheduleType())) { -+ if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) { - future = - executorService.scheduleAtFixedRate( - this, async.initialDelay(), async.period(), async.unit()); ---- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java -+++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java -@@ -1,11 +1,12 @@ - package com.codahale.metrics.health; - -+import static java.util.Collections.unmodifiableMap; -+ - import com.codahale.metrics.Clock; - import java.time.Instant; - import java.time.ZoneId; - import java.time.ZonedDateTime; - import java.time.format.DateTimeFormatter; --import java.util.Collections; - import java.util.LinkedHashMap; - import java.util.Map; - import java.util.concurrent.TimeUnit; -@@ -124,7 +125,7 @@ public abstract class HealthCheck { - this.healthy = isHealthy; - this.message = message; - this.error = error; -- this.details = details == null ? null : Collections.unmodifiableMap(details); -+ this.details = details == null ? null : unmodifiableMap(details); - this.time = clock.getTime(); - } - -@@ -163,7 +164,7 @@ public abstract class HealthCheck { - */ - public String getTimestamp() { - Instant currentInstant = Instant.ofEpochMilli(time); -- ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(currentInstant, ZoneId.systemDefault()); -+ ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault()); - return DATE_FORMAT_PATTERN.format(zonedDateTime); - } - -@@ -219,8 +220,7 @@ public abstract class HealthCheck { - int result = healthy ? 1 : 0; - result = PRIME * result + (message != null ? message.hashCode() : 0); - result = PRIME * result + (error != null ? error.hashCode() : 0); -- result = PRIME * result + (Long.hashCode(time)); -- return result; -+ return PRIME * result + (Long.hashCode(time)); - } - - @Override -@@ -238,7 +238,7 @@ public abstract class HealthCheck { - if (details != null) { - for (Map.Entry e : details.entrySet()) { - builder.append(", "); -- builder.append(e.getKey()).append("=").append(String.valueOf(e.getValue())); -+ builder.append(e.getKey()).append("=").append(e.getValue()); - } - } - builder.append('}'); ---- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java -+++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java -@@ -1,9 +1,10 @@ - package com.codahale.metrics.health; - - import static com.codahale.metrics.health.HealthCheck.Result; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Collections.unmodifiableSortedSet; - - import com.codahale.metrics.health.annotation.Async; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -128,7 +129,7 @@ public class HealthCheckRegistry { - * @return the names of all registered health checks - */ - public SortedSet getNames() { -- return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); -+ return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); - } - - /** -@@ -180,7 +181,7 @@ public class HealthCheckRegistry { - results.put(entry.getKey(), result); - } - } -- return Collections.unmodifiableSortedMap(results); -+ return unmodifiableSortedMap(results); - } - - /** -@@ -208,7 +209,7 @@ public class HealthCheckRegistry { - final String name = entry.getKey(); - final HealthCheck healthCheck = entry.getValue(); - if (filter.matches(name, healthCheck)) { -- futures.put(name, executor.submit(() -> healthCheck.execute())); -+ futures.put(name, executor.submit(healthCheck::execute)); - } - } - -@@ -222,7 +223,7 @@ public class HealthCheckRegistry { - } - } - -- return Collections.unmodifiableSortedMap(results); -+ return unmodifiableSortedMap(results); - } - - private void onHealthCheckAdded(String name, HealthCheck healthCheck) { ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/AsyncHealthCheckDecoratorTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/AsyncHealthCheckDecoratorTest.java -@@ -5,7 +5,6 @@ import static org.mockito.ArgumentCaptor.forClass; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -31,11 +30,11 @@ public class AsyncHealthCheckDecoratorTest { - .withMessage("Result was healthy but it expired 1 milliseconds ago") - .build(); - -- private final HealthCheck mockHealthCheck = mock(HealthCheck.class); -- private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); -+ private final HealthCheck mockHealthCheck = mock(); -+ private final ScheduledExecutorService mockExecutorService = mock(); - - @SuppressWarnings("rawtypes") -- private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); -+ private final ScheduledFuture mockFuture = mock(); - - @Test(expected = IllegalArgumentException.class) - public void nullHealthCheckTriggersInstantiationFailure() { -@@ -74,7 +73,7 @@ public class AsyncHealthCheckDecoratorTest { - AsyncHealthCheckDecorator asyncDecorator = - new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); - -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); - assertThat(asyncDecorator.check().isHealthy()).isTrue(); -@@ -87,7 +86,7 @@ public class AsyncHealthCheckDecoratorTest { - AsyncHealthCheckDecorator asyncDecorator = - new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); - -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); - } -@@ -102,8 +101,8 @@ public class AsyncHealthCheckDecoratorTest { - assertThat(asyncDecorator.check().isHealthy()).isFalse(); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void tearDownTriggersCancellation() throws Exception { - when(mockExecutorService.scheduleAtFixedRate( - any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) -@@ -114,13 +113,13 @@ public class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); - asyncDecorator.tearDown(); - -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -- verify(mockFuture, times(1)).cancel(eq(true)); -+ verify(mockFuture).cancel(true); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { - HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); - when(mockExecutorService.scheduleAtFixedRate( -@@ -133,7 +132,7 @@ public class AsyncHealthCheckDecoratorTest { - HealthCheck.Result initialResult = asyncDecorator.check(); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); - capturedRunnable.run(); -@@ -143,8 +142,8 @@ public class AsyncHealthCheckDecoratorTest { - assertThat(actualResult).isNotEqualTo(initialResult); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { - Exception exception = new Exception("TestException"); - when(mockExecutorService.scheduleAtFixedRate( -@@ -156,7 +155,7 @@ public class AsyncHealthCheckDecoratorTest { - new ConfigurableAsyncHealthCheck(exception), mockExecutorService); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); - capturedRunnable.run(); -@@ -173,7 +172,7 @@ public class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate( - runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); -@@ -192,7 +191,7 @@ public class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate( - runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); -@@ -210,7 +209,7 @@ public class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); - capturedRunnable.run(); ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckRegistryTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckRegistryTest.java -@@ -23,21 +23,21 @@ import org.junit.Test; - import org.mockito.ArgumentCaptor; - - public class HealthCheckRegistryTest { -- private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); -+ private final ScheduledExecutorService executorService = mock(); - private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); -- private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -+ private final HealthCheckRegistryListener listener = mock(); - -- private final HealthCheck hc1 = mock(HealthCheck.class); -- private final HealthCheck hc2 = mock(HealthCheck.class); -+ private final HealthCheck hc1 = mock(); -+ private final HealthCheck hc2 = mock(); - -- private final HealthCheck.Result r1 = mock(HealthCheck.Result.class); -- private final HealthCheck.Result r2 = mock(HealthCheck.Result.class); -+ private final HealthCheck.Result r1 = mock(); -+ private final HealthCheck.Result r2 = mock(); - -- private final HealthCheck.Result ar = mock(HealthCheck.Result.class); -+ private final HealthCheck.Result ar = mock(); - private final HealthCheck ahc = new TestAsyncHealthCheck(ar); - - @SuppressWarnings("rawtypes") -- private final ScheduledFuture af = mock(ScheduledFuture.class); -+ private final ScheduledFuture af = mock(); - - @Before - @SuppressWarnings("unchecked") -@@ -96,7 +96,7 @@ public class HealthCheckRegistryTest { - - @Test - public void addingListenerCatchesExistingHealthChecks() { -- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -+ HealthCheckRegistryListener listener = mock(); - HealthCheckRegistry registry = new HealthCheckRegistry(); - registry.register("hc1", hc1); - registry.register("hc2", hc2); -@@ -110,7 +110,7 @@ public class HealthCheckRegistryTest { - - @Test - public void removedListenerDoesNotReceiveUpdates() { -- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -+ HealthCheckRegistryListener listener = mock(); - HealthCheckRegistry registry = new HealthCheckRegistry(); - registry.addListener(listener); - registry.register("hc1", hc1); ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java -@@ -29,7 +29,7 @@ public class HealthCheckTest { - } - } - -- private final HealthCheck underlying = mock(HealthCheck.class); -+ private final HealthCheck underlying = mock(); - private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); - - @Test -@@ -89,7 +89,7 @@ public class HealthCheckTest { - - @Test - public void canHaveUnhealthyResultsWithExceptions() { -- final RuntimeException e = mock(RuntimeException.class); -+ final RuntimeException e = mock(); - when(e.getMessage()).thenReturn("oh noes"); - - final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); -@@ -144,7 +144,7 @@ public class HealthCheckTest { - - @Test - public void canHaveUnHealthyBuilderWithDetailAndError() { -- final RuntimeException e = mock(RuntimeException.class); -+ final RuntimeException e = mock(); - when(e.getMessage()).thenReturn("oh noes"); - - final HealthCheck.Result result = -@@ -161,7 +161,7 @@ public class HealthCheckTest { - - @Test - public void returnsResultsWhenExecuted() { -- final HealthCheck.Result result = mock(HealthCheck.Result.class); -+ final HealthCheck.Result result = mock(); - when(underlying.execute()).thenReturn(result); - - assertThat(healthCheck.execute()).isEqualTo(result); -@@ -171,7 +171,7 @@ public class HealthCheckTest { - - @Test - public void wrapsExceptionsWhenExecuted() { -- final RuntimeException e = mock(RuntimeException.class); -+ final RuntimeException e = mock(); - when(e.getMessage()).thenReturn("oh noes"); - - when(underlying.execute()).thenThrow(e); -@@ -181,7 +181,7 @@ public class HealthCheckTest { - assertThat(actual.getMessage()).isEqualTo("oh noes"); - assertThat(actual.getError()).isEqualTo(e); - assertThat(actual.getDetails()).isNull(); -- assertThat(actual.getDuration()).isGreaterThanOrEqualTo(0); -+ assertThat(actual.getDuration()).isNotNegative(); - } - - @Test ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java -@@ -30,7 +30,7 @@ public class SharedHealthCheckRegistriesTest { - public void returnsSetOfCreatedRegistries() { - SharedHealthCheckRegistries.getOrCreate("db"); - -- assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); -+ assertThat(SharedHealthCheckRegistries.names()).containsExactly("db"); - } - - @Test ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java -@@ -1,12 +1,12 @@ - package com.codahale.metrics.health.jvm; - -+import static java.util.Collections.emptySet; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; - - import com.codahale.metrics.health.HealthCheck; - import com.codahale.metrics.jvm.ThreadDeadlockDetector; --import java.util.Collections; - import java.util.Set; - import java.util.TreeSet; - import org.junit.Test; -@@ -14,10 +14,10 @@ import org.junit.Test; - public class ThreadDeadlockHealthCheckTest { - @Test - public void isHealthyIfNoThreadsAreDeadlocked() { -- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -+ final ThreadDeadlockDetector detector = mock(); - final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); - -- when(detector.getDeadlockedThreads()).thenReturn(Collections.emptySet()); -+ when(detector.getDeadlockedThreads()).thenReturn(emptySet()); - - assertThat(healthCheck.execute().isHealthy()).isTrue(); - } -@@ -28,7 +28,7 @@ public class ThreadDeadlockHealthCheckTest { - threads.add("one"); - threads.add("two"); - -- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -+ final ThreadDeadlockDetector detector = mock(); - final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); - - when(detector.getDeadlockedThreads()).thenReturn(threads); ---- a/metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/InstrumentedHttpClientsTimerTest.java -+++ b/metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/InstrumentedHttpClientsTimerTest.java -@@ -45,7 +45,7 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - chac.start(); - asyncHttpClient = chac; - -- Timer timer = mock(Timer.class); -+ Timer timer = mock(); - when(timer.time()).thenReturn(context); - when(metricRegistry.timer(any())).thenReturn(timer); - } -@@ -71,13 +71,13 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - verify(context, timeout(200).times(1)).stop(); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { - HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); - HttpGet get = new HttpGet("/?q=something"); - -- FutureCallback futureCallback = mock(FutureCallback.class); -+ FutureCallback futureCallback = mock(); - - // Timer hasn't been stopped prior to executing the request - verify(context, never()).stop(); -@@ -98,14 +98,14 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - verify(context, timeout(200).times(1)).stop(); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { - // There should be nothing listening on this port - HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); - HttpGet get = new HttpGet("/?q=something"); - -- FutureCallback futureCallback = mock(FutureCallback.class); -+ FutureCallback futureCallback = mock(); - - // Timer hasn't been stopped prior to executing the request - verify(context, never()).stop(); ---- a/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientConnectionManagerTest.java -+++ b/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientConnectionManagerTest.java -@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import com.codahale.metrics.MetricRegistry; - import org.junit.Assert; - import org.junit.Test; - import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; - - public class InstrumentedHttpClientConnectionManagerTest { - private final MetricRegistry metricRegistry = new MetricRegistry(); -@@ -36,7 +38,7 @@ public class InstrumentedHttpClientConnectionManagerTest { - - @Test - public void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -+ final MetricRegistry registry = mock(); - - InstrumentedHttpClientConnectionManager.builder(registry) - .name("some-name") -@@ -45,7 +47,7 @@ public class InstrumentedHttpClientConnectionManagerTest { - .close(); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); - assertTrue(argumentCaptor.getValue().contains("some-other-name")); - } - } ---- a/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientsTest.java -@@ -22,9 +22,8 @@ import org.junit.Before; - import org.junit.Test; - - public class InstrumentedHttpClientsTest { -- private final HttpClientMetricNameStrategy metricNameStrategy = -- mock(HttpClientMetricNameStrategy.class); -- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); -+ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); -+ private final MetricRegistryListener registryListener = mock(); - private final MetricRegistry metricRegistry = new MetricRegistry(); - private final HttpClient client = - InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) ---- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java -+++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java -@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import com.codahale.metrics.MetricRegistry; - import org.junit.Assert; - import org.junit.Test; - import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; - - public class InstrumentedAsyncClientConnectionManagerTest { - private final MetricRegistry metricRegistry = new MetricRegistry(); -@@ -43,7 +45,7 @@ public class InstrumentedAsyncClientConnectionManagerTest { - - @Test - public void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -+ final MetricRegistry registry = mock(); - - InstrumentedAsyncClientConnectionManager.builder(registry) - .name("some-name") -@@ -52,7 +54,7 @@ public class InstrumentedAsyncClientConnectionManagerTest { - .close(); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); - assertTrue(argumentCaptor.getValue().contains("some-other-name")); - } - } ---- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java -+++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java -@@ -1,5 +1,6 @@ - package com.codahale.metrics.httpclient5; - -+import static java.nio.charset.StandardCharsets.US_ASCII; - import static org.assertj.core.api.Assertions.assertThat; - import static org.awaitility.Awaitility.await; - import static org.junit.Assert.fail; -@@ -17,7 +18,6 @@ import com.sun.net.httpserver.HttpExchange; - import com.sun.net.httpserver.HttpServer; - import java.io.IOException; - import java.net.InetSocketAddress; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.ExecutionException; - import java.util.concurrent.Future; -@@ -82,7 +82,7 @@ public class InstrumentedHttpAsyncClientsTest { - exchange -> { - exchange.sendResponseHeaders(200, 0L); - exchange.setStreams(null, null); -- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); -+ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); - exchange.close(); - }); - httpServer.start(); -@@ -187,7 +187,7 @@ public class InstrumentedHttpAsyncClientsTest { - exchange -> { - exchange.sendResponseHeaders(200, 0L); - exchange.setStreams(null, null); -- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); -+ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); - exchange.close(); - }); - httpServer.start(); ---- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientConnectionManagerTest.java -+++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientConnectionManagerTest.java -@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import com.codahale.metrics.MetricRegistry; - import org.junit.Assert; - import org.junit.Test; - import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; - - public class InstrumentedHttpClientConnectionManagerTest { - private final MetricRegistry metricRegistry = new MetricRegistry(); -@@ -41,7 +43,7 @@ public class InstrumentedHttpClientConnectionManagerTest { - - @Test - public void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -+ final MetricRegistry registry = mock(); - - InstrumentedHttpClientConnectionManager.builder(registry) - .name("some-name") -@@ -50,7 +52,7 @@ public class InstrumentedHttpClientConnectionManagerTest { - .close(); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); - assertTrue(argumentCaptor.getValue().contains("some-other-name")); - } - } ---- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java -@@ -22,9 +22,8 @@ import org.junit.Before; - import org.junit.Test; - - public class InstrumentedHttpClientsTest { -- private final HttpClientMetricNameStrategy metricNameStrategy = -- mock(HttpClientMetricNameStrategy.class); -- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); -+ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); -+ private final MetricRegistryListener registryListener = mock(); - private final MetricRegistry metricRegistry = new MetricRegistry(); - private final HttpClient client = - InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) ---- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListenerTest.java -+++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListenerTest.java -@@ -10,7 +10,7 @@ import jakarta.servlet.ServletContextEvent; - import org.junit.Test; - - public class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final MetricRegistry registry = mock(); - private final InstrumentedFilterContextListener listener = - new InstrumentedFilterContextListener() { - @Override -@@ -21,9 +21,9 @@ public class InstrumentedFilterContextListenerTest { - - @Test - public void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ final ServletContext context = mock(); - -- final ServletContextEvent event = mock(ServletContextEvent.class); -+ final ServletContextEvent event = mock(); - when(event.getServletContext()).thenReturn(context); - - listener.contextInitialized(event); ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java -@@ -83,7 +83,7 @@ public class HealthCheckServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); - if (registryAttr instanceof HealthCheckRegistry) { - this.registry = (HealthCheckRegistry) registryAttr; ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java -@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(METRICS_REGISTRY); - if (registryAttr instanceof MetricRegistry) { - this.registry = (MetricRegistry) registryAttr; ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java -@@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -102,9 +101,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getStatus()).isEqualTo(200); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -143,9 +141,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getStatus()).isEqualTo(200); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -217,15 +214,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getContent()) - .isEqualTo( - String.format( -- "{%n" -- + " \"fun\" : {%n" -- + " \"healthy\" : true,%n" -- + " \"message\" : \"foo bar 123\",%n" -- + " \"duration\" : 0,%n" -- + " \"timestamp\" : \"" -- + EXPECTED_TIMESTAMP -- + "\"" -- + "%n }%n}")); -+ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", -+ EXPECTED_TIMESTAMP)); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -240,25 +230,25 @@ public class HealthCheckServletTest extends AbstractServletTest { - @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() - throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final io.dropwizard.metrics.servlets.HealthCheckServlet healthCheckServlet = - new io.dropwizard.metrics.servlets.HealthCheckServlet(healthCheckRegistry); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -+ verify(servletConfig).getServletContext(); - verify(servletContext, never()) - .getAttribute(eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY)); - } - - @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute( - eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY))) -@@ -268,16 +258,16 @@ public class HealthCheckServletTest extends AbstractServletTest { - new io.dropwizard.metrics.servlets.HealthCheckServlet(null); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)) -+ verify(servletConfig).getServletContext(); -+ verify(servletContext) - .getAttribute(eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY)); - } - - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute( - eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY))) ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletContextListenerTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletContextListenerTest.java -@@ -17,7 +17,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MetricsServletContextListenerTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private final String allowedOrigin = "some.other.origin"; - ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java -@@ -1,10 +1,8 @@ - package io.dropwizard.metrics.servlets; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -24,7 +22,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MetricsServletTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private ServletTester tester; - -@@ -128,22 +126,8 @@ public class MetricsServletTest extends AbstractServletTest { - assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); - assertThat(response.getContent()) - .isEqualTo( -- callbackParamVal -- + "({" -- + "\"version\":\"4.0.0\"," -- + "\"gauges\":{" -- + "\"g1\":{\"value\":100}" -- + "}," -- + "\"counters\":{" -- + "\"c\":{\"count\":1}" -- + "}," -- + "\"histograms\":{" -- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -- + "}," -- + "\"meters\":{" -- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -- + "}" -- + "})"); -+ "%s({\"version\":\"4.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", -+ callbackParamVal); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -223,47 +207,47 @@ public class MetricsServletTest extends AbstractServletTest { - @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() - throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = - new io.dropwizard.metrics.servlets.MetricsServlet(metricRegistry); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -+ verify(servletConfig).getServletContext(); - verify(servletContext, never()) -- .getAttribute(eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)); -+ .getAttribute(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY); - } - - @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute( -- eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY))) -+ io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)) - .thenReturn(metricRegistry); - - final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = - new io.dropwizard.metrics.servlets.MetricsServlet(null); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)) -- .getAttribute(eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext) -+ .getAttribute(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY); - } - - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute( -- eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY))) -+ io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); - - final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = new MetricsServlet(null); ---- a/metrics-jcache/src/main/java/com/codahale/metrics/jcache/JCacheGaugeSet.java -+++ b/metrics-jcache/src/main/java/com/codahale/metrics/jcache/JCacheGaugeSet.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics.jcache; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Metric; - import com.codahale.metrics.MetricSet; -@@ -8,7 +9,6 @@ import com.codahale.metrics.jvm.JmxAttributeGauge; - import java.lang.management.ManagementFactory; - import java.lang.reflect.Method; - import java.util.ArrayList; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Locale; -@@ -51,7 +51,7 @@ public class JCacheGaugeSet implements MetricSet { - } - } - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - - private Set getCacheBeans() { ---- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java -+++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java -@@ -71,18 +71,18 @@ public class JCacheGaugeSetTest { - assertThat( - (Float) - registry.getGauges().get("jcache.statistics.myCache.average-get-time").getValue()) -- .isGreaterThan(0.0f); -+ .isPositive(); - assertThat( - (Float) - registry.getGauges().get("jcache.statistics.myCache.average-put-time").getValue()) -- .isGreaterThan(0.0f); -+ .isPositive(); - assertThat( - (Float) - registry - .getGauges() - .get("jcache.statistics.myCache.average-remove-time") - .getValue()) -- .isGreaterThan(0.0f); -+ .isPositive(); - } - - @After ---- a/metrics-jdbi/src/main/java/com/codahale/metrics/jdbi/strategies/NameStrategies.java -+++ b/metrics-jdbi/src/main/java/com/codahale/metrics/jdbi/strategies/NameStrategies.java -@@ -45,7 +45,7 @@ public final class NameStrategies { - public String getStatementName(StatementContext statementContext) { - final String rawSql = statementContext.getRawSql(); - -- if (rawSql == null || rawSql.length() == 0) { -+ if (rawSql == null || rawSql.isEmpty()) { - return EMPTY_SQL; - } - return null; ---- a/metrics-jdbi/src/test/java/com/codahale/metrics/jdbi/InstrumentedTimingCollectorTest.java -+++ b/metrics-jdbi/src/test/java/com/codahale/metrics/jdbi/InstrumentedTimingCollectorTest.java -@@ -23,7 +23,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass()).when(ctx).getSqlObjectType(); - doReturn(getClass().getMethod("updatesTimerForSqlObjects")).when(ctx).getSqlObjectMethod(); -@@ -42,7 +42,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass()).when(ctx).getSqlObjectType(); - -@@ -60,7 +60,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - - collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); -@@ -77,7 +77,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - - collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); - -@@ -93,7 +93,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("don't know what it is but it's not SQL").when(ctx).getRawSql(); - - collector.collect(TimeUnit.SECONDS.toNanos(3), ctx); -@@ -110,7 +110,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass().getName()).when(ctx).getAttribute(NameStrategies.STATEMENT_CLASS); - doReturn("updatesTimerForContextClass").when(ctx).getAttribute(NameStrategies.STATEMENT_NAME); -@@ -129,7 +129,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn("foo/bar.stg").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); - doReturn("updatesTimerForTemplateFile").when(ctx).getAttribute(NameStrategies.STATEMENT_NAME); -@@ -148,7 +148,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn("my-group").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); - doReturn("updatesTimerForContextGroupAndName") -@@ -169,7 +169,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn("my-group").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); - doReturn("my-type").when(ctx).getAttribute(NameStrategies.STATEMENT_TYPE); -@@ -192,7 +192,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new ShortNameStrategy("jdbi"); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass()).when(ctx).getSqlObjectType(); - doReturn(getClass().getMethod("updatesTimerForShortSqlObjectStrategy")) -@@ -215,7 +215,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new ShortNameStrategy("jdbi"); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass().getName()).when(ctx).getAttribute(NameStrategies.STATEMENT_CLASS); - doReturn("updatesTimerForShortContextClassStrategy") ---- a/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/InstrumentedSqlLoggerTest.java -+++ b/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/InstrumentedSqlLoggerTest.java -@@ -16,12 +16,12 @@ import org.junit.Test; - public class InstrumentedSqlLoggerTest { - @Test - public void logsExecutionTime() { -- final MetricRegistry mockRegistry = mock(MetricRegistry.class); -- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); -+ final MetricRegistry mockRegistry = mock(); -+ final StatementNameStrategy mockNameStrategy = mock(); - final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); - -- final StatementContext mockContext = mock(StatementContext.class); -- final Timer mockTimer = mock(Timer.class); -+ final StatementContext mockContext = mock(); -+ final Timer mockTimer = mock(); - - final String statementName = "my-fake-name"; - final long fakeElapsed = 1234L; -@@ -38,12 +38,12 @@ public class InstrumentedSqlLoggerTest { - - @Test - public void logsExceptionTime() { -- final MetricRegistry mockRegistry = mock(MetricRegistry.class); -- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); -+ final MetricRegistry mockRegistry = mock(); -+ final StatementNameStrategy mockNameStrategy = mock(); - final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); - -- final StatementContext mockContext = mock(StatementContext.class); -- final Timer mockTimer = mock(Timer.class); -+ final StatementContext mockContext = mock(); -+ final Timer mockTimer = mock(); - - final String statementName = "my-fake-name"; - final long fakeElapsed = 1234L; ---- a/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/AbstractStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/AbstractStrategyTest.java -@@ -10,7 +10,7 @@ import org.junit.Before; - public class AbstractStrategyTest { - - MetricRegistry registry = new MetricRegistry(); -- StatementContext ctx = mock(StatementContext.class); -+ StatementContext ctx = mock(); - - @Before - public void setUp() throws Exception { ---- a/metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.ExponentiallyDecayingReservoir; -@@ -19,7 +22,6 @@ import com.codahale.metrics.annotation.Timed; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener - this.level = responseMetered.level(); - this.meters = - COARSE_METER_LEVELS.contains(level) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(metricName, "1xx-responses")), // 1xx - registry.meter(name(metricName, "2xx-responses")), // 2xx -@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener - registry.meter(name(metricName, "4xx-responses")), // 4xx - registry.meter(name(metricName, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - this.responseCodeMeters = -- DETAILED_METER_LEVELS.contains(level) -- ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); - this.metricRegistry = registry; - } - -@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener - : null; - - if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) -+ if (metric.cause.isInstance(event.getException()) - || (event.getException().getCause() != null -- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -+ && metric.cause.isInstance(event.getException().getCause()))) { - metric.meter.mark(); - } - } -@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener - - @Override - public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = -- new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); - } - - private T getClassLevelAnnotation( -@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener - @Override - public int hashCode() { - int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -+ return 31 * result + method.hashCode(); - } - } - } ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonFilterMetricsJerseyTest.java -@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry, testClock, true)); - config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -+ return config.register(new InstrumentedFilteredResource(testClock)); - } - - @Before ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); - } - - @Test -@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - assertThat(target("subresource/exception-metered").request().get(String.class)) - .isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("subresource/exception-metered") ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsJerseyTest.java -@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -+ return config.register(InstrumentedResource.class); - } - - @Test -@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -87,12 +85,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(0); - } - - @Test -@@ -107,9 +105,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - registry.meter( - name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); - assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); - assertThat( - target("response-metered-detailed") -@@ -119,9 +117,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - .getStatus()) - .isEqualTo(201); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); - } - - @Test -@@ -131,12 +129,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - - @Test ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceMeteredPerClass.class); - } - - @Test ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - - config = config.register(new MetricsFeature(this.registry)); - config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -+ return config.register(new TestExceptionMapper()); - } - - @Test -@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - } ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsTimedPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceTimedPerClass.class); - } - - @Test ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedFilteredResource.java -@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { - } - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick++; - return "yay"; - } - - @GET -- @Timed(name = "fancyName") - @Path("/named") -+ @Timed(name = "fancyName") - public String named() { - testClock.tick++; - return "fancy"; - } - - @GET -- @Timed(name = "absolutelyFancy", absolute = true) - @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) - public String absolute() { - testClock.tick++; - return "absolute"; -@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { - public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick += 2; - return "yay"; ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedResource.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedResource.java -@@ -21,8 +21,8 @@ import javax.ws.rs.core.Response; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -@@ -34,8 +34,8 @@ public class InstrumentedResource { - return "woo"; - } - -- @GET - @ExceptionMetered(cause = IOException.class) -+ @GET - @Path("/exception-metered") - public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) - throws IOException { -@@ -46,24 +46,24 @@ public class InstrumentedResource { - } - - @GET -- @ResponseMetered(level = DETAILED) - @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) - public Response responseMeteredDetailed( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = COARSE) - @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) - public Response responseMeteredCoarse( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = ALL) - @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) - public Response responseMeteredAll( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedSubResource.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedSubResource.java -@@ -10,8 +10,8 @@ import javax.ws.rs.core.MediaType; - public class InstrumentedSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } ---- a/metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.ExponentiallyDecayingReservoir; -@@ -21,7 +24,6 @@ import jakarta.ws.rs.ext.Provider; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener - this.level = responseMetered.level(); - this.meters = - COARSE_METER_LEVELS.contains(level) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(metricName, "1xx-responses")), // 1xx - registry.meter(name(metricName, "2xx-responses")), // 2xx -@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener - registry.meter(name(metricName, "4xx-responses")), // 4xx - registry.meter(name(metricName, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - this.responseCodeMeters = -- DETAILED_METER_LEVELS.contains(level) -- ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); - this.metricRegistry = registry; - } - -@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener - : null; - - if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) -+ if (metric.cause.isInstance(event.getException()) - || (event.getException().getCause() != null -- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -+ && metric.cause.isInstance(event.getException().getCause()))) { - metric.meter.mark(); - } - } -@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener - - @Override - public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = -- new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); - } - - private T getClassLevelAnnotation( -@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener - @Override - public int hashCode() { - int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -+ return 31 * result + method.hashCode(); - } - } - } ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonFilterMetricsJerseyTest.java -@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry, testClock, true)); - config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -+ return config.register(new InstrumentedFilteredResource(testClock)); - } - - @Before ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); - } - - @Test -@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - assertThat(target("subresource/exception-metered").request().get(String.class)) - .isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("subresource/exception-metered") ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsJerseyTest.java -@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -+ return config.register(InstrumentedResource.class); - } - - @Test -@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -92,9 +90,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - registry.meter( - name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); - assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); - assertThat( - target("response-metered-detailed") -@@ -104,9 +102,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - .getStatus()) - .isEqualTo(201); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); - } - - @Test -@@ -116,12 +114,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - - @Test ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceMeteredPerClass.class); - } - - @Test ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - - config = config.register(new MetricsFeature(this.registry)); - config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -+ return config.register(new TestExceptionMapper()); - } - - @Test -@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - } ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsTimedPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceTimedPerClass.class); - } - - @Test ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedFilteredResource.java -@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { - } - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick++; - return "yay"; - } - - @GET -- @Timed(name = "fancyName") - @Path("/named") -+ @Timed(name = "fancyName") - public String named() { - testClock.tick++; - return "fancy"; - } - - @GET -- @Timed(name = "absolutelyFancy", absolute = true) - @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) - public String absolute() { - testClock.tick++; - return "absolute"; -@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { - public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick += 2; - return "yay"; ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedResource.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedResource.java -@@ -21,8 +21,8 @@ import java.io.IOException; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -@@ -34,8 +34,8 @@ public class InstrumentedResource { - return "woo"; - } - -- @GET - @ExceptionMetered(cause = IOException.class) -+ @GET - @Path("/exception-metered") - public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) - throws IOException { -@@ -46,24 +46,24 @@ public class InstrumentedResource { - } - - @GET -- @ResponseMetered(level = DETAILED) - @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) - public Response responseMeteredDetailed( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = COARSE) - @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) - public Response responseMeteredCoarse( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = ALL) - @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) - public Response responseMeteredAll( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedSubResource.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedSubResource.java -@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; - public class InstrumentedSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } ---- a/metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.ExponentiallyDecayingReservoir; -@@ -21,7 +24,6 @@ import jakarta.ws.rs.ext.Provider; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener - this.level = responseMetered.level(); - this.meters = - COARSE_METER_LEVELS.contains(level) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(metricName, "1xx-responses")), // 1xx - registry.meter(name(metricName, "2xx-responses")), // 2xx -@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener - registry.meter(name(metricName, "4xx-responses")), // 4xx - registry.meter(name(metricName, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - this.responseCodeMeters = -- DETAILED_METER_LEVELS.contains(level) -- ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); - this.metricRegistry = registry; - } - -@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener - : null; - - if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) -+ if (metric.cause.isInstance(event.getException()) - || (event.getException().getCause() != null -- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -+ && metric.cause.isInstance(event.getException().getCause()))) { - metric.meter.mark(); - } - } -@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener - - @Override - public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = -- new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); - } - - private T getClassLevelAnnotation( -@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener - @Override - public int hashCode() { - int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -+ return 31 * result + method.hashCode(); - } - } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonFilterMetricsJerseyTest.java -@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry, testClock, true)); - config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -+ return config.register(new InstrumentedFilteredResource(testClock)); - } - - @Before ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); - } - - @Test -@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - assertThat(target("subresource/exception-metered").request().get(String.class)) - .isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("subresource/exception-metered") ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsJerseyTest.java -@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -+ return config.register(InstrumentedResource.class); - } - - @Test -@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -87,12 +85,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(0); - } - - @Test -@@ -107,9 +105,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - registry.meter( - name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); - assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); - assertThat( - target("response-metered-detailed") -@@ -119,9 +117,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - .getStatus()) - .isEqualTo(201); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); - } - - @Test -@@ -131,12 +129,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - - @Test ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceMeteredPerClass.class); - } - - @Test ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - - config = config.register(new MetricsFeature(this.registry)); - config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -+ return config.register(new TestExceptionMapper()); - } - - @Test -@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsTimedPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceTimedPerClass.class); - } - - @Test ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedFilteredResource.java -@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { - } - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick++; - return "yay"; - } - - @GET -- @Timed(name = "fancyName") - @Path("/named") -+ @Timed(name = "fancyName") - public String named() { - testClock.tick++; - return "fancy"; - } - - @GET -- @Timed(name = "absolutelyFancy", absolute = true) - @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) - public String absolute() { - testClock.tick++; - return "absolute"; -@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { - public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick += 2; - return "yay"; ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedResource.java -@@ -21,8 +21,8 @@ import java.io.IOException; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -@@ -34,8 +34,8 @@ public class InstrumentedResource { - return "woo"; - } - -- @GET - @ExceptionMetered(cause = IOException.class) -+ @GET - @Path("/exception-metered") - public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) - throws IOException { -@@ -46,24 +46,24 @@ public class InstrumentedResource { - } - - @GET -- @ResponseMetered(level = DETAILED) - @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) - public Response responseMeteredDetailed( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = COARSE) - @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) - public Response responseMeteredCoarse( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = ALL) - @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) - public Response responseMeteredAll( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedSubResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedSubResource.java -@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; - public class InstrumentedSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -13,7 +16,6 @@ import com.codahale.metrics.Timer; - import com.codahale.metrics.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -172,10 +174,10 @@ public class InstrumentedHandler extends HandlerWrapper { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx - metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx -@@ -183,7 +185,7 @@ public class InstrumentedHandler extends HandlerWrapper { - metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx - metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); - this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -14,7 +17,6 @@ import com.codahale.metrics.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(prefix, "1xx-responses")), // 1xx - registry.meter(name(prefix, "2xx-responses")), // 2xx -@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { - registry.meter(name(prefix, "4xx-responses")), // 4xx - registry.meter(name(prefix, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); - this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java -@@ -1,12 +1,12 @@ - package io.dropwizard.metrics.jetty10; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatCode; - - import com.codahale.metrics.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.TimeUnit; - import javax.servlet.AsyncContext; - import javax.servlet.ServletException; -@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { - assertThatCode(handler::doStop).doesNotThrowAnyException(); - } - -- @Test - @Ignore("flaky on virtual machines") -+ @Test - public void responseTimesAreRecordedForAsyncResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/async")); -@@ -126,15 +126,14 @@ public class InstrumentedHandlerTest { - } - - private void assertResponseTimesValid() { -- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) -- .isGreaterThan(0L); -+ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); - - assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - - assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - } - -@@ -197,7 +196,7 @@ public class InstrumentedHandlerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async\n".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListenerTest.java -@@ -1,11 +1,11 @@ - package io.dropwizard.metrics.jetty10; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - - import com.codahale.metrics.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import javax.servlet.AsyncContext; - import javax.servlet.ServletOutputStream; - import javax.servlet.WriteListener; -@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -172,10 +174,10 @@ public class InstrumentedHandler extends HandlerWrapper { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx - metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx -@@ -183,7 +185,7 @@ public class InstrumentedHandler extends HandlerWrapper { - metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx - metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); - this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(prefix, "1xx-responses")), // 1xx - registry.meter(name(prefix, "2xx-responses")), // 2xx -@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { - registry.meter(name(prefix, "4xx-responses")), // 4xx - registry.meter(name(prefix, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); - this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics.jetty11; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatCode; - -@@ -12,7 +13,6 @@ import jakarta.servlet.WriteListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; -@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { - assertThatCode(handler::doStop).doesNotThrowAnyException(); - } - -- @Test - @Ignore("flaky on virtual machines") -+ @Test - public void responseTimesAreRecordedForAsyncResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/async")); -@@ -126,17 +126,15 @@ public class InstrumentedHandlerTest { - } - - private void assertResponseTimesValid() { -- assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()) -- .isGreaterThan(0L); -- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) -- .isGreaterThan(0L); -+ assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()).isPositive(); -+ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); - - assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - - assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - } - -@@ -199,7 +197,7 @@ public class InstrumentedHandlerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async\n".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListenerTest.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics.jetty11; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - - import com.codahale.metrics.MetricRegistry; -@@ -10,7 +11,6 @@ import jakarta.servlet.WriteListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; - import org.eclipse.jetty.server.Request; -@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java -+++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -13,7 +16,6 @@ import com.codahale.metrics.Timer; - import com.codahale.metrics.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -180,10 +182,10 @@ public class InstrumentedHandler extends HandlerWrapper { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx - metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx -@@ -191,7 +193,7 @@ public class InstrumentedHandler extends HandlerWrapper { - metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx - metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); - this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); ---- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -14,7 +17,6 @@ import com.codahale.metrics.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(prefix, "1xx-responses")), // 1xx - registry.meter(name(prefix, "2xx-responses")), // 2xx -@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { - registry.meter(name(prefix, "4xx-responses")), // 4xx - registry.meter(name(prefix, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); - this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); ---- a/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java -+++ b/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java -@@ -1,12 +1,12 @@ - package com.codahale.metrics.jetty9; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatCode; - - import com.codahale.metrics.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.TimeUnit; - import javax.servlet.AsyncContext; - import javax.servlet.ServletException; -@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { - assertThatCode(handler::doStop).doesNotThrowAnyException(); - } - -- @Test - @Ignore("flaky on virtual machines") -+ @Test - public void responseTimesAreRecordedForAsyncResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/async")); -@@ -126,17 +126,15 @@ public class InstrumentedHandlerTest { - } - - private void assertResponseTimesValid() { -- assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()) -- .isGreaterThan(0L); -- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) -- .isGreaterThan(0L); -+ assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()).isPositive(); -+ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); - - assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - - assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - } - -@@ -199,7 +197,7 @@ public class InstrumentedHandlerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async\n".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListenerTest.java -@@ -1,11 +1,11 @@ - package com.codahale.metrics.jetty9; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - - import com.codahale.metrics.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import javax.servlet.AsyncContext; - import javax.servlet.ServletOutputStream; - import javax.servlet.WriteListener; -@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java -+++ b/metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java -@@ -36,9 +36,8 @@ public class DefaultObjectNameFactory implements ObjectNameFactory { - || shouldQuote(objectName.getKeyProperty("type"))) { - properties.put("type", ObjectName.quote(type)); - } -- objectName = new ObjectName(domain, properties); -+ return new ObjectName(domain, properties); - -- return objectName; - } catch (MalformedObjectNameException e) { - try { - return new ObjectName(domain, "name", ObjectName.quote(name)); ---- a/metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java -+++ b/metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java -@@ -1,5 +1,8 @@ - package com.codahale.metrics.jmx; - -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableMap; -+ - import com.codahale.metrics.Counter; - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Histogram; -@@ -12,7 +15,6 @@ import com.codahale.metrics.Reporter; - import com.codahale.metrics.Timer; - import java.io.Closeable; - import java.lang.management.ManagementFactory; --import java.util.Collections; - import java.util.Locale; - import java.util.Map; - import java.util.concurrent.ConcurrentHashMap; -@@ -60,8 +62,8 @@ public class JmxReporter implements Reporter, Closeable { - this.durationUnit = TimeUnit.MILLISECONDS; - this.domain = "metrics"; - this.objectNameFactory = new DefaultObjectNameFactory(); -- this.specificDurationUnits = Collections.emptyMap(); -- this.specificRateUnits = Collections.emptyMap(); -+ this.specificDurationUnits = emptyMap(); -+ this.specificRateUnits = emptyMap(); - } - - /** -@@ -128,7 +130,7 @@ public class JmxReporter implements Reporter, Closeable { - * @return {@code this} - */ - public Builder specificDurationUnits(Map specificDurationUnits) { -- this.specificDurationUnits = Collections.unmodifiableMap(specificDurationUnits); -+ this.specificDurationUnits = unmodifiableMap(specificDurationUnits); - return this; - } - -@@ -139,7 +141,7 @@ public class JmxReporter implements Reporter, Closeable { - * @return {@code this} - */ - public Builder specificRateUnits(Map specificRateUnits) { -- this.specificRateUnits = Collections.unmodifiableMap(specificRateUnits); -+ this.specificRateUnits = unmodifiableMap(specificRateUnits); - return this; - } - ---- a/metrics-jmx/src/test/java/com/codahale/metrics/jmx/JmxReporterTest.java -+++ b/metrics-jmx/src/test/java/com/codahale/metrics/jmx/JmxReporterTest.java -@@ -1,5 +1,6 @@ - package com.codahale.metrics.jmx; - -+import static java.util.UUID.randomUUID; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -@@ -20,7 +21,6 @@ import com.codahale.metrics.Timer; - import java.lang.management.ManagementFactory; - import java.util.SortedMap; - import java.util.TreeMap; --import java.util.UUID; - import java.util.concurrent.TimeUnit; - import javax.management.Attribute; - import javax.management.AttributeList; -@@ -36,7 +36,7 @@ import org.junit.Test; - @SuppressWarnings("rawtypes") - public class JmxReporterTest { - private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); -- private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); -+ private final String name = randomUUID().toString().replaceAll("[{\\-}]", ""); - private final MetricRegistry registry = new MetricRegistry(); - - private final JmxReporter reporter = -@@ -48,12 +48,12 @@ public class JmxReporterTest { - .filter(MetricFilter.ALL) - .build(); - -- private final Gauge gauge = mock(Gauge.class); -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -- private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); -+ private final Gauge gauge = mock(); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); -+ private final ObjectNameFactory mockObjectNameFactory = mock(); - private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); - - @Before -@@ -64,7 +64,7 @@ public class JmxReporterTest { - - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot hSnapshot = mock(Snapshot.class); -+ final Snapshot hSnapshot = mock(); - when(hSnapshot.getMax()).thenReturn(2L); - when(hSnapshot.getMean()).thenReturn(3.0); - when(hSnapshot.getMin()).thenReturn(4L); -@@ -91,7 +91,7 @@ public class JmxReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot tSnapshot = mock(Snapshot.class); -+ final Snapshot tSnapshot = mock(); - when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -274,7 +274,7 @@ public class JmxReporterTest { - - @Test - public void objectNameModifyingMBeanServer() throws Exception { -- MBeanServer mockedMBeanServer = mock(MBeanServer.class); -+ MBeanServer mockedMBeanServer = mock(); - - // overwrite the objectName - when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))) ---- a/metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java -+++ b/metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java -@@ -1,5 +1,7 @@ - package com.codahale.metrics.json; - -+import static java.util.Collections.singletonList; -+ - import com.codahale.metrics.health.HealthCheck; - import com.fasterxml.jackson.core.JsonGenerator; - import com.fasterxml.jackson.core.Version; -@@ -8,7 +10,6 @@ import com.fasterxml.jackson.databind.SerializerProvider; - import com.fasterxml.jackson.databind.module.SimpleSerializers; - import com.fasterxml.jackson.databind.ser.std.StdSerializer; - import java.io.IOException; --import java.util.Collections; - import java.util.Map; - - public class HealthCheckModule extends Module { -@@ -79,7 +80,6 @@ public class HealthCheckModule extends Module { - - @Override - public void setupModule(SetupContext context) { -- context.addSerializers( -- new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer()))); -+ context.addSerializers(new SimpleSerializers(singletonList(new HealthCheckResultSerializer()))); - } - } ---- a/metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java -+++ b/metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java -@@ -17,8 +17,7 @@ public class HealthCheckModuleTest { - public void serializesAHealthyResult() throws Exception { - HealthCheck.Result result = HealthCheck.Result.healthy(); - assertThat(mapper.writeValueAsString(result)) -- .isEqualTo( -- "{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); -+ .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp()); - } - - @Test -@@ -26,14 +25,8 @@ public class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":true," -- + "\"message\":\"yay for me\"," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -41,14 +34,8 @@ public class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":false," -- + "\"message\":\"boo\"," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -60,19 +47,8 @@ public class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.unhealthy(e); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":false," -- + "\"message\":\"oh no\"," -- + "\"error\":{" -- + "\"type\":\"java.lang.RuntimeException\"," -- + "\"message\":\"oh no\"," -- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" -- + "}," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -88,24 +64,8 @@ public class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.unhealthy(b); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":false," -- + "\"message\":\"oh well\"," -- + "\"error\":{" -- + "\"type\":\"java.lang.RuntimeException\"," -- + "\"message\":\"oh well\"," -- + "\"stack\":[\"Blah.blee(Blah.java:150)\"]," -- + "\"cause\":{" -- + "\"type\":\"java.lang.RuntimeException\"," -- + "\"message\":\"oh no\"," -- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" -- + "}" -- + "}," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -129,23 +89,7 @@ public class HealthCheckModuleTest { - - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":true," -- + "\"duration\":0," -- + "\"boolean\":true," -- + "\"integer\":1," -- + "\"long\":2," -- + "\"float\":3.546," -- + "\"double\":4.567," -- + "\"BigInteger\":12345," -- + "\"BigDecimal\":12345.56789," -- + "\"String\":\"string\"," -- + "\"complex\":{" -- + "\"field\":\"value\"" -- + "}," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - } ---- a/metrics-json/src/test/java/com/codahale/metrics/json/MetricsModuleTest.java -+++ b/metrics-json/src/test/java/com/codahale/metrics/json/MetricsModuleTest.java -@@ -42,7 +42,7 @@ public class MetricsModuleTest { - - @Test - public void serializesCounters() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - assertThat(mapper.writeValueAsString(counter)).isEqualTo("{\"count\":100}"); -@@ -50,10 +50,10 @@ public class MetricsModuleTest { - - @Test - public void serializesHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -107,7 +107,7 @@ public class MetricsModuleTest { - - @Test - public void serializesMeters() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(5.0); -@@ -127,14 +127,14 @@ public class MetricsModuleTest { - - @Test - public void serializesTimers() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/BufferPoolMetricSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/BufferPoolMetricSet.java -@@ -1,10 +1,10 @@ - package com.codahale.metrics.jvm; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Metric; - import com.codahale.metrics.MetricSet; --import java.util.Collections; - import java.util.HashMap; - import java.util.Map; - import javax.management.JMException; -@@ -46,6 +46,6 @@ public class BufferPoolMetricSet implements MetricSet { - } - } - } -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/GarbageCollectorMetricSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/GarbageCollectorMetricSet.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics.jvm; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Metric; -@@ -9,7 +10,6 @@ import java.lang.management.GarbageCollectorMXBean; - import java.lang.management.ManagementFactory; - import java.util.ArrayList; - import java.util.Collection; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -43,6 +43,6 @@ public class GarbageCollectorMetricSet implements MetricSet { - gauges.put(name(name, "count"), (Gauge) gc::getCollectionCount); - gauges.put(name(name, "time"), (Gauge) gc::getCollectionTime); - } -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/JvmAttributeGaugeSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/JvmAttributeGaugeSet.java -@@ -1,11 +1,12 @@ - package com.codahale.metrics.jvm; - -+import static java.util.Collections.unmodifiableMap; -+ - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Metric; - import com.codahale.metrics.MetricSet; - import java.lang.management.ManagementFactory; - import java.lang.management.RuntimeMXBean; --import java.util.Collections; - import java.util.HashMap; - import java.util.Locale; - import java.util.Map; -@@ -46,6 +47,6 @@ public class JvmAttributeGaugeSet implements MetricSet { - runtime.getSpecVersion())); - gauges.put("uptime", (Gauge) runtime::getUptime); - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics.jvm; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Metric; -@@ -12,7 +13,6 @@ import java.lang.management.MemoryPoolMXBean; - import java.lang.management.MemoryUsage; - import java.util.ArrayList; - import java.util.Collection; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -122,6 +122,6 @@ public class MemoryUsageGaugeSet implements MetricSet { - gauges.put(name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); - } - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java -@@ -1,9 +1,11 @@ - package com.codahale.metrics.jvm; - -+import static java.util.Collections.emptySet; -+import static java.util.Collections.unmodifiableSet; -+ - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; --import java.util.Collections; - import java.util.HashSet; - import java.util.Set; - -@@ -40,19 +42,16 @@ public class ThreadDeadlockDetector { - for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { - final StringBuilder stackTrace = new StringBuilder(); - for (StackTraceElement element : info.getStackTrace()) { -- stackTrace.append("\t at ").append(element.toString()).append(String.format("%n")); -+ stackTrace.append("\t at ").append(element).append(String.format("%n")); - } - - deadlocks.add( - String.format( - "%s locked on %s (owned by %s):%n%s", -- info.getThreadName(), -- info.getLockName(), -- info.getLockOwnerName(), -- stackTrace.toString())); -+ info.getThreadName(), info.getLockName(), info.getLockOwnerName(), stackTrace)); - } -- return Collections.unmodifiableSet(deadlocks); -+ return unmodifiableSet(deadlocks); - } -- return Collections.emptySet(); -+ return emptySet(); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics.jvm; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Metric; -@@ -8,7 +9,6 @@ import com.codahale.metrics.MetricSet; - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; --import java.util.Collections; - import java.util.HashMap; - import java.util.Map; - import java.util.Set; -@@ -56,7 +56,7 @@ public class ThreadStatesGaugeSet implements MetricSet { - "deadlock.count", (Gauge) () -> deadlockDetector.getDeadlockedThreads().size()); - gauges.put("deadlocks", (Gauge>) deadlockDetector::getDeadlockedThreads); - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - - private int getThreadCount(Thread.State state) { ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/BufferPoolMetricSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/BufferPoolMetricSetTest.java -@@ -13,7 +13,7 @@ import org.junit.Test; - - @SuppressWarnings("rawtypes") - public class BufferPoolMetricSetTest { -- private final MBeanServer mBeanServer = mock(MBeanServer.class); -+ private final MBeanServer mBeanServer = mock(); - private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); - - private ObjectName mapped; ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ClassLoadingGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ClassLoadingGaugeSetTest.java -@@ -12,7 +12,7 @@ import org.junit.Test; - @SuppressWarnings("rawtypes") - public class ClassLoadingGaugeSetTest { - -- private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); -+ private final ClassLoadingMXBean cl = mock(); - private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); - - @Before ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java -@@ -12,10 +12,10 @@ public class CpuTimeClockTest { - public void cpuTimeClock() { - final CpuTimeClock clock = new CpuTimeClock(); - -- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(250D)); -+ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(250D)); - - assertThat((double) clock.getTick()) -- .isEqualTo( -+ .isCloseTo( - ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(), offset(1000000.0)); - } - } ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeTest.java -@@ -13,7 +13,7 @@ import org.junit.Test; - - @SuppressWarnings("UnusedDeclaration") - public class FileDescriptorRatioGaugeTest { -- private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); -+ private final UnixOperatingSystemMXBean os = mock(); - - private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); - -@@ -33,9 +33,7 @@ public class FileDescriptorRatioGaugeTest { - OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); - assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); - -- assertThat(new FileDescriptorRatioGauge().getValue()) -- .isGreaterThanOrEqualTo(0.0) -- .isLessThanOrEqualTo(1.0); -+ assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative().isLessThanOrEqualTo(1.0); - } - - @Test ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java -@@ -1,20 +1,20 @@ - package com.codahale.metrics.jvm; - -+import static java.util.Collections.singletonList; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; - - import com.codahale.metrics.Gauge; - import java.lang.management.GarbageCollectorMXBean; --import java.util.Collections; - import org.junit.Before; - import org.junit.Test; - - @SuppressWarnings("unchecked") - public class GarbageCollectorMetricSetTest { -- private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); -+ private final GarbageCollectorMXBean gc = mock(); - private final GarbageCollectorMetricSet metrics = -- new GarbageCollectorMetricSet(Collections.singletonList(gc)); -+ new GarbageCollectorMetricSet(singletonList(gc)); - - @Before - public void setUp() { -@@ -42,6 +42,6 @@ public class GarbageCollectorMetricSetTest { - - @Test - public void autoDiscoversGCs() { -- assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()).isNotEmpty(); -+ assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty(); - } - } ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JmxAttributeGaugeTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JmxAttributeGaugeTest.java -@@ -53,7 +53,7 @@ public class JmxAttributeGaugeTest { - JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); - - assertThat(gauge.getValue()).isInstanceOf(Integer.class); -- assertThat((Integer) gauge.getValue()).isGreaterThan(0); -+ assertThat((Integer) gauge.getValue()).isPositive(); - } - - @Test ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JvmAttributeGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JvmAttributeGaugeSetTest.java -@@ -11,7 +11,7 @@ import org.junit.Test; - - @SuppressWarnings("unchecked") - public class JvmAttributeGaugeSetTest { -- private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); -+ private final RuntimeMXBean runtime = mock(); - private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); - - @Before ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/MemoryUsageGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/MemoryUsageGaugeSetTest.java -@@ -14,14 +14,14 @@ import org.junit.Test; - - @SuppressWarnings("rawtypes") - public class MemoryUsageGaugeSetTest { -- private final MemoryUsage heap = mock(MemoryUsage.class); -- private final MemoryUsage nonHeap = mock(MemoryUsage.class); -- private final MemoryUsage pool = mock(MemoryUsage.class); -- private final MemoryUsage weirdPool = mock(MemoryUsage.class); -- private final MemoryUsage weirdCollection = mock(MemoryUsage.class); -- private final MemoryMXBean mxBean = mock(MemoryMXBean.class); -- private final MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); -- private final MemoryPoolMXBean weirdMemoryPool = mock(MemoryPoolMXBean.class); -+ private final MemoryUsage heap = mock(); -+ private final MemoryUsage nonHeap = mock(); -+ private final MemoryUsage pool = mock(); -+ private final MemoryUsage weirdPool = mock(); -+ private final MemoryUsage weirdCollection = mock(); -+ private final MemoryMXBean mxBean = mock(); -+ private final MemoryPoolMXBean memoryPool = mock(); -+ private final MemoryPoolMXBean weirdMemoryPool = mock(); - - private final MemoryUsageGaugeSet gauges = - new MemoryUsageGaugeSet(mxBean, Arrays.asList(memoryPool, weirdMemoryPool)); -@@ -262,6 +262,6 @@ public class MemoryUsageGaugeSetTest { - - @Test - public void autoDetectsMemoryUsageBeanAndMemoryPools() { -- assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()).isNotEmpty(); -+ assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty(); - } - } ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDeadlockDetectorTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDeadlockDetectorTest.java -@@ -12,7 +12,7 @@ import java.util.Locale; - import org.junit.Test; - - public class ThreadDeadlockDetectorTest { -- private final ThreadMXBean threads = mock(ThreadMXBean.class); -+ private final ThreadMXBean threads = mock(); - private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); - - @Test -@@ -24,7 +24,7 @@ public class ThreadDeadlockDetectorTest { - - @Test - public void returnsASetOfThreadsIfAnyAreDeadlocked() { -- final ThreadInfo thread1 = mock(ThreadInfo.class); -+ final ThreadInfo thread1 = mock(); - when(thread1.getThreadName()).thenReturn("thread1"); - when(thread1.getLockName()).thenReturn("lock2"); - when(thread1.getLockOwnerName()).thenReturn("thread2"); -@@ -35,7 +35,7 @@ public class ThreadDeadlockDetectorTest { - new StackTraceElement("Blah", "blee", "Blah.java", 100) - }); - -- final ThreadInfo thread2 = mock(ThreadInfo.class); -+ final ThreadInfo thread2 = mock(); - when(thread2.getThreadName()).thenReturn("thread2"); - when(thread2.getLockName()).thenReturn("lock1"); - when(thread2.getLockOwnerName()).thenReturn("thread1"); ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java -@@ -15,10 +15,10 @@ import org.junit.Test; - // TODO: 3/12/13 -- improve test coverage for ThreadDump - - public class ThreadDumpTest { -- private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); -+ private final ThreadMXBean threadMXBean = mock(); - private final ThreadDump threadDump = new ThreadDump(threadMXBean); - -- private final ThreadInfo runnable = mock(ThreadInfo.class); -+ private final ThreadInfo runnable = mock(); - - @Before - public void setUp() { -@@ -39,8 +39,8 @@ public class ThreadDumpTest { - final ByteArrayOutputStream output = new ByteArrayOutputStream(); - threadDump.dump(output); - -- assertThat(output.toString()) -- .isEqualTo( -+ assertThat(output) -+ .hasToString( - String.format( - "\"runnable\" id=100 state=RUNNABLE%n" - + " at Blah.blee(Blah.java:100)%n" ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadStatesGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadStatesGaugeSetTest.java -@@ -13,17 +13,17 @@ import org.junit.Before; - import org.junit.Test; - - public class ThreadStatesGaugeSetTest { -- private final ThreadMXBean threads = mock(ThreadMXBean.class); -- private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -+ private final ThreadMXBean threads = mock(); -+ private final ThreadDeadlockDetector detector = mock(); - private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); - private final long[] ids = new long[] {1, 2, 3}; - -- private final ThreadInfo newThread = mock(ThreadInfo.class); -- private final ThreadInfo runnableThread = mock(ThreadInfo.class); -- private final ThreadInfo blockedThread = mock(ThreadInfo.class); -- private final ThreadInfo waitingThread = mock(ThreadInfo.class); -- private final ThreadInfo timedWaitingThread = mock(ThreadInfo.class); -- private final ThreadInfo terminatedThread = mock(ThreadInfo.class); -+ private final ThreadInfo newThread = mock(); -+ private final ThreadInfo runnableThread = mock(); -+ private final ThreadInfo blockedThread = mock(); -+ private final ThreadInfo waitingThread = mock(); -+ private final ThreadInfo timedWaitingThread = mock(); -+ private final ThreadInfo terminatedThread = mock(); - - private final Set deadlocks = new HashSet<>(); - ---- a/metrics-log4j2/src/test/java/com/codahale/metrics/log4j2/InstrumentedAppenderTest.java -+++ b/metrics-log4j2/src/test/java/com/codahale/metrics/log4j2/InstrumentedAppenderTest.java -@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final LogEvent event = mock(LogEvent.class); -+ private final LogEvent event = mock(); - - @Before - public void setUp() { ---- a/metrics-logback/src/test/java/com/codahale/metrics/logback/InstrumentedAppenderTest.java -+++ b/metrics-logback/src/test/java/com/codahale/metrics/logback/InstrumentedAppenderTest.java -@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ private final ILoggingEvent event = mock(); - - @Before - public void setUp() { ---- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java -+++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java -@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ private final ILoggingEvent event = mock(); - - @Before - public void setUp() { ---- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java -+++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java -@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ private final ILoggingEvent event = mock(); - - @Before - public void setUp() { ---- a/metrics-servlet/src/test/java/com/codahale/metrics/servlet/InstrumentedFilterContextListenerTest.java -+++ b/metrics-servlet/src/test/java/com/codahale/metrics/servlet/InstrumentedFilterContextListenerTest.java -@@ -10,7 +10,7 @@ import javax.servlet.ServletContextEvent; - import org.junit.Test; - - public class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final MetricRegistry registry = mock(); - private final InstrumentedFilterContextListener listener = - new InstrumentedFilterContextListener() { - @Override -@@ -21,9 +21,9 @@ public class InstrumentedFilterContextListenerTest { - - @Test - public void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ final ServletContext context = mock(); - -- final ServletContextEvent event = mock(ServletContextEvent.class); -+ final ServletContextEvent event = mock(); - when(event.getServletContext()).thenReturn(context); - - listener.contextInitialized(event); ---- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java -+++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java -@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); - if (registryAttr instanceof HealthCheckRegistry) { - this.registry = (HealthCheckRegistry) registryAttr; ---- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java -+++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java -@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(METRICS_REGISTRY); - if (registryAttr instanceof MetricRegistry) { - this.registry = (MetricRegistry) registryAttr; ---- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java -+++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java -@@ -3,7 +3,6 @@ package com.codahale.metrics.servlets; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -94,9 +93,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - } - - @Test -@@ -110,9 +108,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - } - - @Test -@@ -168,15 +165,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getContent()) - .isEqualTo( - String.format( -- "{%n" -- + " \"fun\" : {%n" -- + " \"healthy\" : true,%n" -- + " \"message\" : \"foo bar 123\",%n" -- + " \"duration\" : 0,%n" -- + " \"timestamp\" : \"" -- + EXPECTED_TIMESTAMP -- + "\"" -- + "%n }%n}")); -+ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", -+ EXPECTED_TIMESTAMP)); - } - - private static HealthCheck.Result healthyResultWithMessage(String message) { -@@ -198,23 +188,23 @@ public class HealthCheckServletTest extends AbstractServletTest { - @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() - throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -+ verify(servletConfig).getServletContext(); - verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); - } - - @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn(healthCheckRegistry); -@@ -222,15 +212,15 @@ public class HealthCheckServletTest extends AbstractServletTest { - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); - } - - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); -@@ -242,8 +232,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - @Test - public void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn(registry); ---- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletContextListenerTest.java -+++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletContextListenerTest.java -@@ -17,7 +17,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MetricsServletContextListenerTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private final String allowedOrigin = "some.other.origin"; - ---- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java -+++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java -@@ -1,10 +1,8 @@ - package com.codahale.metrics.servlets; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -24,7 +22,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MetricsServletTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private ServletTester tester; - -@@ -128,22 +126,8 @@ public class MetricsServletTest extends AbstractServletTest { - assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); - assertThat(response.getContent()) - .isEqualTo( -- callbackParamVal -- + "({" -- + "\"version\":\"4.0.0\"," -- + "\"gauges\":{" -- + "\"g1\":{\"value\":100}" -- + "}," -- + "\"counters\":{" -- + "\"c\":{\"count\":1}" -- + "}," -- + "\"histograms\":{" -- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -- + "}," -- + "\"meters\":{" -- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -- + "}" -- + "})"); -+ "%s({\"version\":\"4.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", -+ callbackParamVal); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -223,41 +207,40 @@ public class MetricsServletTest extends AbstractServletTest { - @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() - throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); - } - - @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn(metricRegistry); -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); - - final MetricsServlet metricsServlet = new MetricsServlet(null); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); - } - - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); - - final MetricsServlet metricsServlet = new MetricsServlet(null); diff --git a/integration-tests/metrics-v4.2.19-expected-warnings.txt b/integration-tests/metrics-v4.2.19-expected-warnings.txt index 972ecad639..b9eae8e494 100644 --- a/integration-tests/metrics-v4.2.19-expected-warnings.txt +++ b/integration-tests/metrics-v4.2.19-expected-warnings.txt @@ -1,8 +1,6 @@ -metrics-core/src/main/java/com/codahale/metrics/CsvReporter.java:[382,36] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[429,18] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[434,20] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[447,21] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[189,47] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone -metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[203,47] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone -metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[29,68] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone -metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[30,68] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[37,12] [removal] SecurityManager in java.lang has been deprecated and marked for removal +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[37,38] [removal] getSecurityManager() in System has been deprecated and marked for removal +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[269,32] [removal] getSecurityManager() in System has been deprecated and marked for removal +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[269,6] [removal] SecurityManager in java.lang has been deprecated and marked for removal +metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[55,10] [removal] AccessController in java.security has been deprecated and marked for removal +metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[9,20] [removal] AccessController in java.security has been deprecated and marked for removal diff --git a/integration-tests/metrics-v4.2.19-init.patch b/integration-tests/metrics-v4.2.19-init.patch index 8ce1957ec7..56d6e17097 100644 --- a/integration-tests/metrics-v4.2.19-init.patch +++ b/integration-tests/metrics-v4.2.19-init.patch @@ -23,108 +23,35 @@ index 0bd1297..7c69a08 100644 try { return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); diff --git a/pom.xml b/pom.xml -index 6192b52..f1eebbe 100644 +index 6192b52..bcbd571 100644 --- a/pom.xml +++ b/pom.xml -@@ -66,7 +66,7 @@ - 4.13.1 - 1.3 +@@ -68,7 +68,8 @@ 3.11.0 -- 2.19.1 -+ -Xplugin:ErrorProne ${error-prone.flags} -Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\$StringIsNullOrEmpty)).*) + 2.19.1 9+181-r4173-1 - +- ++ -Xplugin:ErrorProne ${error-prone.flags} -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\$StringIsNullOrEmpty)).*) ++ 8 dropwizard_metrics -@@ -137,60 +137,110 @@ - - - -- jdk8 -- -- 1.8 -- -+ error-prone-compile - - -- -- org.apache.maven.plugins -- maven-compiler-plugin -+ -+ org.apache.maven.plugins -+ maven-compiler-plugin -+ ${maven-compiler-plugin.version} -+ -+ -+ error-prone-compile -+ compile -+ -+ compile -+ + dropwizard + https://sonarcloud.io +@@ -166,10 +167,9 @@ + org.apache.maven.plugins + maven-compiler-plugin -- -- -J-Xbootclasspath/p:${settings.localRepository}/com/google/errorprone/javac/${errorprone.javac.version}/javac-${errorprone.javac.version}.jar -- -+ false -+ 1.8 -+ 1.8 -+ -+ -Xpkginfo:always -+ -XDcompilePolicy=simple -+ ${error-prone-support.flags} -+ -+ -+ -+ com.google.errorprone -+ error_prone_core -+ ${error-prone.version} -+ -+ -+ tech.picnic.error-prone-support -+ error-prone-contrib -+ ${error-prone-support.version} -+ -+ -+ tech.picnic.error-prone-support -+ refaster-runner -+ ${error-prone-support.version} -+ -+ - -- -+ -+ -+ - -- -+ - - -- jdk17 -- -- [17,) -- -+ error-prone-test-compile - -- -- -- org.apache.maven.plugins -- maven-compiler-plugin -- - -- -Xlint:all -- -XDcompilePolicy=simple ++ + -Xlint:all + -XDcompilePolicy=simple - -Xplugin:ErrorProne -XepExcludedPaths:.*/target/generated-sources/.* -- -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED -- -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED -- -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED -- -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED -- -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED -- -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED -- -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED -- -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED -- -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED -- -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED -- + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED +@@ -181,18 +181,129 @@ + -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + - - - com.google.errorprone @@ -132,76 +59,133 @@ index 6192b52..f1eebbe 100644 - ${errorprone.version} - - -- -- -- -+ -+ -+ org.apache.maven.plugins -+ maven-compiler-plugin -+ ${maven-compiler-plugin.version} -+ -+ -+ -+ default-testCompile -+ test-compile -+ -+ testCompile -+ -+ -+ true -+ -+ -+ -+ error-prone-test-compile -+ test-compile -+ -+ testCompile -+ -+ -+ false -+ 1.8 -+ 1.8 -+ -+ -Xpkginfo:always -+ -XDcompilePolicy=simple -+ ${error-prone-support.flags} -+ -+ -+ -+ com.google.errorprone -+ error_prone_core -+ ${error-prone.version} -+ -+ -+ tech.picnic.error-prone-support -+ error-prone-contrib -+ ${error-prone-support.version} -+ -+ -+ tech.picnic.error-prone-support -+ refaster-runner -+ ${error-prone-support.version} -+ -+ -+ -+ -+ -+ -+ + + + ++ ++ error-prone-compile ++ ++ ++ ++ org.apache.maven.plugins ++ maven-compiler-plugin ++ ${maven-compiler-plugin.version} ++ ++ ++ ++ default-compile ++ compile ++ ++ compile ++ ++ ++ true ++ ++ ++ ++ error-prone-compile ++ compile ++ ++ compile ++ ++ ++ true ++ ${java.version} ++ ${java.version} ++ ++ -Xpkginfo:always ++ -XDcompilePolicy=simple ++ ${error-prone-support.flags} ++ ++ ++ ++ com.google.errorprone ++ error_prone_core ++ ${error-prone.version} ++ ++ ++ tech.picnic.error-prone-support ++ error-prone-contrib ++ ${error-prone-support.version} ++ ++ ++ tech.picnic.error-prone-support ++ refaster-runner ++ ${error-prone-support.version} ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ error-prone-test-compile ++ ++ ++ ++ org.apache.maven.plugins ++ maven-compiler-plugin ++ ${maven-compiler-plugin.version} ++ ++ ++ ++ default-testCompile ++ test-compile ++ ++ testCompile ++ ++ ++ true ++ ++ ++ ++ error-prone-test-compile ++ test-compile ++ ++ testCompile ++ ++ ++ true ++ ${java.version} ++ ${java.version} ++ ++ -Xpkginfo:always ++ -XDcompilePolicy=simple ++ ${error-prone-support.flags} ++ ++ ++ ++ com.google.errorprone ++ error_prone_core ++ ${error-prone.version} ++ ++ ++ tech.picnic.error-prone-support ++ error-prone-contrib ++ ${error-prone-support.version} ++ ++ ++ tech.picnic.error-prone-support ++ refaster-runner ++ ${error-prone-support.version} ++ ++ ++ ++ ++ ++ ++ ++ ++ -@@ -315,23 +365,13 @@ - org.apache.maven.plugins - maven-compiler-plugin - -- 1.8 -- 1.8 -- true -+ false - true - true + release-sign-artifacts + +@@ -323,15 +434,7 @@ -Xlint:all -XDcompilePolicy=simple From 36f8b01add477e4ccd6adbc9539a1210b663bccb Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Wed, 13 Dec 2023 10:44:35 +0100 Subject: [PATCH 06/59] run metrics --- .../metrics-v4.2.19-expected-changes.patch | 6660 +++++++++++++++++ .../metrics-v4.2.19-expected-warnings.txt | 133 +- integration-tests/metrics-v4.2.19-init.patch | 2 +- integration-tests/metrics-v4.2.19.sh | 4 +- 4 files changed, 6793 insertions(+), 6 deletions(-) diff --git a/integration-tests/metrics-v4.2.19-expected-changes.patch b/integration-tests/metrics-v4.2.19-expected-changes.patch index e69de29bb2..5d6d51f6b8 100644 --- a/integration-tests/metrics-v4.2.19-expected-changes.patch +++ b/integration-tests/metrics-v4.2.19-expected-changes.patch @@ -0,0 +1,6660 @@ +--- a/metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java ++++ b/metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java +@@ -2,7 +2,6 @@ package com.codahale.metrics.benchmarks; + + import com.codahale.metrics.SlidingTimeWindowArrayReservoir; + import com.codahale.metrics.SlidingTimeWindowReservoir; +-import com.codahale.metrics.Snapshot; + import java.util.concurrent.TimeUnit; + import org.openjdk.jmh.annotations.Benchmark; + import org.openjdk.jmh.annotations.Group; +@@ -42,8 +41,7 @@ public class SlidingTimeWindowReservoirsBenchmark { + @Group("slidingTime") + @GroupThreads(1) + public Object slidingTimeRead() { +- Snapshot snapshot = slidingTime.getSnapshot(); +- return snapshot; ++ return slidingTime.getSnapshot(); + } + + @Benchmark +@@ -58,8 +56,7 @@ public class SlidingTimeWindowReservoirsBenchmark { + @Group("arrTime") + @GroupThreads(1) + public Object arrTimeRead() { +- Snapshot snapshot = arrTime.getSnapshot(); +- return snapshot; ++ return arrTime.getSnapshot(); + } + + public static void main(String[] args) throws RunnerException { +--- a/metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java ++++ b/metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java +@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; + import static com.codahale.metrics.MetricAttribute.M15_RATE; + import static com.codahale.metrics.MetricAttribute.M1_RATE; + import static com.codahale.metrics.MetricAttribute.M5_RATE; +-import static com.codahale.metrics.MetricAttribute.MAX; + import static com.codahale.metrics.MetricAttribute.MEAN; + import static com.codahale.metrics.MetricAttribute.MEAN_RATE; +-import static com.codahale.metrics.MetricAttribute.MIN; + import static com.codahale.metrics.MetricAttribute.P50; + import static com.codahale.metrics.MetricAttribute.P75; + import static com.codahale.metrics.MetricAttribute.P95; +@@ -15,6 +13,7 @@ import static com.codahale.metrics.MetricAttribute.P98; + import static com.codahale.metrics.MetricAttribute.P99; + import static com.codahale.metrics.MetricAttribute.P999; + import static com.codahale.metrics.MetricAttribute.STDDEV; ++import static java.util.Collections.emptySet; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.Counter; +@@ -29,7 +28,6 @@ import com.codahale.metrics.Snapshot; + import com.codahale.metrics.Timer; + import java.io.IOException; + import java.net.InetAddress; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -80,7 +78,7 @@ public class CollectdReporter extends ScheduledReporter { + private SecurityLevel securityLevel = SecurityLevel.NONE; + private String username = ""; + private String password = ""; +- private Set disabledMetricAttributes = Collections.emptySet(); ++ private Set disabledMetricAttributes = emptySet(); + private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; + + private Builder(MetricRegistry registry) { +@@ -302,7 +300,7 @@ public class CollectdReporter extends ScheduledReporter { + try { + writer.write(metaData, value); + } catch (RuntimeException e) { +- LOG.warn("Failed to process metric '" + metaData.getPlugin() + "': " + e.getMessage()); ++ LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage()); + } catch (IOException e) { + LOG.error("Failed to send metric to collectd", e); + } +@@ -337,9 +335,9 @@ public class CollectdReporter extends ScheduledReporter { + private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { + final Snapshot snapshot = metric.getSnapshot(); + writeValue(metaData, COUNT, (double) metric.getCount()); +- writeValue(metaData, MAX, (double) snapshot.getMax()); ++ writeValue(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); + writeValue(metaData, MEAN, snapshot.getMean()); +- writeValue(metaData, MIN, (double) snapshot.getMin()); ++ writeValue(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); + writeValue(metaData, STDDEV, snapshot.getStdDev()); + writeValue(metaData, P50, snapshot.getMedian()); + writeValue(metaData, P75, snapshot.get75thPercentile()); +@@ -352,9 +350,9 @@ public class CollectdReporter extends ScheduledReporter { + private void serializeTimer(MetaData.Builder metaData, Timer metric) { + final Snapshot snapshot = metric.getSnapshot(); + writeValue(metaData, COUNT, (double) metric.getCount()); +- writeDuration(metaData, MAX, (double) snapshot.getMax()); ++ writeDuration(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); + writeDuration(metaData, MEAN, snapshot.getMean()); +- writeDuration(metaData, MIN, (double) snapshot.getMin()); ++ writeDuration(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); + writeDuration(metaData, STDDEV, snapshot.getStdDev()); + writeDuration(metaData, P50, snapshot.getMedian()); + writeDuration(metaData, P75, snapshot.get75thPercentile()); +--- a/metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java ++++ b/metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java +@@ -1,10 +1,12 @@ + package com.codahale.metrics.collectd; + ++import static java.nio.charset.StandardCharsets.US_ASCII; ++import static java.nio.charset.StandardCharsets.UTF_8; ++ + import java.io.IOException; + import java.nio.BufferOverflowException; + import java.nio.ByteBuffer; + import java.nio.ByteOrder; +-import java.nio.charset.StandardCharsets; + import java.security.InvalidKeyException; + import java.security.MessageDigest; + import java.security.NoSuchAlgorithmException; +@@ -64,8 +66,8 @@ class PacketWriter { + PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { + this.sender = sender; + this.securityLevel = securityLevel; +- this.username = username != null ? username.getBytes(StandardCharsets.UTF_8) : null; +- this.password = password != null ? password.getBytes(StandardCharsets.UTF_8) : null; ++ this.username = username != null ? username.getBytes(UTF_8) : null; ++ this.password = password != null ? password.getBytes(UTF_8) : null; + } + + void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { +@@ -119,12 +121,12 @@ class PacketWriter { + } + + private void writeString(ByteBuffer buffer, int type, String val) { +- if (val == null || val.length() == 0) { ++ if (val == null || val.isEmpty()) { + return; + } + int len = HEADER_LEN + val.length() + 1; + writeHeader(buffer, type, len); +- buffer.put(val.getBytes(StandardCharsets.US_ASCII)).put(NULL); ++ buffer.put(val.getBytes(US_ASCII)).put(NULL); + } + + private void writeNumber(ByteBuffer buffer, int type, long val) { +--- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterSecurityTest.java ++++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterSecurityTest.java +@@ -1,6 +1,6 @@ + package com.codahale.metrics.collectd; + +-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + + import com.codahale.metrics.MetricRegistry; + import org.junit.Test; +@@ -11,27 +11,27 @@ public class CollectdReporterSecurityTest { + + @Test + public void testUnableSetSecurityLevelToSignWithoutUsername() { +- assertThatIllegalArgumentException() +- .isThrownBy( ++ assertThatThrownBy( + () -> + CollectdReporter.forRegistry(registry) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withPassword("t1_g3r") + .build(new Sender("localhost", 25826))) +- .withMessage("username is required for securityLevel: SIGN"); ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("username is required for securityLevel: SIGN"); + } + + @Test + public void testUnableSetSecurityLevelToSignWithoutPassword() { +- assertThatIllegalArgumentException() +- .isThrownBy( ++ assertThatThrownBy( + () -> + CollectdReporter.forRegistry(registry) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withUsername("scott") + .build(new Sender("localhost", 25826))) +- .withMessage("password is required for securityLevel: SIGN"); ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("password is required for securityLevel: SIGN"); + } + } +--- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java ++++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java +@@ -1,5 +1,8 @@ + package com.codahale.metrics.collectd; + ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptySortedMap; ++import static java.util.Collections.singletonMap; + import static java.util.concurrent.TimeUnit.MILLISECONDS; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; +@@ -12,7 +15,6 @@ import com.codahale.metrics.MetricAttribute; + import com.codahale.metrics.MetricRegistry; + import com.codahale.metrics.Snapshot; + import com.codahale.metrics.Timer; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -94,7 +96,7 @@ public class CollectdReporterTest { + + @Test + public void reportsCounters() throws Exception { +- Counter counter = mock(Counter.class); ++ Counter counter = mock(); + when(counter.getCount()).thenReturn(42L); + + reporter.report(map(), map("api.rest.requests.count", counter), map(), map(), map()); +@@ -104,7 +106,7 @@ public class CollectdReporterTest { + + @Test + public void reportsMeters() throws Exception { +- Meter meter = mock(Meter.class); ++ Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); +@@ -122,8 +124,8 @@ public class CollectdReporterTest { + + @Test + public void reportsHistograms() throws Exception { +- Histogram histogram = mock(Histogram.class); +- Snapshot snapshot = mock(Snapshot.class); ++ Histogram histogram = mock(); ++ Snapshot snapshot = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSnapshot()).thenReturn(snapshot); + when(snapshot.getMax()).thenReturn(2L); +@@ -146,8 +148,8 @@ public class CollectdReporterTest { + + @Test + public void reportsTimers() throws Exception { +- Timer timer = mock(Timer.class); +- Snapshot snapshot = mock(Snapshot.class); ++ Timer timer = mock(); ++ Snapshot snapshot = mock(); + when(timer.getSnapshot()).thenReturn(snapshot); + when(timer.getCount()).thenReturn(1L); + when(timer.getSnapshot()).thenReturn(snapshot); +@@ -187,14 +189,14 @@ public class CollectdReporterTest { + + @Test + public void doesNotReportDisabledMetricAttributes() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(11L); + + CollectdReporter reporter = +@@ -240,16 +242,16 @@ public class CollectdReporterTest { + } + + private SortedMap map() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + private SortedMap map(String name, T metric) { +- final Map map = Collections.singletonMap(name, metric); ++ final Map map = singletonMap(name, metric); + return new TreeMap<>(map); + } + + private List nextValues(Receiver receiver) throws Exception { + final ValueList valueList = receiver.next(); +- return valueList == null ? Collections.emptyList() : valueList.getValues(); ++ return valueList == null ? emptyList() : valueList.getValues(); + } + } +--- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/PacketWriterTest.java ++++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/PacketWriterTest.java +@@ -190,6 +190,6 @@ public class PacketWriterTest { + assertThat(amountOfValues).isEqualTo((short) 1); + byte dataType = packet.get(); + assertThat(dataType).isEqualTo((byte) 1); +- assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isEqualTo(42.0, offset(0.01)); ++ assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01)); + } + } +--- a/metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java +@@ -1,8 +1,9 @@ + package com.codahale.metrics; + ++import static java.util.Collections.emptySet; ++ + import java.io.PrintStream; + import java.text.DateFormat; +-import java.util.Collections; + import java.util.Date; + import java.util.Locale; + import java.util.Map; +@@ -53,7 +54,7 @@ public class ConsoleReporter extends ScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- disabledMetricAttributes = Collections.emptySet(); ++ disabledMetricAttributes = emptySet(); + } + + /** +--- a/metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java +@@ -1,8 +1,9 @@ + package com.codahale.metrics; + ++import static java.util.Objects.requireNonNull; ++ + import com.codahale.metrics.WeightedSnapshot.WeightedSample; + import java.time.Duration; +-import java.util.Objects; + import java.util.concurrent.ConcurrentSkipListMap; + import java.util.concurrent.ThreadLocalRandom; + import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +@@ -127,7 +128,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + // It's possible that more values were added while the map was scanned, those with the + // minimum priorities are removed. + while (newCount > size) { +- Objects.requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); ++ requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); + newCount--; + } + return new State(alphaNanos, size, newTick, newCount, newValues); +@@ -255,13 +256,13 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + + /** Interval at which this reservoir is rescaled. */ + public Builder rescaleThreshold(Duration value) { +- this.rescaleThreshold = Objects.requireNonNull(value, "rescaleThreshold is required"); ++ this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required"); + return this; + } + + /** Clock instance used for decay. */ + public Builder clock(Clock value) { +- this.clock = Objects.requireNonNull(value, "clock is required"); ++ this.clock = requireNonNull(value, "clock is required"); + return this; + } + +--- a/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java +@@ -1,6 +1,9 @@ + package com.codahale.metrics; + +-import java.util.Collections; ++import static java.util.Collections.unmodifiableMap; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; ++ + import java.util.List; + import java.util.Map; + import java.util.SortedMap; +@@ -207,7 +210,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); ++ return metric instanceof Counter; + } + }); + } +@@ -242,7 +245,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); ++ return metric instanceof Histogram; + } + }); + } +@@ -277,7 +280,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); ++ return metric instanceof Meter; + } + }); + } +@@ -312,7 +315,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); ++ return metric instanceof Timer; + } + }); + } +@@ -350,7 +353,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Gauge.class.isInstance(metric); ++ return metric instanceof Gauge; + } + }); + } +@@ -414,7 +417,7 @@ public class MetricRegistry implements MetricSet { + * @return the names of all the metrics + */ + public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); ++ return unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); + } + + /** +@@ -541,7 +544,7 @@ public class MetricRegistry implements MetricSet { + timers.put(entry.getKey(), (T) entry.getValue()); + } + } +- return Collections.unmodifiableSortedMap(timers); ++ return unmodifiableSortedMap(timers); + } + + private void onMetricAdded(String name, Metric metric) { +@@ -609,7 +612,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public Map getMetrics() { +- return Collections.unmodifiableMap(metrics); ++ return unmodifiableMap(metrics); + } + + @FunctionalInterface +@@ -628,7 +631,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); ++ return metric instanceof Counter; + } + }; + +@@ -641,7 +644,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); ++ return metric instanceof Histogram; + } + }; + +@@ -654,7 +657,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); ++ return metric instanceof Meter; + } + }; + +@@ -667,7 +670,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); ++ return metric instanceof Timer; + } + }; + +@@ -681,7 +684,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Gauge.class.isInstance(metric); ++ return metric instanceof Gauge; + } + }; + +--- a/metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java +@@ -1,9 +1,13 @@ + package com.codahale.metrics; + ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.emptySet; ++import static java.util.Collections.emptySortedMap; ++import static java.util.Collections.emptySortedSet; ++ + import java.io.OutputStream; + import java.time.Duration; + import java.util.Collection; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -137,69 +141,69 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public SortedSet getNames() { +- return Collections.emptySortedSet(); ++ return emptySortedSet(); + } + + /** {@inheritDoc} */ + @Override + @SuppressWarnings("rawtypes") + public SortedMap getGauges() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + @SuppressWarnings("rawtypes") + public SortedMap getGauges(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getCounters() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getCounters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getHistograms() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getHistograms(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getMeters() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getMeters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getTimers() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getTimers(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ +@@ -211,7 +215,7 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public Map getMetrics() { +- return Collections.emptyMap(); ++ return emptyMap(); + } + + static final class NoopGauge implements Gauge { +@@ -601,19 +605,19 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public Set keySet() { +- return Collections.emptySet(); ++ return emptySet(); + } + + /** {@inheritDoc} */ + @Override + public Collection values() { +- return Collections.emptySet(); ++ return emptySet(); + } + + /** {@inheritDoc} */ + @Override + public Set> entrySet() { +- return Collections.emptySet(); ++ return emptySet(); + } + } + } +--- a/metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java +@@ -1,7 +1,8 @@ + package com.codahale.metrics; + ++import static java.util.Collections.emptySet; ++ + import java.io.Closeable; +-import java.util.Collections; + import java.util.Locale; + import java.util.Set; + import java.util.SortedMap; +@@ -128,7 +129,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + durationUnit, + executor, + shutdownExecutorOnStop, +- Collections.emptySet()); ++ emptySet()); + } + + protected ScheduledReporter( +@@ -154,7 +155,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + this.durationFactor = durationUnit.toNanos(1); + this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); + this.disabledMetricAttributes = +- disabledMetricAttributes != null ? disabledMetricAttributes : Collections.emptySet(); ++ disabledMetricAttributes != null ? disabledMetricAttributes : emptySet(); + } + + /** +@@ -185,8 +186,8 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, + * ScheduledExecutorService)} instead. + */ +- @SuppressWarnings("DeprecatedIsStillUsed") + @Deprecated ++ @SuppressWarnings("DeprecatedIsStillUsed") + protected ScheduledFuture getScheduledFuture( + long initialDelay, long period, TimeUnit unit, Runnable runnable) { + return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); +--- a/metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java +@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; + import static com.codahale.metrics.MetricAttribute.M15_RATE; + import static com.codahale.metrics.MetricAttribute.M1_RATE; + import static com.codahale.metrics.MetricAttribute.M5_RATE; +-import static com.codahale.metrics.MetricAttribute.MAX; + import static com.codahale.metrics.MetricAttribute.MEAN; + import static com.codahale.metrics.MetricAttribute.MEAN_RATE; +-import static com.codahale.metrics.MetricAttribute.MIN; + import static com.codahale.metrics.MetricAttribute.P50; + import static com.codahale.metrics.MetricAttribute.P75; + import static com.codahale.metrics.MetricAttribute.P95; +@@ -15,8 +13,8 @@ import static com.codahale.metrics.MetricAttribute.P98; + import static com.codahale.metrics.MetricAttribute.P99; + import static com.codahale.metrics.MetricAttribute.P999; + import static com.codahale.metrics.MetricAttribute.STDDEV; ++import static java.util.Collections.emptySet; + +-import java.util.Collections; + import java.util.Map.Entry; + import java.util.Set; + import java.util.SortedMap; +@@ -81,7 +79,7 @@ public class Slf4jReporter extends ScheduledReporter { + this.loggingLevel = LoggingLevel.INFO; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = emptySet(); + } + + /** +@@ -306,8 +304,8 @@ public class Slf4jReporter extends ScheduledReporter { + b.append("type=TIMER"); + append(b, "name", prefix(name)); + appendCountIfEnabled(b, timer); +- appendLongDurationIfEnabled(b, MIN, snapshot::getMin); +- appendLongDurationIfEnabled(b, MAX, snapshot::getMax); ++ appendLongDurationIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongDurationIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); + appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); + appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); + appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); +@@ -338,8 +336,8 @@ public class Slf4jReporter extends ScheduledReporter { + b.append("type=HISTOGRAM"); + append(b, "name", prefix(name)); + appendCountIfEnabled(b, histogram); +- appendLongIfEnabled(b, MIN, snapshot::getMin); +- appendLongIfEnabled(b, MAX, snapshot::getMax); ++ appendLongIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); + appendDoubleIfEnabled(b, MEAN, snapshot::getMean); + appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); + appendDoubleIfEnabled(b, P50, snapshot::getMedian); +--- a/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowMovingAverages.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowMovingAverages.java +@@ -184,7 +184,6 @@ public class SlidingTimeWindowMovingAverages implements MovingAverages { + buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); + buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); + } +- long retval = adder.longValue(); +- return retval; ++ return adder.longValue(); + } + } +--- a/metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java ++++ b/metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java +@@ -1,13 +1,13 @@ + package com.codahale.metrics; + + import static java.nio.charset.StandardCharsets.UTF_8; ++import static java.util.Comparator.comparingLong; + + import java.io.OutputStream; + import java.io.OutputStreamWriter; + import java.io.PrintWriter; + import java.util.Arrays; + import java.util.Collection; +-import java.util.Comparator; + + /** A statistical snapshot of a {@link WeightedSnapshot}. */ + public class WeightedSnapshot extends Snapshot { +@@ -35,7 +35,7 @@ public class WeightedSnapshot extends Snapshot { + public WeightedSnapshot(Collection values) { + final WeightedSample[] copy = values.toArray(new WeightedSample[] {}); + +- Arrays.sort(copy, Comparator.comparingLong(w -> w.value)); ++ Arrays.sort(copy, comparingLong(w -> w.value)); + + this.values = new long[copy.length]; + this.normWeights = new double[copy.length]; +--- a/metrics-core/src/test/java/com/codahale/metrics/ClockTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/ClockTest.java +@@ -11,9 +11,9 @@ public class ClockTest { + public void userTimeClock() { + final Clock.UserTimeClock clock = new Clock.UserTimeClock(); + +- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(100.0)); ++ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0)); + +- assertThat((double) clock.getTick()).isEqualTo(System.nanoTime(), offset(1000000.0)); ++ assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0)); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/ConsoleReporterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/ConsoleReporterTest.java +@@ -21,8 +21,8 @@ public class ConsoleReporterTest { + private final Locale locale = Locale.US; + private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); + +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); + private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + private final PrintStream output = new PrintStream(bytes); + private final ConsoleReporter reporter = +@@ -68,7 +68,7 @@ public class ConsoleReporterTest { + + @Test + public void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map("test.counter", counter), map(), map(), map()); +@@ -87,10 +87,10 @@ public class ConsoleReporterTest { + + @Test + public void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -130,7 +130,7 @@ public class ConsoleReporterTest { + + @Test + public void reportsMeterValues() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -157,14 +157,14 @@ public class ConsoleReporterTest { + + @Test + public void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -223,7 +223,7 @@ public class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); + +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -266,14 +266,14 @@ public class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); + +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -329,10 +329,10 @@ public class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); + +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +--- a/metrics-core/src/test/java/com/codahale/metrics/CounterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/CounterTest.java +@@ -9,7 +9,7 @@ public class CounterTest { + + @Test + public void startsAtZero() { +- assertThat(counter.getCount()).isZero(); ++ assertThat(counter.getCount()).isEqualTo(0); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/CsvReporterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/CsvReporterTest.java +@@ -7,7 +7,6 @@ import static org.mockito.Mockito.when; + + import java.io.File; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.nio.file.Files; + import java.util.Locale; + import java.util.SortedMap; +@@ -21,8 +20,8 @@ import org.junit.rules.TemporaryFolder; + public class CsvReporterTest { + @Rule public final TemporaryFolder folder = new TemporaryFolder(); + +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); + + private File dataDirectory; + private CsvReporter reporter; +@@ -54,7 +53,7 @@ public class CsvReporterTest { + + @Test + public void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map("test.counter", counter), map(), map(), map()); +@@ -64,10 +63,10 @@ public class CsvReporterTest { + + @Test + public void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -105,14 +104,14 @@ public class CsvReporterTest { + + @Test + public void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -137,7 +136,7 @@ public class CsvReporterTest { + + @Test + public void testCsvFileProviderIsUsed() { +- CsvFileProvider fileProvider = mock(CsvFileProvider.class); ++ CsvFileProvider fileProvider = mock(); + when(fileProvider.getFile(dataDirectory, "gauge")) + .thenReturn(new File(dataDirectory, "guage.csv")); + +@@ -175,7 +174,7 @@ public class CsvReporterTest { + } + + private Meter mockMeter() { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -194,8 +193,7 @@ public class CsvReporterTest { + } + + private String fileContents(String filename) throws IOException { +- return new String( +- Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); ++ return Files.readString(new File(dataDirectory, filename).toPath()); + } + + private SortedMap map() { +--- a/metrics-core/src/test/java/com/codahale/metrics/EWMATest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/EWMATest.java +@@ -13,67 +13,67 @@ public class EWMATest { + ewma.update(3); + ewma.tick(); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.01098938, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00404277, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00148725, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00054713, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00020128, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00007405, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00002724, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00001002, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000369, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000136, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000050, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000018, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001)); + } + + @Test +@@ -82,67 +82,67 @@ public class EWMATest { + ewma.update(3); + ewma.tick(); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.18071653, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.14795818, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.12113791, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.09917933, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.06648190, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.05443077, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.04456415, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.03648604, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); + } + + @Test +@@ -151,67 +151,67 @@ public class EWMATest { + ewma.update(3); + ewma.tick(); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.56130419, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.52510399, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.45955700, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.42991879, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.37625345, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.35198773, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.30805027, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.28818318, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.25221023, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.23594443, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + } + + private void elapseMinute(EWMA ewma) { +--- a/metrics-core/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java +@@ -1,5 +1,6 @@ + package com.codahale.metrics; + ++import static java.util.stream.Collectors.toList; + import static org.assertj.core.api.Assertions.assertThat; + + import com.codahale.metrics.Timer.Context; +@@ -8,7 +9,6 @@ import java.util.Collection; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicBoolean; + import java.util.concurrent.atomic.AtomicInteger; +-import java.util.stream.Collectors; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.junit.runners.Parameterized; +@@ -46,7 +46,7 @@ public class ExponentiallyDecayingReservoirTest { + public static Collection reservoirs() { + return Arrays.stream(ReservoirFactory.values()) + .map(value -> new Object[] {value}) +- .collect(Collectors.toList()); ++ .collect(toList()); + } + + private final ReservoirFactory reservoirFactory; +--- a/metrics-core/src/test/java/com/codahale/metrics/HistogramTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/HistogramTest.java +@@ -8,12 +8,12 @@ import static org.mockito.Mockito.when; + import org.junit.Test; + + public class HistogramTest { +- private final Reservoir reservoir = mock(Reservoir.class); ++ private final Reservoir reservoir = mock(); + private final Histogram histogram = new Histogram(reservoir); + + @Test + public void updatesTheCountOnUpdates() { +- assertThat(histogram.getCount()).isZero(); ++ assertThat(histogram.getCount()).isEqualTo(0); + + histogram.update(1); + +@@ -22,7 +22,7 @@ public class HistogramTest { + + @Test + public void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(reservoir.getSnapshot()).thenReturn(snapshot); + + assertThat(histogram.getSnapshot()).isEqualTo(snapshot); +--- a/metrics-core/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java +@@ -112,8 +112,8 @@ public class InstrumentedExecutorServiceTest { + assertThat(idle.getSnapshot().size()).isEqualTo(1); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void reportsTasksInformationForThreadPoolExecutor() throws Exception { + executor = + new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); +@@ -170,8 +170,8 @@ public class InstrumentedExecutorServiceTest { + assertThat(poolSize.getValue()).isEqualTo(1); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void reportsTasksInformationForForkJoinPool() throws Exception { + executor = Executors.newWorkStealingPool(4); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); +--- a/metrics-core/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java +@@ -36,16 +36,16 @@ public class InstrumentedScheduledExecutorServiceTest { + + @Test + public void testSubmitRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + Future theFuture = + instrumentedScheduledExecutor.submit( +@@ -53,87 +53,87 @@ public class InstrumentedScheduledExecutorServiceTest { + assertThat(submitted.getCount()).isEqualTo(1); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + }); + + theFuture.get(); + + assertThat(submitted.getCount()).isEqualTo(1); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test + public void testScheduleRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + ScheduledFuture theFuture = + instrumentedScheduledExecutor.schedule( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + }, + 10L, + TimeUnit.MILLISECONDS); + + theFuture.get(); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test + public void testSubmitCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + final Object obj = new Object(); + +@@ -143,13 +143,13 @@ public class InstrumentedScheduledExecutorServiceTest { + assertThat(submitted.getCount()).isEqualTo(1); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + return obj; + }); +@@ -158,45 +158,45 @@ public class InstrumentedScheduledExecutorServiceTest { + + assertThat(submitted.getCount()).isEqualTo(1); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test + public void testScheduleCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + final Object obj = new Object(); + + ScheduledFuture theFuture = + instrumentedScheduledExecutor.schedule( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + return obj; + }, +@@ -205,37 +205,37 @@ public class InstrumentedScheduledExecutorServiceTest { + + assertThat(theFuture.get()).isEqualTo(obj); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test + public void testScheduleFixedRateCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + CountDownLatch countDownLatch = new CountDownLatch(1); + ScheduledFuture theFuture = + instrumentedScheduledExecutor.scheduleAtFixedRate( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); + +@@ -257,14 +257,14 @@ public class InstrumentedScheduledExecutorServiceTest { + theFuture.cancel(true); + TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isNotEqualTo(0); + assertThat(duration.getCount()).isNotEqualTo(0); + assertThat(duration.getSnapshot().size()).isNotEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); + assertThat(scheduledRepetitively.getCount()).isEqualTo(1); + assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); + assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); +@@ -272,22 +272,22 @@ public class InstrumentedScheduledExecutorServiceTest { + + @Test + public void testScheduleFixedDelayCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + CountDownLatch countDownLatch = new CountDownLatch(1); + ScheduledFuture theFuture = + instrumentedScheduledExecutor.scheduleWithFixedDelay( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); + +@@ -310,9 +310,9 @@ public class InstrumentedScheduledExecutorServiceTest { + theFuture.cancel(true); + TimeUnit.MILLISECONDS.sleep(200); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isNotEqualTo(0); + assertThat(duration.getCount()).isNotEqualTo(0); + assertThat(duration.getSnapshot().size()).isNotEqualTo(0); +--- a/metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java +@@ -11,7 +11,7 @@ import org.junit.runner.RunWith; + import org.junit.runners.Parameterized; + import org.junit.runners.Parameterized.Parameters; + +-@RunWith(value = Parameterized.class) ++@RunWith(Parameterized.class) + public class MeterApproximationTest { + + @Parameters +@@ -34,7 +34,7 @@ public class MeterApproximationTest { + 3, TimeUnit.MINUTES); + + assertThat(meter.getOneMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } + + @Test +@@ -45,7 +45,7 @@ public class MeterApproximationTest { + 13, TimeUnit.MINUTES); + + assertThat(meter.getFiveMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } + + @Test +@@ -56,7 +56,7 @@ public class MeterApproximationTest { + 38, TimeUnit.MINUTES); + + assertThat(meter.getFifteenMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } + + private Meter simulateMetronome( +--- a/metrics-core/src/test/java/com/codahale/metrics/MeterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/MeterTest.java +@@ -10,7 +10,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MeterTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final Meter meter = new Meter(clock); + + @Before +@@ -20,15 +20,15 @@ public class MeterTest { + + @Test + public void startsOutWithNoRatesOrCount() { +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + +- assertThat(meter.getMeanRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); + } + + @Test +@@ -36,12 +36,12 @@ public class MeterTest { + meter.mark(); + meter.mark(2); + +- assertThat(meter.getMeanRate()).isEqualTo(0.3, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001)); + +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.1840, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001)); + +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.1966, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001)); + +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.1988, offset(0.001)); ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001)); + } + } +--- a/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryListenerTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryListenerTest.java +@@ -6,10 +6,10 @@ import static org.mockito.Mockito.verifyNoInteractions; + import org.junit.Test; + + public class MetricRegistryListenerTest { +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + private final MetricRegistryListener listener = new MetricRegistryListener.Base() {}; + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryTest.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.stream.Collectors.toSet; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.mockito.Mockito.mock; +@@ -10,20 +11,19 @@ import static org.mockito.Mockito.verify; + import java.util.HashMap; + import java.util.Map; + import java.util.Set; +-import java.util.stream.Collectors; + import org.junit.Assert; + import org.junit.Before; + import org.junit.Test; + + public class MetricRegistryTest { +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); ++ private final MetricRegistryListener listener = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final Gauge gauge = () -> ""; + private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + + @Before + public void setUp() { +@@ -230,8 +230,8 @@ public class MetricRegistryTest { + verify(listener).onGaugeAdded("thing", gauge1); + } + +- @Test + @SuppressWarnings("rawtypes") ++ @Test + public void accessingACustomGaugeRegistersAndReusesIt() { + final MetricRegistry.MetricSupplier supplier = () -> gauge; + final Gauge gauge1 = registry.gauge("thing", supplier); +@@ -261,7 +261,7 @@ public class MetricRegistryTest { + registry.register("meter", meter); + registry.register("timer", timer); + +- final MetricRegistryListener other = mock(MetricRegistryListener.class); ++ final MetricRegistryListener other = mock(); + registry.addListener(other); + + verify(other).onGaugeAdded("gauge", gauge); +@@ -383,7 +383,7 @@ public class MetricRegistryTest { + MetricRegistry other = new MetricRegistry(); + other.register("gauge", gauge); + registry.register("nested", other); +- assertThat(registry.getNames()).containsOnly("nested.gauge"); ++ assertThat(registry.getNames()).containsExactly("nested.gauge"); + } + + @Test +@@ -391,8 +391,8 @@ public class MetricRegistryTest { + assertThat(name("one", "two", "three")).isEqualTo("one.two.three"); + } + +- @Test + @SuppressWarnings("NullArgumentToVariableArgMethod") ++ @Test + public void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { + assertThat(name("one", (String) null)).isEqualTo("one"); + } +@@ -456,7 +456,7 @@ public class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + } + + @Test +@@ -474,7 +474,7 @@ public class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + } + + @Test +@@ -498,14 +498,13 @@ public class MetricRegistryTest { + Set deepChildMetrics = deepChild.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + + assertThat(childMetrics) +- .containsAll( +- deepChildMetrics.stream().map(m -> "deep-child." + m).collect(Collectors.toSet())); ++ .containsAll(deepChildMetrics.stream().map(m -> "deep-child." + m).collect(toSet())); + +- assertThat(deepChildMetrics.size()).isEqualTo(3); +- assertThat(childMetrics.size()).isEqualTo(5); ++ assertThat(deepChildMetrics).hasSize(3); ++ assertThat(childMetrics).hasSize(5); + } + + @Test +@@ -523,7 +522,7 @@ public class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + + assertThat(childMetrics).doesNotContain("test-1"); + } +@@ -546,7 +545,7 @@ public class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + + assertThat(childMetrics).doesNotContain("test-1", "test-3"); + } +@@ -572,16 +571,15 @@ public class MetricRegistryTest { + Set deepChildMetrics = deepChild.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); ++ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); + + assertThat(childMetrics) +- .containsAll( +- deepChildMetrics.stream().map(m -> "deep-child." + m).collect(Collectors.toSet())); ++ .containsAll(deepChildMetrics.stream().map(m -> "deep-child." + m).collect(toSet())); + + assertThat(deepChildMetrics).doesNotContain("test-2"); + +- assertThat(deepChildMetrics.size()).isEqualTo(1); +- assertThat(childMetrics.size()).isEqualTo(3); ++ assertThat(deepChildMetrics).hasSize(1); ++ assertThat(childMetrics).hasSize(3); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/NoopMetricRegistryTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/NoopMetricRegistryTest.java +@@ -1,7 +1,7 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatNullPointerException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; + import static org.mockito.Mockito.verify; +@@ -13,13 +13,13 @@ import org.junit.Before; + import org.junit.Test; + + public class NoopMetricRegistryTest { +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); ++ private final MetricRegistryListener listener = mock(); + private final NoopMetricRegistry registry = new NoopMetricRegistry(); + private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + + @Before + public void setUp() { +@@ -218,8 +218,8 @@ public class NoopMetricRegistryTest { + verify(listener, never()).onGaugeAdded("thing", gauge1); + } + +- @Test + @SuppressWarnings("rawtypes") ++ @Test + public void accessingACustomGaugeRegistersAndReusesIt() { + final MetricRegistry.MetricSupplier supplier = () -> gauge; + final Gauge gauge1 = registry.gauge("thing", supplier); +@@ -240,7 +240,7 @@ public class NoopMetricRegistryTest { + registry.register("meter", meter); + registry.register("timer", timer); + +- final MetricRegistryListener other = mock(MetricRegistryListener.class); ++ final MetricRegistryListener other = mock(); + registry.addListener(other); + + verify(other, never()).onGaugeAdded("gauge", gauge); +@@ -488,8 +488,8 @@ public class NoopMetricRegistryTest { + @Test + public void registerNullMetric() { + MetricRegistry registry = new NoopMetricRegistry(); +- assertThatNullPointerException() +- .isThrownBy(() -> registry.register("any_name", null)) +- .withMessage("metric == null"); ++ assertThatThrownBy(() -> registry.register("any_name", null)) ++ .isInstanceOf(NullPointerException.class) ++ .hasMessage("metric == null"); + } + } +--- a/metrics-core/src/test/java/com/codahale/metrics/RatioGaugeTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/RatioGaugeTest.java +@@ -9,7 +9,7 @@ public class RatioGaugeTest { + public void ratiosAreHumanReadable() { + final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); + +- assertThat(ratio.toString()).isEqualTo("100.0:200.0"); ++ assertThat(ratio).hasToString("100.0:200.0"); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java +@@ -26,12 +26,12 @@ import org.junit.Test; + + public class ScheduledReporterTest { + private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + +- private final ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); ++ private final ScheduledExecutorService mockExecutor = mock(); + private final ScheduledExecutorService customExecutor = + Executors.newSingleThreadScheduledExecutor(); + private final ScheduledExecutorService externalExecutor = +@@ -145,7 +145,7 @@ public class ScheduledReporterTest { + public void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { + reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); + +- verify(mockExecutor, times(1)) ++ verify(mockExecutor) + .scheduleWithFixedDelay(any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS)); + } + +@@ -295,7 +295,7 @@ public class ScheduledReporterTest { + + Thread.sleep(1_000); + +- verify(reporter, times(1)) ++ verify(reporter) + .report( + map("gauge", gauge), + map("counter", counter), +--- a/metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java +@@ -29,7 +29,7 @@ public class SharedMetricRegistriesTest { + public void hasASetOfNames() { + SharedMetricRegistries.getOrCreate("one"); + +- assertThat(SharedMetricRegistries.names()).containsOnly("one"); ++ assertThat(SharedMetricRegistries.names()).containsExactly("one"); + } + + @Test +--- a/metrics-core/src/test/java/com/codahale/metrics/Slf4jReporterTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/Slf4jReporterTest.java +@@ -3,7 +3,6 @@ package com.codahale.metrics; + import static com.codahale.metrics.MetricAttribute.COUNT; + import static com.codahale.metrics.MetricAttribute.M1_RATE; + import static com.codahale.metrics.MetricAttribute.MEAN_RATE; +-import static com.codahale.metrics.MetricAttribute.MIN; + import static com.codahale.metrics.MetricAttribute.P50; + import static com.codahale.metrics.MetricAttribute.P999; + import static com.codahale.metrics.MetricAttribute.STDDEV; +@@ -22,9 +21,9 @@ import org.slf4j.Marker; + + public class Slf4jReporterTest { + +- private final Logger logger = mock(Logger.class); +- private final Marker marker = mock(Marker.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final Logger logger = mock(); ++ private final Marker marker = mock(); ++ private final MetricRegistry registry = mock(); + + /** + * The set of disabled metric attributes to pass to the Slf4jReporter builder in the default +@@ -79,7 +78,7 @@ public class Slf4jReporterTest { + } + + private Timer timer() { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + + when(timer.getMeanRate()).thenReturn(2.0); +@@ -87,7 +86,7 @@ public class Slf4jReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -104,10 +103,10 @@ public class Slf4jReporterTest { + } + + private Histogram histogram() { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -124,7 +123,7 @@ public class Slf4jReporterTest { + } + + private Meter meter() { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -134,7 +133,7 @@ public class Slf4jReporterTest { + } + + private Counter counter() { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + return counter; + } +@@ -168,7 +167,7 @@ public class Slf4jReporterTest { + + @Test + public void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); ++ disabledMetricAttributes = EnumSet.of(COUNT, MetricAttribute.MIN, P50); + reportsHistogramValuesAtError( + "type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " + + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); +@@ -192,7 +191,7 @@ public class Slf4jReporterTest { + + @Test + public void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, P50, M1_RATE); + reportsMeterValuesAtError( + "type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " + + "mean_rate=2.0, rate_unit=events/second"); +@@ -218,7 +217,7 @@ public class Slf4jReporterTest { + + @Test + public void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, STDDEV, P999, MEAN_RATE); + reportsTimerValuesAtError( + "type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " + + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " +--- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java +@@ -16,7 +16,7 @@ public class SlidingTimeWindowArrayReservoirTest { + + @Test + public void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); + +@@ -30,7 +30,7 @@ public class SlidingTimeWindowArrayReservoirTest { + + @Test + public void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); + +@@ -99,7 +99,7 @@ public class SlidingTimeWindowArrayReservoirTest { + // Set the clock to overflow in (2*window+1)ns + final ManualClock clock = new ManualClock(); + clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); ++ assertThat(clock.getTick() * 256).isPositive(); + + // Create the reservoir + final SlidingTimeWindowArrayReservoir reservoir = +--- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowMovingAveragesTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowMovingAveragesTest.java +@@ -44,7 +44,7 @@ public class SlidingTimeWindowMovingAveragesTest { + + SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); + +- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(0L)), is(0)); ++ assertThat(stwm.calculateIndexOfTick(Instant.EPOCH), is(0)); + assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L)), is(1)); + } + +@@ -62,7 +62,7 @@ public class SlidingTimeWindowMovingAveragesTest { + } + + // verify that no cleanup happened yet +- assertThat(movingAverages.oldestBucketTime, is(Instant.ofEpochSecond(0L))); ++ assertThat(movingAverages.oldestBucketTime, is(Instant.EPOCH)); + + assertThat(meter.getOneMinuteRate(), is(60.0)); + assertThat(meter.getFiveMinuteRate(), is(300.0)); +@@ -83,7 +83,7 @@ public class SlidingTimeWindowMovingAveragesTest { + } + + // verify that at least one cleanup happened +- assertThat(movingAverages.oldestBucketTime, not(is(Instant.ofEpochSecond(0L)))); ++ assertThat(movingAverages.oldestBucketTime, not(is(Instant.EPOCH))); + + assertThat(meter.getOneMinuteRate(), is(60.0)); + assertThat(meter.getFiveMinuteRate(), is(300.0)); +--- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java +@@ -12,7 +12,7 @@ import org.junit.Test; + public class SlidingTimeWindowReservoirTest { + @Test + public void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowReservoir reservoir = + new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); + +@@ -26,7 +26,7 @@ public class SlidingTimeWindowReservoirTest { + + @Test + public void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + when(clock.getTick()).thenReturn(0L); + + final SlidingTimeWindowReservoir reservoir = +@@ -72,7 +72,7 @@ public class SlidingTimeWindowReservoirTest { + + // Set the clock to overflow in (2*window+1)ns + clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); ++ assertThat(clock.getTick() * 256).isPositive(); + + int updatesAfterThreshold = 0; + while (true) { +--- a/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java +@@ -13,7 +13,7 @@ import java.util.concurrent.atomic.AtomicBoolean; + import org.junit.Test; + + public class TimerTest { +- private final Reservoir reservoir = mock(Reservoir.class); ++ private final Reservoir reservoir = mock(); + private final Clock clock = + new Clock() { + // a mock clock that increments its ticker by 50msec per call +@@ -28,20 +28,20 @@ public class TimerTest { + + @Test + public void hasRates() { +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + +- assertThat(timer.getMeanRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); + } + + @Test + public void updatesTheCountOnUpdates() { +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + timer.update(1, TimeUnit.SECONDS); + +@@ -93,7 +93,7 @@ public class TimerTest { + + @Test + public void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(reservoir.getSnapshot()).thenReturn(snapshot); + + assertThat(timer.getSnapshot()).isEqualTo(snapshot); +@@ -103,7 +103,7 @@ public class TimerTest { + public void ignoresNegativeValues() { + timer.update(-1, TimeUnit.SECONDS); + +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + verifyNoInteractions(reservoir); + } +@@ -121,14 +121,14 @@ public class TimerTest { + public void java8NegativeDuration() { + timer.update(Duration.ofMillis(-5678)); + +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + verifyNoInteractions(reservoir); + } + + @Test + public void tryWithResourcesWork() { +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + int dummy = 0; + try (Timer.Context context = timer.time()) { +--- a/metrics-core/src/test/java/com/codahale/metrics/UniformReservoirTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/UniformReservoirTest.java +@@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; + + public class UniformReservoirTest { +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void aReservoirOf100OutOf1000Elements() { + final UniformReservoir reservoir = new UniformReservoir(100); + for (int i = 0; i < 1000; i++) { +@@ -20,7 +20,7 @@ public class UniformReservoirTest { + assertThat(snapshot.size()).isEqualTo(100); + + for (double i : snapshot.getValues()) { +- assertThat(i).isLessThan(1000).isGreaterThanOrEqualTo(0); ++ assertThat(i).isLessThan(1000).isNotNegative(); + } + } + } +--- a/metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java +@@ -16,12 +16,12 @@ public class UniformSnapshotTest { + + @Test + public void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)).isEqualTo(1, offset(0.1)); ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1)); + } + + @Test + public void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)).isEqualTo(5, offset(0.1)); ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1)); + } + + @Test(expected = IllegalArgumentException.class) +@@ -41,32 +41,32 @@ public class UniformSnapshotTest { + + @Test + public void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); ++ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1)); + } + + @Test + public void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1)); + } + + @Test + public void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test +@@ -125,7 +125,7 @@ public class UniformSnapshotTest { + + snapshot.dump(output); + +- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); + } + + @Test +@@ -145,41 +145,41 @@ public class UniformSnapshotTest { + + @Test + public void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()).isEqualTo(1.5811, offset(0.0001)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001)); + } + + @Test + public void calculatesAMinOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMin()).isZero(); ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); + } + + @Test + public void calculatesAMaxOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMax()).isZero(); ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); + } + + @Test + public void calculatesAMeanOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMean()).isZero(); ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); + } + + @Test + public void calculatesAStdDevOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getStdDev()).isZero(); ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); + } + + @Test + public void calculatesAStdDevOfZeroForASingletonSnapshot() { + final Snapshot singleItemSnapshot = new UniformSnapshot(new long[] {1}); + +- assertThat(singleItemSnapshot.getStdDev()).isZero(); ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); + } + } +--- a/metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java ++++ b/metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java +@@ -2,6 +2,7 @@ package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.offset; ++import static org.mockito.ArgumentMatchers.any; + import static org.mockito.Mockito.doReturn; + import static org.mockito.Mockito.spy; + import static org.mockito.Mockito.when; +@@ -11,7 +12,6 @@ import java.io.ByteArrayOutputStream; + import java.util.ArrayList; + import java.util.List; + import org.junit.Test; +-import org.mockito.ArgumentMatchers; + + public class WeightedSnapshotTest { + +@@ -34,12 +34,12 @@ public class WeightedSnapshotTest { + + @Test + public void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)).isEqualTo(1.0, offset(0.1)); ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1)); + } + + @Test + public void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1)); + } + + @Test(expected = IllegalArgumentException.class) +@@ -59,32 +59,32 @@ public class WeightedSnapshotTest { + + @Test + public void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); ++ assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1)); + } + + @Test + public void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1)); + } + + @Test + public void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + public void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test +@@ -104,7 +104,7 @@ public class WeightedSnapshotTest { + final List spyItems = spy(originalItems); + doReturn(originalItems.toArray(new WeightedSample[] {})) + .when(spyItems) +- .toArray(ArgumentMatchers.any(WeightedSample[].class)); ++ .toArray(any(WeightedSample[].class)); + when(spyItems.size()).thenReturn(4, 5); + + final Snapshot other = new WeightedSnapshot(spyItems); +@@ -119,7 +119,7 @@ public class WeightedSnapshotTest { + final List spyItems = spy(originalItems); + doReturn(originalItems.toArray(new WeightedSample[] {})) + .when(spyItems) +- .toArray(ArgumentMatchers.any(WeightedSample[].class)); ++ .toArray(any(WeightedSample[].class)); + when(spyItems.size()).thenReturn(6, 5); + + final Snapshot other = new WeightedSnapshot(spyItems); +@@ -133,7 +133,7 @@ public class WeightedSnapshotTest { + + snapshot.dump(output); + +- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); + } + + @Test +@@ -153,7 +153,7 @@ public class WeightedSnapshotTest { + + @Test + public void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()).isEqualTo(1.2688, offset(0.0001)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001)); + } + + @Test +@@ -161,7 +161,7 @@ public class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getMin()).isZero(); ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); + } + + @Test +@@ -169,7 +169,7 @@ public class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getMax()).isZero(); ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); + } + + @Test +@@ -177,7 +177,7 @@ public class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getMean()).isZero(); ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); + } + + @Test +@@ -185,7 +185,7 @@ public class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getStdDev()).isZero(); ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); + } + + @Test +@@ -193,7 +193,7 @@ public class WeightedSnapshotTest { + final Snapshot singleItemSnapshot = + new WeightedSnapshot(weightedArray(new long[] {1}, new double[] {1.0})); + +- assertThat(singleItemSnapshot.getStdDev()).isZero(); ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); + } + + @Test +--- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java ++++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java +@@ -132,8 +132,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { + final String sanitizedName = sanitize(name); + final String sanitizedValue = sanitize(value); + +- final String message = +- sanitizedName + ' ' + sanitizedValue + ' ' + Long.toString(timestamp) + '\n'; ++ final String message = sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n'; + channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); + } catch (IOException e) { + failures++; +--- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java ++++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java +@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; + import static com.codahale.metrics.MetricAttribute.M15_RATE; + import static com.codahale.metrics.MetricAttribute.M1_RATE; + import static com.codahale.metrics.MetricAttribute.M5_RATE; +-import static com.codahale.metrics.MetricAttribute.MAX; + import static com.codahale.metrics.MetricAttribute.MEAN; + import static com.codahale.metrics.MetricAttribute.MEAN_RATE; +-import static com.codahale.metrics.MetricAttribute.MIN; + import static com.codahale.metrics.MetricAttribute.P50; + import static com.codahale.metrics.MetricAttribute.P75; + import static com.codahale.metrics.MetricAttribute.P95; +@@ -15,6 +13,7 @@ import static com.codahale.metrics.MetricAttribute.P98; + import static com.codahale.metrics.MetricAttribute.P99; + import static com.codahale.metrics.MetricAttribute.P999; + import static com.codahale.metrics.MetricAttribute.STDDEV; ++import static java.util.Collections.emptySet; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.Counter; +@@ -29,7 +28,6 @@ import com.codahale.metrics.ScheduledReporter; + import com.codahale.metrics.Snapshot; + import com.codahale.metrics.Timer; + import java.io.IOException; +-import java.util.Collections; + import java.util.Locale; + import java.util.Map; + import java.util.Set; +@@ -83,7 +81,7 @@ public class GraphiteReporter extends ScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = emptySet(); + this.addMetricAttributesAsTags = false; + this.floatingPointFormatter = DEFAULT_FP_FORMATTER; + } +@@ -453,9 +451,9 @@ public class GraphiteReporter extends ScheduledReporter { + + private void reportTimer(String name, Timer timer, long timestamp) throws IOException { + final Snapshot snapshot = timer.getSnapshot(); +- sendIfEnabled(MAX, name, convertDuration(snapshot.getMax()), timestamp); ++ sendIfEnabled(MetricAttribute.MAX, name, convertDuration(snapshot.getMax()), timestamp); + sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); +- sendIfEnabled(MIN, name, convertDuration(snapshot.getMin()), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, convertDuration(snapshot.getMin()), timestamp); + sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); + sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); + sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); +@@ -478,9 +476,9 @@ public class GraphiteReporter extends ScheduledReporter { + throws IOException { + final Snapshot snapshot = histogram.getSnapshot(); + sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); +- sendIfEnabled(MAX, name, snapshot.getMax(), timestamp); ++ sendIfEnabled(MetricAttribute.MAX, name, snapshot.getMax(), timestamp); + sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); +- sendIfEnabled(MIN, name, snapshot.getMin(), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, snapshot.getMin(), timestamp); + sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); + sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); + sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); +--- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java ++++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java +@@ -63,7 +63,7 @@ public class GraphiteUDP implements GraphiteSender { + @Override + public void send(String name, String value, long timestamp) throws IOException { + try { +- String str = sanitize(name) + ' ' + sanitize(value) + ' ' + Long.toString(timestamp) + '\n'; ++ String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n'; + ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); + datagramChannel.send(byteBuffer, address); + this.failures = 0; +--- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java ++++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java +@@ -249,7 +249,7 @@ public class PickledGraphite implements GraphiteSender { + * message to graphite 3. Clear out the list of metrics + */ + private void writeMetrics() throws IOException { +- if (metrics.size() > 0) { ++ if (!metrics.isEmpty()) { + try { + byte[] payload = pickleMetrics(metrics); + byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteRabbitMQTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteRabbitMQTest.java +@@ -8,7 +8,6 @@ import static org.mockito.Mockito.anyString; + import static org.mockito.Mockito.atMost; + import static org.mockito.Mockito.doThrow; + import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -21,13 +20,13 @@ import org.junit.Before; + import org.junit.Test; + + public class GraphiteRabbitMQTest { +- private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); +- private final Connection connection = mock(Connection.class); +- private final Channel channel = mock(Channel.class); ++ private final ConnectionFactory connectionFactory = mock(); ++ private final Connection connection = mock(); ++ private final Channel channel = mock(); + +- private final ConnectionFactory bogusConnectionFactory = mock(ConnectionFactory.class); +- private final Connection bogusConnection = mock(Connection.class); +- private final Channel bogusChannel = mock(Channel.class); ++ private final ConnectionFactory bogusConnectionFactory = mock(); ++ private final Connection bogusConnection = mock(); ++ private final Channel bogusChannel = mock(); + + private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); + +@@ -92,10 +91,9 @@ public class GraphiteRabbitMQTest { + + String expectedMessage = "name value 100\n"; + +- verify(channel, times(1)) +- .basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); ++ verify(channel).basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); + +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } + + @Test +@@ -105,10 +103,10 @@ public class GraphiteRabbitMQTest { + + String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; + +- verify(channel, times(1)) ++ verify(channel) + .basicPublish("graphite", "name-to-sanitize", null, expectedMessage.getBytes(UTF_8)); + +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } + + @Test +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java +@@ -1,5 +1,6 @@ + package com.codahale.metrics.graphite; + ++import static java.util.Collections.emptySet; + import static org.mockito.Mockito.doThrow; + import static org.mockito.Mockito.inOrder; + import static org.mockito.Mockito.mock; +@@ -21,7 +22,6 @@ import com.codahale.metrics.Timer; + import java.net.UnknownHostException; + import java.text.DecimalFormat; + import java.text.DecimalFormatSymbols; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.Locale; + import java.util.Set; +@@ -34,9 +34,9 @@ import org.mockito.InOrder; + + public class GraphiteReporterTest { + private final long timestamp = 1000198; +- private final Clock clock = mock(Clock.class); +- private final Graphite graphite = mock(Graphite.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final Clock clock = mock(); ++ private final Graphite graphite = mock(); ++ private final MetricRegistry registry = mock(); + private final GraphiteReporter reporter = + GraphiteReporter.forRegistry(registry) + .withClock(clock) +@@ -44,7 +44,7 @@ public class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(emptySet()) + .build(graphite); + + private final GraphiteReporter minuteRateReporter = +@@ -54,7 +54,7 @@ public class GraphiteReporterTest { + .convertRatesTo(TimeUnit.MINUTES) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(emptySet()) + .build(graphite); + + @Before +@@ -174,7 +174,7 @@ public class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(emptySet()) + .withFloatingPointFormatter(formatter::format) + .build(graphite)) { + reportGaugeValue(graphiteReporter, 0.000045322); +@@ -216,7 +216,7 @@ public class GraphiteReporterTest { + + @Test + public void reportsCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map("counter", counter), map(), map(), map()); +@@ -232,10 +232,10 @@ public class GraphiteReporterTest { + + @Test + public void reportsHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -272,7 +272,7 @@ public class GraphiteReporterTest { + + @Test + public void reportsMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); +@@ -296,7 +296,7 @@ public class GraphiteReporterTest { + + @Test + public void reportsMetersInMinutes() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); +@@ -321,14 +321,14 @@ public class GraphiteReporterTest { + + @Test + public void reportsTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -395,14 +395,14 @@ public class GraphiteReporterTest { + + @Test + public void disabledMetricsAttribute() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(11L); + + Set disabledMetricAttributes = +@@ -433,7 +433,7 @@ public class GraphiteReporterTest { + + @Test + public void sendsMetricAttributesAsTagsIfEnabled() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + getReporterThatSendsMetricAttributesAsTags() +@@ -459,7 +459,7 @@ public class GraphiteReporterTest { + MetricFilter.ALL, + null, + false, +- Collections.emptySet(), ++ emptySet(), + false) { + @Override + protected String format(double v) { +@@ -475,7 +475,7 @@ public class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(emptySet()) + .addMetricAttributesAsTags(true) + .build(graphite); + } +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java +@@ -26,11 +26,11 @@ import org.junit.Test; + public class GraphiteTest { + private final String host = "example.com"; + private final int port = 1234; +- private final SocketFactory socketFactory = mock(SocketFactory.class); ++ private final SocketFactory socketFactory = mock(); + private final InetSocketAddress address = new InetSocketAddress(host, port); + +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); + + @Before + public void setUp() throws Exception { +@@ -84,7 +84,7 @@ public class GraphiteTest { + @Test + public void measuresFailures() throws IOException { + try (Graphite graphite = new Graphite(address, socketFactory)) { +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } + } + +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java +@@ -1,13 +1,13 @@ + package com.codahale.metrics.graphite; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; + + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; + import java.nio.channels.DatagramChannel; + import org.junit.Test; +-import org.mockito.Mockito; + + public class GraphiteUDPTest { + +@@ -30,7 +30,7 @@ public class GraphiteUDPTest { + @Test + public void writesValue() throws Exception { + graphiteUDP = new GraphiteUDP(host, port); +- DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); ++ DatagramChannel mockDatagramChannel = mock(); + graphiteUDP.setDatagramChannel(mockDatagramChannel); + graphiteUDP.setAddress(new InetSocketAddress(host, port)); + +--- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java ++++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java +@@ -32,12 +32,12 @@ import org.python.core.PyList; + import org.python.core.PyTuple; + + public class PickledGraphiteTest { +- private final SocketFactory socketFactory = mock(SocketFactory.class); ++ private final SocketFactory socketFactory = mock(); + private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); + private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); + +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); + + private CompiledScript unpickleScript; + +--- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java ++++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java +@@ -29,10 +29,10 @@ public class AsyncHealthCheckDecorator extends HealthCheck implements Runnable { + this.healthyTtl = + async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); + result = +- Async.InitialState.HEALTHY.equals(async.initialState()) ++ Async.InitialState.HEALTHY == async.initialState() + ? Result.healthy(NO_RESULT_YET_MESSAGE) + : Result.unhealthy(NO_RESULT_YET_MESSAGE); +- if (Async.ScheduleType.FIXED_RATE.equals(async.scheduleType())) { ++ if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) { + future = + executorService.scheduleAtFixedRate( + this, async.initialDelay(), async.period(), async.unit()); +--- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java ++++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java +@@ -1,11 +1,12 @@ + package com.codahale.metrics.health; + ++import static java.util.Collections.unmodifiableMap; ++ + import com.codahale.metrics.Clock; + import java.time.Instant; + import java.time.ZoneId; + import java.time.ZonedDateTime; + import java.time.format.DateTimeFormatter; +-import java.util.Collections; + import java.util.LinkedHashMap; + import java.util.Map; + import java.util.concurrent.TimeUnit; +@@ -124,7 +125,7 @@ public abstract class HealthCheck { + this.healthy = isHealthy; + this.message = message; + this.error = error; +- this.details = details == null ? null : Collections.unmodifiableMap(details); ++ this.details = details == null ? null : unmodifiableMap(details); + this.time = clock.getTime(); + } + +@@ -163,7 +164,7 @@ public abstract class HealthCheck { + */ + public String getTimestamp() { + Instant currentInstant = Instant.ofEpochMilli(time); +- ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(currentInstant, ZoneId.systemDefault()); ++ ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault()); + return DATE_FORMAT_PATTERN.format(zonedDateTime); + } + +@@ -219,8 +220,7 @@ public abstract class HealthCheck { + int result = healthy ? 1 : 0; + result = PRIME * result + (message != null ? message.hashCode() : 0); + result = PRIME * result + (error != null ? error.hashCode() : 0); +- result = PRIME * result + (Long.hashCode(time)); +- return result; ++ return PRIME * result + (Long.hashCode(time)); + } + + @Override +@@ -238,7 +238,7 @@ public abstract class HealthCheck { + if (details != null) { + for (Map.Entry e : details.entrySet()) { + builder.append(", "); +- builder.append(e.getKey()).append("=").append(String.valueOf(e.getValue())); ++ builder.append(e.getKey()).append("=").append(e.getValue()); + } + } + builder.append('}'); +--- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java ++++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java +@@ -1,9 +1,10 @@ + package com.codahale.metrics.health; + + import static com.codahale.metrics.health.HealthCheck.Result; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; + + import com.codahale.metrics.health.annotation.Async; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -128,7 +129,7 @@ public class HealthCheckRegistry { + * @return the names of all registered health checks + */ + public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); ++ return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); + } + + /** +@@ -180,7 +181,7 @@ public class HealthCheckRegistry { + results.put(entry.getKey(), result); + } + } +- return Collections.unmodifiableSortedMap(results); ++ return unmodifiableSortedMap(results); + } + + /** +@@ -208,7 +209,7 @@ public class HealthCheckRegistry { + final String name = entry.getKey(); + final HealthCheck healthCheck = entry.getValue(); + if (filter.matches(name, healthCheck)) { +- futures.put(name, executor.submit(() -> healthCheck.execute())); ++ futures.put(name, executor.submit(healthCheck::execute)); + } + } + +@@ -222,7 +223,7 @@ public class HealthCheckRegistry { + } + } + +- return Collections.unmodifiableSortedMap(results); ++ return unmodifiableSortedMap(results); + } + + private void onHealthCheckAdded(String name, HealthCheck healthCheck) { +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/AsyncHealthCheckDecoratorTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/AsyncHealthCheckDecoratorTest.java +@@ -5,7 +5,6 @@ import static org.mockito.ArgumentCaptor.forClass; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -31,11 +30,11 @@ public class AsyncHealthCheckDecoratorTest { + .withMessage("Result was healthy but it expired 1 milliseconds ago") + .build(); + +- private final HealthCheck mockHealthCheck = mock(HealthCheck.class); +- private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); ++ private final HealthCheck mockHealthCheck = mock(); ++ private final ScheduledExecutorService mockExecutorService = mock(); + + @SuppressWarnings("rawtypes") +- private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); ++ private final ScheduledFuture mockFuture = mock(); + + @Test(expected = IllegalArgumentException.class) + public void nullHealthCheckTriggersInstantiationFailure() { +@@ -74,7 +73,7 @@ public class AsyncHealthCheckDecoratorTest { + AsyncHealthCheckDecorator asyncDecorator = + new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); + assertThat(asyncDecorator.check().isHealthy()).isTrue(); +@@ -87,7 +86,7 @@ public class AsyncHealthCheckDecoratorTest { + AsyncHealthCheckDecorator asyncDecorator = + new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); + } +@@ -102,8 +101,8 @@ public class AsyncHealthCheckDecoratorTest { + assertThat(asyncDecorator.check().isHealthy()).isFalse(); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void tearDownTriggersCancellation() throws Exception { + when(mockExecutorService.scheduleAtFixedRate( + any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) +@@ -114,13 +113,13 @@ public class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); + asyncDecorator.tearDown(); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); +- verify(mockFuture, times(1)).cancel(eq(true)); ++ verify(mockFuture).cancel(true); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { + HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); + when(mockExecutorService.scheduleAtFixedRate( +@@ -133,7 +132,7 @@ public class AsyncHealthCheckDecoratorTest { + HealthCheck.Result initialResult = asyncDecorator.check(); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +@@ -143,8 +142,8 @@ public class AsyncHealthCheckDecoratorTest { + assertThat(actualResult).isNotEqualTo(initialResult); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { + Exception exception = new Exception("TestException"); + when(mockExecutorService.scheduleAtFixedRate( +@@ -156,7 +155,7 @@ public class AsyncHealthCheckDecoratorTest { + new ConfigurableAsyncHealthCheck(exception), mockExecutorService); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +@@ -173,7 +172,7 @@ public class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate( + runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); +@@ -192,7 +191,7 @@ public class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate( + runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); +@@ -210,7 +209,7 @@ public class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckRegistryTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckRegistryTest.java +@@ -23,21 +23,21 @@ import org.junit.Test; + import org.mockito.ArgumentCaptor; + + public class HealthCheckRegistryTest { +- private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); ++ private final ScheduledExecutorService executorService = mock(); + private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); +- private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ private final HealthCheckRegistryListener listener = mock(); + +- private final HealthCheck hc1 = mock(HealthCheck.class); +- private final HealthCheck hc2 = mock(HealthCheck.class); ++ private final HealthCheck hc1 = mock(); ++ private final HealthCheck hc2 = mock(); + +- private final HealthCheck.Result r1 = mock(HealthCheck.Result.class); +- private final HealthCheck.Result r2 = mock(HealthCheck.Result.class); ++ private final HealthCheck.Result r1 = mock(); ++ private final HealthCheck.Result r2 = mock(); + +- private final HealthCheck.Result ar = mock(HealthCheck.Result.class); ++ private final HealthCheck.Result ar = mock(); + private final HealthCheck ahc = new TestAsyncHealthCheck(ar); + + @SuppressWarnings("rawtypes") +- private final ScheduledFuture af = mock(ScheduledFuture.class); ++ private final ScheduledFuture af = mock(); + + @Before + @SuppressWarnings("unchecked") +@@ -96,7 +96,7 @@ public class HealthCheckRegistryTest { + + @Test + public void addingListenerCatchesExistingHealthChecks() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ HealthCheckRegistryListener listener = mock(); + HealthCheckRegistry registry = new HealthCheckRegistry(); + registry.register("hc1", hc1); + registry.register("hc2", hc2); +@@ -110,7 +110,7 @@ public class HealthCheckRegistryTest { + + @Test + public void removedListenerDoesNotReceiveUpdates() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ HealthCheckRegistryListener listener = mock(); + HealthCheckRegistry registry = new HealthCheckRegistry(); + registry.addListener(listener); + registry.register("hc1", hc1); +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java +@@ -29,7 +29,7 @@ public class HealthCheckTest { + } + } + +- private final HealthCheck underlying = mock(HealthCheck.class); ++ private final HealthCheck underlying = mock(); + private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); + + @Test +@@ -89,7 +89,7 @@ public class HealthCheckTest { + + @Test + public void canHaveUnhealthyResultsWithExceptions() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); +@@ -144,7 +144,7 @@ public class HealthCheckTest { + + @Test + public void canHaveUnHealthyBuilderWithDetailAndError() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + final HealthCheck.Result result = +@@ -161,7 +161,7 @@ public class HealthCheckTest { + + @Test + public void returnsResultsWhenExecuted() { +- final HealthCheck.Result result = mock(HealthCheck.Result.class); ++ final HealthCheck.Result result = mock(); + when(underlying.execute()).thenReturn(result); + + assertThat(healthCheck.execute()).isEqualTo(result); +@@ -171,7 +171,7 @@ public class HealthCheckTest { + + @Test + public void wrapsExceptionsWhenExecuted() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + when(underlying.execute()).thenThrow(e); +@@ -181,7 +181,7 @@ public class HealthCheckTest { + assertThat(actual.getMessage()).isEqualTo("oh noes"); + assertThat(actual.getError()).isEqualTo(e); + assertThat(actual.getDetails()).isNull(); +- assertThat(actual.getDuration()).isGreaterThanOrEqualTo(0); ++ assertThat(actual.getDuration()).isNotNegative(); + } + + @Test +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java +@@ -30,7 +30,7 @@ public class SharedHealthCheckRegistriesTest { + public void returnsSetOfCreatedRegistries() { + SharedHealthCheckRegistries.getOrCreate("db"); + +- assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); ++ assertThat(SharedHealthCheckRegistries.names()).containsExactly("db"); + } + + @Test +--- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java +@@ -1,12 +1,12 @@ + package com.codahale.metrics.health.jvm; + ++import static java.util.Collections.emptySet; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + + import com.codahale.metrics.health.HealthCheck; + import com.codahale.metrics.jvm.ThreadDeadlockDetector; +-import java.util.Collections; + import java.util.Set; + import java.util.TreeSet; + import org.junit.Test; +@@ -14,10 +14,10 @@ import org.junit.Test; + public class ThreadDeadlockHealthCheckTest { + @Test + public void isHealthyIfNoThreadsAreDeadlocked() { +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ final ThreadDeadlockDetector detector = mock(); + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); + +- when(detector.getDeadlockedThreads()).thenReturn(Collections.emptySet()); ++ when(detector.getDeadlockedThreads()).thenReturn(emptySet()); + + assertThat(healthCheck.execute().isHealthy()).isTrue(); + } +@@ -28,7 +28,7 @@ public class ThreadDeadlockHealthCheckTest { + threads.add("one"); + threads.add("two"); + +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ final ThreadDeadlockDetector detector = mock(); + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); + + when(detector.getDeadlockedThreads()).thenReturn(threads); +--- a/metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/InstrumentedHttpClientsTimerTest.java ++++ b/metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/InstrumentedHttpClientsTimerTest.java +@@ -45,7 +45,7 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + chac.start(); + asyncHttpClient = chac; + +- Timer timer = mock(Timer.class); ++ Timer timer = mock(); + when(timer.time()).thenReturn(context); + when(metricRegistry.timer(any())).thenReturn(timer); + } +@@ -71,13 +71,13 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + verify(context, timeout(200).times(1)).stop(); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { + HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); + HttpGet get = new HttpGet("/?q=something"); + +- FutureCallback futureCallback = mock(FutureCallback.class); ++ FutureCallback futureCallback = mock(); + + // Timer hasn't been stopped prior to executing the request + verify(context, never()).stop(); +@@ -98,14 +98,14 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + verify(context, timeout(200).times(1)).stop(); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + public void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { + // There should be nothing listening on this port + HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); + HttpGet get = new HttpGet("/?q=something"); + +- FutureCallback futureCallback = mock(FutureCallback.class); ++ FutureCallback futureCallback = mock(); + + // Timer hasn't been stopped prior to executing the request + verify(context, never()).stop(); +--- a/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientConnectionManagerTest.java +@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import com.codahale.metrics.MetricRegistry; + import org.junit.Assert; + import org.junit.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; + + public class InstrumentedHttpClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); +@@ -36,7 +38,7 @@ public class InstrumentedHttpClientConnectionManagerTest { + + @Test + public void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); + + InstrumentedHttpClientConnectionManager.builder(registry) + .name("some-name") +@@ -45,7 +47,7 @@ public class InstrumentedHttpClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); + assertTrue(argumentCaptor.getValue().contains("some-other-name")); + } + } +--- a/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientsTest.java +@@ -22,9 +22,8 @@ import org.junit.Before; + import org.junit.Test; + + public class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); + private final MetricRegistry metricRegistry = new MetricRegistry(); + private final HttpClient client = + InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) +--- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java +@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import com.codahale.metrics.MetricRegistry; + import org.junit.Assert; + import org.junit.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; + + public class InstrumentedAsyncClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); +@@ -43,7 +45,7 @@ public class InstrumentedAsyncClientConnectionManagerTest { + + @Test + public void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); + + InstrumentedAsyncClientConnectionManager.builder(registry) + .name("some-name") +@@ -52,7 +54,7 @@ public class InstrumentedAsyncClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); + assertTrue(argumentCaptor.getValue().contains("some-other-name")); + } + } +--- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java ++++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java +@@ -1,5 +1,6 @@ + package com.codahale.metrics.httpclient5; + ++import static java.nio.charset.StandardCharsets.US_ASCII; + import static org.assertj.core.api.Assertions.assertThat; + import static org.awaitility.Awaitility.await; + import static org.junit.Assert.fail; +@@ -17,7 +18,6 @@ import com.sun.net.httpserver.HttpExchange; + import com.sun.net.httpserver.HttpServer; + import java.io.IOException; + import java.net.InetSocketAddress; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.ExecutionException; + import java.util.concurrent.Future; +@@ -82,7 +82,7 @@ public class InstrumentedHttpAsyncClientsTest { + exchange -> { + exchange.sendResponseHeaders(200, 0L); + exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); + exchange.close(); + }); + httpServer.start(); +@@ -187,7 +187,7 @@ public class InstrumentedHttpAsyncClientsTest { + exchange -> { + exchange.sendResponseHeaders(200, 0L); + exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); + exchange.close(); + }); + httpServer.start(); +--- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientConnectionManagerTest.java +@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import com.codahale.metrics.MetricRegistry; + import org.junit.Assert; + import org.junit.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; + + public class InstrumentedHttpClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); +@@ -41,7 +43,7 @@ public class InstrumentedHttpClientConnectionManagerTest { + + @Test + public void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); + + InstrumentedHttpClientConnectionManager.builder(registry) + .name("some-name") +@@ -50,7 +52,7 @@ public class InstrumentedHttpClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); + assertTrue(argumentCaptor.getValue().contains("some-other-name")); + } + } +--- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java +@@ -22,9 +22,8 @@ import org.junit.Before; + import org.junit.Test; + + public class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); + private final MetricRegistry metricRegistry = new MetricRegistry(); + private final HttpClient client = + InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) +--- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListenerTest.java +@@ -10,7 +10,7 @@ import jakarta.servlet.ServletContextEvent; + import org.junit.Test; + + public class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ public class InstrumentedFilterContextListenerTest { + + @Test + public void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); + + listener.contextInitialized(event); +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java +@@ -83,7 +83,7 @@ public class HealthCheckServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); + if (registryAttr instanceof HealthCheckRegistry) { + this.registry = (HealthCheckRegistry) registryAttr; +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java +@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(METRICS_REGISTRY); + if (registryAttr instanceof MetricRegistry) { + this.registry = (MetricRegistry) registryAttr; +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java +@@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -102,9 +101,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -143,9 +141,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -217,15 +214,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getContent()) + .isEqualTo( + String.format( +- "{%n" +- + " \"fun\" : {%n" +- + " \"healthy\" : true,%n" +- + " \"message\" : \"foo bar 123\",%n" +- + " \"duration\" : 0,%n" +- + " \"timestamp\" : \"" +- + EXPECTED_TIMESTAMP +- + "\"" +- + "%n }%n}")); ++ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", ++ EXPECTED_TIMESTAMP)); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -240,25 +230,25 @@ public class HealthCheckServletTest extends AbstractServletTest { + @Test + public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() + throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final io.dropwizard.metrics.servlets.HealthCheckServlet healthCheckServlet = + new io.dropwizard.metrics.servlets.HealthCheckServlet(healthCheckRegistry); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()) + .getAttribute(eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY)); + } + + @Test + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute( + eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY))) +@@ -268,16 +258,16 @@ public class HealthCheckServletTest extends AbstractServletTest { + new io.dropwizard.metrics.servlets.HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)) ++ verify(servletConfig).getServletContext(); ++ verify(servletContext) + .getAttribute(eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY)); + } + + @Test(expected = ServletException.class) + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute( + eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY))) +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletContextListenerTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletContextListenerTest.java +@@ -17,7 +17,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MetricsServletContextListenerTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final String allowedOrigin = "some.other.origin"; + +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java +@@ -1,10 +1,8 @@ + package io.dropwizard.metrics.servlets; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -24,7 +22,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MetricsServletTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private ServletTester tester; + +@@ -128,22 +126,8 @@ public class MetricsServletTest extends AbstractServletTest { + assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); + assertThat(response.getContent()) + .isEqualTo( +- callbackParamVal +- + "({" +- + "\"version\":\"4.0.0\"," +- + "\"gauges\":{" +- + "\"g1\":{\"value\":100}" +- + "}," +- + "\"counters\":{" +- + "\"c\":{\"count\":1}" +- + "}," +- + "\"histograms\":{" +- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" +- + "}," +- + "\"meters\":{" +- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" +- + "}" +- + "})"); ++ "%s({\"version\":\"4.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", ++ callbackParamVal); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -223,47 +207,47 @@ public class MetricsServletTest extends AbstractServletTest { + @Test + public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() + throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = + new io.dropwizard.metrics.servlets.MetricsServlet(metricRegistry); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()) +- .getAttribute(eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)); ++ .getAttribute(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY); + } + + @Test + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute( +- eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY))) ++ io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)) + .thenReturn(metricRegistry); + + final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = + new io.dropwizard.metrics.servlets.MetricsServlet(null); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)) +- .getAttribute(eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext) ++ .getAttribute(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY); + } + + @Test(expected = ServletException.class) + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute( +- eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY))) ++ io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); + + final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = new MetricsServlet(null); +--- a/metrics-jcache/src/main/java/com/codahale/metrics/jcache/JCacheGaugeSet.java ++++ b/metrics-jcache/src/main/java/com/codahale/metrics/jcache/JCacheGaugeSet.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics.jcache; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Metric; + import com.codahale.metrics.MetricSet; +@@ -8,7 +9,6 @@ import com.codahale.metrics.jvm.JmxAttributeGauge; + import java.lang.management.ManagementFactory; + import java.lang.reflect.Method; + import java.util.ArrayList; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Locale; +@@ -51,7 +51,7 @@ public class JCacheGaugeSet implements MetricSet { + } + } + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + + private Set getCacheBeans() { +--- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java ++++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java +@@ -71,18 +71,18 @@ public class JCacheGaugeSetTest { + assertThat( + (Float) + registry.getGauges().get("jcache.statistics.myCache.average-get-time").getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + assertThat( + (Float) + registry.getGauges().get("jcache.statistics.myCache.average-put-time").getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + assertThat( + (Float) + registry + .getGauges() + .get("jcache.statistics.myCache.average-remove-time") + .getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + } + + @After +--- a/metrics-jdbi/src/main/java/com/codahale/metrics/jdbi/strategies/NameStrategies.java ++++ b/metrics-jdbi/src/main/java/com/codahale/metrics/jdbi/strategies/NameStrategies.java +@@ -45,7 +45,7 @@ public final class NameStrategies { + public String getStatementName(StatementContext statementContext) { + final String rawSql = statementContext.getRawSql(); + +- if (rawSql == null || rawSql.length() == 0) { ++ if (rawSql == null || rawSql.isEmpty()) { + return EMPTY_SQL; + } + return null; +--- a/metrics-jdbi/src/test/java/com/codahale/metrics/jdbi/InstrumentedTimingCollectorTest.java ++++ b/metrics-jdbi/src/test/java/com/codahale/metrics/jdbi/InstrumentedTimingCollectorTest.java +@@ -23,7 +23,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass()).when(ctx).getSqlObjectType(); + doReturn(getClass().getMethod("updatesTimerForSqlObjects")).when(ctx).getSqlObjectMethod(); +@@ -42,7 +42,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass()).when(ctx).getSqlObjectType(); + +@@ -60,7 +60,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + + collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); +@@ -77,7 +77,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + + collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); + +@@ -93,7 +93,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("don't know what it is but it's not SQL").when(ctx).getRawSql(); + + collector.collect(TimeUnit.SECONDS.toNanos(3), ctx); +@@ -110,7 +110,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass().getName()).when(ctx).getAttribute(NameStrategies.STATEMENT_CLASS); + doReturn("updatesTimerForContextClass").when(ctx).getAttribute(NameStrategies.STATEMENT_NAME); +@@ -129,7 +129,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn("foo/bar.stg").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); + doReturn("updatesTimerForTemplateFile").when(ctx).getAttribute(NameStrategies.STATEMENT_NAME); +@@ -148,7 +148,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn("my-group").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); + doReturn("updatesTimerForContextGroupAndName") +@@ -169,7 +169,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new SmartNameStrategy(); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn("my-group").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); + doReturn("my-type").when(ctx).getAttribute(NameStrategies.STATEMENT_TYPE); +@@ -192,7 +192,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new ShortNameStrategy("jdbi"); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass()).when(ctx).getSqlObjectType(); + doReturn(getClass().getMethod("updatesTimerForShortSqlObjectStrategy")) +@@ -215,7 +215,7 @@ public class InstrumentedTimingCollectorTest { + final StatementNameStrategy strategy = new ShortNameStrategy("jdbi"); + final InstrumentedTimingCollector collector = + new InstrumentedTimingCollector(registry, strategy); +- final StatementContext ctx = mock(StatementContext.class); ++ final StatementContext ctx = mock(); + doReturn("SELECT 1").when(ctx).getRawSql(); + doReturn(getClass().getName()).when(ctx).getAttribute(NameStrategies.STATEMENT_CLASS); + doReturn("updatesTimerForShortContextClassStrategy") +--- a/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/InstrumentedSqlLoggerTest.java ++++ b/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/InstrumentedSqlLoggerTest.java +@@ -16,12 +16,12 @@ import org.junit.Test; + public class InstrumentedSqlLoggerTest { + @Test + public void logsExecutionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); + final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); + +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); + + final String statementName = "my-fake-name"; + final long fakeElapsed = 1234L; +@@ -38,12 +38,12 @@ public class InstrumentedSqlLoggerTest { + + @Test + public void logsExceptionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); + final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); + +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); + + final String statementName = "my-fake-name"; + final long fakeElapsed = 1234L; +--- a/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/AbstractStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/AbstractStrategyTest.java +@@ -10,7 +10,7 @@ import org.junit.Before; + public class AbstractStrategyTest { + + MetricRegistry registry = new MetricRegistry(); +- StatementContext ctx = mock(StatementContext.class); ++ StatementContext ctx = mock(); + + @Before + public void setUp() throws Exception { +--- a/metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.ExponentiallyDecayingReservoir; +@@ -19,7 +22,6 @@ import com.codahale.metrics.annotation.Timed; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(metricName, "1xx-responses")), // 1xx + registry.meter(name(metricName, "2xx-responses")), // 2xx +@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(name(metricName, "4xx-responses")), // 4xx + registry.meter(name(metricName, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); + this.metricRegistry = registry; + } + +@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); + } + } + } +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonFilterMetricsJerseyTest.java +@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @Before +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } + + @Test +@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsJerseyTest.java +@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -87,12 +85,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(0); + } + + @Test +@@ -107,9 +105,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -119,9 +117,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } + + @Test +@@ -131,12 +129,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + + @Test +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsTimedPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } + + @Test +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } + + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } + + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedResource.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import javax.ws.rs.core.Response; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,24 +46,24 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +--- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedSubResource.java ++++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import javax.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +--- a/metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.ExponentiallyDecayingReservoir; +@@ -21,7 +24,6 @@ import jakarta.ws.rs.ext.Provider; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(metricName, "1xx-responses")), // 1xx + registry.meter(name(metricName, "2xx-responses")), // 2xx +@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(name(metricName, "4xx-responses")), // 4xx + registry.meter(name(metricName, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); + this.metricRegistry = registry; + } + +@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); + } + } + } +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonFilterMetricsJerseyTest.java +@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @Before +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } + + @Test +@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsJerseyTest.java +@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -92,9 +90,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -104,9 +102,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } + + @Test +@@ -116,12 +114,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + + @Test +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsTimedPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } + + @Test +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } + + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } + + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedResource.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,24 +46,24 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +--- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedSubResource.java ++++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +--- a/metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Clock; + import com.codahale.metrics.ExponentiallyDecayingReservoir; +@@ -21,7 +24,6 @@ import jakarta.ws.rs.ext.Provider; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(metricName, "1xx-responses")), // 1xx + registry.meter(name(metricName, "2xx-responses")), // 2xx +@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(name(metricName, "4xx-responses")), // 4xx + registry.meter(name(metricName, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); + this.metricRegistry = registry; + } + +@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); + } + } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonFilterMetricsJerseyTest.java +@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @Before +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } + + @Test +@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsJerseyTest.java +@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -87,12 +85,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(0); + } + + @Test +@@ -107,9 +105,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -119,9 +117,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } + + @Test +@@ -131,12 +129,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + + @Test +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsTimedPerClassJerseyTest.java +@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } + + @Test +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } + + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } + + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,24 +46,24 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedSubResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -13,7 +16,6 @@ import com.codahale.metrics.Timer; + import com.codahale.metrics.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -172,10 +174,10 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx +@@ -183,7 +185,7 @@ public class InstrumentedHandler extends HandlerWrapper { + metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx + metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -14,7 +17,6 @@ import com.codahale.metrics.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(prefix, "1xx-responses")), // 1xx + registry.meter(name(prefix, "2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(name(prefix, "4xx-responses")), // 4xx + registry.meter(name(prefix, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); + this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java +@@ -1,12 +1,12 @@ + package io.dropwizard.metrics.jetty10; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatCode; + + import com.codahale.metrics.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import javax.servlet.AsyncContext; + import javax.servlet.ServletException; +@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { + assertThatCode(handler::doStop).doesNotThrowAnyException(); + } + +- @Test + @Ignore("flaky on virtual machines") ++ @Test + public void responseTimesAreRecordedForAsyncResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/async")); +@@ -126,15 +126,14 @@ public class InstrumentedHandlerTest { + } + + private void assertResponseTimesValid() { +- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) +- .isGreaterThan(0L); ++ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); + + assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -197,7 +196,7 @@ public class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListenerTest.java +@@ -1,11 +1,11 @@ + package io.dropwizard.metrics.jetty10; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import com.codahale.metrics.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import javax.servlet.AsyncContext; + import javax.servlet.ServletOutputStream; + import javax.servlet.WriteListener; +@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -172,10 +174,10 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx +@@ -183,7 +185,7 @@ public class InstrumentedHandler extends HandlerWrapper { + metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx + metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(prefix, "1xx-responses")), // 1xx + registry.meter(name(prefix, "2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(name(prefix, "4xx-responses")), // 4xx + registry.meter(name(prefix, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); + this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics.jetty11; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatCode; + +@@ -12,7 +13,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; +@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { + assertThatCode(handler::doStop).doesNotThrowAnyException(); + } + +- @Test + @Ignore("flaky on virtual machines") ++ @Test + public void responseTimesAreRecordedForAsyncResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/async")); +@@ -126,17 +126,15 @@ public class InstrumentedHandlerTest { + } + + private void assertResponseTimesValid() { +- assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()) +- .isGreaterThan(0L); +- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) +- .isGreaterThan(0L); ++ assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()).isPositive(); ++ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); + + assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -199,7 +197,7 @@ public class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListenerTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics.jetty11; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import com.codahale.metrics.MetricRegistry; +@@ -10,7 +11,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.Request; +@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java ++++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -13,7 +16,6 @@ import com.codahale.metrics.Timer; + import com.codahale.metrics.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -180,10 +182,10 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx +@@ -191,7 +193,7 @@ public class InstrumentedHandler extends HandlerWrapper { + metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx + metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); +--- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java +@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; + import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.emptyList; ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableList; + + import com.codahale.metrics.Counter; + import com.codahale.metrics.Meter; +@@ -14,7 +17,6 @@ import com.codahale.metrics.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : emptyMap(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(name(prefix, "1xx-responses")), // 1xx + registry.meter(name(prefix, "2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(name(prefix, "4xx-responses")), // 4xx + registry.meter(name(prefix, "5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : emptyList(); + + this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); + this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); +--- a/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java ++++ b/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java +@@ -1,12 +1,12 @@ + package com.codahale.metrics.jetty9; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatCode; + + import com.codahale.metrics.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import javax.servlet.AsyncContext; + import javax.servlet.ServletException; +@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { + assertThatCode(handler::doStop).doesNotThrowAnyException(); + } + +- @Test + @Ignore("flaky on virtual machines") ++ @Test + public void responseTimesAreRecordedForAsyncResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/async")); +@@ -126,17 +126,15 @@ public class InstrumentedHandlerTest { + } + + private void assertResponseTimesValid() { +- assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()) +- .isGreaterThan(0L); +- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) +- .isGreaterThan(0L); ++ assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()).isPositive(); ++ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); + + assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -199,7 +197,7 @@ public class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListenerTest.java +@@ -1,11 +1,11 @@ + package com.codahale.metrics.jetty9; + + import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import com.codahale.metrics.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import javax.servlet.AsyncContext; + import javax.servlet.ServletOutputStream; + import javax.servlet.WriteListener; +@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } + +--- a/metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java ++++ b/metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java +@@ -36,9 +36,8 @@ public class DefaultObjectNameFactory implements ObjectNameFactory { + || shouldQuote(objectName.getKeyProperty("type"))) { + properties.put("type", ObjectName.quote(type)); + } +- objectName = new ObjectName(domain, properties); ++ return new ObjectName(domain, properties); + +- return objectName; + } catch (MalformedObjectNameException e) { + try { + return new ObjectName(domain, "name", ObjectName.quote(name)); +--- a/metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java ++++ b/metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java +@@ -1,5 +1,8 @@ + package com.codahale.metrics.jmx; + ++import static java.util.Collections.emptyMap; ++import static java.util.Collections.unmodifiableMap; ++ + import com.codahale.metrics.Counter; + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Histogram; +@@ -12,7 +15,6 @@ import com.codahale.metrics.Reporter; + import com.codahale.metrics.Timer; + import java.io.Closeable; + import java.lang.management.ManagementFactory; +-import java.util.Collections; + import java.util.Locale; + import java.util.Map; + import java.util.concurrent.ConcurrentHashMap; +@@ -60,8 +62,8 @@ public class JmxReporter implements Reporter, Closeable { + this.durationUnit = TimeUnit.MILLISECONDS; + this.domain = "metrics"; + this.objectNameFactory = new DefaultObjectNameFactory(); +- this.specificDurationUnits = Collections.emptyMap(); +- this.specificRateUnits = Collections.emptyMap(); ++ this.specificDurationUnits = emptyMap(); ++ this.specificRateUnits = emptyMap(); + } + + /** +@@ -128,7 +130,7 @@ public class JmxReporter implements Reporter, Closeable { + * @return {@code this} + */ + public Builder specificDurationUnits(Map specificDurationUnits) { +- this.specificDurationUnits = Collections.unmodifiableMap(specificDurationUnits); ++ this.specificDurationUnits = unmodifiableMap(specificDurationUnits); + return this; + } + +@@ -139,7 +141,7 @@ public class JmxReporter implements Reporter, Closeable { + * @return {@code this} + */ + public Builder specificRateUnits(Map specificRateUnits) { +- this.specificRateUnits = Collections.unmodifiableMap(specificRateUnits); ++ this.specificRateUnits = unmodifiableMap(specificRateUnits); + return this; + } + +--- a/metrics-jmx/src/test/java/com/codahale/metrics/jmx/JmxReporterTest.java ++++ b/metrics-jmx/src/test/java/com/codahale/metrics/jmx/JmxReporterTest.java +@@ -1,5 +1,6 @@ + package com.codahale.metrics.jmx; + ++import static java.util.UUID.randomUUID; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +@@ -20,7 +21,6 @@ import com.codahale.metrics.Timer; + import java.lang.management.ManagementFactory; + import java.util.SortedMap; + import java.util.TreeMap; +-import java.util.UUID; + import java.util.concurrent.TimeUnit; + import javax.management.Attribute; + import javax.management.AttributeList; +@@ -36,7 +36,7 @@ import org.junit.Test; + @SuppressWarnings("rawtypes") + public class JmxReporterTest { + private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); +- private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); ++ private final String name = randomUUID().toString().replaceAll("[{\\-}]", ""); + private final MetricRegistry registry = new MetricRegistry(); + + private final JmxReporter reporter = +@@ -48,12 +48,12 @@ public class JmxReporterTest { + .filter(MetricFilter.ALL) + .build(); + +- private final Gauge gauge = mock(Gauge.class); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); +- private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); ++ private final Gauge gauge = mock(); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); ++ private final ObjectNameFactory mockObjectNameFactory = mock(); + private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); + + @Before +@@ -64,7 +64,7 @@ public class JmxReporterTest { + + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot hSnapshot = mock(Snapshot.class); ++ final Snapshot hSnapshot = mock(); + when(hSnapshot.getMax()).thenReturn(2L); + when(hSnapshot.getMean()).thenReturn(3.0); + when(hSnapshot.getMin()).thenReturn(4L); +@@ -91,7 +91,7 @@ public class JmxReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot tSnapshot = mock(Snapshot.class); ++ final Snapshot tSnapshot = mock(); + when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -274,7 +274,7 @@ public class JmxReporterTest { + + @Test + public void objectNameModifyingMBeanServer() throws Exception { +- MBeanServer mockedMBeanServer = mock(MBeanServer.class); ++ MBeanServer mockedMBeanServer = mock(); + + // overwrite the objectName + when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))) +--- a/metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java ++++ b/metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java +@@ -1,5 +1,7 @@ + package com.codahale.metrics.json; + ++import static java.util.Collections.singletonList; ++ + import com.codahale.metrics.health.HealthCheck; + import com.fasterxml.jackson.core.JsonGenerator; + import com.fasterxml.jackson.core.Version; +@@ -8,7 +10,6 @@ import com.fasterxml.jackson.databind.SerializerProvider; + import com.fasterxml.jackson.databind.module.SimpleSerializers; + import com.fasterxml.jackson.databind.ser.std.StdSerializer; + import java.io.IOException; +-import java.util.Collections; + import java.util.Map; + + public class HealthCheckModule extends Module { +@@ -79,7 +80,6 @@ public class HealthCheckModule extends Module { + + @Override + public void setupModule(SetupContext context) { +- context.addSerializers( +- new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer()))); ++ context.addSerializers(new SimpleSerializers(singletonList(new HealthCheckResultSerializer()))); + } + } +--- a/metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java ++++ b/metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java +@@ -17,8 +17,7 @@ public class HealthCheckModuleTest { + public void serializesAHealthyResult() throws Exception { + HealthCheck.Result result = HealthCheck.Result.healthy(); + assertThat(mapper.writeValueAsString(result)) +- .isEqualTo( +- "{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); ++ .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp()); + } + + @Test +@@ -26,14 +25,8 @@ public class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":true," +- + "\"message\":\"yay for me\"," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -41,14 +34,8 @@ public class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"boo\"," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -60,19 +47,8 @@ public class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy(e); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"oh no\"," +- + "\"error\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh no\"," +- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" +- + "}," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -88,24 +64,8 @@ public class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy(b); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"oh well\"," +- + "\"error\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh well\"," +- + "\"stack\":[\"Blah.blee(Blah.java:150)\"]," +- + "\"cause\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh no\"," +- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" +- + "}" +- + "}," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -129,23 +89,7 @@ public class HealthCheckModuleTest { + + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":true," +- + "\"duration\":0," +- + "\"boolean\":true," +- + "\"integer\":1," +- + "\"long\":2," +- + "\"float\":3.546," +- + "\"double\":4.567," +- + "\"BigInteger\":12345," +- + "\"BigDecimal\":12345.56789," +- + "\"String\":\"string\"," +- + "\"complex\":{" +- + "\"field\":\"value\"" +- + "}," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + } +--- a/metrics-json/src/test/java/com/codahale/metrics/json/MetricsModuleTest.java ++++ b/metrics-json/src/test/java/com/codahale/metrics/json/MetricsModuleTest.java +@@ -42,7 +42,7 @@ public class MetricsModuleTest { + + @Test + public void serializesCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + assertThat(mapper.writeValueAsString(counter)).isEqualTo("{\"count\":100}"); +@@ -50,10 +50,10 @@ public class MetricsModuleTest { + + @Test + public void serializesHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -107,7 +107,7 @@ public class MetricsModuleTest { + + @Test + public void serializesMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(5.0); +@@ -127,14 +127,14 @@ public class MetricsModuleTest { + + @Test + public void serializesTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/BufferPoolMetricSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/BufferPoolMetricSet.java +@@ -1,10 +1,10 @@ + package com.codahale.metrics.jvm; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Metric; + import com.codahale.metrics.MetricSet; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + import javax.management.JMException; +@@ -46,6 +46,6 @@ public class BufferPoolMetricSet implements MetricSet { + } + } + } +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/GarbageCollectorMetricSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/GarbageCollectorMetricSet.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics.jvm; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Metric; +@@ -9,7 +10,6 @@ import java.lang.management.GarbageCollectorMXBean; + import java.lang.management.ManagementFactory; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -43,6 +43,6 @@ public class GarbageCollectorMetricSet implements MetricSet { + gauges.put(name(name, "count"), (Gauge) gc::getCollectionCount); + gauges.put(name(name, "time"), (Gauge) gc::getCollectionTime); + } +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/JvmAttributeGaugeSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/JvmAttributeGaugeSet.java +@@ -1,11 +1,12 @@ + package com.codahale.metrics.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Metric; + import com.codahale.metrics.MetricSet; + import java.lang.management.ManagementFactory; + import java.lang.management.RuntimeMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Locale; + import java.util.Map; +@@ -46,6 +47,6 @@ public class JvmAttributeGaugeSet implements MetricSet { + runtime.getSpecVersion())); + gauges.put("uptime", (Gauge) runtime::getUptime); + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics.jvm; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Metric; +@@ -12,7 +13,6 @@ import java.lang.management.MemoryPoolMXBean; + import java.lang.management.MemoryUsage; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -122,6 +122,6 @@ public class MemoryUsageGaugeSet implements MetricSet { + gauges.put(name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); + } + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java +@@ -1,9 +1,11 @@ + package com.codahale.metrics.jvm; + ++import static java.util.Collections.emptySet; ++import static java.util.Collections.unmodifiableSet; ++ + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashSet; + import java.util.Set; + +@@ -40,19 +42,16 @@ public class ThreadDeadlockDetector { + for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { + final StringBuilder stackTrace = new StringBuilder(); + for (StackTraceElement element : info.getStackTrace()) { +- stackTrace.append("\t at ").append(element.toString()).append(String.format("%n")); ++ stackTrace.append("\t at ").append(element).append(String.format("%n")); + } + + deadlocks.add( + String.format( + "%s locked on %s (owned by %s):%n%s", +- info.getThreadName(), +- info.getLockName(), +- info.getLockOwnerName(), +- stackTrace.toString())); ++ info.getThreadName(), info.getLockName(), info.getLockOwnerName(), stackTrace)); + } +- return Collections.unmodifiableSet(deadlocks); ++ return unmodifiableSet(deadlocks); + } +- return Collections.emptySet(); ++ return emptySet(); + } + } +--- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java ++++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java +@@ -1,6 +1,7 @@ + package com.codahale.metrics.jvm; + + import static com.codahale.metrics.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import com.codahale.metrics.Gauge; + import com.codahale.metrics.Metric; +@@ -8,7 +9,6 @@ import com.codahale.metrics.MetricSet; + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + import java.util.Set; +@@ -56,7 +56,7 @@ public class ThreadStatesGaugeSet implements MetricSet { + "deadlock.count", (Gauge) () -> deadlockDetector.getDeadlockedThreads().size()); + gauges.put("deadlocks", (Gauge>) deadlockDetector::getDeadlockedThreads); + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + + private int getThreadCount(Thread.State state) { +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/BufferPoolMetricSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/BufferPoolMetricSetTest.java +@@ -13,7 +13,7 @@ import org.junit.Test; + + @SuppressWarnings("rawtypes") + public class BufferPoolMetricSetTest { +- private final MBeanServer mBeanServer = mock(MBeanServer.class); ++ private final MBeanServer mBeanServer = mock(); + private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); + + private ObjectName mapped; +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ClassLoadingGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ClassLoadingGaugeSetTest.java +@@ -12,7 +12,7 @@ import org.junit.Test; + @SuppressWarnings("rawtypes") + public class ClassLoadingGaugeSetTest { + +- private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); ++ private final ClassLoadingMXBean cl = mock(); + private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); + + @Before +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java +@@ -12,10 +12,10 @@ public class CpuTimeClockTest { + public void cpuTimeClock() { + final CpuTimeClock clock = new CpuTimeClock(); + +- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(250D)); ++ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(250D)); + + assertThat((double) clock.getTick()) +- .isEqualTo( ++ .isCloseTo( + ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(), offset(1000000.0)); + } + } +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeTest.java +@@ -13,7 +13,7 @@ import org.junit.Test; + + @SuppressWarnings("UnusedDeclaration") + public class FileDescriptorRatioGaugeTest { +- private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); ++ private final UnixOperatingSystemMXBean os = mock(); + + private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); + +@@ -33,9 +33,7 @@ public class FileDescriptorRatioGaugeTest { + OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); + assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); + +- assertThat(new FileDescriptorRatioGauge().getValue()) +- .isGreaterThanOrEqualTo(0.0) +- .isLessThanOrEqualTo(1.0); ++ assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative().isLessThanOrEqualTo(1.0); + } + + @Test +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java +@@ -1,20 +1,20 @@ + package com.codahale.metrics.jvm; + ++import static java.util.Collections.singletonList; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + + import com.codahale.metrics.Gauge; + import java.lang.management.GarbageCollectorMXBean; +-import java.util.Collections; + import org.junit.Before; + import org.junit.Test; + + @SuppressWarnings("unchecked") + public class GarbageCollectorMetricSetTest { +- private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); ++ private final GarbageCollectorMXBean gc = mock(); + private final GarbageCollectorMetricSet metrics = +- new GarbageCollectorMetricSet(Collections.singletonList(gc)); ++ new GarbageCollectorMetricSet(singletonList(gc)); + + @Before + public void setUp() { +@@ -42,6 +42,6 @@ public class GarbageCollectorMetricSetTest { + + @Test + public void autoDiscoversGCs() { +- assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()).isNotEmpty(); ++ assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty(); + } + } +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JmxAttributeGaugeTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JmxAttributeGaugeTest.java +@@ -53,7 +53,7 @@ public class JmxAttributeGaugeTest { + JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); + + assertThat(gauge.getValue()).isInstanceOf(Integer.class); +- assertThat((Integer) gauge.getValue()).isGreaterThan(0); ++ assertThat((Integer) gauge.getValue()).isPositive(); + } + + @Test +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JvmAttributeGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JvmAttributeGaugeSetTest.java +@@ -11,7 +11,7 @@ import org.junit.Test; + + @SuppressWarnings("unchecked") + public class JvmAttributeGaugeSetTest { +- private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); ++ private final RuntimeMXBean runtime = mock(); + private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); + + @Before +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/MemoryUsageGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/MemoryUsageGaugeSetTest.java +@@ -14,14 +14,14 @@ import org.junit.Test; + + @SuppressWarnings("rawtypes") + public class MemoryUsageGaugeSetTest { +- private final MemoryUsage heap = mock(MemoryUsage.class); +- private final MemoryUsage nonHeap = mock(MemoryUsage.class); +- private final MemoryUsage pool = mock(MemoryUsage.class); +- private final MemoryUsage weirdPool = mock(MemoryUsage.class); +- private final MemoryUsage weirdCollection = mock(MemoryUsage.class); +- private final MemoryMXBean mxBean = mock(MemoryMXBean.class); +- private final MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); +- private final MemoryPoolMXBean weirdMemoryPool = mock(MemoryPoolMXBean.class); ++ private final MemoryUsage heap = mock(); ++ private final MemoryUsage nonHeap = mock(); ++ private final MemoryUsage pool = mock(); ++ private final MemoryUsage weirdPool = mock(); ++ private final MemoryUsage weirdCollection = mock(); ++ private final MemoryMXBean mxBean = mock(); ++ private final MemoryPoolMXBean memoryPool = mock(); ++ private final MemoryPoolMXBean weirdMemoryPool = mock(); + + private final MemoryUsageGaugeSet gauges = + new MemoryUsageGaugeSet(mxBean, Arrays.asList(memoryPool, weirdMemoryPool)); +@@ -262,6 +262,6 @@ public class MemoryUsageGaugeSetTest { + + @Test + public void autoDetectsMemoryUsageBeanAndMemoryPools() { +- assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()).isNotEmpty(); ++ assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty(); + } + } +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDeadlockDetectorTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDeadlockDetectorTest.java +@@ -12,7 +12,7 @@ import java.util.Locale; + import org.junit.Test; + + public class ThreadDeadlockDetectorTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); ++ private final ThreadMXBean threads = mock(); + private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); + + @Test +@@ -24,7 +24,7 @@ public class ThreadDeadlockDetectorTest { + + @Test + public void returnsASetOfThreadsIfAnyAreDeadlocked() { +- final ThreadInfo thread1 = mock(ThreadInfo.class); ++ final ThreadInfo thread1 = mock(); + when(thread1.getThreadName()).thenReturn("thread1"); + when(thread1.getLockName()).thenReturn("lock2"); + when(thread1.getLockOwnerName()).thenReturn("thread2"); +@@ -35,7 +35,7 @@ public class ThreadDeadlockDetectorTest { + new StackTraceElement("Blah", "blee", "Blah.java", 100) + }); + +- final ThreadInfo thread2 = mock(ThreadInfo.class); ++ final ThreadInfo thread2 = mock(); + when(thread2.getThreadName()).thenReturn("thread2"); + when(thread2.getLockName()).thenReturn("lock1"); + when(thread2.getLockOwnerName()).thenReturn("thread1"); +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java +@@ -15,10 +15,10 @@ import org.junit.Test; + // TODO: 3/12/13 -- improve test coverage for ThreadDump + + public class ThreadDumpTest { +- private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); ++ private final ThreadMXBean threadMXBean = mock(); + private final ThreadDump threadDump = new ThreadDump(threadMXBean); + +- private final ThreadInfo runnable = mock(ThreadInfo.class); ++ private final ThreadInfo runnable = mock(); + + @Before + public void setUp() { +@@ -39,8 +39,8 @@ public class ThreadDumpTest { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + threadDump.dump(output); + +- assertThat(output.toString()) +- .isEqualTo( ++ assertThat(output) ++ .hasToString( + String.format( + "\"runnable\" id=100 state=RUNNABLE%n" + + " at Blah.blee(Blah.java:100)%n" +--- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadStatesGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadStatesGaugeSetTest.java +@@ -13,17 +13,17 @@ import org.junit.Before; + import org.junit.Test; + + public class ThreadStatesGaugeSetTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); +- private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ private final ThreadMXBean threads = mock(); ++ private final ThreadDeadlockDetector detector = mock(); + private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); + private final long[] ids = new long[] {1, 2, 3}; + +- private final ThreadInfo newThread = mock(ThreadInfo.class); +- private final ThreadInfo runnableThread = mock(ThreadInfo.class); +- private final ThreadInfo blockedThread = mock(ThreadInfo.class); +- private final ThreadInfo waitingThread = mock(ThreadInfo.class); +- private final ThreadInfo timedWaitingThread = mock(ThreadInfo.class); +- private final ThreadInfo terminatedThread = mock(ThreadInfo.class); ++ private final ThreadInfo newThread = mock(); ++ private final ThreadInfo runnableThread = mock(); ++ private final ThreadInfo blockedThread = mock(); ++ private final ThreadInfo waitingThread = mock(); ++ private final ThreadInfo timedWaitingThread = mock(); ++ private final ThreadInfo terminatedThread = mock(); + + private final Set deadlocks = new HashSet<>(); + +--- a/metrics-log4j2/src/test/java/com/codahale/metrics/log4j2/InstrumentedAppenderTest.java ++++ b/metrics-log4j2/src/test/java/com/codahale/metrics/log4j2/InstrumentedAppenderTest.java +@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final LogEvent event = mock(LogEvent.class); ++ private final LogEvent event = mock(); + + @Before + public void setUp() { +--- a/metrics-logback/src/test/java/com/codahale/metrics/logback/InstrumentedAppenderTest.java ++++ b/metrics-logback/src/test/java/com/codahale/metrics/logback/InstrumentedAppenderTest.java +@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); + + @Before + public void setUp() { +--- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java ++++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java +@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); + + @Before + public void setUp() { +--- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java ++++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java +@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); + + @Before + public void setUp() { +--- a/metrics-servlet/src/test/java/com/codahale/metrics/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-servlet/src/test/java/com/codahale/metrics/servlet/InstrumentedFilterContextListenerTest.java +@@ -10,7 +10,7 @@ import javax.servlet.ServletContextEvent; + import org.junit.Test; + + public class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ public class InstrumentedFilterContextListenerTest { + + @Test + public void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); + + listener.contextInitialized(event); +--- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java ++++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java +@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); + if (registryAttr instanceof HealthCheckRegistry) { + this.registry = (HealthCheckRegistry) registryAttr; +--- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java ++++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java +@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(METRICS_REGISTRY); + if (registryAttr instanceof MetricRegistry) { + this.registry = (MetricRegistry) registryAttr; +--- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java ++++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java +@@ -3,7 +3,6 @@ package com.codahale.metrics.servlets; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -94,9 +93,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } + + @Test +@@ -110,9 +108,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } + + @Test +@@ -168,15 +165,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getContent()) + .isEqualTo( + String.format( +- "{%n" +- + " \"fun\" : {%n" +- + " \"healthy\" : true,%n" +- + " \"message\" : \"foo bar 123\",%n" +- + " \"duration\" : 0,%n" +- + " \"timestamp\" : \"" +- + EXPECTED_TIMESTAMP +- + "\"" +- + "%n }%n}")); ++ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", ++ EXPECTED_TIMESTAMP)); + } + + private static HealthCheck.Result healthyResultWithMessage(String message) { +@@ -198,23 +188,23 @@ public class HealthCheckServletTest extends AbstractServletTest { + @Test + public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() + throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(healthCheckRegistry); +@@ -222,15 +212,15 @@ public class HealthCheckServletTest extends AbstractServletTest { + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test(expected = ServletException.class) + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); +@@ -242,8 +232,8 @@ public class HealthCheckServletTest extends AbstractServletTest { + @Test + public void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(registry); +--- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletContextListenerTest.java ++++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletContextListenerTest.java +@@ -17,7 +17,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MetricsServletContextListenerTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final String allowedOrigin = "some.other.origin"; + +--- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java ++++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java +@@ -1,10 +1,8 @@ + package com.codahale.metrics.servlets; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -24,7 +22,7 @@ import org.junit.Before; + import org.junit.Test; + + public class MetricsServletTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private ServletTester tester; + +@@ -128,22 +126,8 @@ public class MetricsServletTest extends AbstractServletTest { + assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); + assertThat(response.getContent()) + .isEqualTo( +- callbackParamVal +- + "({" +- + "\"version\":\"4.0.0\"," +- + "\"gauges\":{" +- + "\"g1\":{\"value\":100}" +- + "}," +- + "\"counters\":{" +- + "\"c\":{\"count\":1}" +- + "}," +- + "\"histograms\":{" +- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" +- + "}," +- + "\"meters\":{" +- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" +- + "}" +- + "})"); ++ "%s({\"version\":\"4.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", ++ callbackParamVal); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -223,41 +207,40 @@ public class MetricsServletTest extends AbstractServletTest { + @Test + public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() + throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); + } + + @Test + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn(metricRegistry); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); + + final MetricsServlet metricsServlet = new MetricsServlet(null); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); + } + + @Test(expected = ServletException.class) + public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); + + final MetricsServlet metricsServlet = new MetricsServlet(null); diff --git a/integration-tests/metrics-v4.2.19-expected-warnings.txt b/integration-tests/metrics-v4.2.19-expected-warnings.txt index b9eae8e494..e7e82b304a 100644 --- a/integration-tests/metrics-v4.2.19-expected-warnings.txt +++ b/integration-tests/metrics-v4.2.19-expected-warnings.txt @@ -1,6 +1,131 @@ -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[37,12] [removal] SecurityManager in java.lang has been deprecated and marked for removal -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[37,38] [removal] getSecurityManager() in System has been deprecated and marked for removal -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[269,32] [removal] getSecurityManager() in System has been deprecated and marked for removal -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[269,6] [removal] SecurityManager in java.lang has been deprecated and marked for removal +metrics-caffeine/src/test/java/com/codahale/metrics/caffeine/MetricsStatsCounterTest.java:[89,9] [deprecation] recordEviction() in MetricsStatsCounter has been deprecated +metrics-caffeine/src/test/java/com/codahale/metrics/caffeine/MetricsStatsCounterTest.java:[96,9] [deprecation] recordEviction(int) in MetricsStatsCounter has been deprecated +metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[150,8] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[154,8] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[81,68] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[124,20] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[162,12] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[167,11] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[173,17] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[198,8] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[201,21] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[204,11] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[241,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[250,36] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[266,6] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity +metrics-collectd/src/main/java/com/codahale/metrics/collectd/Sender.java:[22,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity +metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java:[249,43] [Refaster Rule] ImmutableMapRules.ImmutableMapOf1: Refactoring opportunity +metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java:[255,40] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java:[57,41] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/CsvReporter.java:[382,35] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-core/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java:[196,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement +metrics-core/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java:[218,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement +metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java:[240,6] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java:[101,4] [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java:[50,21] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[218,19] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[39,4] [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[608,21] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[614,21] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[620,21] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[132,16] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[145,4] [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[158,78] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[176,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[38,12] [removal] SecurityManager in java.lang has been deprecated and marked for removal +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[38,38] [removal] getSecurityManager() in System has been deprecated and marked for removal +metrics-core/src/main/java/com/codahale/metrics/SharedMetricRegistries.java:[87,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java:[82,46] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/UniformSnapshot.java:[50,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java:[67,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[12,62] [deprecation] none() in ExpectedException has been deprecated +metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java:[19,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-graphite/src/main/java/com/codahale/metrics/graphite/Graphite.java:[119,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity +metrics-graphite/src/main/java/com/codahale/metrics/graphite/Graphite.java:[66,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-graphite/src/main/java/com/codahale/metrics/graphite/Graphite.java:[70,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java:[112,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[429,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[434,19] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[447,20] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[84,46] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java:[46,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity +metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java:[176,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[177,46] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[462,16] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[47,44] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[478,42] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[57,44] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java:[80,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[270,32] [removal] getSecurityManager() in System has been deprecated and marked for removal +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[270,6] [removal] SecurityManager in java.lang has been deprecated and marked for removal +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[96,6] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java:[13,70] [deprecation] none() in ExpectedException has been deprecated +metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java:[20,61] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[101,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[112,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[120,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[31,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[38,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[45,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[54,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[63,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[70,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[78,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[86,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[94,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[23,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[30,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[37,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[44,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[53,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[62,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[69,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[80,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[88,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[126,8] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[182,10] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[26,47] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[77,8] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java:[67,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics/servlet/AbstractInstrumentedFilter.java:[67,27] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[29,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-jdbi3/src/main/java/com/codahale/metrics/jdbi3/InstrumentedTimingCollector.java:[9,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated +metrics-jdbi3/src/main/java/com/codahale/metrics/jdbi3/strategies/DefaultNameStrategy.java:[15,28] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity +metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/SmartNameStrategyTest.java:[17,10] [deprecation] InstrumentedTimingCollector in com.codahale.metrics.jdbi3 has been deprecated +metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/SmartNameStrategyTest.java:[23,20] [deprecation] InstrumentedTimingCollector in com.codahale.metrics.jdbi3 has been deprecated +metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/SmartNameStrategyTest.java:[8,33] [deprecation] InstrumentedTimingCollector in com.codahale.metrics.jdbi3 has been deprecated +metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java:[172,25] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java:[174,86] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java:[543,29] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity +metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java:[172,25] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java:[174,86] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java:[543,29] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity +metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java:[172,25] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java:[174,86] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java:[543,29] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity +metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java:[177,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java:[188,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java:[137,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java:[148,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java:[177,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java:[188,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java:[137,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java:[148,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java:[185,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java:[196,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java:[137,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java:[148,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity +metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java:[65,43] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java:[66,39] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity +metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java:[92,6] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java:[83,62] [Refaster Rule] ImmutableListRules.ImmutableListOf1: Refactoring opportunity +metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java:[55,19] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[55,10] [removal] AccessController in java.security has been deprecated and marked for removal metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[9,20] [removal] AccessController in java.security has been deprecated and marked for removal +metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java:[17,49] [Refaster Rule] ImmutableListRules.ImmutableListOf1: Refactoring opportunity +metrics-log4j2/src/main/java/com/codahale/metrics/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +metrics-log4j2/src/main/java/com/codahale/metrics/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +metrics-servlet/src/main/java/com/codahale/metrics/servlet/AbstractInstrumentedFilter.java:[67,27] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity +metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[30,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone diff --git a/integration-tests/metrics-v4.2.19-init.patch b/integration-tests/metrics-v4.2.19-init.patch index 56d6e17097..613465ecb1 100644 --- a/integration-tests/metrics-v4.2.19-init.patch +++ b/integration-tests/metrics-v4.2.19-init.patch @@ -31,7 +31,7 @@ index 6192b52..bcbd571 100644 2.19.1 9+181-r4173-1 - -+ -Xplugin:ErrorProne ${error-prone.flags} -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\$StringIsNullOrEmpty)).*) ++ -Xplugin:ErrorProne ${error-prone.flags} + 8 dropwizard_metrics dropwizard diff --git a/integration-tests/metrics-v4.2.19.sh b/integration-tests/metrics-v4.2.19.sh index 96f1488a12..afed0bbe42 100755 --- a/integration-tests/metrics-v4.2.19.sh +++ b/integration-tests/metrics-v4.2.19.sh @@ -14,4 +14,6 @@ fi do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" -"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "" "" "" "$do_sync" "$report_directory" +patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\.StringIsNullOrEmpty)).*)" + +"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "${patch_flags}" "" "" "$do_sync" "$report_directory" From 952451c87745a6d73687129c5adf6a895dd52ece Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Wed, 13 Dec 2023 11:33:19 +0100 Subject: [PATCH 07/59] clarify reason for check exclusion --- integration-tests/metrics-v4.2.19.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/integration-tests/metrics-v4.2.19.sh b/integration-tests/metrics-v4.2.19.sh index afed0bbe42..64f75f6f6b 100755 --- a/integration-tests/metrics-v4.2.19.sh +++ b/integration-tests/metrics-v4.2.19.sh @@ -14,6 +14,8 @@ fi do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" +# XXX: We exclude the CollectorMutability and the Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty refaster rules +# as they introduce changes that expect guava to be on the classpath. patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\.StringIsNullOrEmpty)).*)" "$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "${patch_flags}" "" "" "$do_sync" "$report_directory" From 2ebd53050ce82ea780989929b88dc271df47ae9c Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Wed, 10 Jan 2024 09:45:48 +0100 Subject: [PATCH 08/59] add `additional_src_directories` flag --- integration-tests/checkstyle.sh | 3 ++- integration-tests/integration-test.sh | 17 +++++++++-------- integration-tests/metrics-v4.2.19.sh | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index fc4ee882dd..a06ebce4c6 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -17,5 +17,6 @@ report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ # XXX: Configure Renovate to manage the AssertJ version declared here. build_flags="-Dassertj.version=3.24.2" validation_mvn_flags="-Dtest=!MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles,!XdocsJavaDocsTest#allCheckSectionJavaDocs" +additional_src_directories="\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java" -"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" +"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "" "$validation_mvn_flags" "$do_sync" "$report_directory" diff --git a/integration-tests/integration-test.sh b/integration-tests/integration-test.sh index 952d97273a..d9e73aa497 100755 --- a/integration-tests/integration-test.sh +++ b/integration-tests/integration-test.sh @@ -8,8 +8,8 @@ integration_test_root="$(cd "$(dirname -- "${0}")" && pwd)" error_prone_support_root="${integration_test_root}/.." repos_root="${integration_test_root}/.repos" -if [ "${#}" -ne 10 ]; then - >&2 echo "Usage $(basename "${0}") [TestName] [Project] [Repository] [Revision] [BuildFlags] [PatchFlags] [ValidationEpFlags] [ValidationMvnFlags] [DoSync] [ReportDirectory]" +if [ "${#}" -ne 11 ]; then + >&2 echo "Usage $(basename "${0}") [TestName] [Project] [Repository] [Revision] [BuildFlags] [AdditionalSourceDirectories] [PatchFlags] [ValidationEpFlags] [ValidationMvnFlags] [DoSync] [ReportDirectory]" exit 1 fi @@ -18,11 +18,12 @@ project="${2}" repository="${3}" revision="${4}" build_flags="${5}" -patch_flags="${6}" -validation_ep_flags="${7}" -validation_mvn_flags="${8}" -do_sync="${9}" -report_directory="${10}" +additional_src_directories="${6}" +patch_flags="${7}" +validation_ep_flags="${8}" +validation_mvn_flags="${9}" +do_sync="${10}" +report_directory="${11}" if [ -n "${report_directory}" ]; then mkdir -p "${report_directory}" @@ -55,7 +56,7 @@ shared_build_flags=" -Derror-prone-support.version=$( mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=project.version -q -DforceStdout ) - -DadditionalSourceDirectories=\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java + -DadditionalSourceDirectories=${additional_src_directories} ${build_flags} " diff --git a/integration-tests/metrics-v4.2.19.sh b/integration-tests/metrics-v4.2.19.sh index 64f75f6f6b..4b121c9938 100755 --- a/integration-tests/metrics-v4.2.19.sh +++ b/integration-tests/metrics-v4.2.19.sh @@ -18,4 +18,4 @@ report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ # as they introduce changes that expect guava to be on the classpath. patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\.StringIsNullOrEmpty)).*)" -"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "${patch_flags}" "" "" "$do_sync" "$report_directory" +"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "" "${patch_flags}" "" "" "$do_sync" "$report_directory" From b6bed8698a78ecd3df5c6c1a8f16660e106745d3 Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Wed, 10 Jan 2024 10:06:46 +0100 Subject: [PATCH 09/59] fix checkstyle integration test script --- integration-tests/checkstyle.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index a06ebce4c6..f489b75dd5 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -19,4 +19,4 @@ build_flags="-Dassertj.version=3.24.2" validation_mvn_flags="-Dtest=!MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles,!XdocsJavaDocsTest#allCheckSectionJavaDocs" additional_src_directories="\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java" -"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "" "$validation_mvn_flags" "$do_sync" "$report_directory" +"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" From 3b2a0b4563a8f601476c741327ecb53a6f22973e Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Wed, 10 Jan 2024 10:10:40 +0100 Subject: [PATCH 10/59] add matrix to integration test workflow --- .github/workflows/run-integration-tests.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 6776c89b61..c38b444d89 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -13,6 +13,9 @@ permissions: contents: read jobs: run-integration-tests: + strategy: + matrix: + integration-test: ["checkstyle.sh", "metrics-v4.2.19.sh"] name: On-demand integration test if: | github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') @@ -40,7 +43,7 @@ jobs: - name: Install project to local Maven repository run: mvn -T1C install -DskipTests -Dverification.skip - name: Run integration test - run: xvfb-run ./integration-tests/checkstyle.sh "${{ runner.temp }}/artifacts" + run: xvfb-run ./integration-tests/${{ matrix.integration-test }} "${{ runner.temp }}/artifacts" - name: Upload artifacts on failure if: ${{ failure() }} uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1 From 713853dfe1b6a011a773af86d9debddbd902dfee Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Wed, 10 Jan 2024 11:03:13 +0100 Subject: [PATCH 11/59] suggestions --- .github/workflows/run-integration-tests.yml | 6 +++--- integration-tests/checkstyle.sh | 2 +- integration-tests/metrics-v4.2.19.sh | 4 ++-- .../{integration-test.sh => run-integration-test.sh} | 1 + 4 files changed, 7 insertions(+), 6 deletions(-) rename integration-tests/{integration-test.sh => run-integration-test.sh} (99%) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index c38b444d89..81bdd89946 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -15,7 +15,7 @@ jobs: run-integration-tests: strategy: matrix: - integration-test: ["checkstyle.sh", "metrics-v4.2.19.sh"] + integration-test: ["checkstyle", "metrics-v4.2.19"] name: On-demand integration test if: | github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') @@ -43,12 +43,12 @@ jobs: - name: Install project to local Maven repository run: mvn -T1C install -DskipTests -Dverification.skip - name: Run integration test - run: xvfb-run ./integration-tests/${{ matrix.integration-test }} "${{ runner.temp }}/artifacts" + run: xvfb-run "./integration-tests/${{ matrix.integration-test }}.sh" "${{ runner.temp }}/artifacts" - name: Upload artifacts on failure if: ${{ failure() }} uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1 with: - name: integration-test-checkstyle + name: "integration-test-${{ matrix.integration-test }}" path: "${{ runner.temp }}/artifacts" - name: Remove installed project artifacts run: mvn build-helper:remove-project-artifact diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index f489b75dd5..0d41554390 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -19,4 +19,4 @@ build_flags="-Dassertj.version=3.24.2" validation_mvn_flags="-Dtest=!MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles,!XdocsJavaDocsTest#allCheckSectionJavaDocs" additional_src_directories="\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java" -"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" +"$(dirname ${0})"/run-integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" diff --git a/integration-tests/metrics-v4.2.19.sh b/integration-tests/metrics-v4.2.19.sh index 4b121c9938..1918e469db 100755 --- a/integration-tests/metrics-v4.2.19.sh +++ b/integration-tests/metrics-v4.2.19.sh @@ -14,8 +14,8 @@ fi do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" -# XXX: We exclude the CollectorMutability and the Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty refaster rules +# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` refaster rules # as they introduce changes that expect guava to be on the classpath. patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\.StringIsNullOrEmpty)).*)" -"$(dirname ${0})"/integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "" "${patch_flags}" "" "" "$do_sync" "$report_directory" +"$(dirname ${0})"/run-integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "" "${patch_flags}" "" "" "$do_sync" "$report_directory" diff --git a/integration-tests/integration-test.sh b/integration-tests/run-integration-test.sh similarity index 99% rename from integration-tests/integration-test.sh rename to integration-tests/run-integration-test.sh index d9e73aa497..f02be0917c 100755 --- a/integration-tests/integration-test.sh +++ b/integration-tests/run-integration-test.sh @@ -1,4 +1,5 @@ #!/usr/bin/env bash + # This script is not meant to be invoked manually, instead it should be invoked # through one of the integration test scripts such as the metrics or checkstyle one. From 5825498becfe7f24ac97cef8c054c9036eb916fb Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Thu, 11 Jan 2024 11:16:40 +0100 Subject: [PATCH 12/59] apply suggestions in init patch --- integration-tests/metrics-v4.2.19-init.patch | 6 +++--- integration-tests/metrics-v4.2.19.sh | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/integration-tests/metrics-v4.2.19-init.patch b/integration-tests/metrics-v4.2.19-init.patch index 613465ecb1..d3fa6c456d 100644 --- a/integration-tests/metrics-v4.2.19-init.patch +++ b/integration-tests/metrics-v4.2.19-init.patch @@ -23,7 +23,7 @@ index 0bd1297..7c69a08 100644 try { return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); diff --git a/pom.xml b/pom.xml -index 6192b52..bcbd571 100644 +index 6192b52..8c312b6 100644 --- a/pom.xml +++ b/pom.xml @@ -68,7 +68,8 @@ @@ -73,7 +73,7 @@ index 6192b52..bcbd571 100644 + maven-compiler-plugin + ${maven-compiler-plugin.version} + -+ ++ + + default-compile + compile @@ -132,7 +132,7 @@ index 6192b52..bcbd571 100644 + maven-compiler-plugin + ${maven-compiler-plugin.version} + -+ ++ + + default-testCompile + test-compile diff --git a/integration-tests/metrics-v4.2.19.sh b/integration-tests/metrics-v4.2.19.sh index 1918e469db..8daca93d3e 100755 --- a/integration-tests/metrics-v4.2.19.sh +++ b/integration-tests/metrics-v4.2.19.sh @@ -15,7 +15,7 @@ do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" # XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` refaster rules -# as they introduce changes that expect guava to be on the classpath. +# as they introduce changes that expect Guava to be on the classpath. patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\.StringIsNullOrEmpty)).*)" "$(dirname ${0})"/run-integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "" "${patch_flags}" "" "" "$do_sync" "$report_directory" From 97989c62940d59433d5c5f8489045a4948811415 Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Thu, 11 Jan 2024 11:42:36 +0100 Subject: [PATCH 13/59] trigger integration-test action --- .github/workflows/run-integration-tests.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 81bdd89946..7ac40e8140 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -7,6 +7,8 @@ # https://docs.github.com/en/actions/learn-github-actions/expressions#example-returning-a-json-object name: "Integration tests" on: + pull_request: + branches: [ master ] issue_comment: types: [ created ] permissions: From 4dcfb10dd97a9fe527efaebb9fd9bb0a0d14b378 Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Thu, 11 Jan 2024 11:43:39 +0100 Subject: [PATCH 14/59] temporarily remove condition --- .github/workflows/run-integration-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 7ac40e8140..89e5118d55 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -19,8 +19,8 @@ jobs: matrix: integration-test: ["checkstyle", "metrics-v4.2.19"] name: On-demand integration test - if: | - github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') + # if: | + # github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') runs-on: ubuntu-22.04 steps: - name: Install Harden-Runner From 79931df7802167b2e80b25b3bc39c7790ada5545 Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Wed, 24 Jan 2024 10:20:57 +0100 Subject: [PATCH 15/59] disable new checks as they cause errors --- integration-tests/checkstyle.sh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index 0d41554390..124920eb05 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -16,7 +16,10 @@ report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ # XXX: Configure Renovate to manage the AssertJ version declared here. build_flags="-Dassertj.version=3.24.2" -validation_mvn_flags="-Dtest=!MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles,!XdocsJavaDocsTest#allCheckSectionJavaDocs" additional_src_directories="\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java" -"$(dirname ${0})"/run-integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" +# XXX: re-enable these once the required fixes have been added to the init patch +patch_flags="-Xep:CanonicalClassNameUsage:OFF -Xep:ErrorProneRuntimeClasspath:OFF -Xep:UnqualifiedSuggestedFixImport:OFF" +validation_mvn_flags="-Dtest=!MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles,!XdocsJavaDocsTest#allCheckSectionJavaDocs" + +"$(dirname ${0})"/run-integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" From 4dafc7e6eef0a5ab0cffa7ec2bb3c65cc12757e1 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 13 Feb 2024 09:25:52 +0100 Subject: [PATCH 16/59] Post-rebase fix --- integration-tests/checkstyle.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index 124920eb05..0aa61154b4 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -18,8 +18,8 @@ report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ build_flags="-Dassertj.version=3.24.2" additional_src_directories="\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java" -# XXX: re-enable these once the required fixes have been added to the init patch +# XXX: Re-enable these once the required fixes have been added to the init patch. patch_flags="-Xep:CanonicalClassNameUsage:OFF -Xep:ErrorProneRuntimeClasspath:OFF -Xep:UnqualifiedSuggestedFixImport:OFF" validation_mvn_flags="-Dtest=!MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles,!XdocsJavaDocsTest#allCheckSectionJavaDocs" -"$(dirname ${0})"/run-integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "" "" "$validation_mvn_flags" "$do_sync" "$report_directory" +"$(dirname ${0})"/run-integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "${patch_flags}" "" "$validation_mvn_flags" "${do_sync}" "$report_directory" From dddb602869872705b27488c5dc6e224f9a322194 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 13 Feb 2024 09:29:44 +0100 Subject: [PATCH 17/59] Rename metrics files to drop the version --- .github/workflows/run-integration-tests.yml | 2 +- ...19-expected-changes.patch => metrics-expected-changes.patch} | 0 ...2.19-expected-warnings.txt => metrics-expected-warnings.txt} | 0 .../{metrics-v4.2.19-init.patch => metrics-init.patch} | 0 integration-tests/{metrics-v4.2.19.sh => metrics.sh} | 0 5 files changed, 1 insertion(+), 1 deletion(-) rename integration-tests/{metrics-v4.2.19-expected-changes.patch => metrics-expected-changes.patch} (100%) rename integration-tests/{metrics-v4.2.19-expected-warnings.txt => metrics-expected-warnings.txt} (100%) rename integration-tests/{metrics-v4.2.19-init.patch => metrics-init.patch} (100%) rename integration-tests/{metrics-v4.2.19.sh => metrics.sh} (100%) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 89e5118d55..56d22a8142 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -17,7 +17,7 @@ jobs: run-integration-tests: strategy: matrix: - integration-test: ["checkstyle", "metrics-v4.2.19"] + integration-test: ["checkstyle", "metrics"] name: On-demand integration test # if: | # github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') diff --git a/integration-tests/metrics-v4.2.19-expected-changes.patch b/integration-tests/metrics-expected-changes.patch similarity index 100% rename from integration-tests/metrics-v4.2.19-expected-changes.patch rename to integration-tests/metrics-expected-changes.patch diff --git a/integration-tests/metrics-v4.2.19-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt similarity index 100% rename from integration-tests/metrics-v4.2.19-expected-warnings.txt rename to integration-tests/metrics-expected-warnings.txt diff --git a/integration-tests/metrics-v4.2.19-init.patch b/integration-tests/metrics-init.patch similarity index 100% rename from integration-tests/metrics-v4.2.19-init.patch rename to integration-tests/metrics-init.patch diff --git a/integration-tests/metrics-v4.2.19.sh b/integration-tests/metrics.sh similarity index 100% rename from integration-tests/metrics-v4.2.19.sh rename to integration-tests/metrics.sh From 041778308b55f8dc3198e5cf1c1748bb26ede842 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 13 Feb 2024 09:46:32 +0100 Subject: [PATCH 18/59] Style improvements --- integration-tests/checkstyle.sh | 15 ++++++++++++--- integration-tests/metrics.sh | 15 +++++++++++++-- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index 0aa61154b4..4c1ca56e7e 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -18,8 +18,17 @@ report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ build_flags="-Dassertj.version=3.24.2" additional_src_directories="\${project.basedir}\${file.separator}src\${file.separator}it\${file.separator}java,\${project.basedir}\${file.separator}src\${file.separator}xdocs-examples\${file.separator}java" -# XXX: Re-enable these once the required fixes have been added to the init patch. -patch_flags="-Xep:CanonicalClassNameUsage:OFF -Xep:ErrorProneRuntimeClasspath:OFF -Xep:UnqualifiedSuggestedFixImport:OFF" validation_mvn_flags="-Dtest=!MetadataGeneratorUtilTest#metadataFilesGenerationAllFiles,!XdocsJavaDocsTest#allCheckSectionJavaDocs" -"$(dirname ${0})"/run-integration-test.sh "$test_name" "$project" "$repository" "$revision" "$build_flags" "$additional_src_directories" "${patch_flags}" "" "$validation_mvn_flags" "${do_sync}" "$report_directory" +"$(dirname "${0}")"/run-integration-test.sh \ + "${test_name}" \ + "${project}" \ + "${repository}" \ + "${revision}" \ + "${build_flags}" \ + "${additional_src_directories}" \ + "" \ + "" \ + "${validation_mvn_flags}" \ + "${do_sync}" \ + "${report_directory}" diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 8daca93d3e..58284e8bcf 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -14,8 +14,19 @@ fi do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" -# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` refaster rules +# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Refaster rules # as they introduce changes that expect Guava to be on the classpath. patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\.StringIsNullOrEmpty)).*)" -"$(dirname ${0})"/run-integration-test.sh "$test_name" "$project" "$repository" "$revision" "" "" "${patch_flags}" "" "" "$do_sync" "$report_directory" +"$(dirname "${0}")"/run-integration-test.sh \ + "${test_name}" \ + "${project}" \ + "${repository}" \ + "${revision}" \ + "" \ + "" \ + "${patch_flags}" \ + "" \ + "" \ + "${do_sync}" \ + "${report_directory}" From 75eb8d27e1c6200a9aedd2ebd00db4f8de5203ac Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 13 Feb 2024 10:54:23 +0100 Subject: [PATCH 19/59] Typo --- integration-tests/metrics.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 58284e8bcf..7da98d03e8 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -14,7 +14,7 @@ fi do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" -# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Refaster rules +# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Rsefaster rules # as they introduce changes that expect Guava to be on the classpath. patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\.StringIsNullOrEmpty)).*)" From b9836c601782dc6226f4a292624dbeb4422f4f4a Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Fri, 1 Mar 2024 11:33:54 +0100 Subject: [PATCH 20/59] sync metrics --- .../metrics-expected-changes.patch | 6660 ----------------- .../metrics-expected-warnings.txt | 334 +- 2 files changed, 245 insertions(+), 6749 deletions(-) diff --git a/integration-tests/metrics-expected-changes.patch b/integration-tests/metrics-expected-changes.patch index 5d6d51f6b8..e69de29bb2 100644 --- a/integration-tests/metrics-expected-changes.patch +++ b/integration-tests/metrics-expected-changes.patch @@ -1,6660 +0,0 @@ ---- a/metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java -+++ b/metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java -@@ -2,7 +2,6 @@ package com.codahale.metrics.benchmarks; - - import com.codahale.metrics.SlidingTimeWindowArrayReservoir; - import com.codahale.metrics.SlidingTimeWindowReservoir; --import com.codahale.metrics.Snapshot; - import java.util.concurrent.TimeUnit; - import org.openjdk.jmh.annotations.Benchmark; - import org.openjdk.jmh.annotations.Group; -@@ -42,8 +41,7 @@ public class SlidingTimeWindowReservoirsBenchmark { - @Group("slidingTime") - @GroupThreads(1) - public Object slidingTimeRead() { -- Snapshot snapshot = slidingTime.getSnapshot(); -- return snapshot; -+ return slidingTime.getSnapshot(); - } - - @Benchmark -@@ -58,8 +56,7 @@ public class SlidingTimeWindowReservoirsBenchmark { - @Group("arrTime") - @GroupThreads(1) - public Object arrTimeRead() { -- Snapshot snapshot = arrTime.getSnapshot(); -- return snapshot; -+ return arrTime.getSnapshot(); - } - - public static void main(String[] args) throws RunnerException { ---- a/metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java -+++ b/metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java -@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; - import static com.codahale.metrics.MetricAttribute.M15_RATE; - import static com.codahale.metrics.MetricAttribute.M1_RATE; - import static com.codahale.metrics.MetricAttribute.M5_RATE; --import static com.codahale.metrics.MetricAttribute.MAX; - import static com.codahale.metrics.MetricAttribute.MEAN; - import static com.codahale.metrics.MetricAttribute.MEAN_RATE; --import static com.codahale.metrics.MetricAttribute.MIN; - import static com.codahale.metrics.MetricAttribute.P50; - import static com.codahale.metrics.MetricAttribute.P75; - import static com.codahale.metrics.MetricAttribute.P95; -@@ -15,6 +13,7 @@ import static com.codahale.metrics.MetricAttribute.P98; - import static com.codahale.metrics.MetricAttribute.P99; - import static com.codahale.metrics.MetricAttribute.P999; - import static com.codahale.metrics.MetricAttribute.STDDEV; -+import static java.util.Collections.emptySet; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.Counter; -@@ -29,7 +28,6 @@ import com.codahale.metrics.Snapshot; - import com.codahale.metrics.Timer; - import java.io.IOException; - import java.net.InetAddress; --import java.util.Collections; - import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -80,7 +78,7 @@ public class CollectdReporter extends ScheduledReporter { - private SecurityLevel securityLevel = SecurityLevel.NONE; - private String username = ""; - private String password = ""; -- private Set disabledMetricAttributes = Collections.emptySet(); -+ private Set disabledMetricAttributes = emptySet(); - private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; - - private Builder(MetricRegistry registry) { -@@ -302,7 +300,7 @@ public class CollectdReporter extends ScheduledReporter { - try { - writer.write(metaData, value); - } catch (RuntimeException e) { -- LOG.warn("Failed to process metric '" + metaData.getPlugin() + "': " + e.getMessage()); -+ LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage()); - } catch (IOException e) { - LOG.error("Failed to send metric to collectd", e); - } -@@ -337,9 +335,9 @@ public class CollectdReporter extends ScheduledReporter { - private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { - final Snapshot snapshot = metric.getSnapshot(); - writeValue(metaData, COUNT, (double) metric.getCount()); -- writeValue(metaData, MAX, (double) snapshot.getMax()); -+ writeValue(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); - writeValue(metaData, MEAN, snapshot.getMean()); -- writeValue(metaData, MIN, (double) snapshot.getMin()); -+ writeValue(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); - writeValue(metaData, STDDEV, snapshot.getStdDev()); - writeValue(metaData, P50, snapshot.getMedian()); - writeValue(metaData, P75, snapshot.get75thPercentile()); -@@ -352,9 +350,9 @@ public class CollectdReporter extends ScheduledReporter { - private void serializeTimer(MetaData.Builder metaData, Timer metric) { - final Snapshot snapshot = metric.getSnapshot(); - writeValue(metaData, COUNT, (double) metric.getCount()); -- writeDuration(metaData, MAX, (double) snapshot.getMax()); -+ writeDuration(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); - writeDuration(metaData, MEAN, snapshot.getMean()); -- writeDuration(metaData, MIN, (double) snapshot.getMin()); -+ writeDuration(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); - writeDuration(metaData, STDDEV, snapshot.getStdDev()); - writeDuration(metaData, P50, snapshot.getMedian()); - writeDuration(metaData, P75, snapshot.get75thPercentile()); ---- a/metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java -+++ b/metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java -@@ -1,10 +1,12 @@ - package com.codahale.metrics.collectd; - -+import static java.nio.charset.StandardCharsets.US_ASCII; -+import static java.nio.charset.StandardCharsets.UTF_8; -+ - import java.io.IOException; - import java.nio.BufferOverflowException; - import java.nio.ByteBuffer; - import java.nio.ByteOrder; --import java.nio.charset.StandardCharsets; - import java.security.InvalidKeyException; - import java.security.MessageDigest; - import java.security.NoSuchAlgorithmException; -@@ -64,8 +66,8 @@ class PacketWriter { - PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { - this.sender = sender; - this.securityLevel = securityLevel; -- this.username = username != null ? username.getBytes(StandardCharsets.UTF_8) : null; -- this.password = password != null ? password.getBytes(StandardCharsets.UTF_8) : null; -+ this.username = username != null ? username.getBytes(UTF_8) : null; -+ this.password = password != null ? password.getBytes(UTF_8) : null; - } - - void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { -@@ -119,12 +121,12 @@ class PacketWriter { - } - - private void writeString(ByteBuffer buffer, int type, String val) { -- if (val == null || val.length() == 0) { -+ if (val == null || val.isEmpty()) { - return; - } - int len = HEADER_LEN + val.length() + 1; - writeHeader(buffer, type, len); -- buffer.put(val.getBytes(StandardCharsets.US_ASCII)).put(NULL); -+ buffer.put(val.getBytes(US_ASCII)).put(NULL); - } - - private void writeNumber(ByteBuffer buffer, int type, long val) { ---- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterSecurityTest.java -+++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterSecurityTest.java -@@ -1,6 +1,6 @@ - package com.codahale.metrics.collectd; - --import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - - import com.codahale.metrics.MetricRegistry; - import org.junit.Test; -@@ -11,27 +11,27 @@ public class CollectdReporterSecurityTest { - - @Test - public void testUnableSetSecurityLevelToSignWithoutUsername() { -- assertThatIllegalArgumentException() -- .isThrownBy( -+ assertThatThrownBy( - () -> - CollectdReporter.forRegistry(registry) - .withHostName("eddie") - .withSecurityLevel(SecurityLevel.SIGN) - .withPassword("t1_g3r") - .build(new Sender("localhost", 25826))) -- .withMessage("username is required for securityLevel: SIGN"); -+ .isInstanceOf(IllegalArgumentException.class) -+ .hasMessage("username is required for securityLevel: SIGN"); - } - - @Test - public void testUnableSetSecurityLevelToSignWithoutPassword() { -- assertThatIllegalArgumentException() -- .isThrownBy( -+ assertThatThrownBy( - () -> - CollectdReporter.forRegistry(registry) - .withHostName("eddie") - .withSecurityLevel(SecurityLevel.SIGN) - .withUsername("scott") - .build(new Sender("localhost", 25826))) -- .withMessage("password is required for securityLevel: SIGN"); -+ .isInstanceOf(IllegalArgumentException.class) -+ .hasMessage("password is required for securityLevel: SIGN"); - } - } ---- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java -+++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java -@@ -1,5 +1,8 @@ - package com.codahale.metrics.collectd; - -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptySortedMap; -+import static java.util.Collections.singletonMap; - import static java.util.concurrent.TimeUnit.MILLISECONDS; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; -@@ -12,7 +15,6 @@ import com.codahale.metrics.MetricAttribute; - import com.codahale.metrics.MetricRegistry; - import com.codahale.metrics.Snapshot; - import com.codahale.metrics.Timer; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -94,7 +96,7 @@ public class CollectdReporterTest { - - @Test - public void reportsCounters() throws Exception { -- Counter counter = mock(Counter.class); -+ Counter counter = mock(); - when(counter.getCount()).thenReturn(42L); - - reporter.report(map(), map("api.rest.requests.count", counter), map(), map(), map()); -@@ -104,7 +106,7 @@ public class CollectdReporterTest { - - @Test - public void reportsMeters() throws Exception { -- Meter meter = mock(Meter.class); -+ Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); -@@ -122,8 +124,8 @@ public class CollectdReporterTest { - - @Test - public void reportsHistograms() throws Exception { -- Histogram histogram = mock(Histogram.class); -- Snapshot snapshot = mock(Snapshot.class); -+ Histogram histogram = mock(); -+ Snapshot snapshot = mock(); - when(histogram.getCount()).thenReturn(1L); - when(histogram.getSnapshot()).thenReturn(snapshot); - when(snapshot.getMax()).thenReturn(2L); -@@ -146,8 +148,8 @@ public class CollectdReporterTest { - - @Test - public void reportsTimers() throws Exception { -- Timer timer = mock(Timer.class); -- Snapshot snapshot = mock(Snapshot.class); -+ Timer timer = mock(); -+ Snapshot snapshot = mock(); - when(timer.getSnapshot()).thenReturn(snapshot); - when(timer.getCount()).thenReturn(1L); - when(timer.getSnapshot()).thenReturn(snapshot); -@@ -187,14 +189,14 @@ public class CollectdReporterTest { - - @Test - public void doesNotReportDisabledMetricAttributes() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); - when(meter.getFifteenMinuteRate()).thenReturn(4.0); - when(meter.getMeanRate()).thenReturn(5.0); - -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(11L); - - CollectdReporter reporter = -@@ -240,16 +242,16 @@ public class CollectdReporterTest { - } - - private SortedMap map() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - private SortedMap map(String name, T metric) { -- final Map map = Collections.singletonMap(name, metric); -+ final Map map = singletonMap(name, metric); - return new TreeMap<>(map); - } - - private List nextValues(Receiver receiver) throws Exception { - final ValueList valueList = receiver.next(); -- return valueList == null ? Collections.emptyList() : valueList.getValues(); -+ return valueList == null ? emptyList() : valueList.getValues(); - } - } ---- a/metrics-collectd/src/test/java/com/codahale/metrics/collectd/PacketWriterTest.java -+++ b/metrics-collectd/src/test/java/com/codahale/metrics/collectd/PacketWriterTest.java -@@ -190,6 +190,6 @@ public class PacketWriterTest { - assertThat(amountOfValues).isEqualTo((short) 1); - byte dataType = packet.get(); - assertThat(dataType).isEqualTo((byte) 1); -- assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isEqualTo(42.0, offset(0.01)); -+ assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01)); - } - } ---- a/metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java -@@ -1,8 +1,9 @@ - package com.codahale.metrics; - -+import static java.util.Collections.emptySet; -+ - import java.io.PrintStream; - import java.text.DateFormat; --import java.util.Collections; - import java.util.Date; - import java.util.Locale; - import java.util.Map; -@@ -53,7 +54,7 @@ public class ConsoleReporter extends ScheduledReporter { - this.filter = MetricFilter.ALL; - this.executor = null; - this.shutdownExecutorOnStop = true; -- disabledMetricAttributes = Collections.emptySet(); -+ disabledMetricAttributes = emptySet(); - } - - /** ---- a/metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java -@@ -1,8 +1,9 @@ - package com.codahale.metrics; - -+import static java.util.Objects.requireNonNull; -+ - import com.codahale.metrics.WeightedSnapshot.WeightedSample; - import java.time.Duration; --import java.util.Objects; - import java.util.concurrent.ConcurrentSkipListMap; - import java.util.concurrent.ThreadLocalRandom; - import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -@@ -127,7 +128,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - // It's possible that more values were added while the map was scanned, those with the - // minimum priorities are removed. - while (newCount > size) { -- Objects.requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); -+ requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); - newCount--; - } - return new State(alphaNanos, size, newTick, newCount, newValues); -@@ -255,13 +256,13 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - - /** Interval at which this reservoir is rescaled. */ - public Builder rescaleThreshold(Duration value) { -- this.rescaleThreshold = Objects.requireNonNull(value, "rescaleThreshold is required"); -+ this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required"); - return this; - } - - /** Clock instance used for decay. */ - public Builder clock(Clock value) { -- this.clock = Objects.requireNonNull(value, "clock is required"); -+ this.clock = requireNonNull(value, "clock is required"); - return this; - } - ---- a/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java -@@ -1,6 +1,9 @@ - package com.codahale.metrics; - --import java.util.Collections; -+import static java.util.Collections.unmodifiableMap; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Collections.unmodifiableSortedSet; -+ - import java.util.List; - import java.util.Map; - import java.util.SortedMap; -@@ -207,7 +210,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Counter.class.isInstance(metric); -+ return metric instanceof Counter; - } - }); - } -@@ -242,7 +245,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Histogram.class.isInstance(metric); -+ return metric instanceof Histogram; - } - }); - } -@@ -277,7 +280,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Meter.class.isInstance(metric); -+ return metric instanceof Meter; - } - }); - } -@@ -312,7 +315,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Timer.class.isInstance(metric); -+ return metric instanceof Timer; - } - }); - } -@@ -350,7 +353,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Gauge.class.isInstance(metric); -+ return metric instanceof Gauge; - } - }); - } -@@ -414,7 +417,7 @@ public class MetricRegistry implements MetricSet { - * @return the names of all the metrics - */ - public SortedSet getNames() { -- return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); -+ return unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); - } - - /** -@@ -541,7 +544,7 @@ public class MetricRegistry implements MetricSet { - timers.put(entry.getKey(), (T) entry.getValue()); - } - } -- return Collections.unmodifiableSortedMap(timers); -+ return unmodifiableSortedMap(timers); - } - - private void onMetricAdded(String name, Metric metric) { -@@ -609,7 +612,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public Map getMetrics() { -- return Collections.unmodifiableMap(metrics); -+ return unmodifiableMap(metrics); - } - - @FunctionalInterface -@@ -628,7 +631,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Counter.class.isInstance(metric); -+ return metric instanceof Counter; - } - }; - -@@ -641,7 +644,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Histogram.class.isInstance(metric); -+ return metric instanceof Histogram; - } - }; - -@@ -654,7 +657,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Meter.class.isInstance(metric); -+ return metric instanceof Meter; - } - }; - -@@ -667,7 +670,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Timer.class.isInstance(metric); -+ return metric instanceof Timer; - } - }; - -@@ -681,7 +684,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Gauge.class.isInstance(metric); -+ return metric instanceof Gauge; - } - }; - ---- a/metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java -@@ -1,9 +1,13 @@ - package com.codahale.metrics; - -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.emptySet; -+import static java.util.Collections.emptySortedMap; -+import static java.util.Collections.emptySortedSet; -+ - import java.io.OutputStream; - import java.time.Duration; - import java.util.Collection; --import java.util.Collections; - import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -137,69 +141,69 @@ public final class NoopMetricRegistry extends MetricRegistry { - /** {@inheritDoc} */ - @Override - public SortedSet getNames() { -- return Collections.emptySortedSet(); -+ return emptySortedSet(); - } - - /** {@inheritDoc} */ - @Override - @SuppressWarnings("rawtypes") - public SortedMap getGauges() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - @SuppressWarnings("rawtypes") - public SortedMap getGauges(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getCounters() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getCounters(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getHistograms() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getHistograms(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getMeters() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getMeters(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getTimers() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getTimers(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ -@@ -211,7 +215,7 @@ public final class NoopMetricRegistry extends MetricRegistry { - /** {@inheritDoc} */ - @Override - public Map getMetrics() { -- return Collections.emptyMap(); -+ return emptyMap(); - } - - static final class NoopGauge implements Gauge { -@@ -601,19 +605,19 @@ public final class NoopMetricRegistry extends MetricRegistry { - /** {@inheritDoc} */ - @Override - public Set keySet() { -- return Collections.emptySet(); -+ return emptySet(); - } - - /** {@inheritDoc} */ - @Override - public Collection values() { -- return Collections.emptySet(); -+ return emptySet(); - } - - /** {@inheritDoc} */ - @Override - public Set> entrySet() { -- return Collections.emptySet(); -+ return emptySet(); - } - } - } ---- a/metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java -@@ -1,7 +1,8 @@ - package com.codahale.metrics; - -+import static java.util.Collections.emptySet; -+ - import java.io.Closeable; --import java.util.Collections; - import java.util.Locale; - import java.util.Set; - import java.util.SortedMap; -@@ -128,7 +129,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - durationUnit, - executor, - shutdownExecutorOnStop, -- Collections.emptySet()); -+ emptySet()); - } - - protected ScheduledReporter( -@@ -154,7 +155,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - this.durationFactor = durationUnit.toNanos(1); - this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); - this.disabledMetricAttributes = -- disabledMetricAttributes != null ? disabledMetricAttributes : Collections.emptySet(); -+ disabledMetricAttributes != null ? disabledMetricAttributes : emptySet(); - } - - /** -@@ -185,8 +186,8 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, - * ScheduledExecutorService)} instead. - */ -- @SuppressWarnings("DeprecatedIsStillUsed") - @Deprecated -+ @SuppressWarnings("DeprecatedIsStillUsed") - protected ScheduledFuture getScheduledFuture( - long initialDelay, long period, TimeUnit unit, Runnable runnable) { - return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); ---- a/metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java -@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; - import static com.codahale.metrics.MetricAttribute.M15_RATE; - import static com.codahale.metrics.MetricAttribute.M1_RATE; - import static com.codahale.metrics.MetricAttribute.M5_RATE; --import static com.codahale.metrics.MetricAttribute.MAX; - import static com.codahale.metrics.MetricAttribute.MEAN; - import static com.codahale.metrics.MetricAttribute.MEAN_RATE; --import static com.codahale.metrics.MetricAttribute.MIN; - import static com.codahale.metrics.MetricAttribute.P50; - import static com.codahale.metrics.MetricAttribute.P75; - import static com.codahale.metrics.MetricAttribute.P95; -@@ -15,8 +13,8 @@ import static com.codahale.metrics.MetricAttribute.P98; - import static com.codahale.metrics.MetricAttribute.P99; - import static com.codahale.metrics.MetricAttribute.P999; - import static com.codahale.metrics.MetricAttribute.STDDEV; -+import static java.util.Collections.emptySet; - --import java.util.Collections; - import java.util.Map.Entry; - import java.util.Set; - import java.util.SortedMap; -@@ -81,7 +79,7 @@ public class Slf4jReporter extends ScheduledReporter { - this.loggingLevel = LoggingLevel.INFO; - this.executor = null; - this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -+ this.disabledMetricAttributes = emptySet(); - } - - /** -@@ -306,8 +304,8 @@ public class Slf4jReporter extends ScheduledReporter { - b.append("type=TIMER"); - append(b, "name", prefix(name)); - appendCountIfEnabled(b, timer); -- appendLongDurationIfEnabled(b, MIN, snapshot::getMin); -- appendLongDurationIfEnabled(b, MAX, snapshot::getMax); -+ appendLongDurationIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); -+ appendLongDurationIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); - appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); - appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); - appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); -@@ -338,8 +336,8 @@ public class Slf4jReporter extends ScheduledReporter { - b.append("type=HISTOGRAM"); - append(b, "name", prefix(name)); - appendCountIfEnabled(b, histogram); -- appendLongIfEnabled(b, MIN, snapshot::getMin); -- appendLongIfEnabled(b, MAX, snapshot::getMax); -+ appendLongIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); -+ appendLongIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); - appendDoubleIfEnabled(b, MEAN, snapshot::getMean); - appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); - appendDoubleIfEnabled(b, P50, snapshot::getMedian); ---- a/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowMovingAverages.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/SlidingTimeWindowMovingAverages.java -@@ -184,7 +184,6 @@ public class SlidingTimeWindowMovingAverages implements MovingAverages { - buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); - buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); - } -- long retval = adder.longValue(); -- return retval; -+ return adder.longValue(); - } - } ---- a/metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java -+++ b/metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java -@@ -1,13 +1,13 @@ - package com.codahale.metrics; - - import static java.nio.charset.StandardCharsets.UTF_8; -+import static java.util.Comparator.comparingLong; - - import java.io.OutputStream; - import java.io.OutputStreamWriter; - import java.io.PrintWriter; - import java.util.Arrays; - import java.util.Collection; --import java.util.Comparator; - - /** A statistical snapshot of a {@link WeightedSnapshot}. */ - public class WeightedSnapshot extends Snapshot { -@@ -35,7 +35,7 @@ public class WeightedSnapshot extends Snapshot { - public WeightedSnapshot(Collection values) { - final WeightedSample[] copy = values.toArray(new WeightedSample[] {}); - -- Arrays.sort(copy, Comparator.comparingLong(w -> w.value)); -+ Arrays.sort(copy, comparingLong(w -> w.value)); - - this.values = new long[copy.length]; - this.normWeights = new double[copy.length]; ---- a/metrics-core/src/test/java/com/codahale/metrics/ClockTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/ClockTest.java -@@ -11,9 +11,9 @@ public class ClockTest { - public void userTimeClock() { - final Clock.UserTimeClock clock = new Clock.UserTimeClock(); - -- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(100.0)); -+ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0)); - -- assertThat((double) clock.getTick()).isEqualTo(System.nanoTime(), offset(1000000.0)); -+ assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0)); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/ConsoleReporterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/ConsoleReporterTest.java -@@ -21,8 +21,8 @@ public class ConsoleReporterTest { - private final Locale locale = Locale.US; - private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); - -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final Clock clock = mock(Clock.class); -+ private final MetricRegistry registry = mock(); -+ private final Clock clock = mock(); - private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - private final PrintStream output = new PrintStream(bytes); - private final ConsoleReporter reporter = -@@ -68,7 +68,7 @@ public class ConsoleReporterTest { - - @Test - public void reportsCounterValues() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map("test.counter", counter), map(), map(), map()); -@@ -87,10 +87,10 @@ public class ConsoleReporterTest { - - @Test - public void reportsHistogramValues() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -130,7 +130,7 @@ public class ConsoleReporterTest { - - @Test - public void reportsMeterValues() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(3.0); -@@ -157,14 +157,14 @@ public class ConsoleReporterTest { - - @Test - public void reportsTimerValues() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -223,7 +223,7 @@ public class ConsoleReporterTest { - .disabledMetricAttributes(disabledMetricAttributes) - .build(); - -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(3.0); -@@ -266,14 +266,14 @@ public class ConsoleReporterTest { - .disabledMetricAttributes(disabledMetricAttributes) - .build(); - -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -329,10 +329,10 @@ public class ConsoleReporterTest { - .disabledMetricAttributes(disabledMetricAttributes) - .build(); - -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); ---- a/metrics-core/src/test/java/com/codahale/metrics/CounterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/CounterTest.java -@@ -9,7 +9,7 @@ public class CounterTest { - - @Test - public void startsAtZero() { -- assertThat(counter.getCount()).isZero(); -+ assertThat(counter.getCount()).isEqualTo(0); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/CsvReporterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/CsvReporterTest.java -@@ -7,7 +7,6 @@ import static org.mockito.Mockito.when; - - import java.io.File; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.nio.file.Files; - import java.util.Locale; - import java.util.SortedMap; -@@ -21,8 +20,8 @@ import org.junit.rules.TemporaryFolder; - public class CsvReporterTest { - @Rule public final TemporaryFolder folder = new TemporaryFolder(); - -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final Clock clock = mock(Clock.class); -+ private final MetricRegistry registry = mock(); -+ private final Clock clock = mock(); - - private File dataDirectory; - private CsvReporter reporter; -@@ -54,7 +53,7 @@ public class CsvReporterTest { - - @Test - public void reportsCounterValues() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map("test.counter", counter), map(), map(), map()); -@@ -64,10 +63,10 @@ public class CsvReporterTest { - - @Test - public void reportsHistogramValues() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -105,14 +104,14 @@ public class CsvReporterTest { - - @Test - public void reportsTimerValues() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -137,7 +136,7 @@ public class CsvReporterTest { - - @Test - public void testCsvFileProviderIsUsed() { -- CsvFileProvider fileProvider = mock(CsvFileProvider.class); -+ CsvFileProvider fileProvider = mock(); - when(fileProvider.getFile(dataDirectory, "gauge")) - .thenReturn(new File(dataDirectory, "guage.csv")); - -@@ -175,7 +174,7 @@ public class CsvReporterTest { - } - - private Meter mockMeter() { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(3.0); -@@ -194,8 +193,7 @@ public class CsvReporterTest { - } - - private String fileContents(String filename) throws IOException { -- return new String( -- Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); -+ return Files.readString(new File(dataDirectory, filename).toPath()); - } - - private SortedMap map() { ---- a/metrics-core/src/test/java/com/codahale/metrics/EWMATest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/EWMATest.java -@@ -13,67 +13,67 @@ public class EWMATest { - ewma.update(3); - ewma.tick(); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.01098938, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00404277, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00148725, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00054713, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00020128, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00007405, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00002724, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00001002, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000369, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000136, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000050, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000018, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001)); - } - - @Test -@@ -82,67 +82,67 @@ public class EWMATest { - ewma.update(3); - ewma.tick(); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.18071653, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.14795818, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.12113791, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.09917933, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.06648190, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.05443077, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.04456415, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.03648604, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); - } - - @Test -@@ -151,67 +151,67 @@ public class EWMATest { - ewma.update(3); - ewma.tick(); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.56130419, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.52510399, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.45955700, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.42991879, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.37625345, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.35198773, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.30805027, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.28818318, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.25221023, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.23594443, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); - } - - private void elapseMinute(EWMA ewma) { ---- a/metrics-core/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -@@ -1,5 +1,6 @@ - package com.codahale.metrics; - -+import static java.util.stream.Collectors.toList; - import static org.assertj.core.api.Assertions.assertThat; - - import com.codahale.metrics.Timer.Context; -@@ -8,7 +9,6 @@ import java.util.Collection; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicBoolean; - import java.util.concurrent.atomic.AtomicInteger; --import java.util.stream.Collectors; - import org.junit.Test; - import org.junit.runner.RunWith; - import org.junit.runners.Parameterized; -@@ -46,7 +46,7 @@ public class ExponentiallyDecayingReservoirTest { - public static Collection reservoirs() { - return Arrays.stream(ReservoirFactory.values()) - .map(value -> new Object[] {value}) -- .collect(Collectors.toList()); -+ .collect(toList()); - } - - private final ReservoirFactory reservoirFactory; ---- a/metrics-core/src/test/java/com/codahale/metrics/HistogramTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/HistogramTest.java -@@ -8,12 +8,12 @@ import static org.mockito.Mockito.when; - import org.junit.Test; - - public class HistogramTest { -- private final Reservoir reservoir = mock(Reservoir.class); -+ private final Reservoir reservoir = mock(); - private final Histogram histogram = new Histogram(reservoir); - - @Test - public void updatesTheCountOnUpdates() { -- assertThat(histogram.getCount()).isZero(); -+ assertThat(histogram.getCount()).isEqualTo(0); - - histogram.update(1); - -@@ -22,7 +22,7 @@ public class HistogramTest { - - @Test - public void returnsTheSnapshotFromTheReservoir() { -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(reservoir.getSnapshot()).thenReturn(snapshot); - - assertThat(histogram.getSnapshot()).isEqualTo(snapshot); ---- a/metrics-core/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java -@@ -112,8 +112,8 @@ public class InstrumentedExecutorServiceTest { - assertThat(idle.getSnapshot().size()).isEqualTo(1); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void reportsTasksInformationForThreadPoolExecutor() throws Exception { - executor = - new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); -@@ -170,8 +170,8 @@ public class InstrumentedExecutorServiceTest { - assertThat(poolSize.getValue()).isEqualTo(1); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void reportsTasksInformationForForkJoinPool() throws Exception { - executor = Executors.newWorkStealingPool(4); - instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); ---- a/metrics-core/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java -@@ -36,16 +36,16 @@ public class InstrumentedScheduledExecutorServiceTest { - - @Test - public void testSubmitRunnable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - Future theFuture = - instrumentedScheduledExecutor.submit( -@@ -53,87 +53,87 @@ public class InstrumentedScheduledExecutorServiceTest { - assertThat(submitted.getCount()).isEqualTo(1); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - }); - - theFuture.get(); - - assertThat(submitted.getCount()).isEqualTo(1); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test - public void testScheduleRunnable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - ScheduledFuture theFuture = - instrumentedScheduledExecutor.schedule( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - }, - 10L, - TimeUnit.MILLISECONDS); - - theFuture.get(); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test - public void testSubmitCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - final Object obj = new Object(); - -@@ -143,13 +143,13 @@ public class InstrumentedScheduledExecutorServiceTest { - assertThat(submitted.getCount()).isEqualTo(1); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - return obj; - }); -@@ -158,45 +158,45 @@ public class InstrumentedScheduledExecutorServiceTest { - - assertThat(submitted.getCount()).isEqualTo(1); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test - public void testScheduleCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - final Object obj = new Object(); - - ScheduledFuture theFuture = - instrumentedScheduledExecutor.schedule( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - return obj; - }, -@@ -205,37 +205,37 @@ public class InstrumentedScheduledExecutorServiceTest { - - assertThat(theFuture.get()).isEqualTo(obj); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test - public void testScheduleFixedRateCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - CountDownLatch countDownLatch = new CountDownLatch(1); - ScheduledFuture theFuture = - instrumentedScheduledExecutor.scheduleAtFixedRate( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); - -@@ -257,14 +257,14 @@ public class InstrumentedScheduledExecutorServiceTest { - theFuture.cancel(true); - TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isNotEqualTo(0); - assertThat(duration.getCount()).isNotEqualTo(0); - assertThat(duration.getSnapshot().size()).isNotEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); - assertThat(scheduledRepetitively.getCount()).isEqualTo(1); - assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); - assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); -@@ -272,22 +272,22 @@ public class InstrumentedScheduledExecutorServiceTest { - - @Test - public void testScheduleFixedDelayCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - CountDownLatch countDownLatch = new CountDownLatch(1); - ScheduledFuture theFuture = - instrumentedScheduledExecutor.scheduleWithFixedDelay( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); - -@@ -310,9 +310,9 @@ public class InstrumentedScheduledExecutorServiceTest { - theFuture.cancel(true); - TimeUnit.MILLISECONDS.sleep(200); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isNotEqualTo(0); - assertThat(duration.getCount()).isNotEqualTo(0); - assertThat(duration.getSnapshot().size()).isNotEqualTo(0); ---- a/metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java -@@ -11,7 +11,7 @@ import org.junit.runner.RunWith; - import org.junit.runners.Parameterized; - import org.junit.runners.Parameterized.Parameters; - --@RunWith(value = Parameterized.class) -+@RunWith(Parameterized.class) - public class MeterApproximationTest { - - @Parameters -@@ -34,7 +34,7 @@ public class MeterApproximationTest { - 3, TimeUnit.MINUTES); - - assertThat(meter.getOneMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); - } - - @Test -@@ -45,7 +45,7 @@ public class MeterApproximationTest { - 13, TimeUnit.MINUTES); - - assertThat(meter.getFiveMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); - } - - @Test -@@ -56,7 +56,7 @@ public class MeterApproximationTest { - 38, TimeUnit.MINUTES); - - assertThat(meter.getFifteenMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); - } - - private Meter simulateMetronome( ---- a/metrics-core/src/test/java/com/codahale/metrics/MeterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/MeterTest.java -@@ -10,7 +10,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MeterTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final Meter meter = new Meter(clock); - - @Before -@@ -20,15 +20,15 @@ public class MeterTest { - - @Test - public void startsOutWithNoRatesOrCount() { -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - -- assertThat(meter.getMeanRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); - } - - @Test -@@ -36,12 +36,12 @@ public class MeterTest { - meter.mark(); - meter.mark(2); - -- assertThat(meter.getMeanRate()).isEqualTo(0.3, offset(0.001)); -+ assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001)); - -- assertThat(meter.getOneMinuteRate()).isEqualTo(0.1840, offset(0.001)); -+ assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001)); - -- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.1966, offset(0.001)); -+ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001)); - -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.1988, offset(0.001)); -+ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001)); - } - } ---- a/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryListenerTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryListenerTest.java -@@ -6,10 +6,10 @@ import static org.mockito.Mockito.verifyNoInteractions; - import org.junit.Test; - - public class MetricRegistryListenerTest { -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - private final MetricRegistryListener listener = new MetricRegistryListener.Base() {}; - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/MetricRegistryTest.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.stream.Collectors.toSet; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.mockito.Mockito.mock; -@@ -10,20 +11,19 @@ import static org.mockito.Mockito.verify; - import java.util.HashMap; - import java.util.Map; - import java.util.Set; --import java.util.stream.Collectors; - import org.junit.Assert; - import org.junit.Before; - import org.junit.Test; - - public class MetricRegistryTest { -- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); -+ private final MetricRegistryListener listener = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private final Gauge gauge = () -> ""; - private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - - @Before - public void setUp() { -@@ -230,8 +230,8 @@ public class MetricRegistryTest { - verify(listener).onGaugeAdded("thing", gauge1); - } - -- @Test - @SuppressWarnings("rawtypes") -+ @Test - public void accessingACustomGaugeRegistersAndReusesIt() { - final MetricRegistry.MetricSupplier supplier = () -> gauge; - final Gauge gauge1 = registry.gauge("thing", supplier); -@@ -261,7 +261,7 @@ public class MetricRegistryTest { - registry.register("meter", meter); - registry.register("timer", timer); - -- final MetricRegistryListener other = mock(MetricRegistryListener.class); -+ final MetricRegistryListener other = mock(); - registry.addListener(other); - - verify(other).onGaugeAdded("gauge", gauge); -@@ -383,7 +383,7 @@ public class MetricRegistryTest { - MetricRegistry other = new MetricRegistry(); - other.register("gauge", gauge); - registry.register("nested", other); -- assertThat(registry.getNames()).containsOnly("nested.gauge"); -+ assertThat(registry.getNames()).containsExactly("nested.gauge"); - } - - @Test -@@ -391,8 +391,8 @@ public class MetricRegistryTest { - assertThat(name("one", "two", "three")).isEqualTo("one.two.three"); - } - -- @Test - @SuppressWarnings("NullArgumentToVariableArgMethod") -+ @Test - public void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { - assertThat(name("one", (String) null)).isEqualTo("one"); - } -@@ -456,7 +456,7 @@ public class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - } - - @Test -@@ -474,7 +474,7 @@ public class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - } - - @Test -@@ -498,14 +498,13 @@ public class MetricRegistryTest { - Set deepChildMetrics = deepChild.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - - assertThat(childMetrics) -- .containsAll( -- deepChildMetrics.stream().map(m -> "deep-child." + m).collect(Collectors.toSet())); -+ .containsAll(deepChildMetrics.stream().map(m -> "deep-child." + m).collect(toSet())); - -- assertThat(deepChildMetrics.size()).isEqualTo(3); -- assertThat(childMetrics.size()).isEqualTo(5); -+ assertThat(deepChildMetrics).hasSize(3); -+ assertThat(childMetrics).hasSize(5); - } - - @Test -@@ -523,7 +522,7 @@ public class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - - assertThat(childMetrics).doesNotContain("test-1"); - } -@@ -546,7 +545,7 @@ public class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - - assertThat(childMetrics).doesNotContain("test-1", "test-3"); - } -@@ -572,16 +571,15 @@ public class MetricRegistryTest { - Set deepChildMetrics = deepChild.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> "child." + m).collect(Collectors.toSet())); -+ .hasSameElementsAs(childMetrics.stream().map(m -> "child." + m).collect(toSet())); - - assertThat(childMetrics) -- .containsAll( -- deepChildMetrics.stream().map(m -> "deep-child." + m).collect(Collectors.toSet())); -+ .containsAll(deepChildMetrics.stream().map(m -> "deep-child." + m).collect(toSet())); - - assertThat(deepChildMetrics).doesNotContain("test-2"); - -- assertThat(deepChildMetrics.size()).isEqualTo(1); -- assertThat(childMetrics.size()).isEqualTo(3); -+ assertThat(deepChildMetrics).hasSize(1); -+ assertThat(childMetrics).hasSize(3); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/NoopMetricRegistryTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/NoopMetricRegistryTest.java -@@ -1,7 +1,7 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatNullPointerException; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; - import static org.mockito.Mockito.verify; -@@ -13,13 +13,13 @@ import org.junit.Before; - import org.junit.Test; - - public class NoopMetricRegistryTest { -- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); -+ private final MetricRegistryListener listener = mock(); - private final NoopMetricRegistry registry = new NoopMetricRegistry(); - private final Gauge gauge = () -> ""; -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - - @Before - public void setUp() { -@@ -218,8 +218,8 @@ public class NoopMetricRegistryTest { - verify(listener, never()).onGaugeAdded("thing", gauge1); - } - -- @Test - @SuppressWarnings("rawtypes") -+ @Test - public void accessingACustomGaugeRegistersAndReusesIt() { - final MetricRegistry.MetricSupplier supplier = () -> gauge; - final Gauge gauge1 = registry.gauge("thing", supplier); -@@ -240,7 +240,7 @@ public class NoopMetricRegistryTest { - registry.register("meter", meter); - registry.register("timer", timer); - -- final MetricRegistryListener other = mock(MetricRegistryListener.class); -+ final MetricRegistryListener other = mock(); - registry.addListener(other); - - verify(other, never()).onGaugeAdded("gauge", gauge); -@@ -488,8 +488,8 @@ public class NoopMetricRegistryTest { - @Test - public void registerNullMetric() { - MetricRegistry registry = new NoopMetricRegistry(); -- assertThatNullPointerException() -- .isThrownBy(() -> registry.register("any_name", null)) -- .withMessage("metric == null"); -+ assertThatThrownBy(() -> registry.register("any_name", null)) -+ .isInstanceOf(NullPointerException.class) -+ .hasMessage("metric == null"); - } - } ---- a/metrics-core/src/test/java/com/codahale/metrics/RatioGaugeTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/RatioGaugeTest.java -@@ -9,7 +9,7 @@ public class RatioGaugeTest { - public void ratiosAreHumanReadable() { - final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); - -- assertThat(ratio.toString()).isEqualTo("100.0:200.0"); -+ assertThat(ratio).hasToString("100.0:200.0"); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java -@@ -26,12 +26,12 @@ import org.junit.Test; - - public class ScheduledReporterTest { - private final Gauge gauge = () -> ""; -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - -- private final ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); -+ private final ScheduledExecutorService mockExecutor = mock(); - private final ScheduledExecutorService customExecutor = - Executors.newSingleThreadScheduledExecutor(); - private final ScheduledExecutorService externalExecutor = -@@ -145,7 +145,7 @@ public class ScheduledReporterTest { - public void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { - reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); - -- verify(mockExecutor, times(1)) -+ verify(mockExecutor) - .scheduleWithFixedDelay(any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS)); - } - -@@ -295,7 +295,7 @@ public class ScheduledReporterTest { - - Thread.sleep(1_000); - -- verify(reporter, times(1)) -+ verify(reporter) - .report( - map("gauge", gauge), - map("counter", counter), ---- a/metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java -@@ -29,7 +29,7 @@ public class SharedMetricRegistriesTest { - public void hasASetOfNames() { - SharedMetricRegistries.getOrCreate("one"); - -- assertThat(SharedMetricRegistries.names()).containsOnly("one"); -+ assertThat(SharedMetricRegistries.names()).containsExactly("one"); - } - - @Test ---- a/metrics-core/src/test/java/com/codahale/metrics/Slf4jReporterTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/Slf4jReporterTest.java -@@ -3,7 +3,6 @@ package com.codahale.metrics; - import static com.codahale.metrics.MetricAttribute.COUNT; - import static com.codahale.metrics.MetricAttribute.M1_RATE; - import static com.codahale.metrics.MetricAttribute.MEAN_RATE; --import static com.codahale.metrics.MetricAttribute.MIN; - import static com.codahale.metrics.MetricAttribute.P50; - import static com.codahale.metrics.MetricAttribute.P999; - import static com.codahale.metrics.MetricAttribute.STDDEV; -@@ -22,9 +21,9 @@ import org.slf4j.Marker; - - public class Slf4jReporterTest { - -- private final Logger logger = mock(Logger.class); -- private final Marker marker = mock(Marker.class); -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final Logger logger = mock(); -+ private final Marker marker = mock(); -+ private final MetricRegistry registry = mock(); - - /** - * The set of disabled metric attributes to pass to the Slf4jReporter builder in the default -@@ -79,7 +78,7 @@ public class Slf4jReporterTest { - } - - private Timer timer() { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - - when(timer.getMeanRate()).thenReturn(2.0); -@@ -87,7 +86,7 @@ public class Slf4jReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -104,10 +103,10 @@ public class Slf4jReporterTest { - } - - private Histogram histogram() { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -124,7 +123,7 @@ public class Slf4jReporterTest { - } - - private Meter meter() { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(3.0); -@@ -134,7 +133,7 @@ public class Slf4jReporterTest { - } - - private Counter counter() { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - return counter; - } -@@ -168,7 +167,7 @@ public class Slf4jReporterTest { - - @Test - public void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); -+ disabledMetricAttributes = EnumSet.of(COUNT, MetricAttribute.MIN, P50); - reportsHistogramValuesAtError( - "type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " - + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -@@ -192,7 +191,7 @@ public class Slf4jReporterTest { - - @Test - public void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); -+ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, P50, M1_RATE); - reportsMeterValuesAtError( - "type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " - + "mean_rate=2.0, rate_unit=events/second"); -@@ -218,7 +217,7 @@ public class Slf4jReporterTest { - - @Test - public void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); -+ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, STDDEV, P999, MEAN_RATE); - reportsTimerValuesAtError( - "type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " - + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " ---- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java -@@ -16,7 +16,7 @@ public class SlidingTimeWindowArrayReservoirTest { - - @Test - public void storesMeasurementsWithDuplicateTicks() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - final SlidingTimeWindowArrayReservoir reservoir = - new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); - -@@ -30,7 +30,7 @@ public class SlidingTimeWindowArrayReservoirTest { - - @Test - public void boundsMeasurementsToATimeWindow() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - final SlidingTimeWindowArrayReservoir reservoir = - new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); - -@@ -99,7 +99,7 @@ public class SlidingTimeWindowArrayReservoirTest { - // Set the clock to overflow in (2*window+1)ns - final ManualClock clock = new ManualClock(); - clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -- assertThat(clock.getTick() * 256).isGreaterThan(0); -+ assertThat(clock.getTick() * 256).isPositive(); - - // Create the reservoir - final SlidingTimeWindowArrayReservoir reservoir = ---- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowMovingAveragesTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowMovingAveragesTest.java -@@ -44,7 +44,7 @@ public class SlidingTimeWindowMovingAveragesTest { - - SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); - -- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(0L)), is(0)); -+ assertThat(stwm.calculateIndexOfTick(Instant.EPOCH), is(0)); - assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L)), is(1)); - } - -@@ -62,7 +62,7 @@ public class SlidingTimeWindowMovingAveragesTest { - } - - // verify that no cleanup happened yet -- assertThat(movingAverages.oldestBucketTime, is(Instant.ofEpochSecond(0L))); -+ assertThat(movingAverages.oldestBucketTime, is(Instant.EPOCH)); - - assertThat(meter.getOneMinuteRate(), is(60.0)); - assertThat(meter.getFiveMinuteRate(), is(300.0)); -@@ -83,7 +83,7 @@ public class SlidingTimeWindowMovingAveragesTest { - } - - // verify that at least one cleanup happened -- assertThat(movingAverages.oldestBucketTime, not(is(Instant.ofEpochSecond(0L)))); -+ assertThat(movingAverages.oldestBucketTime, not(is(Instant.EPOCH))); - - assertThat(meter.getOneMinuteRate(), is(60.0)); - assertThat(meter.getFiveMinuteRate(), is(300.0)); ---- a/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java -@@ -12,7 +12,7 @@ import org.junit.Test; - public class SlidingTimeWindowReservoirTest { - @Test - public void storesMeasurementsWithDuplicateTicks() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - final SlidingTimeWindowReservoir reservoir = - new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); - -@@ -26,7 +26,7 @@ public class SlidingTimeWindowReservoirTest { - - @Test - public void boundsMeasurementsToATimeWindow() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - when(clock.getTick()).thenReturn(0L); - - final SlidingTimeWindowReservoir reservoir = -@@ -72,7 +72,7 @@ public class SlidingTimeWindowReservoirTest { - - // Set the clock to overflow in (2*window+1)ns - clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -- assertThat(clock.getTick() * 256).isGreaterThan(0); -+ assertThat(clock.getTick() * 256).isPositive(); - - int updatesAfterThreshold = 0; - while (true) { ---- a/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/TimerTest.java -@@ -13,7 +13,7 @@ import java.util.concurrent.atomic.AtomicBoolean; - import org.junit.Test; - - public class TimerTest { -- private final Reservoir reservoir = mock(Reservoir.class); -+ private final Reservoir reservoir = mock(); - private final Clock clock = - new Clock() { - // a mock clock that increments its ticker by 50msec per call -@@ -28,20 +28,20 @@ public class TimerTest { - - @Test - public void hasRates() { -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - -- assertThat(timer.getMeanRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); - } - - @Test - public void updatesTheCountOnUpdates() { -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - - timer.update(1, TimeUnit.SECONDS); - -@@ -93,7 +93,7 @@ public class TimerTest { - - @Test - public void returnsTheSnapshotFromTheReservoir() { -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(reservoir.getSnapshot()).thenReturn(snapshot); - - assertThat(timer.getSnapshot()).isEqualTo(snapshot); -@@ -103,7 +103,7 @@ public class TimerTest { - public void ignoresNegativeValues() { - timer.update(-1, TimeUnit.SECONDS); - -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - - verifyNoInteractions(reservoir); - } -@@ -121,14 +121,14 @@ public class TimerTest { - public void java8NegativeDuration() { - timer.update(Duration.ofMillis(-5678)); - -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - - verifyNoInteractions(reservoir); - } - - @Test - public void tryWithResourcesWork() { -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - - int dummy = 0; - try (Timer.Context context = timer.time()) { ---- a/metrics-core/src/test/java/com/codahale/metrics/UniformReservoirTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/UniformReservoirTest.java -@@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; - - public class UniformReservoirTest { -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void aReservoirOf100OutOf1000Elements() { - final UniformReservoir reservoir = new UniformReservoir(100); - for (int i = 0; i < 1000; i++) { -@@ -20,7 +20,7 @@ public class UniformReservoirTest { - assertThat(snapshot.size()).isEqualTo(100); - - for (double i : snapshot.getValues()) { -- assertThat(i).isLessThan(1000).isGreaterThanOrEqualTo(0); -+ assertThat(i).isLessThan(1000).isNotNegative(); - } - } - } ---- a/metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java -@@ -16,12 +16,12 @@ public class UniformSnapshotTest { - - @Test - public void smallQuantilesAreTheFirstValue() { -- assertThat(snapshot.getValue(0.0)).isEqualTo(1, offset(0.1)); -+ assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1)); - } - - @Test - public void bigQuantilesAreTheLastValue() { -- assertThat(snapshot.getValue(1.0)).isEqualTo(5, offset(0.1)); -+ assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1)); - } - - @Test(expected = IllegalArgumentException.class) -@@ -41,32 +41,32 @@ public class UniformSnapshotTest { - - @Test - public void hasAMedian() { -- assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); -+ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1)); - } - - @Test - public void hasAp75() { -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1)); - } - - @Test - public void hasAp95() { -- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp98() { -- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp99() { -- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp999() { -- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test -@@ -125,7 +125,7 @@ public class UniformSnapshotTest { - - snapshot.dump(output); - -- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); -+ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); - } - - @Test -@@ -145,41 +145,41 @@ public class UniformSnapshotTest { - - @Test - public void calculatesTheStdDev() { -- assertThat(snapshot.getStdDev()).isEqualTo(1.5811, offset(0.0001)); -+ assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001)); - } - - @Test - public void calculatesAMinOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMin()).isZero(); -+ assertThat(emptySnapshot.getMin()).isEqualTo(0); - } - - @Test - public void calculatesAMaxOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMax()).isZero(); -+ assertThat(emptySnapshot.getMax()).isEqualTo(0); - } - - @Test - public void calculatesAMeanOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMean()).isZero(); -+ assertThat(emptySnapshot.getMean()).isEqualTo(0); - } - - @Test - public void calculatesAStdDevOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getStdDev()).isZero(); -+ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); - } - - @Test - public void calculatesAStdDevOfZeroForASingletonSnapshot() { - final Snapshot singleItemSnapshot = new UniformSnapshot(new long[] {1}); - -- assertThat(singleItemSnapshot.getStdDev()).isZero(); -+ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); - } - } ---- a/metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java -+++ b/metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java -@@ -2,6 +2,7 @@ package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.offset; -+import static org.mockito.ArgumentMatchers.any; - import static org.mockito.Mockito.doReturn; - import static org.mockito.Mockito.spy; - import static org.mockito.Mockito.when; -@@ -11,7 +12,6 @@ import java.io.ByteArrayOutputStream; - import java.util.ArrayList; - import java.util.List; - import org.junit.Test; --import org.mockito.ArgumentMatchers; - - public class WeightedSnapshotTest { - -@@ -34,12 +34,12 @@ public class WeightedSnapshotTest { - - @Test - public void smallQuantilesAreTheFirstValue() { -- assertThat(snapshot.getValue(0.0)).isEqualTo(1.0, offset(0.1)); -+ assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1)); - } - - @Test - public void bigQuantilesAreTheLastValue() { -- assertThat(snapshot.getValue(1.0)).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1)); - } - - @Test(expected = IllegalArgumentException.class) -@@ -59,32 +59,32 @@ public class WeightedSnapshotTest { - - @Test - public void hasAMedian() { -- assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); -+ assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1)); - } - - @Test - public void hasAp75() { -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1)); - } - - @Test - public void hasAp95() { -- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp98() { -- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp99() { -- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - public void hasAp999() { -- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test -@@ -104,7 +104,7 @@ public class WeightedSnapshotTest { - final List spyItems = spy(originalItems); - doReturn(originalItems.toArray(new WeightedSample[] {})) - .when(spyItems) -- .toArray(ArgumentMatchers.any(WeightedSample[].class)); -+ .toArray(any(WeightedSample[].class)); - when(spyItems.size()).thenReturn(4, 5); - - final Snapshot other = new WeightedSnapshot(spyItems); -@@ -119,7 +119,7 @@ public class WeightedSnapshotTest { - final List spyItems = spy(originalItems); - doReturn(originalItems.toArray(new WeightedSample[] {})) - .when(spyItems) -- .toArray(ArgumentMatchers.any(WeightedSample[].class)); -+ .toArray(any(WeightedSample[].class)); - when(spyItems.size()).thenReturn(6, 5); - - final Snapshot other = new WeightedSnapshot(spyItems); -@@ -133,7 +133,7 @@ public class WeightedSnapshotTest { - - snapshot.dump(output); - -- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); -+ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); - } - - @Test -@@ -153,7 +153,7 @@ public class WeightedSnapshotTest { - - @Test - public void calculatesTheStdDev() { -- assertThat(snapshot.getStdDev()).isEqualTo(1.2688, offset(0.0001)); -+ assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001)); - } - - @Test -@@ -161,7 +161,7 @@ public class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getMin()).isZero(); -+ assertThat(emptySnapshot.getMin()).isEqualTo(0); - } - - @Test -@@ -169,7 +169,7 @@ public class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getMax()).isZero(); -+ assertThat(emptySnapshot.getMax()).isEqualTo(0); - } - - @Test -@@ -177,7 +177,7 @@ public class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getMean()).isZero(); -+ assertThat(emptySnapshot.getMean()).isEqualTo(0); - } - - @Test -@@ -185,7 +185,7 @@ public class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getStdDev()).isZero(); -+ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); - } - - @Test -@@ -193,7 +193,7 @@ public class WeightedSnapshotTest { - final Snapshot singleItemSnapshot = - new WeightedSnapshot(weightedArray(new long[] {1}, new double[] {1.0})); - -- assertThat(singleItemSnapshot.getStdDev()).isZero(); -+ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); - } - - @Test ---- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java -+++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java -@@ -132,8 +132,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { - final String sanitizedName = sanitize(name); - final String sanitizedValue = sanitize(value); - -- final String message = -- sanitizedName + ' ' + sanitizedValue + ' ' + Long.toString(timestamp) + '\n'; -+ final String message = sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n'; - channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); - } catch (IOException e) { - failures++; ---- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java -+++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java -@@ -4,10 +4,8 @@ import static com.codahale.metrics.MetricAttribute.COUNT; - import static com.codahale.metrics.MetricAttribute.M15_RATE; - import static com.codahale.metrics.MetricAttribute.M1_RATE; - import static com.codahale.metrics.MetricAttribute.M5_RATE; --import static com.codahale.metrics.MetricAttribute.MAX; - import static com.codahale.metrics.MetricAttribute.MEAN; - import static com.codahale.metrics.MetricAttribute.MEAN_RATE; --import static com.codahale.metrics.MetricAttribute.MIN; - import static com.codahale.metrics.MetricAttribute.P50; - import static com.codahale.metrics.MetricAttribute.P75; - import static com.codahale.metrics.MetricAttribute.P95; -@@ -15,6 +13,7 @@ import static com.codahale.metrics.MetricAttribute.P98; - import static com.codahale.metrics.MetricAttribute.P99; - import static com.codahale.metrics.MetricAttribute.P999; - import static com.codahale.metrics.MetricAttribute.STDDEV; -+import static java.util.Collections.emptySet; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.Counter; -@@ -29,7 +28,6 @@ import com.codahale.metrics.ScheduledReporter; - import com.codahale.metrics.Snapshot; - import com.codahale.metrics.Timer; - import java.io.IOException; --import java.util.Collections; - import java.util.Locale; - import java.util.Map; - import java.util.Set; -@@ -83,7 +81,7 @@ public class GraphiteReporter extends ScheduledReporter { - this.filter = MetricFilter.ALL; - this.executor = null; - this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -+ this.disabledMetricAttributes = emptySet(); - this.addMetricAttributesAsTags = false; - this.floatingPointFormatter = DEFAULT_FP_FORMATTER; - } -@@ -453,9 +451,9 @@ public class GraphiteReporter extends ScheduledReporter { - - private void reportTimer(String name, Timer timer, long timestamp) throws IOException { - final Snapshot snapshot = timer.getSnapshot(); -- sendIfEnabled(MAX, name, convertDuration(snapshot.getMax()), timestamp); -+ sendIfEnabled(MetricAttribute.MAX, name, convertDuration(snapshot.getMax()), timestamp); - sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); -- sendIfEnabled(MIN, name, convertDuration(snapshot.getMin()), timestamp); -+ sendIfEnabled(MetricAttribute.MIN, name, convertDuration(snapshot.getMin()), timestamp); - sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); - sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); - sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); -@@ -478,9 +476,9 @@ public class GraphiteReporter extends ScheduledReporter { - throws IOException { - final Snapshot snapshot = histogram.getSnapshot(); - sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); -- sendIfEnabled(MAX, name, snapshot.getMax(), timestamp); -+ sendIfEnabled(MetricAttribute.MAX, name, snapshot.getMax(), timestamp); - sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); -- sendIfEnabled(MIN, name, snapshot.getMin(), timestamp); -+ sendIfEnabled(MetricAttribute.MIN, name, snapshot.getMin(), timestamp); - sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); - sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); - sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); ---- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java -+++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java -@@ -63,7 +63,7 @@ public class GraphiteUDP implements GraphiteSender { - @Override - public void send(String name, String value, long timestamp) throws IOException { - try { -- String str = sanitize(name) + ' ' + sanitize(value) + ' ' + Long.toString(timestamp) + '\n'; -+ String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n'; - ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); - datagramChannel.send(byteBuffer, address); - this.failures = 0; ---- a/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java -+++ b/metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java -@@ -249,7 +249,7 @@ public class PickledGraphite implements GraphiteSender { - * message to graphite 3. Clear out the list of metrics - */ - private void writeMetrics() throws IOException { -- if (metrics.size() > 0) { -+ if (!metrics.isEmpty()) { - try { - byte[] payload = pickleMetrics(metrics); - byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteRabbitMQTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteRabbitMQTest.java -@@ -8,7 +8,6 @@ import static org.mockito.Mockito.anyString; - import static org.mockito.Mockito.atMost; - import static org.mockito.Mockito.doThrow; - import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -21,13 +20,13 @@ import org.junit.Before; - import org.junit.Test; - - public class GraphiteRabbitMQTest { -- private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); -- private final Connection connection = mock(Connection.class); -- private final Channel channel = mock(Channel.class); -+ private final ConnectionFactory connectionFactory = mock(); -+ private final Connection connection = mock(); -+ private final Channel channel = mock(); - -- private final ConnectionFactory bogusConnectionFactory = mock(ConnectionFactory.class); -- private final Connection bogusConnection = mock(Connection.class); -- private final Channel bogusChannel = mock(Channel.class); -+ private final ConnectionFactory bogusConnectionFactory = mock(); -+ private final Connection bogusConnection = mock(); -+ private final Channel bogusChannel = mock(); - - private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); - -@@ -92,10 +91,9 @@ public class GraphiteRabbitMQTest { - - String expectedMessage = "name value 100\n"; - -- verify(channel, times(1)) -- .basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); -+ verify(channel).basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); - -- assertThat(graphite.getFailures()).isZero(); -+ assertThat(graphite.getFailures()).isEqualTo(0); - } - - @Test -@@ -105,10 +103,10 @@ public class GraphiteRabbitMQTest { - - String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; - -- verify(channel, times(1)) -+ verify(channel) - .basicPublish("graphite", "name-to-sanitize", null, expectedMessage.getBytes(UTF_8)); - -- assertThat(graphite.getFailures()).isZero(); -+ assertThat(graphite.getFailures()).isEqualTo(0); - } - - @Test ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java -@@ -1,5 +1,6 @@ - package com.codahale.metrics.graphite; - -+import static java.util.Collections.emptySet; - import static org.mockito.Mockito.doThrow; - import static org.mockito.Mockito.inOrder; - import static org.mockito.Mockito.mock; -@@ -21,7 +22,6 @@ import com.codahale.metrics.Timer; - import java.net.UnknownHostException; - import java.text.DecimalFormat; - import java.text.DecimalFormatSymbols; --import java.util.Collections; - import java.util.EnumSet; - import java.util.Locale; - import java.util.Set; -@@ -34,9 +34,9 @@ import org.mockito.InOrder; - - public class GraphiteReporterTest { - private final long timestamp = 1000198; -- private final Clock clock = mock(Clock.class); -- private final Graphite graphite = mock(Graphite.class); -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final Clock clock = mock(); -+ private final Graphite graphite = mock(); -+ private final MetricRegistry registry = mock(); - private final GraphiteReporter reporter = - GraphiteReporter.forRegistry(registry) - .withClock(clock) -@@ -44,7 +44,7 @@ public class GraphiteReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(emptySet()) - .build(graphite); - - private final GraphiteReporter minuteRateReporter = -@@ -54,7 +54,7 @@ public class GraphiteReporterTest { - .convertRatesTo(TimeUnit.MINUTES) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(emptySet()) - .build(graphite); - - @Before -@@ -174,7 +174,7 @@ public class GraphiteReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(emptySet()) - .withFloatingPointFormatter(formatter::format) - .build(graphite)) { - reportGaugeValue(graphiteReporter, 0.000045322); -@@ -216,7 +216,7 @@ public class GraphiteReporterTest { - - @Test - public void reportsCounters() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map("counter", counter), map(), map(), map()); -@@ -232,10 +232,10 @@ public class GraphiteReporterTest { - - @Test - public void reportsHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -272,7 +272,7 @@ public class GraphiteReporterTest { - - @Test - public void reportsMeters() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); -@@ -296,7 +296,7 @@ public class GraphiteReporterTest { - - @Test - public void reportsMetersInMinutes() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); -@@ -321,14 +321,14 @@ public class GraphiteReporterTest { - - @Test - public void reportsTimers() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -395,14 +395,14 @@ public class GraphiteReporterTest { - - @Test - public void disabledMetricsAttribute() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); - when(meter.getFifteenMinuteRate()).thenReturn(4.0); - when(meter.getMeanRate()).thenReturn(5.0); - -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(11L); - - Set disabledMetricAttributes = -@@ -433,7 +433,7 @@ public class GraphiteReporterTest { - - @Test - public void sendsMetricAttributesAsTagsIfEnabled() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - getReporterThatSendsMetricAttributesAsTags() -@@ -459,7 +459,7 @@ public class GraphiteReporterTest { - MetricFilter.ALL, - null, - false, -- Collections.emptySet(), -+ emptySet(), - false) { - @Override - protected String format(double v) { -@@ -475,7 +475,7 @@ public class GraphiteReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(emptySet()) - .addMetricAttributesAsTags(true) - .build(graphite); - } ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java -@@ -26,11 +26,11 @@ import org.junit.Test; - public class GraphiteTest { - private final String host = "example.com"; - private final int port = 1234; -- private final SocketFactory socketFactory = mock(SocketFactory.class); -+ private final SocketFactory socketFactory = mock(); - private final InetSocketAddress address = new InetSocketAddress(host, port); - -- private final Socket socket = mock(Socket.class); -- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); -+ private final Socket socket = mock(); -+ private final ByteArrayOutputStream output = spy(); - - @Before - public void setUp() throws Exception { -@@ -84,7 +84,7 @@ public class GraphiteTest { - @Test - public void measuresFailures() throws IOException { - try (Graphite graphite = new Graphite(address, socketFactory)) { -- assertThat(graphite.getFailures()).isZero(); -+ assertThat(graphite.getFailures()).isEqualTo(0); - } - } - ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java -@@ -1,13 +1,13 @@ - package com.codahale.metrics.graphite; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; - - import java.net.InetSocketAddress; - import java.nio.ByteBuffer; - import java.nio.channels.DatagramChannel; - import org.junit.Test; --import org.mockito.Mockito; - - public class GraphiteUDPTest { - -@@ -30,7 +30,7 @@ public class GraphiteUDPTest { - @Test - public void writesValue() throws Exception { - graphiteUDP = new GraphiteUDP(host, port); -- DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); -+ DatagramChannel mockDatagramChannel = mock(); - graphiteUDP.setDatagramChannel(mockDatagramChannel); - graphiteUDP.setAddress(new InetSocketAddress(host, port)); - ---- a/metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java -+++ b/metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java -@@ -32,12 +32,12 @@ import org.python.core.PyList; - import org.python.core.PyTuple; - - public class PickledGraphiteTest { -- private final SocketFactory socketFactory = mock(SocketFactory.class); -+ private final SocketFactory socketFactory = mock(); - private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); - private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); - -- private final Socket socket = mock(Socket.class); -- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); -+ private final Socket socket = mock(); -+ private final ByteArrayOutputStream output = spy(); - - private CompiledScript unpickleScript; - ---- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java -+++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java -@@ -29,10 +29,10 @@ public class AsyncHealthCheckDecorator extends HealthCheck implements Runnable { - this.healthyTtl = - async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); - result = -- Async.InitialState.HEALTHY.equals(async.initialState()) -+ Async.InitialState.HEALTHY == async.initialState() - ? Result.healthy(NO_RESULT_YET_MESSAGE) - : Result.unhealthy(NO_RESULT_YET_MESSAGE); -- if (Async.ScheduleType.FIXED_RATE.equals(async.scheduleType())) { -+ if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) { - future = - executorService.scheduleAtFixedRate( - this, async.initialDelay(), async.period(), async.unit()); ---- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java -+++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java -@@ -1,11 +1,12 @@ - package com.codahale.metrics.health; - -+import static java.util.Collections.unmodifiableMap; -+ - import com.codahale.metrics.Clock; - import java.time.Instant; - import java.time.ZoneId; - import java.time.ZonedDateTime; - import java.time.format.DateTimeFormatter; --import java.util.Collections; - import java.util.LinkedHashMap; - import java.util.Map; - import java.util.concurrent.TimeUnit; -@@ -124,7 +125,7 @@ public abstract class HealthCheck { - this.healthy = isHealthy; - this.message = message; - this.error = error; -- this.details = details == null ? null : Collections.unmodifiableMap(details); -+ this.details = details == null ? null : unmodifiableMap(details); - this.time = clock.getTime(); - } - -@@ -163,7 +164,7 @@ public abstract class HealthCheck { - */ - public String getTimestamp() { - Instant currentInstant = Instant.ofEpochMilli(time); -- ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(currentInstant, ZoneId.systemDefault()); -+ ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault()); - return DATE_FORMAT_PATTERN.format(zonedDateTime); - } - -@@ -219,8 +220,7 @@ public abstract class HealthCheck { - int result = healthy ? 1 : 0; - result = PRIME * result + (message != null ? message.hashCode() : 0); - result = PRIME * result + (error != null ? error.hashCode() : 0); -- result = PRIME * result + (Long.hashCode(time)); -- return result; -+ return PRIME * result + (Long.hashCode(time)); - } - - @Override -@@ -238,7 +238,7 @@ public abstract class HealthCheck { - if (details != null) { - for (Map.Entry e : details.entrySet()) { - builder.append(", "); -- builder.append(e.getKey()).append("=").append(String.valueOf(e.getValue())); -+ builder.append(e.getKey()).append("=").append(e.getValue()); - } - } - builder.append('}'); ---- a/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java -+++ b/metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java -@@ -1,9 +1,10 @@ - package com.codahale.metrics.health; - - import static com.codahale.metrics.health.HealthCheck.Result; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Collections.unmodifiableSortedSet; - - import com.codahale.metrics.health.annotation.Async; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -128,7 +129,7 @@ public class HealthCheckRegistry { - * @return the names of all registered health checks - */ - public SortedSet getNames() { -- return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); -+ return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); - } - - /** -@@ -180,7 +181,7 @@ public class HealthCheckRegistry { - results.put(entry.getKey(), result); - } - } -- return Collections.unmodifiableSortedMap(results); -+ return unmodifiableSortedMap(results); - } - - /** -@@ -208,7 +209,7 @@ public class HealthCheckRegistry { - final String name = entry.getKey(); - final HealthCheck healthCheck = entry.getValue(); - if (filter.matches(name, healthCheck)) { -- futures.put(name, executor.submit(() -> healthCheck.execute())); -+ futures.put(name, executor.submit(healthCheck::execute)); - } - } - -@@ -222,7 +223,7 @@ public class HealthCheckRegistry { - } - } - -- return Collections.unmodifiableSortedMap(results); -+ return unmodifiableSortedMap(results); - } - - private void onHealthCheckAdded(String name, HealthCheck healthCheck) { ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/AsyncHealthCheckDecoratorTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/AsyncHealthCheckDecoratorTest.java -@@ -5,7 +5,6 @@ import static org.mockito.ArgumentCaptor.forClass; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -31,11 +30,11 @@ public class AsyncHealthCheckDecoratorTest { - .withMessage("Result was healthy but it expired 1 milliseconds ago") - .build(); - -- private final HealthCheck mockHealthCheck = mock(HealthCheck.class); -- private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); -+ private final HealthCheck mockHealthCheck = mock(); -+ private final ScheduledExecutorService mockExecutorService = mock(); - - @SuppressWarnings("rawtypes") -- private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); -+ private final ScheduledFuture mockFuture = mock(); - - @Test(expected = IllegalArgumentException.class) - public void nullHealthCheckTriggersInstantiationFailure() { -@@ -74,7 +73,7 @@ public class AsyncHealthCheckDecoratorTest { - AsyncHealthCheckDecorator asyncDecorator = - new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); - -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); - assertThat(asyncDecorator.check().isHealthy()).isTrue(); -@@ -87,7 +86,7 @@ public class AsyncHealthCheckDecoratorTest { - AsyncHealthCheckDecorator asyncDecorator = - new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); - -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); - } -@@ -102,8 +101,8 @@ public class AsyncHealthCheckDecoratorTest { - assertThat(asyncDecorator.check().isHealthy()).isFalse(); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void tearDownTriggersCancellation() throws Exception { - when(mockExecutorService.scheduleAtFixedRate( - any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) -@@ -114,13 +113,13 @@ public class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); - asyncDecorator.tearDown(); - -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -- verify(mockFuture, times(1)).cancel(eq(true)); -+ verify(mockFuture).cancel(true); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { - HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); - when(mockExecutorService.scheduleAtFixedRate( -@@ -133,7 +132,7 @@ public class AsyncHealthCheckDecoratorTest { - HealthCheck.Result initialResult = asyncDecorator.check(); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); - capturedRunnable.run(); -@@ -143,8 +142,8 @@ public class AsyncHealthCheckDecoratorTest { - assertThat(actualResult).isNotEqualTo(initialResult); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { - Exception exception = new Exception("TestException"); - when(mockExecutorService.scheduleAtFixedRate( -@@ -156,7 +155,7 @@ public class AsyncHealthCheckDecoratorTest { - new ConfigurableAsyncHealthCheck(exception), mockExecutorService); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); - capturedRunnable.run(); -@@ -173,7 +172,7 @@ public class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate( - runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); -@@ -192,7 +191,7 @@ public class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate( - runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); -@@ -210,7 +209,7 @@ public class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); - capturedRunnable.run(); ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckRegistryTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckRegistryTest.java -@@ -23,21 +23,21 @@ import org.junit.Test; - import org.mockito.ArgumentCaptor; - - public class HealthCheckRegistryTest { -- private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); -+ private final ScheduledExecutorService executorService = mock(); - private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); -- private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -+ private final HealthCheckRegistryListener listener = mock(); - -- private final HealthCheck hc1 = mock(HealthCheck.class); -- private final HealthCheck hc2 = mock(HealthCheck.class); -+ private final HealthCheck hc1 = mock(); -+ private final HealthCheck hc2 = mock(); - -- private final HealthCheck.Result r1 = mock(HealthCheck.Result.class); -- private final HealthCheck.Result r2 = mock(HealthCheck.Result.class); -+ private final HealthCheck.Result r1 = mock(); -+ private final HealthCheck.Result r2 = mock(); - -- private final HealthCheck.Result ar = mock(HealthCheck.Result.class); -+ private final HealthCheck.Result ar = mock(); - private final HealthCheck ahc = new TestAsyncHealthCheck(ar); - - @SuppressWarnings("rawtypes") -- private final ScheduledFuture af = mock(ScheduledFuture.class); -+ private final ScheduledFuture af = mock(); - - @Before - @SuppressWarnings("unchecked") -@@ -96,7 +96,7 @@ public class HealthCheckRegistryTest { - - @Test - public void addingListenerCatchesExistingHealthChecks() { -- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -+ HealthCheckRegistryListener listener = mock(); - HealthCheckRegistry registry = new HealthCheckRegistry(); - registry.register("hc1", hc1); - registry.register("hc2", hc2); -@@ -110,7 +110,7 @@ public class HealthCheckRegistryTest { - - @Test - public void removedListenerDoesNotReceiveUpdates() { -- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -+ HealthCheckRegistryListener listener = mock(); - HealthCheckRegistry registry = new HealthCheckRegistry(); - registry.addListener(listener); - registry.register("hc1", hc1); ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java -@@ -29,7 +29,7 @@ public class HealthCheckTest { - } - } - -- private final HealthCheck underlying = mock(HealthCheck.class); -+ private final HealthCheck underlying = mock(); - private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); - - @Test -@@ -89,7 +89,7 @@ public class HealthCheckTest { - - @Test - public void canHaveUnhealthyResultsWithExceptions() { -- final RuntimeException e = mock(RuntimeException.class); -+ final RuntimeException e = mock(); - when(e.getMessage()).thenReturn("oh noes"); - - final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); -@@ -144,7 +144,7 @@ public class HealthCheckTest { - - @Test - public void canHaveUnHealthyBuilderWithDetailAndError() { -- final RuntimeException e = mock(RuntimeException.class); -+ final RuntimeException e = mock(); - when(e.getMessage()).thenReturn("oh noes"); - - final HealthCheck.Result result = -@@ -161,7 +161,7 @@ public class HealthCheckTest { - - @Test - public void returnsResultsWhenExecuted() { -- final HealthCheck.Result result = mock(HealthCheck.Result.class); -+ final HealthCheck.Result result = mock(); - when(underlying.execute()).thenReturn(result); - - assertThat(healthCheck.execute()).isEqualTo(result); -@@ -171,7 +171,7 @@ public class HealthCheckTest { - - @Test - public void wrapsExceptionsWhenExecuted() { -- final RuntimeException e = mock(RuntimeException.class); -+ final RuntimeException e = mock(); - when(e.getMessage()).thenReturn("oh noes"); - - when(underlying.execute()).thenThrow(e); -@@ -181,7 +181,7 @@ public class HealthCheckTest { - assertThat(actual.getMessage()).isEqualTo("oh noes"); - assertThat(actual.getError()).isEqualTo(e); - assertThat(actual.getDetails()).isNull(); -- assertThat(actual.getDuration()).isGreaterThanOrEqualTo(0); -+ assertThat(actual.getDuration()).isNotNegative(); - } - - @Test ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java -@@ -30,7 +30,7 @@ public class SharedHealthCheckRegistriesTest { - public void returnsSetOfCreatedRegistries() { - SharedHealthCheckRegistries.getOrCreate("db"); - -- assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); -+ assertThat(SharedHealthCheckRegistries.names()).containsExactly("db"); - } - - @Test ---- a/metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java -+++ b/metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java -@@ -1,12 +1,12 @@ - package com.codahale.metrics.health.jvm; - -+import static java.util.Collections.emptySet; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; - - import com.codahale.metrics.health.HealthCheck; - import com.codahale.metrics.jvm.ThreadDeadlockDetector; --import java.util.Collections; - import java.util.Set; - import java.util.TreeSet; - import org.junit.Test; -@@ -14,10 +14,10 @@ import org.junit.Test; - public class ThreadDeadlockHealthCheckTest { - @Test - public void isHealthyIfNoThreadsAreDeadlocked() { -- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -+ final ThreadDeadlockDetector detector = mock(); - final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); - -- when(detector.getDeadlockedThreads()).thenReturn(Collections.emptySet()); -+ when(detector.getDeadlockedThreads()).thenReturn(emptySet()); - - assertThat(healthCheck.execute().isHealthy()).isTrue(); - } -@@ -28,7 +28,7 @@ public class ThreadDeadlockHealthCheckTest { - threads.add("one"); - threads.add("two"); - -- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -+ final ThreadDeadlockDetector detector = mock(); - final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); - - when(detector.getDeadlockedThreads()).thenReturn(threads); ---- a/metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/InstrumentedHttpClientsTimerTest.java -+++ b/metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/InstrumentedHttpClientsTimerTest.java -@@ -45,7 +45,7 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - chac.start(); - asyncHttpClient = chac; - -- Timer timer = mock(Timer.class); -+ Timer timer = mock(); - when(timer.time()).thenReturn(context); - when(metricRegistry.timer(any())).thenReturn(timer); - } -@@ -71,13 +71,13 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - verify(context, timeout(200).times(1)).stop(); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { - HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); - HttpGet get = new HttpGet("/?q=something"); - -- FutureCallback futureCallback = mock(FutureCallback.class); -+ FutureCallback futureCallback = mock(); - - // Timer hasn't been stopped prior to executing the request - verify(context, never()).stop(); -@@ -98,14 +98,14 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - verify(context, timeout(200).times(1)).stop(); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - public void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { - // There should be nothing listening on this port - HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); - HttpGet get = new HttpGet("/?q=something"); - -- FutureCallback futureCallback = mock(FutureCallback.class); -+ FutureCallback futureCallback = mock(); - - // Timer hasn't been stopped prior to executing the request - verify(context, never()).stop(); ---- a/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientConnectionManagerTest.java -+++ b/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientConnectionManagerTest.java -@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import com.codahale.metrics.MetricRegistry; - import org.junit.Assert; - import org.junit.Test; - import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; - - public class InstrumentedHttpClientConnectionManagerTest { - private final MetricRegistry metricRegistry = new MetricRegistry(); -@@ -36,7 +38,7 @@ public class InstrumentedHttpClientConnectionManagerTest { - - @Test - public void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -+ final MetricRegistry registry = mock(); - - InstrumentedHttpClientConnectionManager.builder(registry) - .name("some-name") -@@ -45,7 +47,7 @@ public class InstrumentedHttpClientConnectionManagerTest { - .close(); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); - assertTrue(argumentCaptor.getValue().contains("some-other-name")); - } - } ---- a/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/InstrumentedHttpClientsTest.java -@@ -22,9 +22,8 @@ import org.junit.Before; - import org.junit.Test; - - public class InstrumentedHttpClientsTest { -- private final HttpClientMetricNameStrategy metricNameStrategy = -- mock(HttpClientMetricNameStrategy.class); -- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); -+ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); -+ private final MetricRegistryListener registryListener = mock(); - private final MetricRegistry metricRegistry = new MetricRegistry(); - private final HttpClient client = - InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) ---- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java -+++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java -@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import com.codahale.metrics.MetricRegistry; - import org.junit.Assert; - import org.junit.Test; - import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; - - public class InstrumentedAsyncClientConnectionManagerTest { - private final MetricRegistry metricRegistry = new MetricRegistry(); -@@ -43,7 +45,7 @@ public class InstrumentedAsyncClientConnectionManagerTest { - - @Test - public void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -+ final MetricRegistry registry = mock(); - - InstrumentedAsyncClientConnectionManager.builder(registry) - .name("some-name") -@@ -52,7 +54,7 @@ public class InstrumentedAsyncClientConnectionManagerTest { - .close(); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); - assertTrue(argumentCaptor.getValue().contains("some-other-name")); - } - } ---- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java -+++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java -@@ -1,5 +1,6 @@ - package com.codahale.metrics.httpclient5; - -+import static java.nio.charset.StandardCharsets.US_ASCII; - import static org.assertj.core.api.Assertions.assertThat; - import static org.awaitility.Awaitility.await; - import static org.junit.Assert.fail; -@@ -17,7 +18,6 @@ import com.sun.net.httpserver.HttpExchange; - import com.sun.net.httpserver.HttpServer; - import java.io.IOException; - import java.net.InetSocketAddress; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.ExecutionException; - import java.util.concurrent.Future; -@@ -82,7 +82,7 @@ public class InstrumentedHttpAsyncClientsTest { - exchange -> { - exchange.sendResponseHeaders(200, 0L); - exchange.setStreams(null, null); -- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); -+ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); - exchange.close(); - }); - httpServer.start(); -@@ -187,7 +187,7 @@ public class InstrumentedHttpAsyncClientsTest { - exchange -> { - exchange.sendResponseHeaders(200, 0L); - exchange.setStreams(null, null); -- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); -+ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); - exchange.close(); - }); - httpServer.start(); ---- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientConnectionManagerTest.java -+++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientConnectionManagerTest.java -@@ -4,12 +4,14 @@ import static junit.framework.TestCase.assertTrue; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import com.codahale.metrics.MetricRegistry; - import org.junit.Assert; - import org.junit.Test; - import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; - - public class InstrumentedHttpClientConnectionManagerTest { - private final MetricRegistry metricRegistry = new MetricRegistry(); -@@ -41,7 +43,7 @@ public class InstrumentedHttpClientConnectionManagerTest { - - @Test - public void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -+ final MetricRegistry registry = mock(); - - InstrumentedHttpClientConnectionManager.builder(registry) - .name("some-name") -@@ -50,7 +52,7 @@ public class InstrumentedHttpClientConnectionManagerTest { - .close(); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); - assertTrue(argumentCaptor.getValue().contains("some-other-name")); - } - } ---- a/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java -@@ -22,9 +22,8 @@ import org.junit.Before; - import org.junit.Test; - - public class InstrumentedHttpClientsTest { -- private final HttpClientMetricNameStrategy metricNameStrategy = -- mock(HttpClientMetricNameStrategy.class); -- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); -+ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); -+ private final MetricRegistryListener registryListener = mock(); - private final MetricRegistry metricRegistry = new MetricRegistry(); - private final HttpClient client = - InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) ---- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListenerTest.java -+++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListenerTest.java -@@ -10,7 +10,7 @@ import jakarta.servlet.ServletContextEvent; - import org.junit.Test; - - public class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final MetricRegistry registry = mock(); - private final InstrumentedFilterContextListener listener = - new InstrumentedFilterContextListener() { - @Override -@@ -21,9 +21,9 @@ public class InstrumentedFilterContextListenerTest { - - @Test - public void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ final ServletContext context = mock(); - -- final ServletContextEvent event = mock(ServletContextEvent.class); -+ final ServletContextEvent event = mock(); - when(event.getServletContext()).thenReturn(context); - - listener.contextInitialized(event); ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java -@@ -83,7 +83,7 @@ public class HealthCheckServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); - if (registryAttr instanceof HealthCheckRegistry) { - this.registry = (HealthCheckRegistry) registryAttr; ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java -@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(METRICS_REGISTRY); - if (registryAttr instanceof MetricRegistry) { - this.registry = (MetricRegistry) registryAttr; ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java -@@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -102,9 +101,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getStatus()).isEqualTo(200); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -143,9 +141,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getStatus()).isEqualTo(200); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -217,15 +214,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getContent()) - .isEqualTo( - String.format( -- "{%n" -- + " \"fun\" : {%n" -- + " \"healthy\" : true,%n" -- + " \"message\" : \"foo bar 123\",%n" -- + " \"duration\" : 0,%n" -- + " \"timestamp\" : \"" -- + EXPECTED_TIMESTAMP -- + "\"" -- + "%n }%n}")); -+ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", -+ EXPECTED_TIMESTAMP)); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -240,25 +230,25 @@ public class HealthCheckServletTest extends AbstractServletTest { - @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() - throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final io.dropwizard.metrics.servlets.HealthCheckServlet healthCheckServlet = - new io.dropwizard.metrics.servlets.HealthCheckServlet(healthCheckRegistry); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -+ verify(servletConfig).getServletContext(); - verify(servletContext, never()) - .getAttribute(eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY)); - } - - @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute( - eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY))) -@@ -268,16 +258,16 @@ public class HealthCheckServletTest extends AbstractServletTest { - new io.dropwizard.metrics.servlets.HealthCheckServlet(null); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)) -+ verify(servletConfig).getServletContext(); -+ verify(servletContext) - .getAttribute(eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY)); - } - - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute( - eq(io.dropwizard.metrics.servlets.HealthCheckServlet.HEALTH_CHECK_REGISTRY))) ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletContextListenerTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletContextListenerTest.java -@@ -17,7 +17,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MetricsServletContextListenerTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private final String allowedOrigin = "some.other.origin"; - ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java -@@ -1,10 +1,8 @@ - package io.dropwizard.metrics.servlets; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -24,7 +22,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MetricsServletTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private ServletTester tester; - -@@ -128,22 +126,8 @@ public class MetricsServletTest extends AbstractServletTest { - assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); - assertThat(response.getContent()) - .isEqualTo( -- callbackParamVal -- + "({" -- + "\"version\":\"4.0.0\"," -- + "\"gauges\":{" -- + "\"g1\":{\"value\":100}" -- + "}," -- + "\"counters\":{" -- + "\"c\":{\"count\":1}" -- + "}," -- + "\"histograms\":{" -- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -- + "}," -- + "\"meters\":{" -- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -- + "}" -- + "})"); -+ "%s({\"version\":\"4.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", -+ callbackParamVal); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -223,47 +207,47 @@ public class MetricsServletTest extends AbstractServletTest { - @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() - throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = - new io.dropwizard.metrics.servlets.MetricsServlet(metricRegistry); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -+ verify(servletConfig).getServletContext(); - verify(servletContext, never()) -- .getAttribute(eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)); -+ .getAttribute(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY); - } - - @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute( -- eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY))) -+ io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)) - .thenReturn(metricRegistry); - - final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = - new io.dropwizard.metrics.servlets.MetricsServlet(null); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)) -- .getAttribute(eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext) -+ .getAttribute(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY); - } - - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute( -- eq(io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY))) -+ io.dropwizard.metrics.servlets.MetricsServlet.METRICS_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); - - final io.dropwizard.metrics.servlets.MetricsServlet metricsServlet = new MetricsServlet(null); ---- a/metrics-jcache/src/main/java/com/codahale/metrics/jcache/JCacheGaugeSet.java -+++ b/metrics-jcache/src/main/java/com/codahale/metrics/jcache/JCacheGaugeSet.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics.jcache; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Metric; - import com.codahale.metrics.MetricSet; -@@ -8,7 +9,6 @@ import com.codahale.metrics.jvm.JmxAttributeGauge; - import java.lang.management.ManagementFactory; - import java.lang.reflect.Method; - import java.util.ArrayList; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Locale; -@@ -51,7 +51,7 @@ public class JCacheGaugeSet implements MetricSet { - } - } - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - - private Set getCacheBeans() { ---- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java -+++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java -@@ -71,18 +71,18 @@ public class JCacheGaugeSetTest { - assertThat( - (Float) - registry.getGauges().get("jcache.statistics.myCache.average-get-time").getValue()) -- .isGreaterThan(0.0f); -+ .isPositive(); - assertThat( - (Float) - registry.getGauges().get("jcache.statistics.myCache.average-put-time").getValue()) -- .isGreaterThan(0.0f); -+ .isPositive(); - assertThat( - (Float) - registry - .getGauges() - .get("jcache.statistics.myCache.average-remove-time") - .getValue()) -- .isGreaterThan(0.0f); -+ .isPositive(); - } - - @After ---- a/metrics-jdbi/src/main/java/com/codahale/metrics/jdbi/strategies/NameStrategies.java -+++ b/metrics-jdbi/src/main/java/com/codahale/metrics/jdbi/strategies/NameStrategies.java -@@ -45,7 +45,7 @@ public final class NameStrategies { - public String getStatementName(StatementContext statementContext) { - final String rawSql = statementContext.getRawSql(); - -- if (rawSql == null || rawSql.length() == 0) { -+ if (rawSql == null || rawSql.isEmpty()) { - return EMPTY_SQL; - } - return null; ---- a/metrics-jdbi/src/test/java/com/codahale/metrics/jdbi/InstrumentedTimingCollectorTest.java -+++ b/metrics-jdbi/src/test/java/com/codahale/metrics/jdbi/InstrumentedTimingCollectorTest.java -@@ -23,7 +23,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass()).when(ctx).getSqlObjectType(); - doReturn(getClass().getMethod("updatesTimerForSqlObjects")).when(ctx).getSqlObjectMethod(); -@@ -42,7 +42,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass()).when(ctx).getSqlObjectType(); - -@@ -60,7 +60,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - - collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); -@@ -77,7 +77,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - - collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); - -@@ -93,7 +93,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("don't know what it is but it's not SQL").when(ctx).getRawSql(); - - collector.collect(TimeUnit.SECONDS.toNanos(3), ctx); -@@ -110,7 +110,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass().getName()).when(ctx).getAttribute(NameStrategies.STATEMENT_CLASS); - doReturn("updatesTimerForContextClass").when(ctx).getAttribute(NameStrategies.STATEMENT_NAME); -@@ -129,7 +129,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn("foo/bar.stg").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); - doReturn("updatesTimerForTemplateFile").when(ctx).getAttribute(NameStrategies.STATEMENT_NAME); -@@ -148,7 +148,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn("my-group").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); - doReturn("updatesTimerForContextGroupAndName") -@@ -169,7 +169,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new SmartNameStrategy(); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn("my-group").when(ctx).getAttribute(NameStrategies.STATEMENT_GROUP); - doReturn("my-type").when(ctx).getAttribute(NameStrategies.STATEMENT_TYPE); -@@ -192,7 +192,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new ShortNameStrategy("jdbi"); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass()).when(ctx).getSqlObjectType(); - doReturn(getClass().getMethod("updatesTimerForShortSqlObjectStrategy")) -@@ -215,7 +215,7 @@ public class InstrumentedTimingCollectorTest { - final StatementNameStrategy strategy = new ShortNameStrategy("jdbi"); - final InstrumentedTimingCollector collector = - new InstrumentedTimingCollector(registry, strategy); -- final StatementContext ctx = mock(StatementContext.class); -+ final StatementContext ctx = mock(); - doReturn("SELECT 1").when(ctx).getRawSql(); - doReturn(getClass().getName()).when(ctx).getAttribute(NameStrategies.STATEMENT_CLASS); - doReturn("updatesTimerForShortContextClassStrategy") ---- a/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/InstrumentedSqlLoggerTest.java -+++ b/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/InstrumentedSqlLoggerTest.java -@@ -16,12 +16,12 @@ import org.junit.Test; - public class InstrumentedSqlLoggerTest { - @Test - public void logsExecutionTime() { -- final MetricRegistry mockRegistry = mock(MetricRegistry.class); -- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); -+ final MetricRegistry mockRegistry = mock(); -+ final StatementNameStrategy mockNameStrategy = mock(); - final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); - -- final StatementContext mockContext = mock(StatementContext.class); -- final Timer mockTimer = mock(Timer.class); -+ final StatementContext mockContext = mock(); -+ final Timer mockTimer = mock(); - - final String statementName = "my-fake-name"; - final long fakeElapsed = 1234L; -@@ -38,12 +38,12 @@ public class InstrumentedSqlLoggerTest { - - @Test - public void logsExceptionTime() { -- final MetricRegistry mockRegistry = mock(MetricRegistry.class); -- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); -+ final MetricRegistry mockRegistry = mock(); -+ final StatementNameStrategy mockNameStrategy = mock(); - final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); - -- final StatementContext mockContext = mock(StatementContext.class); -- final Timer mockTimer = mock(Timer.class); -+ final StatementContext mockContext = mock(); -+ final Timer mockTimer = mock(); - - final String statementName = "my-fake-name"; - final long fakeElapsed = 1234L; ---- a/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/AbstractStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/AbstractStrategyTest.java -@@ -10,7 +10,7 @@ import org.junit.Before; - public class AbstractStrategyTest { - - MetricRegistry registry = new MetricRegistry(); -- StatementContext ctx = mock(StatementContext.class); -+ StatementContext ctx = mock(); - - @Before - public void setUp() throws Exception { ---- a/metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.ExponentiallyDecayingReservoir; -@@ -19,7 +22,6 @@ import com.codahale.metrics.annotation.Timed; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener - this.level = responseMetered.level(); - this.meters = - COARSE_METER_LEVELS.contains(level) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(metricName, "1xx-responses")), // 1xx - registry.meter(name(metricName, "2xx-responses")), // 2xx -@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener - registry.meter(name(metricName, "4xx-responses")), // 4xx - registry.meter(name(metricName, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - this.responseCodeMeters = -- DETAILED_METER_LEVELS.contains(level) -- ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); - this.metricRegistry = registry; - } - -@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener - : null; - - if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) -+ if (metric.cause.isInstance(event.getException()) - || (event.getException().getCause() != null -- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -+ && metric.cause.isInstance(event.getException().getCause()))) { - metric.meter.mark(); - } - } -@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener - - @Override - public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = -- new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); - } - - private T getClassLevelAnnotation( -@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener - @Override - public int hashCode() { - int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -+ return 31 * result + method.hashCode(); - } - } - } ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonFilterMetricsJerseyTest.java -@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry, testClock, true)); - config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -+ return config.register(new InstrumentedFilteredResource(testClock)); - } - - @Before ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); - } - - @Test -@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - assertThat(target("subresource/exception-metered").request().get(String.class)) - .isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("subresource/exception-metered") ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsJerseyTest.java -@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -+ return config.register(InstrumentedResource.class); - } - - @Test -@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -87,12 +85,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(0); - } - - @Test -@@ -107,9 +105,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - registry.meter( - name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); - assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); - assertThat( - target("response-metered-detailed") -@@ -119,9 +117,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - .getStatus()) - .isEqualTo(201); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); - } - - @Test -@@ -131,12 +129,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - - @Test ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceMeteredPerClass.class); - } - - @Test ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - - config = config.register(new MetricsFeature(this.registry)); - config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -+ return config.register(new TestExceptionMapper()); - } - - @Test -@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - } ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/SingletonMetricsTimedPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceTimedPerClass.class); - } - - @Test ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedFilteredResource.java -@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { - } - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick++; - return "yay"; - } - - @GET -- @Timed(name = "fancyName") - @Path("/named") -+ @Timed(name = "fancyName") - public String named() { - testClock.tick++; - return "fancy"; - } - - @GET -- @Timed(name = "absolutelyFancy", absolute = true) - @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) - public String absolute() { - testClock.tick++; - return "absolute"; -@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { - public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick += 2; - return "yay"; ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedResource.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedResource.java -@@ -21,8 +21,8 @@ import javax.ws.rs.core.Response; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -@@ -34,8 +34,8 @@ public class InstrumentedResource { - return "woo"; - } - -- @GET - @ExceptionMetered(cause = IOException.class) -+ @GET - @Path("/exception-metered") - public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) - throws IOException { -@@ -46,24 +46,24 @@ public class InstrumentedResource { - } - - @GET -- @ResponseMetered(level = DETAILED) - @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) - public Response responseMeteredDetailed( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = COARSE) - @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) - public Response responseMeteredCoarse( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = ALL) - @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) - public Response responseMeteredAll( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ---- a/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedSubResource.java -+++ b/metrics-jersey2/src/test/java/com/codahale/metrics/jersey2/resources/InstrumentedSubResource.java -@@ -10,8 +10,8 @@ import javax.ws.rs.core.MediaType; - public class InstrumentedSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } ---- a/metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.ExponentiallyDecayingReservoir; -@@ -21,7 +24,6 @@ import jakarta.ws.rs.ext.Provider; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener - this.level = responseMetered.level(); - this.meters = - COARSE_METER_LEVELS.contains(level) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(metricName, "1xx-responses")), // 1xx - registry.meter(name(metricName, "2xx-responses")), // 2xx -@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener - registry.meter(name(metricName, "4xx-responses")), // 4xx - registry.meter(name(metricName, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - this.responseCodeMeters = -- DETAILED_METER_LEVELS.contains(level) -- ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); - this.metricRegistry = registry; - } - -@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener - : null; - - if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) -+ if (metric.cause.isInstance(event.getException()) - || (event.getException().getCause() != null -- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -+ && metric.cause.isInstance(event.getException().getCause()))) { - metric.meter.mark(); - } - } -@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener - - @Override - public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = -- new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); - } - - private T getClassLevelAnnotation( -@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener - @Override - public int hashCode() { - int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -+ return 31 * result + method.hashCode(); - } - } - } ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonFilterMetricsJerseyTest.java -@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry, testClock, true)); - config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -+ return config.register(new InstrumentedFilteredResource(testClock)); - } - - @Before ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); - } - - @Test -@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - assertThat(target("subresource/exception-metered").request().get(String.class)) - .isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("subresource/exception-metered") ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsJerseyTest.java -@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -+ return config.register(InstrumentedResource.class); - } - - @Test -@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -92,9 +90,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - registry.meter( - name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); - assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); - assertThat( - target("response-metered-detailed") -@@ -104,9 +102,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - .getStatus()) - .isEqualTo(201); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); - } - - @Test -@@ -116,12 +114,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - - @Test ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceMeteredPerClass.class); - } - - @Test ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - - config = config.register(new MetricsFeature(this.registry)); - config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -+ return config.register(new TestExceptionMapper()); - } - - @Test -@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - } ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/SingletonMetricsTimedPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceTimedPerClass.class); - } - - @Test ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedFilteredResource.java -@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { - } - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick++; - return "yay"; - } - - @GET -- @Timed(name = "fancyName") - @Path("/named") -+ @Timed(name = "fancyName") - public String named() { - testClock.tick++; - return "fancy"; - } - - @GET -- @Timed(name = "absolutelyFancy", absolute = true) - @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) - public String absolute() { - testClock.tick++; - return "absolute"; -@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { - public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick += 2; - return "yay"; ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedResource.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedResource.java -@@ -21,8 +21,8 @@ import java.io.IOException; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -@@ -34,8 +34,8 @@ public class InstrumentedResource { - return "woo"; - } - -- @GET - @ExceptionMetered(cause = IOException.class) -+ @GET - @Path("/exception-metered") - public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) - throws IOException { -@@ -46,24 +46,24 @@ public class InstrumentedResource { - } - - @GET -- @ResponseMetered(level = DETAILED) - @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) - public Response responseMeteredDetailed( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = COARSE) - @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) - public Response responseMeteredCoarse( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = ALL) - @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) - public Response responseMeteredAll( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ---- a/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedSubResource.java -+++ b/metrics-jersey3/src/test/java/com/codahale/metrics/jersey3/resources/InstrumentedSubResource.java -@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; - public class InstrumentedSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } ---- a/metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Clock; - import com.codahale.metrics.ExponentiallyDecayingReservoir; -@@ -21,7 +24,6 @@ import jakarta.ws.rs.ext.Provider; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -159,7 +161,7 @@ public class InstrumentedResourceMethodApplicationListener - this.level = responseMetered.level(); - this.meters = - COARSE_METER_LEVELS.contains(level) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(metricName, "1xx-responses")), // 1xx - registry.meter(name(metricName, "2xx-responses")), // 2xx -@@ -167,11 +169,9 @@ public class InstrumentedResourceMethodApplicationListener - registry.meter(name(metricName, "4xx-responses")), // 4xx - registry.meter(name(metricName, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - this.responseCodeMeters = -- DETAILED_METER_LEVELS.contains(level) -- ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : emptyMap(); - this.metricRegistry = registry; - } - -@@ -305,9 +305,9 @@ public class InstrumentedResourceMethodApplicationListener - : null; - - if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) -+ if (metric.cause.isInstance(event.getException()) - || (event.getException().getCause() != null -- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -+ && metric.cause.isInstance(event.getException().getCause()))) { - metric.meter.mark(); - } - } -@@ -418,14 +418,11 @@ public class InstrumentedResourceMethodApplicationListener - - @Override - public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = -- new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); - } - - private T getClassLevelAnnotation( -@@ -598,8 +595,7 @@ public class InstrumentedResourceMethodApplicationListener - @Override - public int hashCode() { - int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -+ return 31 * result + method.hashCode(); - } - } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonFilterMetricsJerseyTest.java -@@ -35,8 +35,7 @@ public class SingletonFilterMetricsJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry, testClock, true)); - config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -+ return config.register(new InstrumentedFilteredResource(testClock)); - } - - @Before ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); - } - - @Test -@@ -51,7 +49,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -76,7 +74,7 @@ public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTe - assertThat(target("subresource/exception-metered").request().get(String.class)) - .isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("subresource/exception-metered") ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsJerseyTest.java -@@ -38,9 +38,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -+ return config.register(InstrumentedResource.class); - } - - @Test -@@ -67,7 +65,7 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -87,12 +85,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(0); - } - - @Test -@@ -107,9 +105,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - registry.meter( - name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); - assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); - assertThat( - target("response-metered-detailed") -@@ -119,9 +117,9 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - .getStatus()) - .isEqualTo(201); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); - } - - @Test -@@ -131,12 +129,12 @@ public class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - - @Test ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceMeteredPerClass.class); - } - - @Test ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -35,9 +35,7 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - - config = config.register(new MetricsFeature(this.registry)); - config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -+ return config.register(new TestExceptionMapper()); - } - - @Test -@@ -140,12 +138,12 @@ public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTes - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/SingletonMetricsTimedPerClassJerseyTest.java -@@ -32,9 +32,7 @@ public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceTimedPerClass.class); - } - - @Test ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedFilteredResource.java -@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { - } - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick++; - return "yay"; - } - - @GET -- @Timed(name = "fancyName") - @Path("/named") -+ @Timed(name = "fancyName") - public String named() { - testClock.tick++; - return "fancy"; - } - - @GET -- @Timed(name = "absolutelyFancy", absolute = true) - @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) - public String absolute() { - testClock.tick++; - return "absolute"; -@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { - public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick += 2; - return "yay"; ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedResource.java -@@ -21,8 +21,8 @@ import java.io.IOException; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -@@ -34,8 +34,8 @@ public class InstrumentedResource { - return "woo"; - } - -- @GET - @ExceptionMetered(cause = IOException.class) -+ @GET - @Path("/exception-metered") - public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) - throws IOException { -@@ -46,24 +46,24 @@ public class InstrumentedResource { - } - - @GET -- @ResponseMetered(level = DETAILED) - @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) - public Response responseMeteredDetailed( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = COARSE) - @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) - public Response responseMeteredCoarse( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = ALL) - @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) - public Response responseMeteredAll( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedSubResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics/jersey31/resources/InstrumentedSubResource.java -@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; - public class InstrumentedSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -13,7 +16,6 @@ import com.codahale.metrics.Timer; - import com.codahale.metrics.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -172,10 +174,10 @@ public class InstrumentedHandler extends HandlerWrapper { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx - metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx -@@ -183,7 +185,7 @@ public class InstrumentedHandler extends HandlerWrapper { - metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx - metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); - this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -14,7 +17,6 @@ import com.codahale.metrics.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(prefix, "1xx-responses")), // 1xx - registry.meter(name(prefix, "2xx-responses")), // 2xx -@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { - registry.meter(name(prefix, "4xx-responses")), // 4xx - registry.meter(name(prefix, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); - this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java -@@ -1,12 +1,12 @@ - package io.dropwizard.metrics.jetty10; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatCode; - - import com.codahale.metrics.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.TimeUnit; - import javax.servlet.AsyncContext; - import javax.servlet.ServletException; -@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { - assertThatCode(handler::doStop).doesNotThrowAnyException(); - } - -- @Test - @Ignore("flaky on virtual machines") -+ @Test - public void responseTimesAreRecordedForAsyncResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/async")); -@@ -126,15 +126,14 @@ public class InstrumentedHandlerTest { - } - - private void assertResponseTimesValid() { -- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) -- .isGreaterThan(0L); -+ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); - - assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - - assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - } - -@@ -197,7 +196,7 @@ public class InstrumentedHandlerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async\n".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListenerTest.java -@@ -1,11 +1,11 @@ - package io.dropwizard.metrics.jetty10; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - - import com.codahale.metrics.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import javax.servlet.AsyncContext; - import javax.servlet.ServletOutputStream; - import javax.servlet.WriteListener; -@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -172,10 +174,10 @@ public class InstrumentedHandler extends HandlerWrapper { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx - metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx -@@ -183,7 +185,7 @@ public class InstrumentedHandler extends HandlerWrapper { - metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx - metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); - this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(prefix, "1xx-responses")), // 1xx - registry.meter(name(prefix, "2xx-responses")), // 2xx -@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { - registry.meter(name(prefix, "4xx-responses")), // 4xx - registry.meter(name(prefix, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); - this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics.jetty11; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatCode; - -@@ -12,7 +13,6 @@ import jakarta.servlet.WriteListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; -@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { - assertThatCode(handler::doStop).doesNotThrowAnyException(); - } - -- @Test - @Ignore("flaky on virtual machines") -+ @Test - public void responseTimesAreRecordedForAsyncResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/async")); -@@ -126,17 +126,15 @@ public class InstrumentedHandlerTest { - } - - private void assertResponseTimesValid() { -- assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()) -- .isGreaterThan(0L); -- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) -- .isGreaterThan(0L); -+ assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()).isPositive(); -+ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); - - assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - - assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - } - -@@ -199,7 +197,7 @@ public class InstrumentedHandlerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async\n".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListenerTest.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics.jetty11; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - - import com.codahale.metrics.MetricRegistry; -@@ -10,7 +11,6 @@ import jakarta.servlet.WriteListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; - import org.eclipse.jetty.server.Request; -@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java -+++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -13,7 +16,6 @@ import com.codahale.metrics.Timer; - import com.codahale.metrics.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -180,10 +182,10 @@ public class InstrumentedHandler extends HandlerWrapper { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - metricRegistry.meter(name(prefix, NAME_1XX_RESPONSES)), // 1xx - metricRegistry.meter(name(prefix, NAME_2XX_RESPONSES)), // 2xx -@@ -191,7 +193,7 @@ public class InstrumentedHandler extends HandlerWrapper { - metricRegistry.meter(name(prefix, NAME_4XX_RESPONSES)), // 4xx - metricRegistry.meter(name(prefix, NAME_5XX_RESPONSES)) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, NAME_GET_REQUESTS)); - this.postRequests = metricRegistry.timer(name(prefix, NAME_POST_REQUESTS)); ---- a/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java -@@ -4,6 +4,9 @@ import static com.codahale.metrics.MetricRegistry.name; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.COARSE; - import static com.codahale.metrics.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.emptyList; -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableList; - - import com.codahale.metrics.Counter; - import com.codahale.metrics.Meter; -@@ -14,7 +17,6 @@ import com.codahale.metrics.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : emptyMap(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(name(prefix, "1xx-responses")), // 1xx - registry.meter(name(prefix, "2xx-responses")), // 2xx -@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { - registry.meter(name(prefix, "4xx-responses")), // 4xx - registry.meter(name(prefix, "5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : emptyList(); - - this.getRequests = metricRegistry.timer(name(prefix, "get-requests")); - this.postRequests = metricRegistry.timer(name(prefix, "post-requests")); ---- a/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java -+++ b/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java -@@ -1,12 +1,12 @@ - package com.codahale.metrics.jetty9; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatCode; - - import com.codahale.metrics.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.TimeUnit; - import javax.servlet.AsyncContext; - import javax.servlet.ServletException; -@@ -114,8 +114,8 @@ public class InstrumentedHandlerTest { - assertThatCode(handler::doStop).doesNotThrowAnyException(); - } - -- @Test - @Ignore("flaky on virtual machines") -+ @Test - public void responseTimesAreRecordedForAsyncResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/async")); -@@ -126,17 +126,15 @@ public class InstrumentedHandlerTest { - } - - private void assertResponseTimesValid() { -- assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()) -- .isGreaterThan(0L); -- assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()) -- .isGreaterThan(0L); -+ assertThat(registry.getMeters().get(metricName() + ".2xx-responses").getCount()).isPositive(); -+ assertThat(registry.getMeters().get(metricName() + ".200-responses").getCount()).isPositive(); - - assertThat(registry.getTimers().get(metricName() + ".get-requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - - assertThat(registry.getTimers().get(metricName() + ".requests").getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - } - -@@ -199,7 +197,7 @@ public class InstrumentedHandlerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async\n".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListenerTest.java -@@ -1,11 +1,11 @@ - package com.codahale.metrics.jetty9; - - import static com.codahale.metrics.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - - import com.codahale.metrics.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import javax.servlet.AsyncContext; - import javax.servlet.ServletOutputStream; - import javax.servlet.WriteListener; -@@ -187,7 +187,7 @@ public class InstrumentedHttpChannelListenerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async".getBytes(UTF_8)); - context.complete(); - } - ---- a/metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java -+++ b/metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java -@@ -36,9 +36,8 @@ public class DefaultObjectNameFactory implements ObjectNameFactory { - || shouldQuote(objectName.getKeyProperty("type"))) { - properties.put("type", ObjectName.quote(type)); - } -- objectName = new ObjectName(domain, properties); -+ return new ObjectName(domain, properties); - -- return objectName; - } catch (MalformedObjectNameException e) { - try { - return new ObjectName(domain, "name", ObjectName.quote(name)); ---- a/metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java -+++ b/metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java -@@ -1,5 +1,8 @@ - package com.codahale.metrics.jmx; - -+import static java.util.Collections.emptyMap; -+import static java.util.Collections.unmodifiableMap; -+ - import com.codahale.metrics.Counter; - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Histogram; -@@ -12,7 +15,6 @@ import com.codahale.metrics.Reporter; - import com.codahale.metrics.Timer; - import java.io.Closeable; - import java.lang.management.ManagementFactory; --import java.util.Collections; - import java.util.Locale; - import java.util.Map; - import java.util.concurrent.ConcurrentHashMap; -@@ -60,8 +62,8 @@ public class JmxReporter implements Reporter, Closeable { - this.durationUnit = TimeUnit.MILLISECONDS; - this.domain = "metrics"; - this.objectNameFactory = new DefaultObjectNameFactory(); -- this.specificDurationUnits = Collections.emptyMap(); -- this.specificRateUnits = Collections.emptyMap(); -+ this.specificDurationUnits = emptyMap(); -+ this.specificRateUnits = emptyMap(); - } - - /** -@@ -128,7 +130,7 @@ public class JmxReporter implements Reporter, Closeable { - * @return {@code this} - */ - public Builder specificDurationUnits(Map specificDurationUnits) { -- this.specificDurationUnits = Collections.unmodifiableMap(specificDurationUnits); -+ this.specificDurationUnits = unmodifiableMap(specificDurationUnits); - return this; - } - -@@ -139,7 +141,7 @@ public class JmxReporter implements Reporter, Closeable { - * @return {@code this} - */ - public Builder specificRateUnits(Map specificRateUnits) { -- this.specificRateUnits = Collections.unmodifiableMap(specificRateUnits); -+ this.specificRateUnits = unmodifiableMap(specificRateUnits); - return this; - } - ---- a/metrics-jmx/src/test/java/com/codahale/metrics/jmx/JmxReporterTest.java -+++ b/metrics-jmx/src/test/java/com/codahale/metrics/jmx/JmxReporterTest.java -@@ -1,5 +1,6 @@ - package com.codahale.metrics.jmx; - -+import static java.util.UUID.randomUUID; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -@@ -20,7 +21,6 @@ import com.codahale.metrics.Timer; - import java.lang.management.ManagementFactory; - import java.util.SortedMap; - import java.util.TreeMap; --import java.util.UUID; - import java.util.concurrent.TimeUnit; - import javax.management.Attribute; - import javax.management.AttributeList; -@@ -36,7 +36,7 @@ import org.junit.Test; - @SuppressWarnings("rawtypes") - public class JmxReporterTest { - private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); -- private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); -+ private final String name = randomUUID().toString().replaceAll("[{\\-}]", ""); - private final MetricRegistry registry = new MetricRegistry(); - - private final JmxReporter reporter = -@@ -48,12 +48,12 @@ public class JmxReporterTest { - .filter(MetricFilter.ALL) - .build(); - -- private final Gauge gauge = mock(Gauge.class); -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -- private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); -+ private final Gauge gauge = mock(); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); -+ private final ObjectNameFactory mockObjectNameFactory = mock(); - private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); - - @Before -@@ -64,7 +64,7 @@ public class JmxReporterTest { - - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot hSnapshot = mock(Snapshot.class); -+ final Snapshot hSnapshot = mock(); - when(hSnapshot.getMax()).thenReturn(2L); - when(hSnapshot.getMean()).thenReturn(3.0); - when(hSnapshot.getMin()).thenReturn(4L); -@@ -91,7 +91,7 @@ public class JmxReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot tSnapshot = mock(Snapshot.class); -+ final Snapshot tSnapshot = mock(); - when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -274,7 +274,7 @@ public class JmxReporterTest { - - @Test - public void objectNameModifyingMBeanServer() throws Exception { -- MBeanServer mockedMBeanServer = mock(MBeanServer.class); -+ MBeanServer mockedMBeanServer = mock(); - - // overwrite the objectName - when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))) ---- a/metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java -+++ b/metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java -@@ -1,5 +1,7 @@ - package com.codahale.metrics.json; - -+import static java.util.Collections.singletonList; -+ - import com.codahale.metrics.health.HealthCheck; - import com.fasterxml.jackson.core.JsonGenerator; - import com.fasterxml.jackson.core.Version; -@@ -8,7 +10,6 @@ import com.fasterxml.jackson.databind.SerializerProvider; - import com.fasterxml.jackson.databind.module.SimpleSerializers; - import com.fasterxml.jackson.databind.ser.std.StdSerializer; - import java.io.IOException; --import java.util.Collections; - import java.util.Map; - - public class HealthCheckModule extends Module { -@@ -79,7 +80,6 @@ public class HealthCheckModule extends Module { - - @Override - public void setupModule(SetupContext context) { -- context.addSerializers( -- new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer()))); -+ context.addSerializers(new SimpleSerializers(singletonList(new HealthCheckResultSerializer()))); - } - } ---- a/metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java -+++ b/metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java -@@ -17,8 +17,7 @@ public class HealthCheckModuleTest { - public void serializesAHealthyResult() throws Exception { - HealthCheck.Result result = HealthCheck.Result.healthy(); - assertThat(mapper.writeValueAsString(result)) -- .isEqualTo( -- "{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); -+ .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp()); - } - - @Test -@@ -26,14 +25,8 @@ public class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":true," -- + "\"message\":\"yay for me\"," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -41,14 +34,8 @@ public class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":false," -- + "\"message\":\"boo\"," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -60,19 +47,8 @@ public class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.unhealthy(e); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":false," -- + "\"message\":\"oh no\"," -- + "\"error\":{" -- + "\"type\":\"java.lang.RuntimeException\"," -- + "\"message\":\"oh no\"," -- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" -- + "}," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -88,24 +64,8 @@ public class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.unhealthy(b); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":false," -- + "\"message\":\"oh well\"," -- + "\"error\":{" -- + "\"type\":\"java.lang.RuntimeException\"," -- + "\"message\":\"oh well\"," -- + "\"stack\":[\"Blah.blee(Blah.java:150)\"]," -- + "\"cause\":{" -- + "\"type\":\"java.lang.RuntimeException\"," -- + "\"message\":\"oh no\"," -- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" -- + "}" -- + "}," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -129,23 +89,7 @@ public class HealthCheckModuleTest { - - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":true," -- + "\"duration\":0," -- + "\"boolean\":true," -- + "\"integer\":1," -- + "\"long\":2," -- + "\"float\":3.546," -- + "\"double\":4.567," -- + "\"BigInteger\":12345," -- + "\"BigDecimal\":12345.56789," -- + "\"String\":\"string\"," -- + "\"complex\":{" -- + "\"field\":\"value\"" -- + "}," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - } ---- a/metrics-json/src/test/java/com/codahale/metrics/json/MetricsModuleTest.java -+++ b/metrics-json/src/test/java/com/codahale/metrics/json/MetricsModuleTest.java -@@ -42,7 +42,7 @@ public class MetricsModuleTest { - - @Test - public void serializesCounters() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - assertThat(mapper.writeValueAsString(counter)).isEqualTo("{\"count\":100}"); -@@ -50,10 +50,10 @@ public class MetricsModuleTest { - - @Test - public void serializesHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -107,7 +107,7 @@ public class MetricsModuleTest { - - @Test - public void serializesMeters() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(5.0); -@@ -127,14 +127,14 @@ public class MetricsModuleTest { - - @Test - public void serializesTimers() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/BufferPoolMetricSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/BufferPoolMetricSet.java -@@ -1,10 +1,10 @@ - package com.codahale.metrics.jvm; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Metric; - import com.codahale.metrics.MetricSet; --import java.util.Collections; - import java.util.HashMap; - import java.util.Map; - import javax.management.JMException; -@@ -46,6 +46,6 @@ public class BufferPoolMetricSet implements MetricSet { - } - } - } -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/GarbageCollectorMetricSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/GarbageCollectorMetricSet.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics.jvm; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Metric; -@@ -9,7 +10,6 @@ import java.lang.management.GarbageCollectorMXBean; - import java.lang.management.ManagementFactory; - import java.util.ArrayList; - import java.util.Collection; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -43,6 +43,6 @@ public class GarbageCollectorMetricSet implements MetricSet { - gauges.put(name(name, "count"), (Gauge) gc::getCollectionCount); - gauges.put(name(name, "time"), (Gauge) gc::getCollectionTime); - } -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/JvmAttributeGaugeSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/JvmAttributeGaugeSet.java -@@ -1,11 +1,12 @@ - package com.codahale.metrics.jvm; - -+import static java.util.Collections.unmodifiableMap; -+ - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Metric; - import com.codahale.metrics.MetricSet; - import java.lang.management.ManagementFactory; - import java.lang.management.RuntimeMXBean; --import java.util.Collections; - import java.util.HashMap; - import java.util.Locale; - import java.util.Map; -@@ -46,6 +47,6 @@ public class JvmAttributeGaugeSet implements MetricSet { - runtime.getSpecVersion())); - gauges.put("uptime", (Gauge) runtime::getUptime); - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics.jvm; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Metric; -@@ -12,7 +13,6 @@ import java.lang.management.MemoryPoolMXBean; - import java.lang.management.MemoryUsage; - import java.util.ArrayList; - import java.util.Collection; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -122,6 +122,6 @@ public class MemoryUsageGaugeSet implements MetricSet { - gauges.put(name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); - } - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java -@@ -1,9 +1,11 @@ - package com.codahale.metrics.jvm; - -+import static java.util.Collections.emptySet; -+import static java.util.Collections.unmodifiableSet; -+ - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; --import java.util.Collections; - import java.util.HashSet; - import java.util.Set; - -@@ -40,19 +42,16 @@ public class ThreadDeadlockDetector { - for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { - final StringBuilder stackTrace = new StringBuilder(); - for (StackTraceElement element : info.getStackTrace()) { -- stackTrace.append("\t at ").append(element.toString()).append(String.format("%n")); -+ stackTrace.append("\t at ").append(element).append(String.format("%n")); - } - - deadlocks.add( - String.format( - "%s locked on %s (owned by %s):%n%s", -- info.getThreadName(), -- info.getLockName(), -- info.getLockOwnerName(), -- stackTrace.toString())); -+ info.getThreadName(), info.getLockName(), info.getLockOwnerName(), stackTrace)); - } -- return Collections.unmodifiableSet(deadlocks); -+ return unmodifiableSet(deadlocks); - } -- return Collections.emptySet(); -+ return emptySet(); - } - } ---- a/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java -+++ b/metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java -@@ -1,6 +1,7 @@ - package com.codahale.metrics.jvm; - - import static com.codahale.metrics.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import com.codahale.metrics.Gauge; - import com.codahale.metrics.Metric; -@@ -8,7 +9,6 @@ import com.codahale.metrics.MetricSet; - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; --import java.util.Collections; - import java.util.HashMap; - import java.util.Map; - import java.util.Set; -@@ -56,7 +56,7 @@ public class ThreadStatesGaugeSet implements MetricSet { - "deadlock.count", (Gauge) () -> deadlockDetector.getDeadlockedThreads().size()); - gauges.put("deadlocks", (Gauge>) deadlockDetector::getDeadlockedThreads); - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - - private int getThreadCount(Thread.State state) { ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/BufferPoolMetricSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/BufferPoolMetricSetTest.java -@@ -13,7 +13,7 @@ import org.junit.Test; - - @SuppressWarnings("rawtypes") - public class BufferPoolMetricSetTest { -- private final MBeanServer mBeanServer = mock(MBeanServer.class); -+ private final MBeanServer mBeanServer = mock(); - private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); - - private ObjectName mapped; ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ClassLoadingGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ClassLoadingGaugeSetTest.java -@@ -12,7 +12,7 @@ import org.junit.Test; - @SuppressWarnings("rawtypes") - public class ClassLoadingGaugeSetTest { - -- private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); -+ private final ClassLoadingMXBean cl = mock(); - private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); - - @Before ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java -@@ -12,10 +12,10 @@ public class CpuTimeClockTest { - public void cpuTimeClock() { - final CpuTimeClock clock = new CpuTimeClock(); - -- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(250D)); -+ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(250D)); - - assertThat((double) clock.getTick()) -- .isEqualTo( -+ .isCloseTo( - ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(), offset(1000000.0)); - } - } ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeTest.java -@@ -13,7 +13,7 @@ import org.junit.Test; - - @SuppressWarnings("UnusedDeclaration") - public class FileDescriptorRatioGaugeTest { -- private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); -+ private final UnixOperatingSystemMXBean os = mock(); - - private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); - -@@ -33,9 +33,7 @@ public class FileDescriptorRatioGaugeTest { - OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); - assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); - -- assertThat(new FileDescriptorRatioGauge().getValue()) -- .isGreaterThanOrEqualTo(0.0) -- .isLessThanOrEqualTo(1.0); -+ assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative().isLessThanOrEqualTo(1.0); - } - - @Test ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java -@@ -1,20 +1,20 @@ - package com.codahale.metrics.jvm; - -+import static java.util.Collections.singletonList; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; - - import com.codahale.metrics.Gauge; - import java.lang.management.GarbageCollectorMXBean; --import java.util.Collections; - import org.junit.Before; - import org.junit.Test; - - @SuppressWarnings("unchecked") - public class GarbageCollectorMetricSetTest { -- private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); -+ private final GarbageCollectorMXBean gc = mock(); - private final GarbageCollectorMetricSet metrics = -- new GarbageCollectorMetricSet(Collections.singletonList(gc)); -+ new GarbageCollectorMetricSet(singletonList(gc)); - - @Before - public void setUp() { -@@ -42,6 +42,6 @@ public class GarbageCollectorMetricSetTest { - - @Test - public void autoDiscoversGCs() { -- assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()).isNotEmpty(); -+ assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty(); - } - } ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JmxAttributeGaugeTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JmxAttributeGaugeTest.java -@@ -53,7 +53,7 @@ public class JmxAttributeGaugeTest { - JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); - - assertThat(gauge.getValue()).isInstanceOf(Integer.class); -- assertThat((Integer) gauge.getValue()).isGreaterThan(0); -+ assertThat((Integer) gauge.getValue()).isPositive(); - } - - @Test ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JvmAttributeGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/JvmAttributeGaugeSetTest.java -@@ -11,7 +11,7 @@ import org.junit.Test; - - @SuppressWarnings("unchecked") - public class JvmAttributeGaugeSetTest { -- private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); -+ private final RuntimeMXBean runtime = mock(); - private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); - - @Before ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/MemoryUsageGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/MemoryUsageGaugeSetTest.java -@@ -14,14 +14,14 @@ import org.junit.Test; - - @SuppressWarnings("rawtypes") - public class MemoryUsageGaugeSetTest { -- private final MemoryUsage heap = mock(MemoryUsage.class); -- private final MemoryUsage nonHeap = mock(MemoryUsage.class); -- private final MemoryUsage pool = mock(MemoryUsage.class); -- private final MemoryUsage weirdPool = mock(MemoryUsage.class); -- private final MemoryUsage weirdCollection = mock(MemoryUsage.class); -- private final MemoryMXBean mxBean = mock(MemoryMXBean.class); -- private final MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); -- private final MemoryPoolMXBean weirdMemoryPool = mock(MemoryPoolMXBean.class); -+ private final MemoryUsage heap = mock(); -+ private final MemoryUsage nonHeap = mock(); -+ private final MemoryUsage pool = mock(); -+ private final MemoryUsage weirdPool = mock(); -+ private final MemoryUsage weirdCollection = mock(); -+ private final MemoryMXBean mxBean = mock(); -+ private final MemoryPoolMXBean memoryPool = mock(); -+ private final MemoryPoolMXBean weirdMemoryPool = mock(); - - private final MemoryUsageGaugeSet gauges = - new MemoryUsageGaugeSet(mxBean, Arrays.asList(memoryPool, weirdMemoryPool)); -@@ -262,6 +262,6 @@ public class MemoryUsageGaugeSetTest { - - @Test - public void autoDetectsMemoryUsageBeanAndMemoryPools() { -- assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()).isNotEmpty(); -+ assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty(); - } - } ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDeadlockDetectorTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDeadlockDetectorTest.java -@@ -12,7 +12,7 @@ import java.util.Locale; - import org.junit.Test; - - public class ThreadDeadlockDetectorTest { -- private final ThreadMXBean threads = mock(ThreadMXBean.class); -+ private final ThreadMXBean threads = mock(); - private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); - - @Test -@@ -24,7 +24,7 @@ public class ThreadDeadlockDetectorTest { - - @Test - public void returnsASetOfThreadsIfAnyAreDeadlocked() { -- final ThreadInfo thread1 = mock(ThreadInfo.class); -+ final ThreadInfo thread1 = mock(); - when(thread1.getThreadName()).thenReturn("thread1"); - when(thread1.getLockName()).thenReturn("lock2"); - when(thread1.getLockOwnerName()).thenReturn("thread2"); -@@ -35,7 +35,7 @@ public class ThreadDeadlockDetectorTest { - new StackTraceElement("Blah", "blee", "Blah.java", 100) - }); - -- final ThreadInfo thread2 = mock(ThreadInfo.class); -+ final ThreadInfo thread2 = mock(); - when(thread2.getThreadName()).thenReturn("thread2"); - when(thread2.getLockName()).thenReturn("lock1"); - when(thread2.getLockOwnerName()).thenReturn("thread1"); ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java -@@ -15,10 +15,10 @@ import org.junit.Test; - // TODO: 3/12/13 -- improve test coverage for ThreadDump - - public class ThreadDumpTest { -- private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); -+ private final ThreadMXBean threadMXBean = mock(); - private final ThreadDump threadDump = new ThreadDump(threadMXBean); - -- private final ThreadInfo runnable = mock(ThreadInfo.class); -+ private final ThreadInfo runnable = mock(); - - @Before - public void setUp() { -@@ -39,8 +39,8 @@ public class ThreadDumpTest { - final ByteArrayOutputStream output = new ByteArrayOutputStream(); - threadDump.dump(output); - -- assertThat(output.toString()) -- .isEqualTo( -+ assertThat(output) -+ .hasToString( - String.format( - "\"runnable\" id=100 state=RUNNABLE%n" - + " at Blah.blee(Blah.java:100)%n" ---- a/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadStatesGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadStatesGaugeSetTest.java -@@ -13,17 +13,17 @@ import org.junit.Before; - import org.junit.Test; - - public class ThreadStatesGaugeSetTest { -- private final ThreadMXBean threads = mock(ThreadMXBean.class); -- private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -+ private final ThreadMXBean threads = mock(); -+ private final ThreadDeadlockDetector detector = mock(); - private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); - private final long[] ids = new long[] {1, 2, 3}; - -- private final ThreadInfo newThread = mock(ThreadInfo.class); -- private final ThreadInfo runnableThread = mock(ThreadInfo.class); -- private final ThreadInfo blockedThread = mock(ThreadInfo.class); -- private final ThreadInfo waitingThread = mock(ThreadInfo.class); -- private final ThreadInfo timedWaitingThread = mock(ThreadInfo.class); -- private final ThreadInfo terminatedThread = mock(ThreadInfo.class); -+ private final ThreadInfo newThread = mock(); -+ private final ThreadInfo runnableThread = mock(); -+ private final ThreadInfo blockedThread = mock(); -+ private final ThreadInfo waitingThread = mock(); -+ private final ThreadInfo timedWaitingThread = mock(); -+ private final ThreadInfo terminatedThread = mock(); - - private final Set deadlocks = new HashSet<>(); - ---- a/metrics-log4j2/src/test/java/com/codahale/metrics/log4j2/InstrumentedAppenderTest.java -+++ b/metrics-log4j2/src/test/java/com/codahale/metrics/log4j2/InstrumentedAppenderTest.java -@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final LogEvent event = mock(LogEvent.class); -+ private final LogEvent event = mock(); - - @Before - public void setUp() { ---- a/metrics-logback/src/test/java/com/codahale/metrics/logback/InstrumentedAppenderTest.java -+++ b/metrics-logback/src/test/java/com/codahale/metrics/logback/InstrumentedAppenderTest.java -@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ private final ILoggingEvent event = mock(); - - @Before - public void setUp() { ---- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java -+++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java -@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ private final ILoggingEvent event = mock(); - - @Before - public void setUp() { ---- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java -+++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java -@@ -18,7 +18,7 @@ public class InstrumentedAppenderTest { - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ private final ILoggingEvent event = mock(); - - @Before - public void setUp() { ---- a/metrics-servlet/src/test/java/com/codahale/metrics/servlet/InstrumentedFilterContextListenerTest.java -+++ b/metrics-servlet/src/test/java/com/codahale/metrics/servlet/InstrumentedFilterContextListenerTest.java -@@ -10,7 +10,7 @@ import javax.servlet.ServletContextEvent; - import org.junit.Test; - - public class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final MetricRegistry registry = mock(); - private final InstrumentedFilterContextListener listener = - new InstrumentedFilterContextListener() { - @Override -@@ -21,9 +21,9 @@ public class InstrumentedFilterContextListenerTest { - - @Test - public void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ final ServletContext context = mock(); - -- final ServletContextEvent event = mock(ServletContextEvent.class); -+ final ServletContextEvent event = mock(); - when(event.getServletContext()).thenReturn(context); - - listener.contextInitialized(event); ---- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java -+++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java -@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); - if (registryAttr instanceof HealthCheckRegistry) { - this.registry = (HealthCheckRegistry) registryAttr; ---- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java -+++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java -@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(METRICS_REGISTRY); - if (registryAttr instanceof MetricRegistry) { - this.registry = (MetricRegistry) registryAttr; ---- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java -+++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java -@@ -3,7 +3,6 @@ package com.codahale.metrics.servlets; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -94,9 +93,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - } - - @Test -@@ -110,9 +108,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - } - - @Test -@@ -168,15 +165,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getContent()) - .isEqualTo( - String.format( -- "{%n" -- + " \"fun\" : {%n" -- + " \"healthy\" : true,%n" -- + " \"message\" : \"foo bar 123\",%n" -- + " \"duration\" : 0,%n" -- + " \"timestamp\" : \"" -- + EXPECTED_TIMESTAMP -- + "\"" -- + "%n }%n}")); -+ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", -+ EXPECTED_TIMESTAMP)); - } - - private static HealthCheck.Result healthyResultWithMessage(String message) { -@@ -198,23 +188,23 @@ public class HealthCheckServletTest extends AbstractServletTest { - @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() - throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -+ verify(servletConfig).getServletContext(); - verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); - } - - @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn(healthCheckRegistry); -@@ -222,15 +212,15 @@ public class HealthCheckServletTest extends AbstractServletTest { - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); - } - - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); -@@ -242,8 +232,8 @@ public class HealthCheckServletTest extends AbstractServletTest { - @Test - public void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn(registry); ---- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletContextListenerTest.java -+++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletContextListenerTest.java -@@ -17,7 +17,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MetricsServletContextListenerTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private final String allowedOrigin = "some.other.origin"; - ---- a/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java -+++ b/metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java -@@ -1,10 +1,8 @@ - package com.codahale.metrics.servlets; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -24,7 +22,7 @@ import org.junit.Before; - import org.junit.Test; - - public class MetricsServletTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private ServletTester tester; - -@@ -128,22 +126,8 @@ public class MetricsServletTest extends AbstractServletTest { - assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); - assertThat(response.getContent()) - .isEqualTo( -- callbackParamVal -- + "({" -- + "\"version\":\"4.0.0\"," -- + "\"gauges\":{" -- + "\"g1\":{\"value\":100}" -- + "}," -- + "\"counters\":{" -- + "\"c\":{\"count\":1}" -- + "}," -- + "\"histograms\":{" -- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -- + "}," -- + "\"meters\":{" -- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -- + "}" -- + "})"); -+ "%s({\"version\":\"4.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", -+ callbackParamVal); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -223,41 +207,40 @@ public class MetricsServletTest extends AbstractServletTest { - @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() - throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); - } - - @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn(metricRegistry); -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); - - final MetricsServlet metricsServlet = new MetricsServlet(null); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); - } - - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); - - final MetricsServlet metricsServlet = new MetricsServlet(null); diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index e7e82b304a..5ed79ddef6 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -1,68 +1,195 @@ +metrics-annotation/src/main/java/com/codahale/metrics/annotation/CachedGauge.java:[32,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/CachedGauge.java:[37,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/CachedGauge.java:[43,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/CachedGauge.java:[48,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Counted.java:[39,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Counted.java:[44,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Counted.java:[51,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/ExceptionMetered.java:[55,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/ExceptionMetered.java:[61,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/ExceptionMetered.java:[68,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Gauge.java:[27,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Gauge.java:[32,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Metered.java:[36,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Metered.java:[41,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Metric.java:[39,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Metric.java:[44,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/ResponseMetered.java:[37,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/ResponseMetered.java:[42,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/ResponseMetered.java:[49,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Timed.java:[36,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-annotation/src/main/java/com/codahale/metrics/annotation/Timed.java:[41,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java:[21,3] [MissingSummary] A summary line is required on public/protected Javadocs. +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[9,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[9,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 metrics-caffeine/src/test/java/com/codahale/metrics/caffeine/MetricsStatsCounterTest.java:[89,9] [deprecation] recordEviction() in MetricsStatsCounter has been deprecated metrics-caffeine/src/test/java/com/codahale/metrics/caffeine/MetricsStatsCounterTest.java:[96,9] [deprecation] recordEviction(int) in MetricsStatsCounter has been deprecated -metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[150,8] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[154,8] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[81,68] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[124,20] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[162,12] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[167,11] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[173,17] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[198,8] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[201,21] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[204,11] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[241,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[250,36] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[266,6] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity -metrics-collectd/src/main/java/com/codahale/metrics/collectd/Sender.java:[22,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity -metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java:[249,43] [Refaster Rule] ImmutableMapRules.ImmutableMapOf1: Refactoring opportunity -metrics-collectd/src/test/java/com/codahale/metrics/collectd/CollectdReporterTest.java:[255,40] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java:[57,41] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[193,13] [InconsistentCapitalization] Found the field 'hostName' with the same name as the parameter 'hostname' but with different capitalization. +metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[305,14] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[160,12] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[165,11] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[171,17] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[196,8] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[199,21] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[202,11] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[248,36] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/com/codahale/metrics/collectd/Sanitize.java:[7,3] [MissingSummary] A summary fragment is required; consider using the value of the @see block as a summary fragment instead. +metrics-collectd/src/test/java/com/codahale/metrics/collectd/Receiver.java:[51,16] [CatchAndPrintStackTrace] Logging or rethrowing exceptions should usually be preferred to catching and calling printStackTrace +metrics-collectd/src/test/java/com/codahale/metrics/collectd/SanitizeTest.java:[26,41] [UnnecessaryParentheses] These grouping parentheses are unnecessary; it is unlikely the code will be misinterpreted without them +metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java:[239,46] [JavaUtilDate] Date has a bad API that leads to bugs; prefer java.time.Instant or LocalDate. +metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java:[406,43] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java:[413,43] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-core/src/main/java/com/codahale/metrics/CsvReporter.java:[310,39] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-core/src/main/java/com/codahale/metrics/CsvReporter.java:[312,39] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional metrics-core/src/main/java/com/codahale/metrics/CsvReporter.java:[382,35] [FormatStringConcatenation] Defer string concatenation to the invoked method metrics-core/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java:[196,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement metrics-core/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java:[218,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement -metrics-core/src/main/java/com/codahale/metrics/LockFreeExponentiallyDecayingReservoir.java:[240,6] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java:[101,4] [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java:[50,21] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[218,19] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[39,4] [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[608,21] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[614,21] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[620,21] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[132,16] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[145,4] [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[158,78] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[176,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[38,12] [removal] SecurityManager in java.lang has been deprecated and marked for removal -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[38,38] [removal] getSecurityManager() in System has been deprecated and marked for removal -metrics-core/src/main/java/com/codahale/metrics/SharedMetricRegistries.java:[87,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java:[82,46] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/UniformSnapshot.java:[50,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java:[67,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java:[329,29] [TypeParameterUnusedInFormals] Declaring a type parameter that is only used in the return type is a misuse of generics: operations on the type parameter are unchecked, it hides unsafe casts at invocations of the method, and it interacts badly with method overload resolution. +metrics-core/src/main/java/com/codahale/metrics/MovingAverages.java:[26,5] [EmptyBlockTag] A block tag (@param, @return, @throws, @deprecated) has an empty description. Block tags without descriptions don't add much value for future readers of the code; consider removing the tag entirely or adding a description. +metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[102,29] [TypeParameterUnusedInFormals] Declaring a type parameter that is only used in the return type is a misuse of generics: operations on the type parameter are unchecked, it hides unsafe casts at invocations of the method, and it interacts badly with method overload resolution. +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[37,12] [removal] SecurityManager in java.lang has been deprecated and marked for removal +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[37,38] [removal] getSecurityManager() in System has been deprecated and marked for removal +metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[47,21] [ThreadPriorityCheck] Relying on the thread scheduler is discouraged. +metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java:[183,29] [InvalidInlineTag] Curly braces should be used for inline Javadoc tags: {@link ...} +metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java:[76,26] [UnnecessaryParentheses] These grouping parentheses are unnecessary; it is unlikely the code will be misinterpreted without them +metrics-core/src/test/java/com/codahale/metrics/ClockTest.java:[14,75] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-core/src/test/java/com/codahale/metrics/ClockTest.java:[16,66] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java:[37,19] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java:[48,19] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java:[59,19] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[230,41] [DirectInvocationOnMock] Methods should not be directly invoked on the mock `mockExecutor`. Should this be part of a verify(..) call? +metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[231,39] [DirectInvocationOnMock] Methods should not be directly invoked on the mock `mockExecutor`. Should this be part of a verify(..) call? metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[12,62] [deprecation] none() in ExpectedException has been deprecated -metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java:[19,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-graphite/src/main/java/com/codahale/metrics/graphite/Graphite.java:[119,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity -metrics-graphite/src/main/java/com/codahale/metrics/graphite/Graphite.java:[66,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-graphite/src/main/java/com/codahale/metrics/graphite/Graphite.java:[70,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteRabbitMQ.java:[112,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[429,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[434,19] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[447,20] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[84,46] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteUDP.java:[46,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity -metrics-graphite/src/main/java/com/codahale/metrics/graphite/PickledGraphite.java:[176,4] [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[177,46] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[462,16] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[47,44] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[478,42] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteReporterTest.java:[57,44] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity -metrics-healthchecks/src/main/java/com/codahale/metrics/health/AsyncHealthCheckDecorator.java:[80,4] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[270,32] [removal] getSecurityManager() in System has been deprecated and marked for removal -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[270,6] [removal] SecurityManager in java.lang has been deprecated and marked for removal -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[96,6] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity +metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[88,15] [UnnecessaryAsync] Variables which are initialized and do not escape the current scope do not need to worry about concurrency. Using the non-concurrent type will reduce overhead and verbosity. +metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java:[128,30] [DefaultCharset] Implicit use of the platform default charset, which can result in differing behaviour between JVM executions or incorrect behavior if the encoding of the data source doesn't match expectations. +metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java:[136,30] [DefaultCharset] Implicit use of the platform default charset, which can result in differing behaviour between JVM executions or incorrect behavior if the encoding of the data source doesn't match expectations. +metrics-graphite/src/main/java/com/codahale/metrics/graphite/Graphite.java:[129,57] [OperatorPrecedence] Use grouping parenthesis to make the operator precedence explicit +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[253,46] [UnnecessaryLambda] Returning a lambda from a helper method or saving it in a constant is unnecessary; prefer to implement the functional interface method directly and use a method reference instead. +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[431,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[436,19] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[449,20] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[456,60] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[458,60] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java:[140,65] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java:[30,66] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java:[59,26] [DirectInvocationOnMock] Methods should not be directly invoked on the mock `socket`. Should this be part of a verify(..) call? +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java:[25,73] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java:[35,49] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java:[40,60] [StringCharset] StringCharset +metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java:[41,34] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address +metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java:[36,66] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address +metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java:[68,26] [DirectInvocationOnMock] Methods should not be directly invoked on the mock `socket`. Should this be part of a verify(..) call? +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[203,19] [EqualsGetClass] Prefer instanceof to getClass when implementing Object#equals. +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[222,32] [UnnecessaryParentheses] These grouping parentheses are unnecessary; it is unlikely the code will be misinterpreted without them +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[318,25] [AnnotateFormatMethod] This method uses a pair of parameters as a format string and its arguments, but the enclosing method wasn't annotated @FormatMethod. Doing so gives compile-time rather than run-time protection against malformed format strings. +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[55,25] [AnnotateFormatMethod] This method uses a pair of parameters as a format string and its arguments, but the enclosing method wasn't annotated @FormatMethod. Doing so gives compile-time rather than run-time protection against malformed format strings. +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[79,25] [AnnotateFormatMethod] This method uses a pair of parameters as a format string and its arguments, but the enclosing method wasn't annotated @FormatMethod. Doing so gives compile-time rather than run-time protection against malformed format strings. +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[269,32] [removal] getSecurityManager() in System has been deprecated and marked for removal +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[269,6] [removal] SecurityManager in java.lang has been deprecated and marked for removal +metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[278,64] [ThreadPriorityCheck] Relying on the thread scheduler is discouraged. +metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[189,46] [JavaTimeDefaultTimeZone] ZonedDateTime.now() is not allowed because it silently uses the system default time-zone. You must pass an explicit time-zone (e.g., ZoneId.of("America/Los_Angeles")) to this method. metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[203,46] [JavaTimeDefaultTimeZone] ZonedDateTime.now() is not allowed because it silently uses the system default time-zone. You must pass an explicit time-zone (e.g., ZoneId.of("America/Los_Angeles")) to this method. metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java:[13,70] [deprecation] none() in ExpectedException has been deprecated -metrics-healthchecks/src/test/java/com/codahale/metrics/health/jvm/ThreadDeadlockHealthCheckTest.java:[20,61] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/HttpClientTestBase.java:[24,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-httpclient/src/main/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategies.java:[43,59] [StringCaseLocaleUsage] Specify a `Locale` when calling `String#to{Lower,Upper}Case`. (Note: there are multiple suggested fixes; the third may be most appropriate if you're dealing with ASCII Strings.) metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[101,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[112,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[120,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated @@ -88,44 +215,73 @@ metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedH metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[182,10] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[26,47] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[77,8] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java:[67,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics/servlet/AbstractInstrumentedFilter.java:[67,27] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity -metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[29,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListener.java:[14,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/AdminServlet.java:[32,30] [InlineFormatString] Prefer to create format strings inline, instead of extracting them to a single-use constant +metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java:[26,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java:[31,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java:[40,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java:[32,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java:[37,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java:[46,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java:[55,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[104,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[145,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[219,25] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[30,67] [JavaTimeDefaultTimeZone] ZonedDateTime.now() is not allowed because it silently uses the system default time-zone. You must pass an explicit time-zone (e.g., ZoneId.of("America/Los_Angeles")) to this method. +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[30,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java:[130,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[1] [DefaultPackage] Java classes shouldn't use default package metrics-jdbi3/src/main/java/com/codahale/metrics/jdbi3/InstrumentedTimingCollector.java:[9,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated -metrics-jdbi3/src/main/java/com/codahale/metrics/jdbi3/strategies/DefaultNameStrategy.java:[15,28] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/SmartNameStrategyTest.java:[17,10] [deprecation] InstrumentedTimingCollector in com.codahale.metrics.jdbi3 has been deprecated metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/SmartNameStrategyTest.java:[23,20] [deprecation] InstrumentedTimingCollector in com.codahale.metrics.jdbi3 has been deprecated metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/SmartNameStrategyTest.java:[8,33] [deprecation] InstrumentedTimingCollector in com.codahale.metrics.jdbi3 has been deprecated -metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java:[172,25] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java:[174,86] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java:[543,29] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity -metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java:[172,25] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java:[174,86] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java:[543,29] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity -metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java:[172,25] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java:[174,86] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java:[543,29] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity -metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java:[177,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHandler.java:[188,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java:[137,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jetty10/src/main/java/io/dropwizard/metrics/jetty10/InstrumentedHttpChannelListener.java:[148,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java:[177,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHandler.java:[188,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java:[137,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jetty11/src/main/java/io/dropwizard/metrics/jetty11/InstrumentedHttpChannelListener.java:[148,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java:[185,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHandler.java:[196,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java:[137,22] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jetty9/src/main/java/com/codahale/metrics/jetty9/InstrumentedHttpChannelListener.java:[148,23] [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity -metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java:[65,43] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java:[66,39] [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity -metrics-jmx/src/main/java/com/codahale/metrics/jmx/JmxReporter.java:[92,6] [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity -metrics-json/src/main/java/com/codahale/metrics/json/HealthCheckModule.java:[83,62] [Refaster Rule] ImmutableListRules.ImmutableListOf1: Refactoring opportunity -metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadDeadlockDetector.java:[55,19] [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity +metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java:[582,19] [EqualsGetClass] Prefer instanceof to getClass when implementing Object#equals. +metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java:[582,19] [EqualsGetClass] Prefer instanceof to getClass when implementing Object#equals. +metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java:[582,19] [EqualsGetClass] Prefer instanceof to getClass when implementing Object#equals. +metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java:[134,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java:[138,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java:[136,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java:[140,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java:[136,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java:[140,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java:[18,45] [JdkObsolete] Hashtable performs synchronization this is usually unnecessary; prefer LinkedHashMap. +metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[131,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[20,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[28,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[43,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[62,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[90,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-jvm/src/main/java/com/codahale/metrics/jvm/FileDescriptorRatioGauge.java:[42,55] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jvm/src/main/java/com/codahale/metrics/jvm/FileDescriptorRatioGauge.java:[42,91] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[107,31] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[107,56] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[77,41] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[77,57] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[93,29] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[93,54] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java:[47,43] [StringCaseLocaleUsage] Specify a `Locale` when calling `String#to{Lower,Upper}Case`. (Note: there are multiple suggested fixes; the third may be most appropriate if you're dealing with ASCII Strings.) +metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java:[15,75] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional +metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java:[19,71] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[55,10] [removal] AccessController in java.security has been deprecated and marked for removal +metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[67,36] [URLEqualsHashCode] Avoid hash-based containers of java.net.URL--the containers rely on equals() and hashCode(), which cause java.net.URL to make blocking internet connections. metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[9,20] [removal] AccessController in java.security has been deprecated and marked for removal -metrics-jvm/src/test/java/com/codahale/metrics/jvm/GarbageCollectorMetricSetTest.java:[17,49] [Refaster Rule] ImmutableListRules.ImmutableListOf1: Refactoring opportunity +metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java:[42,30] [DefaultCharset] Implicit use of the platform default charset, which can result in differing behaviour between JVM executions or incorrect behavior if the encoding of the data source doesn't match expectations. metrics-log4j2/src/main/java/com/codahale/metrics/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated metrics-log4j2/src/main/java/com/codahale/metrics/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -metrics-servlet/src/main/java/com/codahale/metrics/servlet/AbstractInstrumentedFilter.java:[67,27] [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity -metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[30,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-servlet/src/main/java/com/codahale/metrics/servlet/InstrumentedFilterContextListener.java:[14,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-servlets/src/main/java/com/codahale/metrics/servlets/AdminServlet.java:[32,30] [InlineFormatString] Prefer to create format strings inline, instead of extracting them to a single-use constant +metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java:[26,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java:[31,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java:[40,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java:[48,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java:[32,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java:[37,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java:[46,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java:[55,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. +metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[112,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[170,25] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[31,67] [JavaTimeDefaultTimeZone] ZonedDateTime.now() is not allowed because it silently uses the system default time-zone. You must pass an explicit time-zone (e.g., ZoneId.of("America/Los_Angeles")) to this method. +metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[96,18] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java:[130,18] [FormatStringConcatenation] Defer string concatenation to the invoked method From 78cac86a2844e4ad3a7600a1d796cf9e49263aaf Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Wed, 6 Mar 2024 11:02:56 +0100 Subject: [PATCH 21/59] Only run on GH comment --- .github/workflows/run-integration-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 56d22a8142..a771f010b9 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -19,8 +19,8 @@ jobs: matrix: integration-test: ["checkstyle", "metrics"] name: On-demand integration test - # if: | - # github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') + if: | + github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') runs-on: ubuntu-22.04 steps: - name: Install Harden-Runner From 1ff1d5705bd35090733ac145c57c44c477c74007 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Wed, 6 Mar 2024 13:42:22 +0100 Subject: [PATCH 22/59] Try to trigger metrics --- .github/workflows/run-integration-tests.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index a771f010b9..029da0d19a 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -15,13 +15,14 @@ permissions: contents: read jobs: run-integration-tests: + runs-on: ubuntu-22.04 + if: github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') + # XXX: Configure permissions. strategy: matrix: - integration-test: ["checkstyle", "metrics"] + integration-test: [ "metrics", "checkstyle" ] name: On-demand integration test - if: | - github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') - runs-on: ubuntu-22.04 + steps: - name: Install Harden-Runner uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0 From 51ec7bcbd4699c48cb074ed4ef0a63738bdf3975 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Wed, 6 Mar 2024 13:57:27 +0100 Subject: [PATCH 23/59] Try to run both variants --- .github/workflows/run-integration-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 029da0d19a..d9f71aabdd 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -16,7 +16,7 @@ permissions: jobs: run-integration-tests: runs-on: ubuntu-22.04 - if: github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') +# if: github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') # XXX: Configure permissions. strategy: matrix: @@ -39,7 +39,7 @@ jobs: - name: Check out code and set up JDK and Maven uses: s4u/setup-maven-action@6d44c18d67d9e1549907b8815efa5e4dada1801b # v1.12.0 with: - checkout-ref: "refs/pull/${{ github.event.issue.number }}/head" + checkout-ref: "refs/pull/894/head" java-version: 17.0.10 java-distribution: temurin maven-version: 3.9.6 From ee0018114de1d74caa46026c1fbda75c420be103 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Wed, 6 Mar 2024 15:37:09 +0100 Subject: [PATCH 24/59] Dont analyse generated files --- integration-tests/metrics-init.patch | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index d3fa6c456d..78052905c5 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -31,7 +31,7 @@ index 6192b52..8c312b6 100644 2.19.1 9+181-r4173-1 - -+ -Xplugin:ErrorProne ${error-prone.flags} ++ -Xplugin:ErrorProne -XepDisableWarningsInGeneratedCode ${error-prone.flags} + 8 dropwizard_metrics dropwizard From 8b4cba4ac9d50bac314d05aaabb74ec5e66f1c63 Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Wed, 20 Mar 2024 10:47:07 +0100 Subject: [PATCH 25/59] Fix metrics init patch --- integration-tests/metrics-init.patch | 2 +- integration-tests/metrics.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index 78052905c5..9a00955441 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -31,7 +31,7 @@ index 6192b52..8c312b6 100644 2.19.1 9+181-r4173-1 - -+ -Xplugin:ErrorProne -XepDisableWarningsInGeneratedCode ${error-prone.flags} ++ -Xplugin:ErrorProne -XepDisableWarningsInGeneratedCode ${error-prone.configuration-args} + 8 dropwizard_metrics dropwizard diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 7da98d03e8..58284e8bcf 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -14,7 +14,7 @@ fi do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" -# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Rsefaster rules +# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Refaster rules # as they introduce changes that expect Guava to be on the classpath. patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\.StringIsNullOrEmpty)).*)" From cc69b87b8976ab718bb1cde6eee408807393c807 Mon Sep 17 00:00:00 2001 From: Gijs de Jong Date: Wed, 20 Mar 2024 12:01:08 +0100 Subject: [PATCH 26/59] Try different refaster name patterns --- .../metrics-expected-warnings.txt | 196 +++++++++--------- integration-tests/metrics.sh | 2 +- 2 files changed, 99 insertions(+), 99 deletions(-) diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index 5ed79ddef6..93deb90769 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -20,104 +20,104 @@ metrics-annotation/src/main/java/com/codahale/metrics/annotation/ResponseMetered metrics-annotation/src/main/java/com/codahale/metrics/annotation/Timed.java:[36,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. metrics-annotation/src/main/java/com/codahale/metrics/annotation/Timed.java:[41,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java:[21,3] [MissingSummary] A summary line is required on public/protected Javadocs. -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[3,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[4,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[5,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[6,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[7,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[8,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[9,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B3.java:[9,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: SlidingTimeWindowReservoirsBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[9,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 +metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[9,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 metrics-caffeine/src/test/java/com/codahale/metrics/caffeine/MetricsStatsCounterTest.java:[89,9] [deprecation] recordEviction() in MetricsStatsCounter has been deprecated metrics-caffeine/src/test/java/com/codahale/metrics/caffeine/MetricsStatsCounterTest.java:[96,9] [deprecation] recordEviction(int) in MetricsStatsCounter has been deprecated metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[193,13] [InconsistentCapitalization] Found the field 'hostName' with the same name as the parameter 'hostname' but with different capitalization. diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 58284e8bcf..38e14fb07c 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -16,7 +16,7 @@ report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ # XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Refaster rules # as they introduce changes that expect Guava to be on the classpath. -patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^((?!(Immutable|Preconditions|StringRules\.StringIsNullOrEmpty)).*)" +patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!ImmutableSetRules\$ImmutableSetOf).*" "$(dirname "${0}")"/run-integration-test.sh \ "${test_name}" \ From 1ac65e9f53039dcdc8d2c58c71226643c2ffa80f Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Thu, 14 Nov 2024 09:28:43 +0100 Subject: [PATCH 27/59] Fix missed merge conflicts --- integration-tests/run-integration-test.sh | 25 ----------------------- 1 file changed, 25 deletions(-) diff --git a/integration-tests/run-integration-test.sh b/integration-tests/run-integration-test.sh index 80ec95a1f5..9944a7b133 100755 --- a/integration-tests/run-integration-test.sh +++ b/integration-tests/run-integration-test.sh @@ -1,15 +1,10 @@ #!/usr/bin/env bash -<<<<<<< HEAD -# This script is not meant to be invoked manually, instead it should be invoked -# through one of the integration test scripts such as the metrics or checkstyle one. -======= # Integration test framework for Maven builds. # # This script is not meant to be invoked manually. Instead it should be invoked # through one of the top-level integration test scripts, such as # `checkstyle.sh`. ->>>>>>> master set -e -u -o pipefail @@ -17,13 +12,8 @@ integration_test_root="$(cd "$(dirname -- "${0}")" && pwd)" error_prone_support_root="${integration_test_root}/.." repos_root="${integration_test_root}/.repos" -<<<<<<< HEAD -if [ "${#}" -ne 11 ]; then - >&2 echo "Usage $(basename "${0}") [TestName] [Project] [Repository] [Revision] [BuildFlags] [AdditionalSourceDirectories] [PatchFlags] [ValidationEpFlags] [ValidationMvnFlags] [DoSync] [ReportDirectory]" -======= if [ "${#}" -lt 9 ] || [ "${#}" -gt 11 ] || ([ "${#}" = 11 ] && [ "${10:---sync}" != '--sync' ]); then >&2 echo "Usage: $(basename "${0}") [--sync] []" ->>>>>>> master exit 1 fi @@ -31,15 +21,6 @@ test_name="${1}" project="${2}" repository="${3}" revision="${4}" -<<<<<<< HEAD -build_flags="${5}" -additional_src_directories="${6}" -patch_flags="${7}" -validation_ep_flags="${8}" -validation_mvn_flags="${9}" -do_sync="${10}" -report_directory="${11}" -======= additional_build_flags="${5}" additional_source_directories="${6}" patch_error_prone_flags="${7}" @@ -47,7 +28,6 @@ validation_error_prone_flags="${8}" validation_build_flags="${9}" do_sync="$([ "${#}" = 9 ] || [ "${10:-}" != '--sync' ] || echo 1)" report_directory="$([ "${#}" = 9 ] || ([ -z "${do_sync}" ] && echo "${10}") || ([ "${#}" = 10 ] || echo "${11}"))" ->>>>>>> master if [ -n "${report_directory}" ]; then mkdir -p "${report_directory}" @@ -79,13 +59,8 @@ shared_build_flags=" -Derror-prone-support.version=$( mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=project.version -q -DforceStdout ) -<<<<<<< HEAD - -DadditionalSourceDirectories=${additional_src_directories} - ${build_flags} -======= -DadditionalSourceDirectories=${additional_source_directories} ${additional_build_flags} ->>>>>>> master " # XXX: Configure Renovate to manage the fmt-maven-plugin version declared here. From 54f541ab5b573e58f360d06ec0618e85a496d34f Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Thu, 14 Nov 2024 16:21:29 +0100 Subject: [PATCH 28/59] Checkpoint --- .../metrics-expected-changes.patch | 86832 ++++++++++++++++ .../metrics-expected-warnings.txt | 287 - integration-tests/metrics-init.patch | 371 +- integration-tests/metrics.sh | 34 +- integration-tests/run-integration-test.sh | 18 +- 5 files changed, 87065 insertions(+), 477 deletions(-) diff --git a/integration-tests/metrics-expected-changes.patch b/integration-tests/metrics-expected-changes.patch index e69de29bb2..c4961042fa 100644 --- a/integration-tests/metrics-expected-changes.patch +++ b/integration-tests/metrics-expected-changes.patch @@ -0,0 +1,86832 @@ +--- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/CachedGauge.java ++++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/CachedGauge.java +@@ -9,8 +9,8 @@ import java.util.concurrent.TimeUnit; + /** + * An annotation for marking a method as a gauge, which caches the result for a specified time. + * +- *

+- * Given a method like this: ++ *

Given a method like this: ++ * + *


+  *     {@literal @}CachedGauge(name = "queueSize", timeout = 30, timeoutUnit = TimeUnit.SECONDS)
+  *     public int getQueueSize() {
+@@ -18,36 +18,34 @@ import java.util.concurrent.TimeUnit;
+  *     }
+  *
+  * 
+- *

+ * +- * A gauge for the defining class with the name queueSize will be created which uses the annotated method's +- * return value as its value, and which caches the result for 30 seconds. ++ *

A gauge for the defining class with the name queueSize will be created which uses the ++ * annotated method's return value as its value, and which caches the result for 30 seconds. + * + * @since 3.1 + */ + @Retention(RetentionPolicy.RUNTIME) +-@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) ++@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + public @interface CachedGauge { + +- /** +- * @return The name of the counter. +- */ +- String name() default ""; +- +- /** +- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name +- * relative to the annotated class. +- */ +- boolean absolute() default false; ++ /** ++ * @return The name of the counter. ++ */ ++ String name() default ""; + +- /** +- * @return The amount of time to cache the result +- */ +- long timeout(); ++ /** ++ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the ++ * given name relative to the annotated class. ++ */ ++ boolean absolute() default false; + +- /** +- * @return The unit of timeout +- */ +- TimeUnit timeoutUnit() default TimeUnit.MILLISECONDS; ++ /** ++ * @return The amount of time to cache the result ++ */ ++ long timeout(); + ++ /** ++ * @return The unit of timeout ++ */ ++ TimeUnit timeoutUnit() default TimeUnit.MILLISECONDS; + } +--- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Counted.java ++++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Counted.java +@@ -10,44 +10,47 @@ import java.lang.annotation.Target; + /** + * An annotation for marking a method of an annotated object as counted. + * +- *

+- * Given a method like this: ++ *

Given a method like this: ++ * + *


+  *     {@literal @}Counted(name = "fancyName")
+  *     public String fancyName(String name) {
+  *         return "Sir Captain " + name;
+  *     }
+  * 
+- *

+- * A counter for the defining class with the name {@code fancyName} will be created and each time the +- * {@code #fancyName(String)} method is invoked, the counter will be marked. ++ * ++ *

A counter for the defining class with the name {@code fancyName} will be created and each time ++ * the {@code #fancyName(String)} method is invoked, the counter will be marked. + * + * @since 3.1 + */ + @Inherited + @Documented + @Retention(RetentionPolicy.RUNTIME) +-@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) ++@Target({ ++ ElementType.TYPE, ++ ElementType.CONSTRUCTOR, ++ ElementType.METHOD, ++ ElementType.ANNOTATION_TYPE ++}) + public @interface Counted { + +- /** +- * @return The name of the counter. +- */ +- String name() default ""; +- +- /** +- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name +- * relative to the annotated class. When annotating a class, this must be {@code false}. +- */ +- boolean absolute() default false; ++ /** ++ * @return The name of the counter. ++ */ ++ String name() default ""; + +- /** +- * @return +- * If {@code false} (default), the counter is decremented when the annotated +- * method returns, counting current invocations of the annotated method. +- * If {@code true}, the counter increases monotonically, counting total +- * invocations of the annotated method. +- */ +- boolean monotonic() default false; ++ /** ++ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the ++ * given name relative to the annotated class. When annotating a class, this must be {@code ++ * false}. ++ */ ++ boolean absolute() default false; + ++ /** ++ * @return If {@code false} (default), the counter is decremented when the annotated method ++ * returns, counting current invocations of the annotated method. If {@code true}, the counter ++ * increases monotonically, counting total invocations of the annotated method. ++ */ ++ boolean monotonic() default false; + } +--- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ExceptionMetered.java ++++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ExceptionMetered.java +@@ -9,57 +9,63 @@ import java.lang.annotation.Target; + + /** + * An annotation for marking a method of an annotated object as metered. +- *

+- * Given a method like this: ++ * ++ *

Given a method like this: ++ * + *


+  *     {@literal @}ExceptionMetered(name = "fancyName", cause=IllegalArgumentException.class)
+  *     public String fancyName(String name) {
+  *         return "Sir Captain " + name;
+  *     }
+  * 
+- *

+- * A meter for the defining class with the name {@code fancyName} will be created and each time the +- * {@code #fancyName(String)} throws an exception of type {@code cause} (or a subclass), the meter +- * will be marked. +- *

+- * A name for the metric can be specified as an annotation parameter, otherwise, the metric will be +- * named based on the method name. +- *

+- * For instance, given a declaration of ++ * ++ *

A meter for the defining class with the name {@code fancyName} will be created and each time ++ * the {@code #fancyName(String)} throws an exception of type {@code cause} (or a subclass), the ++ * meter will be marked. ++ * ++ *

A name for the metric can be specified as an annotation parameter, otherwise, the metric will ++ * be named based on the method name. ++ * ++ *

For instance, given a declaration of ++ * + *


+  *     {@literal @}ExceptionMetered
+  *     public String fancyName(String name) {
+  *         return "Sir Captain " + name;
+  *     }
+  * 
+- *

+- * A meter named {@code fancyName.exceptions} will be created and marked every time an exception is +- * thrown. ++ * ++ *

A meter named {@code fancyName.exceptions} will be created and marked every time an exception ++ * is thrown. + */ + @Inherited + @Documented + @Retention(RetentionPolicy.RUNTIME) +-@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) ++@Target({ ++ ElementType.TYPE, ++ ElementType.CONSTRUCTOR, ++ ElementType.METHOD, ++ ElementType.ANNOTATION_TYPE ++}) + public @interface ExceptionMetered { +- /** +- * The default suffix for meter names. +- */ +- String DEFAULT_NAME_SUFFIX = "exceptions"; ++ /** The default suffix for meter names. */ ++ String DEFAULT_NAME_SUFFIX = "exceptions"; + +- /** +- * @return The name of the meter. If not specified, the meter will be given a name based on the method +- * it decorates and the suffix "Exceptions". +- */ +- String name() default ""; ++ /** ++ * @return The name of the meter. If not specified, the meter will be given a name based on the ++ * method it decorates and the suffix "Exceptions". ++ */ ++ String name() default ""; + +- /** +- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name +- * relative to the annotated class. When annotating a class, this must be {@code false}. +- */ +- boolean absolute() default false; ++ /** ++ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the ++ * given name relative to the annotated class. When annotating a class, this must be {@code ++ * false}. ++ */ ++ boolean absolute() default false; + +- /** +- * @return The type of exceptions that the meter will catch and count. +- */ +- Class cause() default Exception.class; ++ /** ++ * @return The type of exceptions that the meter will catch and count. ++ */ ++ Class cause() default Exception.class; + } +--- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Gauge.java ++++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Gauge.java +@@ -7,29 +7,30 @@ import java.lang.annotation.Target; + + /** + * An annotation for marking a method of an annotated object as a gauge. +- *

+- * Given a method like this: ++ * ++ *

Given a method like this: ++ * + *


+  *     {@literal @}Gauge(name = "queueSize")
+  *     public int getQueueSize() {
+  *         return queue.size;
+  *     }
+  * 
+- *

+- * A gauge for the defining class with the name {@code queueSize} will be created which uses the ++ * ++ *

A gauge for the defining class with the name {@code queueSize} will be created which uses the + * annotated method's return value as its value. + */ + @Retention(RetentionPolicy.RUNTIME) +-@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) ++@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) + public @interface Gauge { +- /** +- * @return The gauge's name. +- */ +- String name() default ""; ++ /** ++ * @return The gauge's name. ++ */ ++ String name() default ""; + +- /** +- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name +- * relative to the annotated class. +- */ +- boolean absolute() default false; ++ /** ++ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the ++ * given name relative to the annotated class. ++ */ ++ boolean absolute() default false; + } +--- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Metered.java ++++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Metered.java +@@ -9,31 +9,38 @@ import java.lang.annotation.Target; + + /** + * An annotation for marking a method of an annotated object as metered. +- *

+- * Given a method like this: ++ * ++ *

Given a method like this: ++ * + *


+  *     {@literal @}Metered(name = "fancyName")
+  *     public String fancyName(String name) {
+  *         return "Sir Captain " + name;
+  *     }
+  * 
+- *

+- * A meter for the defining class with the name {@code fancyName} will be created and each time the +- * {@code #fancyName(String)} method is invoked, the meter will be marked. ++ * ++ *

A meter for the defining class with the name {@code fancyName} will be created and each time ++ * the {@code #fancyName(String)} method is invoked, the meter will be marked. + */ + @Inherited + @Documented + @Retention(RetentionPolicy.RUNTIME) +-@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) ++@Target({ ++ ElementType.TYPE, ++ ElementType.CONSTRUCTOR, ++ ElementType.METHOD, ++ ElementType.ANNOTATION_TYPE ++}) + public @interface Metered { +- /** +- * @return The name of the meter. +- */ +- String name() default ""; ++ /** ++ * @return The name of the meter. ++ */ ++ String name() default ""; + +- /** +- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name +- * relative to the annotated class. When annotating a class, this must be {@code false}. +- */ +- boolean absolute() default false; ++ /** ++ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the ++ * given name relative to the annotated class. When annotating a class, this must be {@code ++ * false}. ++ */ ++ boolean absolute() default false; + } +--- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Metric.java ++++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Metric.java +@@ -8,41 +8,41 @@ import java.lang.annotation.Target; + /** + * An annotation requesting that a metric be injected or registered. + * +- *

+- * Given a field like this: ++ *

Given a field like this: ++ * + *


+  *     {@literal @}Metric
+  *     public Histogram histogram;
+  * 
+- *

+- * A meter of the field's type will be created and injected into managed objects. +- * It will be up to the user to interact with the metric. This annotation +- * can be used on fields of type Meter, Timer, Counter, and Histogram. + * +- *

+- * This may also be used to register a metric, which is useful for creating a histogram with +- * a custom Reservoir. ++ *

A meter of the field's type will be created and injected into managed objects. It will be up ++ * to the user to interact with the metric. This annotation can be used on fields of type Meter, ++ * Timer, Counter, and Histogram. ++ * ++ *

This may also be used to register a metric, which is useful for creating a histogram with a ++ * custom Reservoir. ++ * + *


+  *     {@literal @}Metric
+  *     public Histogram uniformHistogram = new Histogram(new UniformReservoir());
+  * 
++ * + *

+ * + * @since 3.1 + */ + @Retention(RetentionPolicy.RUNTIME) +-@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) ++@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE}) + public @interface Metric { + +- /** +- * @return The name of the metric. +- */ +- String name() default ""; +- +- /** +- * @return If {@code true}, use the given name as an absolute name. If {@code false}, +- * use the given name relative to the annotated class. +- */ +- boolean absolute() default false; ++ /** ++ * @return The name of the metric. ++ */ ++ String name() default ""; + ++ /** ++ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the ++ * given name relative to the annotated class. ++ */ ++ boolean absolute() default false; + } +--- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ResponseMetered.java ++++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ResponseMetered.java +@@ -9,37 +9,44 @@ import java.lang.annotation.Target; + + /** + * An annotation for marking a method of an annotated object as metered. +- *

+- * Given a method like this: ++ * ++ *

Given a method like this: ++ * + *


+  *     {@literal @}ResponseMetered(name = "fancyName", level = ResponseMeteredLevel.ALL)
+  *     public String fancyName(String name) {
+  *         return "Sir Captain " + name;
+  *     }
+  * 
+- *

+- * Meters for the defining class with the name {@code fancyName} will be created for response codes +- * based on the ResponseMeteredLevel selected. Each time the {@code #fancyName(String)} method is invoked, +- * the appropriate response meter will be marked. ++ * ++ *

Meters for the defining class with the name {@code fancyName} will be created for response ++ * codes based on the ResponseMeteredLevel selected. Each time the {@code #fancyName(String)} method ++ * is invoked, the appropriate response meter will be marked. + */ + @Inherited + @Documented + @Retention(RetentionPolicy.RUNTIME) +-@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) ++@Target({ ++ ElementType.TYPE, ++ ElementType.CONSTRUCTOR, ++ ElementType.METHOD, ++ ElementType.ANNOTATION_TYPE ++}) + public @interface ResponseMetered { +- /** +- * @return The name of the meter. +- */ +- String name() default ""; ++ /** ++ * @return The name of the meter. ++ */ ++ String name() default ""; + +- /** +- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name +- * relative to the annotated class. When annotating a class, this must be {@code false}. +- */ +- boolean absolute() default false; ++ /** ++ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the ++ * given name relative to the annotated class. When annotating a class, this must be {@code ++ * false}. ++ */ ++ boolean absolute() default false; + +- /** +- * @return the ResponseMeteredLevel which decides which response code meters are marked. +- */ +- ResponseMeteredLevel level() default ResponseMeteredLevel.COARSE; ++ /** ++ * @return the ResponseMeteredLevel which decides which response code meters are marked. ++ */ ++ ResponseMeteredLevel level() default ResponseMeteredLevel.COARSE; + } +--- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ResponseMeteredLevel.java ++++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ResponseMeteredLevel.java +@@ -1,23 +1,19 @@ + package io.dropwizard.metrics5.annotation; + + /** +- * {@link ResponseMeteredLevel} is a parameter for the {@link ResponseMetered} annotation. +- * The constants of this enumerated type decide what meters are included when a class +- * or method is annotated with the {@link ResponseMetered} annotation. ++ * {@link ResponseMeteredLevel} is a parameter for the {@link ResponseMetered} annotation. The ++ * constants of this enumerated type decide what meters are included when a class or method is ++ * annotated with the {@link ResponseMetered} annotation. + */ + public enum ResponseMeteredLevel { +- /** +- * Include meters for 1xx/2xx/3xx/4xx/5xx responses +- */ +- COARSE, ++ /** Include meters for 1xx/2xx/3xx/4xx/5xx responses */ ++ COARSE, + +- /** +- * Include meters for every response code (200, 201, 303, 304, 401, 404, 501, etc.) +- */ +- DETAILED, ++ /** Include meters for every response code (200, 201, 303, 304, 401, 404, 501, etc.) */ ++ DETAILED, + +- /** +- * Include meters for every response code in addition to top level 1xx/2xx/3xx/4xx/5xx responses +- */ +- ALL; ++ /** ++ * Include meters for every response code in addition to top level 1xx/2xx/3xx/4xx/5xx responses ++ */ ++ ALL; + } +--- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Timed.java ++++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Timed.java +@@ -9,31 +9,38 @@ import java.lang.annotation.Target; + + /** + * An annotation for marking a method of an annotated object as timed. +- *

+- * Given a method like this: ++ * ++ *

Given a method like this: ++ * + *


+  *     {@literal @}Timed(name = "fancyName")
+  *     public String fancyName(String name) {
+  *         return "Sir Captain " + name;
+  *     }
+  * 
+- *

+- * A timer for the defining class with the name {@code fancyName} will be created and each time the +- * {@code #fancyName(String)} method is invoked, the method's execution will be timed. ++ * ++ *

A timer for the defining class with the name {@code fancyName} will be created and each time ++ * the {@code #fancyName(String)} method is invoked, the method's execution will be timed. + */ + @Inherited + @Documented + @Retention(RetentionPolicy.RUNTIME) +-@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) ++@Target({ ++ ElementType.TYPE, ++ ElementType.CONSTRUCTOR, ++ ElementType.METHOD, ++ ElementType.ANNOTATION_TYPE ++}) + public @interface Timed { +- /** +- * @return The name of the timer. +- */ +- String name() default ""; ++ /** ++ * @return The name of the timer. ++ */ ++ String name() default ""; + +- /** +- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name +- * relative to the annotated class. When annotating a class, this must be {@code false}. +- */ +- boolean absolute() default false; ++ /** ++ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the ++ * given name relative to the annotated class. When annotating a class, this must be {@code ++ * false}. ++ */ ++ boolean absolute() default false; + } +--- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/CachedGaugeBenchmark.java ++++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/CachedGaugeBenchmark.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics5.benchmarks; + + import io.dropwizard.metrics5.CachedGauge; ++import java.util.concurrent.TimeUnit; + import org.openjdk.jmh.annotations.Benchmark; + import org.openjdk.jmh.annotations.Scope; + import org.openjdk.jmh.annotations.State; +@@ -10,37 +11,37 @@ import org.openjdk.jmh.runner.RunnerException; + import org.openjdk.jmh.runner.options.Options; + import org.openjdk.jmh.runner.options.OptionsBuilder; + +-import java.util.concurrent.TimeUnit; +- + @State(Scope.Benchmark) + public class CachedGaugeBenchmark { + +- private CachedGauge cachedGauge = new CachedGauge(100, TimeUnit.MILLISECONDS) { ++ private CachedGauge cachedGauge = ++ new CachedGauge(100, TimeUnit.MILLISECONDS) { + @Override + protected Integer loadValue() { +- try { +- Thread.sleep(10); +- } catch (InterruptedException e) { +- throw new RuntimeException("Thread was interrupted", e); +- } +- return 12345; ++ try { ++ Thread.sleep(10); ++ } catch (InterruptedException e) { ++ throw new RuntimeException("Thread was interrupted", e); ++ } ++ return 12345; + } +- }; ++ }; + +- @Benchmark +- public void perfGetValue(Blackhole blackhole) { +- blackhole.consume(cachedGauge.getValue()); +- } ++ @Benchmark ++ public void perfGetValue(Blackhole blackhole) { ++ blackhole.consume(cachedGauge.getValue()); ++ } + +- public static void main(String[] args) throws RunnerException { +- Options opt = new OptionsBuilder() +- .include(".*" + CachedGaugeBenchmark.class.getSimpleName() + ".*") +- .warmupIterations(3) +- .measurementIterations(5) +- .threads(4) +- .forks(1) +- .build(); ++ public static void main(String[] args) throws RunnerException { ++ Options opt = ++ new OptionsBuilder() ++ .include(".*" + CachedGaugeBenchmark.class.getSimpleName() + ".*") ++ .warmupIterations(3) ++ .measurementIterations(5) ++ .threads(4) ++ .forks(1) ++ .build(); + +- new Runner(opt).run(); +- } ++ new Runner(opt).run(); ++ } + } +--- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/CounterBenchmark.java ++++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/CounterBenchmark.java +@@ -12,27 +12,27 @@ import org.openjdk.jmh.runner.options.OptionsBuilder; + @State(Scope.Benchmark) + public class CounterBenchmark { + +- private final Counter counter = new Counter(); +- +- // It's intentionally not declared as final to avoid constant folding +- private long nextValue = 0xFBFBABBA; +- +- @Benchmark +- public Object perfIncrement() { +- counter.inc(nextValue); +- return counter; +- } +- +- public static void main(String[] args) throws RunnerException { +- Options opt = new OptionsBuilder() +- .include(".*" + CounterBenchmark.class.getSimpleName() + ".*") +- .warmupIterations(3) +- .measurementIterations(5) +- .threads(4) +- .forks(1) +- .build(); +- +- new Runner(opt).run(); +- } +- ++ private final Counter counter = new Counter(); ++ ++ // It's intentionally not declared as final to avoid constant folding ++ private long nextValue = 0xFBFBABBA; ++ ++ @Benchmark ++ public Object perfIncrement() { ++ counter.inc(nextValue); ++ return counter; ++ } ++ ++ public static void main(String[] args) throws RunnerException { ++ Options opt = ++ new OptionsBuilder() ++ .include(".*" + CounterBenchmark.class.getSimpleName() + ".*") ++ .warmupIterations(3) ++ .measurementIterations(5) ++ .threads(4) ++ .forks(1) ++ .build(); ++ ++ new Runner(opt).run(); ++ } + } +--- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/MeterBenchmark.java ++++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/MeterBenchmark.java +@@ -12,27 +12,27 @@ import org.openjdk.jmh.runner.options.OptionsBuilder; + @State(Scope.Benchmark) + public class MeterBenchmark { + +- private final Meter meter = new Meter(); +- +- // It's intentionally not declared as final to avoid constant folding +- private long nextValue = 0xFBFBABBA; +- +- @Benchmark +- public Object perfMark() { +- meter.mark(nextValue); +- return meter; +- } +- +- public static void main(String[] args) throws RunnerException { +- Options opt = new OptionsBuilder() +- .include(".*" + MeterBenchmark.class.getSimpleName() + ".*") +- .warmupIterations(3) +- .measurementIterations(5) +- .threads(4) +- .forks(1) +- .build(); +- +- new Runner(opt).run(); +- } +- ++ private final Meter meter = new Meter(); ++ ++ // It's intentionally not declared as final to avoid constant folding ++ private long nextValue = 0xFBFBABBA; ++ ++ @Benchmark ++ public Object perfMark() { ++ meter.mark(nextValue); ++ return meter; ++ } ++ ++ public static void main(String[] args) throws RunnerException { ++ Options opt = ++ new OptionsBuilder() ++ .include(".*" + MeterBenchmark.class.getSimpleName() + ".*") ++ .warmupIterations(3) ++ .measurementIterations(5) ++ .threads(4) ++ .forks(1) ++ .build(); ++ ++ new Runner(opt).run(); ++ } + } +--- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/ReservoirBenchmark.java ++++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/ReservoirBenchmark.java +@@ -7,6 +7,7 @@ import io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir; + import io.dropwizard.metrics5.SlidingTimeWindowReservoir; + import io.dropwizard.metrics5.SlidingWindowReservoir; + import io.dropwizard.metrics5.UniformReservoir; ++import java.util.concurrent.TimeUnit; + import org.openjdk.jmh.annotations.Benchmark; + import org.openjdk.jmh.annotations.Mode; + import org.openjdk.jmh.annotations.Scope; +@@ -18,59 +19,61 @@ import org.openjdk.jmh.runner.options.Options; + import org.openjdk.jmh.runner.options.OptionsBuilder; + import org.openjdk.jmh.runner.options.TimeValue; + +-import java.util.concurrent.TimeUnit; +- + @State(Scope.Benchmark) + public class ReservoirBenchmark { + +- private final UniformReservoir uniform = new UniformReservoir(); +- private final ExponentiallyDecayingReservoir exponential = new ExponentiallyDecayingReservoir(); +- private final Reservoir lockFreeExponential = LockFreeExponentiallyDecayingReservoir.builder().build(); +- private final SlidingWindowReservoir sliding = new SlidingWindowReservoir(1000); +- private final SlidingTimeWindowReservoir slidingTime = new SlidingTimeWindowReservoir(200, TimeUnit.MILLISECONDS); +- private final SlidingTimeWindowArrayReservoir arrTime = new SlidingTimeWindowArrayReservoir(200, TimeUnit.MILLISECONDS); ++ private final UniformReservoir uniform = new UniformReservoir(); ++ private final ExponentiallyDecayingReservoir exponential = new ExponentiallyDecayingReservoir(); ++ private final Reservoir lockFreeExponential = ++ LockFreeExponentiallyDecayingReservoir.builder().build(); ++ private final SlidingWindowReservoir sliding = new SlidingWindowReservoir(1000); ++ private final SlidingTimeWindowReservoir slidingTime = ++ new SlidingTimeWindowReservoir(200, TimeUnit.MILLISECONDS); ++ private final SlidingTimeWindowArrayReservoir arrTime = ++ new SlidingTimeWindowArrayReservoir(200, TimeUnit.MILLISECONDS); + +- // It's intentionally not declared as final to avoid constant folding +- private long nextValue = 0xFBFBABBA; ++ // It's intentionally not declared as final to avoid constant folding ++ private long nextValue = 0xFBFBABBA; + +- @Benchmark +- public Object perfUniformReservoir() { +- uniform.update(nextValue); +- return uniform; +- } ++ @Benchmark ++ public Object perfUniformReservoir() { ++ uniform.update(nextValue); ++ return uniform; ++ } + +- @Benchmark +- public Object perfSlidingTimeWindowArrayReservoir() { +- arrTime.update(nextValue); +- return arrTime; +- } ++ @Benchmark ++ public Object perfSlidingTimeWindowArrayReservoir() { ++ arrTime.update(nextValue); ++ return arrTime; ++ } + +- @Benchmark +- public Object perfExponentiallyDecayingReservoir() { +- exponential.update(nextValue); +- return exponential; +- } ++ @Benchmark ++ public Object perfExponentiallyDecayingReservoir() { ++ exponential.update(nextValue); ++ return exponential; ++ } + +- @Benchmark +- public Object perfSlidingWindowReservoir() { +- sliding.update(nextValue); +- return sliding; +- } ++ @Benchmark ++ public Object perfSlidingWindowReservoir() { ++ sliding.update(nextValue); ++ return sliding; ++ } + +- @Benchmark +- public Object perfSlidingTimeWindowReservoir() { +- slidingTime.update(nextValue); +- return slidingTime; +- } ++ @Benchmark ++ public Object perfSlidingTimeWindowReservoir() { ++ slidingTime.update(nextValue); ++ return slidingTime; ++ } + +- @Benchmark +- public Object perfLockFreeExponentiallyDecayingReservoir() { +- lockFreeExponential.update(nextValue); +- return lockFreeExponential; +- } ++ @Benchmark ++ public Object perfLockFreeExponentiallyDecayingReservoir() { ++ lockFreeExponential.update(nextValue); ++ return lockFreeExponential; ++ } + +- public static void main(String[] args) throws RunnerException { +- Options opt = new OptionsBuilder() ++ public static void main(String[] args) throws RunnerException { ++ Options opt = ++ new OptionsBuilder() + .include(".*" + ReservoirBenchmark.class.getSimpleName() + ".*") + .warmupIterations(10) + .measurementIterations(10) +@@ -82,7 +85,6 @@ public class ReservoirBenchmark { + .forks(1) + .build(); + +- new Runner(opt).run(); +- } +- ++ new Runner(opt).run(); ++ } + } +--- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java ++++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java +@@ -2,7 +2,7 @@ package io.dropwizard.metrics5.benchmarks; + + import io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir; + import io.dropwizard.metrics5.SlidingTimeWindowReservoir; +-import io.dropwizard.metrics5.Snapshot; ++import java.util.concurrent.TimeUnit; + import org.openjdk.jmh.annotations.Benchmark; + import org.openjdk.jmh.annotations.Group; + import org.openjdk.jmh.annotations.GroupThreads; +@@ -16,53 +16,52 @@ import org.openjdk.jmh.runner.options.Options; + import org.openjdk.jmh.runner.options.OptionsBuilder; + import org.openjdk.jmh.runner.options.TimeValue; + +-import java.util.concurrent.TimeUnit; +- + /** + * @author bstorozhuk + */ + @State(Scope.Benchmark) + public class SlidingTimeWindowReservoirsBenchmark { +- private final SlidingTimeWindowReservoir slidingTime = new SlidingTimeWindowReservoir(200, TimeUnit.MILLISECONDS); +- private final SlidingTimeWindowArrayReservoir arrTime = new SlidingTimeWindowArrayReservoir(200, TimeUnit.MILLISECONDS); ++ private final SlidingTimeWindowReservoir slidingTime = ++ new SlidingTimeWindowReservoir(200, TimeUnit.MILLISECONDS); ++ private final SlidingTimeWindowArrayReservoir arrTime = ++ new SlidingTimeWindowArrayReservoir(200, TimeUnit.MILLISECONDS); + +- // It's intentionally not declared as final to avoid constant folding +- private long nextValue = 0xFBFBABBA; ++ // It's intentionally not declared as final to avoid constant folding ++ private long nextValue = 0xFBFBABBA; + +- @Benchmark +- @Group("slidingTime") +- @GroupThreads(3) +- public Object slidingTimeAddMeasurement() { +- slidingTime.update(nextValue); +- return slidingTime; +- } ++ @Benchmark ++ @Group("slidingTime") ++ @GroupThreads(3) ++ public Object slidingTimeAddMeasurement() { ++ slidingTime.update(nextValue); ++ return slidingTime; ++ } + +- @Benchmark +- @Group("slidingTime") +- @GroupThreads(1) +- public Object slidingTimeRead() { +- Snapshot snapshot = slidingTime.getSnapshot(); +- return snapshot; +- } ++ @Benchmark ++ @Group("slidingTime") ++ @GroupThreads(1) ++ public Object slidingTimeRead() { ++ return slidingTime.getSnapshot(); ++ } + +- @Benchmark +- @Group("arrTime") +- @GroupThreads(3) +- public Object arrTimeAddMeasurement() { +- arrTime.update(nextValue); +- return slidingTime; +- } ++ @Benchmark ++ @Group("arrTime") ++ @GroupThreads(3) ++ public Object arrTimeAddMeasurement() { ++ arrTime.update(nextValue); ++ return slidingTime; ++ } + +- @Benchmark +- @Group("arrTime") +- @GroupThreads(1) +- public Object arrTimeRead() { +- Snapshot snapshot = arrTime.getSnapshot(); +- return snapshot; +- } ++ @Benchmark ++ @Group("arrTime") ++ @GroupThreads(1) ++ public Object arrTimeRead() { ++ return arrTime.getSnapshot(); ++ } + +- public static void main(String[] args) throws RunnerException { +- Options opt = new OptionsBuilder() ++ public static void main(String[] args) throws RunnerException { ++ Options opt = ++ new OptionsBuilder() + .include(".*" + SlidingTimeWindowReservoirsBenchmark.class.getSimpleName() + ".*") + .warmupIterations(10) + .measurementIterations(10) +@@ -73,7 +72,6 @@ public class SlidingTimeWindowReservoirsBenchmark { + .forks(1) + .build(); + +- new Runner(opt).run(); +- } ++ new Runner(opt).run(); ++ } + } +- +--- a/metrics-caffeine3/src/main/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounter.java ++++ b/metrics-caffeine3/src/main/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounter.java +@@ -15,6 +15,8 @@ + */ + package io.dropwizard.metrics5.caffeine3; + ++import static java.util.Objects.requireNonNull; ++ + import com.github.benmanes.caffeine.cache.RemovalCause; + import com.github.benmanes.caffeine.cache.stats.CacheStats; + import com.github.benmanes.caffeine.cache.stats.StatsCounter; +@@ -22,13 +24,10 @@ import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Histogram; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; +-import org.checkerframework.checker.index.qual.NonNegative; +- + import java.util.EnumMap; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.LongAdder; +- +-import static java.util.Objects.requireNonNull; ++import org.checkerframework.checker.index.qual.NonNegative; + + /** + * A {@link StatsCounter} instrumented with Dropwizard Metrics. +@@ -64,8 +63,7 @@ public final class MetricsStatsCounter implements StatsCounter { + evictionsWithCause = new EnumMap<>(RemovalCause.class); + for (RemovalCause cause : RemovalCause.values()) { + evictionsWithCause.put( +- cause, +- registry.histogram(MetricRegistry.name(metricsPrefix, "evictions", cause.name()))); ++ cause, registry.histogram(MetricRegistry.name(metricsPrefix, "evictions", cause.name()))); + } + } + +--- a/metrics-caffeine3/src/test/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounterTest.java ++++ b/metrics-caffeine3/src/test/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounterTest.java +@@ -15,19 +15,18 @@ + */ + package io.dropwizard.metrics5.caffeine3; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.junit.jupiter.api.Assertions.assertEquals; ++ + import com.github.benmanes.caffeine.cache.Caffeine; + import com.github.benmanes.caffeine.cache.LoadingCache; + import com.github.benmanes.caffeine.cache.RemovalCause; +-import com.google.errorprone.annotations.CanIgnoreReturnValue; + import io.dropwizard.metrics5.MetricRegistry; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertEquals; +- + /** +- * An example of exporting stats to Dropwizard Metrics. ++ * An example of exporting stats to Dropwizard Metrics. + * + * @author ben.manes@gmail.com (Ben Manes) + * @author John Karp +@@ -47,9 +46,10 @@ final class MetricsStatsCounterTest { + + @Test + void basicUsage() { +- LoadingCache cache = Caffeine.newBuilder() +- .recordStats(() -> new MetricsStatsCounter(registry, PREFIX)) +- .build(key -> key); ++ LoadingCache cache = ++ Caffeine.newBuilder() ++ .recordStats(() -> new MetricsStatsCounter(registry, PREFIX)) ++ .build(key -> key); + + // Perform application work + for (int i = 0; i < 4; i++) { +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java +@@ -1,5 +1,21 @@ + package io.dropwizard.metrics5.collectd; + ++import static com.google.common.base.Preconditions.checkArgument; ++import static io.dropwizard.metrics5.MetricAttribute.COUNT; ++import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; ++import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; ++import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; ++import static io.dropwizard.metrics5.MetricAttribute.MEAN; ++import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; ++import static io.dropwizard.metrics5.MetricAttribute.P50; ++import static io.dropwizard.metrics5.MetricAttribute.P75; ++import static io.dropwizard.metrics5.MetricAttribute.P95; ++import static io.dropwizard.metrics5.MetricAttribute.P98; ++import static io.dropwizard.metrics5.MetricAttribute.P99; ++import static io.dropwizard.metrics5.MetricAttribute.P999; ++import static io.dropwizard.metrics5.MetricAttribute.STDDEV; ++ ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -12,326 +28,337 @@ import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.ScheduledReporter; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; +- + import java.io.IOException; + import java.net.InetAddress; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.MetricAttribute.COUNT; +-import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MAX; +-import static io.dropwizard.metrics5.MetricAttribute.MEAN; +-import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; +-import static io.dropwizard.metrics5.MetricAttribute.P50; +-import static io.dropwizard.metrics5.MetricAttribute.P75; +-import static io.dropwizard.metrics5.MetricAttribute.P95; +-import static io.dropwizard.metrics5.MetricAttribute.P98; +-import static io.dropwizard.metrics5.MetricAttribute.P99; +-import static io.dropwizard.metrics5.MetricAttribute.P999; +-import static io.dropwizard.metrics5.MetricAttribute.STDDEV; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + + /** + * A reporter which publishes metric values to a Collectd server. + * +- * @see collectd – The system statistics +- * collection daemon ++ * @see collectd – The system statistics collection daemon + */ + public class CollectdReporter extends ScheduledReporter { + +- /** +- * Returns a builder for the specified registry. +- *

+- * The default settings are: +- *

    +- *
  • hostName: InetAddress.getLocalHost().getHostName()
  • +- *
  • executor: default executor created by {@code ScheduledReporter}
  • +- *
  • shutdownExecutorOnStop: true
  • +- *
  • clock: Clock.defaultClock()
  • +- *
  • rateUnit: TimeUnit.SECONDS
  • +- *
  • durationUnit: TimeUnit.MILLISECONDS
  • +- *
  • filter: MetricFilter.ALL
  • +- *
  • securityLevel: NONE
  • +- *
  • username: ""
  • +- *
  • password: ""
  • +- *
+- */ +- public static Builder forRegistry(MetricRegistry registry) { +- return new Builder(registry); ++ /** ++ * Returns a builder for the specified registry. ++ * ++ *

The default settings are: ++ * ++ *

    ++ *
  • hostName: InetAddress.getLocalHost().getHostName() ++ *
  • executor: default executor created by {@code ScheduledReporter} ++ *
  • shutdownExecutorOnStop: true ++ *
  • clock: Clock.defaultClock() ++ *
  • rateUnit: TimeUnit.SECONDS ++ *
  • durationUnit: TimeUnit.MILLISECONDS ++ *
  • filter: MetricFilter.ALL ++ *
  • securityLevel: NONE ++ *
  • username: "" ++ *
  • password: "" ++ *
++ */ ++ public static Builder forRegistry(MetricRegistry registry) { ++ return new Builder(registry); ++ } ++ ++ public static class Builder { ++ ++ private final MetricRegistry registry; ++ private String hostName; ++ private ScheduledExecutorService executor; ++ private boolean shutdownExecutorOnStop = true; ++ private Clock clock = Clock.defaultClock(); ++ private TimeUnit rateUnit = TimeUnit.SECONDS; ++ private TimeUnit durationUnit = TimeUnit.MILLISECONDS; ++ private MetricFilter filter = MetricFilter.ALL; ++ private SecurityLevel securityLevel = SecurityLevel.NONE; ++ private String username = ""; ++ private String password = ""; ++ private Set disabledMetricAttributes = ImmutableSet.of(); ++ private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; ++ ++ private Builder(MetricRegistry registry) { ++ this.registry = registry; + } + +- public static class Builder { +- +- private final MetricRegistry registry; +- private String hostName; +- private ScheduledExecutorService executor; +- private boolean shutdownExecutorOnStop = true; +- private Clock clock = Clock.defaultClock(); +- private TimeUnit rateUnit = TimeUnit.SECONDS; +- private TimeUnit durationUnit = TimeUnit.MILLISECONDS; +- private MetricFilter filter = MetricFilter.ALL; +- private SecurityLevel securityLevel = SecurityLevel.NONE; +- private String username = ""; +- private String password = ""; +- private Set disabledMetricAttributes = Collections.emptySet(); +- private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; +- +- private Builder(MetricRegistry registry) { +- this.registry = registry; +- } +- +- public Builder withHostName(String hostName) { +- this.hostName = hostName; +- return this; +- } +- +- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { +- this.shutdownExecutorOnStop = shutdownExecutorOnStop; +- return this; +- } +- +- public Builder scheduleOn(ScheduledExecutorService executor) { +- this.executor = executor; +- return this; +- } +- +- public Builder withClock(Clock clock) { +- this.clock = clock; +- return this; +- } +- +- public Builder convertRatesTo(TimeUnit rateUnit) { +- this.rateUnit = rateUnit; +- return this; +- } +- +- public Builder convertDurationsTo(TimeUnit durationUnit) { +- this.durationUnit = durationUnit; +- return this; +- } +- +- public Builder filter(MetricFilter filter) { +- this.filter = filter; +- return this; +- } +- +- public Builder withUsername(String username) { +- this.username = username; +- return this; +- } +- +- public Builder withPassword(String password) { +- this.password = password; +- return this; +- } +- +- public Builder withSecurityLevel(SecurityLevel securityLevel) { +- this.securityLevel = securityLevel; +- return this; +- } +- +- public Builder disabledMetricAttributes(Set attributes) { +- this.disabledMetricAttributes = attributes; +- return this; +- } +- +- public Builder withMaxLength(int maxLength) { +- this.maxLength = maxLength; +- return this; +- } +- +- public CollectdReporter build(Sender sender) { +- if (securityLevel != SecurityLevel.NONE) { +- if (username.isEmpty()) { +- throw new IllegalArgumentException("username is required for securityLevel: " + securityLevel); +- } +- if (password.isEmpty()) { +- throw new IllegalArgumentException("password is required for securityLevel: " + securityLevel); +- } +- } +- return new CollectdReporter(registry, +- hostName, sender, +- executor, shutdownExecutorOnStop, +- clock, rateUnit, durationUnit, +- filter, disabledMetricAttributes, +- username, password, securityLevel, new Sanitize(maxLength)); +- } ++ public Builder withHostName(String hostName) { ++ this.hostName = hostName; ++ return this; + } + +- private static final Logger LOG = LoggerFactory.getLogger(CollectdReporter.class); +- private static final String REPORTER_NAME = "collectd-reporter"; +- private static final String FALLBACK_HOST_NAME = "localhost"; +- private static final String COLLECTD_TYPE_GAUGE = "gauge"; +- +- private String hostName; +- private final Sender sender; +- private final Clock clock; +- private long period; +- private final PacketWriter writer; +- private final Sanitize sanitize; +- +- private CollectdReporter(MetricRegistry registry, +- String hostname, Sender sender, +- ScheduledExecutorService executor, boolean shutdownExecutorOnStop, +- Clock clock, TimeUnit rateUnit, TimeUnit durationUnit, +- MetricFilter filter, Set disabledMetricAttributes, +- String username, String password, +- SecurityLevel securityLevel, Sanitize sanitize) { +- super(registry, REPORTER_NAME, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, +- disabledMetricAttributes); +- this.hostName = (hostname != null) ? hostname : resolveHostName(); +- this.sender = sender; +- this.clock = clock; +- this.sanitize = sanitize; +- writer = new PacketWriter(sender, username, password, securityLevel); ++ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { ++ this.shutdownExecutorOnStop = shutdownExecutorOnStop; ++ return this; + } + +- private String resolveHostName() { +- try { +- return InetAddress.getLocalHost().getHostName(); +- } catch (Exception e) { +- LOG.error("Failed to lookup local host name: {}", e.getMessage(), e); +- return FALLBACK_HOST_NAME; +- } ++ public Builder scheduleOn(ScheduledExecutorService executor) { ++ this.executor = executor; ++ return this; + } + +- @Override +- public void start(long period, TimeUnit unit) { +- this.period = period; +- super.start(period, unit); ++ public Builder withClock(Clock clock) { ++ this.clock = clock; ++ return this; + } + +- @Override +- public void report(SortedMap> gauges, SortedMap counters, +- SortedMap histograms, SortedMap meters, +- SortedMap timers) { +- MetaData.Builder metaData = new MetaData.Builder(sanitize, hostName, clock.getTime() / 1000, period) +- .type(COLLECTD_TYPE_GAUGE); +- try { +- connect(sender); +- for (Map.Entry> entry : gauges.entrySet()) { +- serializeGauge(metaData.plugin(entry.getKey().getKey()), entry.getValue()); +- } +- for (Map.Entry entry : counters.entrySet()) { +- serializeCounter(metaData.plugin(entry.getKey().getKey()), entry.getValue()); +- } +- for (Map.Entry entry : histograms.entrySet()) { +- serializeHistogram(metaData.plugin(entry.getKey().getKey()), entry.getValue()); +- } +- for (Map.Entry entry : meters.entrySet()) { +- serializeMeter(metaData.plugin(entry.getKey().getKey()), entry.getValue()); +- } +- for (Map.Entry entry : timers.entrySet()) { +- serializeTimer(metaData.plugin(entry.getKey().getKey()), entry.getValue()); +- } +- } catch (IOException e) { +- LOG.warn("Unable to report to Collectd", e); +- } finally { +- disconnect(sender); +- } ++ public Builder convertRatesTo(TimeUnit rateUnit) { ++ this.rateUnit = rateUnit; ++ return this; + } + +- private void connect(Sender sender) throws IOException { +- if (!sender.isConnected()) { +- sender.connect(); +- } ++ public Builder convertDurationsTo(TimeUnit durationUnit) { ++ this.durationUnit = durationUnit; ++ return this; + } + +- private void disconnect(Sender sender) { +- try { +- sender.disconnect(); +- } catch (Exception e) { +- LOG.warn("Error disconnecting from Collectd", e); +- } ++ public Builder filter(MetricFilter filter) { ++ this.filter = filter; ++ return this; + } + +- private void writeValue(MetaData.Builder metaData, MetricAttribute attribute, Number value) { +- if (!getDisabledMetricAttributes().contains(attribute)) { +- write(metaData.typeInstance(attribute.getCode()).get(), value); +- } ++ public Builder withUsername(String username) { ++ this.username = username; ++ return this; + } + +- private void writeRate(MetaData.Builder metaData, MetricAttribute attribute, double rate) { +- writeValue(metaData, attribute, convertRate(rate)); ++ public Builder withPassword(String password) { ++ this.password = password; ++ return this; + } + +- private void writeDuration(MetaData.Builder metaData, MetricAttribute attribute, double duration) { +- writeValue(metaData, attribute, convertDuration(duration)); ++ public Builder withSecurityLevel(SecurityLevel securityLevel) { ++ this.securityLevel = securityLevel; ++ return this; + } + +- private void write(MetaData metaData, Number value) { +- try { +- writer.write(metaData, value); +- } catch (RuntimeException e) { +- LOG.warn("Failed to process metric '" + metaData.getPlugin() + "': " + e.getMessage()); +- } catch (IOException e) { +- LOG.error("Failed to send metric to collectd", e); +- } ++ public Builder disabledMetricAttributes(Set attributes) { ++ this.disabledMetricAttributes = attributes; ++ return this; + } + +- private void serializeGauge(MetaData.Builder metaData, Gauge metric) { +- if (metric.getValue() instanceof Number) { +- write(metaData.typeInstance("value").get(), (Number) metric.getValue()); +- } else if (metric.getValue() instanceof Boolean) { +- write(metaData.typeInstance("value").get(), ((Boolean) metric.getValue()) ? 1 : 0); +- } else { +- LOG.warn("Failed to process metric '{}'. Unsupported gauge of type: {} ", metaData.get().getPlugin(), +- metric.getValue().getClass().getName()); +- } ++ public Builder withMaxLength(int maxLength) { ++ this.maxLength = maxLength; ++ return this; + } + +- private void serializeMeter(MetaData.Builder metaData, Meter metric) { +- writeValue(metaData, COUNT, (double) metric.getCount()); +- writeRate(metaData, M1_RATE, metric.getOneMinuteRate()); +- writeRate(metaData, M5_RATE, metric.getFiveMinuteRate()); +- writeRate(metaData, M15_RATE, metric.getFifteenMinuteRate()); +- writeRate(metaData, MEAN_RATE, metric.getMeanRate()); ++ public CollectdReporter build(Sender sender) { ++ if (securityLevel != SecurityLevel.NONE) { ++ checkArgument( ++ !username.isEmpty(), "username is required for securityLevel: %s", securityLevel); ++ checkArgument( ++ !password.isEmpty(), "password is required for securityLevel: %s", securityLevel); ++ } ++ return new CollectdReporter( ++ registry, ++ hostName, ++ sender, ++ executor, ++ shutdownExecutorOnStop, ++ clock, ++ rateUnit, ++ durationUnit, ++ filter, ++ disabledMetricAttributes, ++ username, ++ password, ++ securityLevel, ++ new Sanitize(maxLength)); ++ } ++ } ++ ++ private static final Logger LOG = LoggerFactory.getLogger(CollectdReporter.class); ++ private static final String REPORTER_NAME = "collectd-reporter"; ++ private static final String FALLBACK_HOST_NAME = "localhost"; ++ private static final String COLLECTD_TYPE_GAUGE = "gauge"; ++ ++ private String hostName; ++ private final Sender sender; ++ private final Clock clock; ++ private long period; ++ private final PacketWriter writer; ++ private final Sanitize sanitize; ++ ++ private CollectdReporter( ++ MetricRegistry registry, ++ String hostname, ++ Sender sender, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Clock clock, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ MetricFilter filter, ++ Set disabledMetricAttributes, ++ String username, ++ String password, ++ SecurityLevel securityLevel, ++ Sanitize sanitize) { ++ super( ++ registry, ++ REPORTER_NAME, ++ filter, ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes); ++ this.hostName = (hostname != null) ? hostname : resolveHostName(); ++ this.sender = sender; ++ this.clock = clock; ++ this.sanitize = sanitize; ++ writer = new PacketWriter(sender, username, password, securityLevel); ++ } ++ ++ private String resolveHostName() { ++ try { ++ return InetAddress.getLocalHost().getHostName(); ++ } catch (Exception e) { ++ LOG.error("Failed to lookup local host name: {}", e.getMessage(), e); ++ return FALLBACK_HOST_NAME; ++ } ++ } ++ ++ @Override ++ public void start(long period, TimeUnit unit) { ++ this.period = period; ++ super.start(period, unit); ++ } ++ ++ @Override ++ public void report( ++ SortedMap> gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ MetaData.Builder metaData = ++ new MetaData.Builder(sanitize, hostName, clock.getTime() / 1000, period) ++ .type(COLLECTD_TYPE_GAUGE); ++ try { ++ connect(sender); ++ for (Map.Entry> entry : gauges.entrySet()) { ++ serializeGauge(metaData.plugin(entry.getKey().getKey()), entry.getValue()); ++ } ++ for (Map.Entry entry : counters.entrySet()) { ++ serializeCounter(metaData.plugin(entry.getKey().getKey()), entry.getValue()); ++ } ++ for (Map.Entry entry : histograms.entrySet()) { ++ serializeHistogram(metaData.plugin(entry.getKey().getKey()), entry.getValue()); ++ } ++ for (Map.Entry entry : meters.entrySet()) { ++ serializeMeter(metaData.plugin(entry.getKey().getKey()), entry.getValue()); ++ } ++ for (Map.Entry entry : timers.entrySet()) { ++ serializeTimer(metaData.plugin(entry.getKey().getKey()), entry.getValue()); ++ } ++ } catch (IOException e) { ++ LOG.warn("Unable to report to Collectd", e); ++ } finally { ++ disconnect(sender); + } ++ } + +- private void serializeCounter(MetaData.Builder metaData, Counter metric) { +- writeValue(metaData, COUNT, (double) metric.getCount()); ++ private void connect(Sender sender) throws IOException { ++ if (!sender.isConnected()) { ++ sender.connect(); + } ++ } + +- private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { +- final Snapshot snapshot = metric.getSnapshot(); +- writeValue(metaData, COUNT, (double) metric.getCount()); +- writeValue(metaData, MAX, (double) snapshot.getMax()); +- writeValue(metaData, MEAN, snapshot.getMean()); +- writeValue(metaData, MIN, (double) snapshot.getMin()); +- writeValue(metaData, STDDEV, snapshot.getStdDev()); +- writeValue(metaData, P50, snapshot.getMedian()); +- writeValue(metaData, P75, snapshot.get75thPercentile()); +- writeValue(metaData, P95, snapshot.get95thPercentile()); +- writeValue(metaData, P98, snapshot.get98thPercentile()); +- writeValue(metaData, P99, snapshot.get99thPercentile()); +- writeValue(metaData, P999, snapshot.get999thPercentile()); ++ private void disconnect(Sender sender) { ++ try { ++ sender.disconnect(); ++ } catch (Exception e) { ++ LOG.warn("Error disconnecting from Collectd", e); + } ++ } + +- private void serializeTimer(MetaData.Builder metaData, Timer metric) { +- final Snapshot snapshot = metric.getSnapshot(); +- writeValue(metaData, COUNT, (double) metric.getCount()); +- writeDuration(metaData, MAX, (double) snapshot.getMax()); +- writeDuration(metaData, MEAN, snapshot.getMean()); +- writeDuration(metaData, MIN, (double) snapshot.getMin()); +- writeDuration(metaData, STDDEV, snapshot.getStdDev()); +- writeDuration(metaData, P50, snapshot.getMedian()); +- writeDuration(metaData, P75, snapshot.get75thPercentile()); +- writeDuration(metaData, P95, snapshot.get95thPercentile()); +- writeDuration(metaData, P98, snapshot.get98thPercentile()); +- writeDuration(metaData, P99, snapshot.get99thPercentile()); +- writeDuration(metaData, P999, snapshot.get999thPercentile()); +- writeRate(metaData, M1_RATE, metric.getOneMinuteRate()); +- writeRate(metaData, M5_RATE, metric.getFiveMinuteRate()); +- writeRate(metaData, M15_RATE, metric.getFifteenMinuteRate()); +- writeRate(metaData, MEAN_RATE, metric.getMeanRate()); ++ private void writeValue(MetaData.Builder metaData, MetricAttribute attribute, Number value) { ++ if (!getDisabledMetricAttributes().contains(attribute)) { ++ write(metaData.typeInstance(attribute.getCode()).get(), value); ++ } ++ } ++ ++ private void writeRate(MetaData.Builder metaData, MetricAttribute attribute, double rate) { ++ writeValue(metaData, attribute, convertRate(rate)); ++ } ++ ++ private void writeDuration( ++ MetaData.Builder metaData, MetricAttribute attribute, double duration) { ++ writeValue(metaData, attribute, convertDuration(duration)); ++ } ++ ++ private void write(MetaData metaData, Number value) { ++ try { ++ writer.write(metaData, value); ++ } catch (RuntimeException e) { ++ LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage()); ++ } catch (IOException e) { ++ LOG.error("Failed to send metric to collectd", e); ++ } ++ } ++ ++ private void serializeGauge(MetaData.Builder metaData, Gauge metric) { ++ if (metric.getValue() instanceof Number) { ++ write(metaData.typeInstance("value").get(), (Number) metric.getValue()); ++ } else if (metric.getValue() instanceof Boolean) { ++ write(metaData.typeInstance("value").get(), ((Boolean) metric.getValue()) ? 1 : 0); ++ } else { ++ LOG.warn( ++ "Failed to process metric '{}'. Unsupported gauge of type: {} ", ++ metaData.get().getPlugin(), ++ metric.getValue().getClass().getName()); + } ++ } ++ ++ private void serializeMeter(MetaData.Builder metaData, Meter metric) { ++ writeValue(metaData, COUNT, (double) metric.getCount()); ++ writeRate(metaData, M1_RATE, metric.getOneMinuteRate()); ++ writeRate(metaData, M5_RATE, metric.getFiveMinuteRate()); ++ writeRate(metaData, M15_RATE, metric.getFifteenMinuteRate()); ++ writeRate(metaData, MEAN_RATE, metric.getMeanRate()); ++ } ++ ++ private void serializeCounter(MetaData.Builder metaData, Counter metric) { ++ writeValue(metaData, COUNT, (double) metric.getCount()); ++ } ++ ++ private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { ++ final Snapshot snapshot = metric.getSnapshot(); ++ writeValue(metaData, COUNT, (double) metric.getCount()); ++ writeValue(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); ++ writeValue(metaData, MEAN, snapshot.getMean()); ++ writeValue(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); ++ writeValue(metaData, STDDEV, snapshot.getStdDev()); ++ writeValue(metaData, P50, snapshot.getMedian()); ++ writeValue(metaData, P75, snapshot.get75thPercentile()); ++ writeValue(metaData, P95, snapshot.get95thPercentile()); ++ writeValue(metaData, P98, snapshot.get98thPercentile()); ++ writeValue(metaData, P99, snapshot.get99thPercentile()); ++ writeValue(metaData, P999, snapshot.get999thPercentile()); ++ } ++ ++ private void serializeTimer(MetaData.Builder metaData, Timer metric) { ++ final Snapshot snapshot = metric.getSnapshot(); ++ writeValue(metaData, COUNT, (double) metric.getCount()); ++ writeDuration(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); ++ writeDuration(metaData, MEAN, snapshot.getMean()); ++ writeDuration(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); ++ writeDuration(metaData, STDDEV, snapshot.getStdDev()); ++ writeDuration(metaData, P50, snapshot.getMedian()); ++ writeDuration(metaData, P75, snapshot.get75thPercentile()); ++ writeDuration(metaData, P95, snapshot.get95thPercentile()); ++ writeDuration(metaData, P98, snapshot.get98thPercentile()); ++ writeDuration(metaData, P99, snapshot.get99thPercentile()); ++ writeDuration(metaData, P999, snapshot.get999thPercentile()); ++ writeRate(metaData, M1_RATE, metric.getOneMinuteRate()); ++ writeRate(metaData, M5_RATE, metric.getFiveMinuteRate()); ++ writeRate(metaData, M15_RATE, metric.getFifteenMinuteRate()); ++ writeRate(metaData, MEAN_RATE, metric.getMeanRate()); ++ } + } +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/MetaData.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/MetaData.java +@@ -2,97 +2,103 @@ package io.dropwizard.metrics5.collectd; + + class MetaData { + +- private final String host; +- private final String plugin; +- private final String pluginInstance; +- private final String type; +- private final String typeInstance; +- private final long timestamp; +- private final long period; +- +- MetaData(String host, String plugin, String pluginInstance, String type, String typeInstance, +- long timestamp, long period) { +- this.host = host; +- this.plugin = plugin; +- this.pluginInstance = pluginInstance; +- this.type = type; +- this.typeInstance = typeInstance; +- this.timestamp = timestamp; +- this.period = period; ++ private final String host; ++ private final String plugin; ++ private final String pluginInstance; ++ private final String type; ++ private final String typeInstance; ++ private final long timestamp; ++ private final long period; ++ ++ MetaData( ++ String host, ++ String plugin, ++ String pluginInstance, ++ String type, ++ String typeInstance, ++ long timestamp, ++ long period) { ++ this.host = host; ++ this.plugin = plugin; ++ this.pluginInstance = pluginInstance; ++ this.type = type; ++ this.typeInstance = typeInstance; ++ this.timestamp = timestamp; ++ this.period = period; ++ } ++ ++ String getHost() { ++ return host; ++ } ++ ++ String getPlugin() { ++ return plugin; ++ } ++ ++ String getPluginInstance() { ++ return pluginInstance; ++ } ++ ++ String getType() { ++ return type; ++ } ++ ++ String getTypeInstance() { ++ return typeInstance; ++ } ++ ++ long getTimestamp() { ++ return timestamp; ++ } ++ ++ long getPeriod() { ++ return period; ++ } ++ ++ static class Builder { ++ ++ private String host; ++ private String plugin; ++ private String pluginInstance; ++ private String type; ++ private String typeInstance; ++ private long timestamp; ++ private long period; ++ private Sanitize sanitize; ++ ++ Builder(String host, long timestamp, long duration) { ++ this(new Sanitize(Sanitize.DEFAULT_MAX_LENGTH), host, timestamp, duration); + } + +- String getHost() { +- return host; ++ Builder(Sanitize sanitize, String host, long timestamp, long duration) { ++ this.sanitize = sanitize; ++ this.host = sanitize.instanceName(host); ++ this.timestamp = timestamp; ++ period = duration; + } + +- String getPlugin() { +- return plugin; ++ Builder plugin(String name) { ++ plugin = sanitize.name(name); ++ return this; + } + +- String getPluginInstance() { +- return pluginInstance; ++ Builder pluginInstance(String name) { ++ pluginInstance = sanitize.instanceName(name); ++ return this; + } + +- String getType() { +- return type; ++ Builder type(String name) { ++ type = sanitize.name(name); ++ return this; + } + +- String getTypeInstance() { +- return typeInstance; ++ Builder typeInstance(String name) { ++ typeInstance = sanitize.instanceName(name); ++ return this; + } + +- long getTimestamp() { +- return timestamp; +- } +- +- long getPeriod() { +- return period; +- } +- +- static class Builder { +- +- private String host; +- private String plugin; +- private String pluginInstance; +- private String type; +- private String typeInstance; +- private long timestamp; +- private long period; +- private Sanitize sanitize; +- +- Builder(String host, long timestamp, long duration) { +- this(new Sanitize(Sanitize.DEFAULT_MAX_LENGTH), host, timestamp, duration); +- } +- +- Builder(Sanitize sanitize, String host, long timestamp, long duration) { +- this.sanitize = sanitize; +- this.host = sanitize.instanceName(host); +- this.timestamp = timestamp; +- period = duration; +- } +- +- Builder plugin(String name) { +- plugin = sanitize.name(name); +- return this; +- } +- +- Builder pluginInstance(String name) { +- pluginInstance = sanitize.instanceName(name); +- return this; +- } +- +- Builder type(String name) { +- type = sanitize.name(name); +- return this; +- } +- +- Builder typeInstance(String name) { +- typeInstance = sanitize.instanceName(name); +- return this; +- } +- +- MetaData get() { +- return new MetaData(host, plugin, pluginInstance, type, typeInstance, timestamp, period); +- } ++ MetaData get() { ++ return new MetaData(host, plugin, pluginInstance, type, typeInstance, timestamp, period); + } ++ } + } +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java +@@ -1,275 +1,283 @@ + package io.dropwizard.metrics5.collectd; + +-import javax.crypto.BadPaddingException; +-import javax.crypto.Cipher; +-import javax.crypto.IllegalBlockSizeException; +-import javax.crypto.Mac; +-import javax.crypto.NoSuchPaddingException; +-import javax.crypto.ShortBufferException; +-import javax.crypto.spec.IvParameterSpec; +-import javax.crypto.spec.SecretKeySpec; ++import static com.google.common.base.Preconditions.checkState; ++import static java.nio.charset.StandardCharsets.US_ASCII; ++import static java.nio.charset.StandardCharsets.UTF_8; ++ ++import com.google.common.base.Strings; + import java.io.IOException; + import java.nio.BufferOverflowException; + import java.nio.ByteBuffer; + import java.nio.ByteOrder; +-import java.nio.charset.StandardCharsets; + import java.security.InvalidKeyException; + import java.security.MessageDigest; + import java.security.NoSuchAlgorithmException; + import java.security.spec.InvalidParameterSpecException; + import java.util.Arrays; ++import javax.crypto.BadPaddingException; ++import javax.crypto.Cipher; ++import javax.crypto.IllegalBlockSizeException; ++import javax.crypto.Mac; ++import javax.crypto.NoSuchPaddingException; ++import javax.crypto.ShortBufferException; ++import javax.crypto.spec.IvParameterSpec; ++import javax.crypto.spec.SecretKeySpec; + + class PacketWriter { + +- private static final int TYPE_HOST = 0; +- private static final int TYPE_TIME = 1; +- private static final int TYPE_PLUGIN = 2; +- private static final int TYPE_PLUGIN_INSTANCE = 3; +- private static final int TYPE_TYPE = 4; +- private static final int TYPE_TYPE_INSTANCE = 5; +- private static final int TYPE_VALUES = 6; +- private static final int TYPE_INTERVAL = 7; +- private static final int TYPE_SIGN_SHA256 = 0x0200; +- private static final int TYPE_ENCR_AES256 = 0x0210; ++ private static final int TYPE_HOST = 0; ++ private static final int TYPE_TIME = 1; ++ private static final int TYPE_PLUGIN = 2; ++ private static final int TYPE_PLUGIN_INSTANCE = 3; ++ private static final int TYPE_TYPE = 4; ++ private static final int TYPE_TYPE_INSTANCE = 5; ++ private static final int TYPE_VALUES = 6; ++ private static final int TYPE_INTERVAL = 7; ++ private static final int TYPE_SIGN_SHA256 = 0x0200; ++ private static final int TYPE_ENCR_AES256 = 0x0210; + +- private static final int UINT16_LEN = 2; +- private static final int UINT32_LEN = UINT16_LEN * 2; +- private static final int UINT64_LEN = UINT32_LEN * 2; +- private static final int HEADER_LEN = UINT16_LEN * 2; +- private static final int BUFFER_SIZE = 1024; ++ private static final int UINT16_LEN = 2; ++ private static final int UINT32_LEN = UINT16_LEN * 2; ++ private static final int UINT64_LEN = UINT32_LEN * 2; ++ private static final int HEADER_LEN = UINT16_LEN * 2; ++ private static final int BUFFER_SIZE = 1024; + +- private static final int VALUE_COUNT_LEN = UINT16_LEN; +- private static final int NUMBER_LEN = HEADER_LEN + UINT64_LEN; +- private static final int SIGNATURE_LEN = 36; // 2b Type + 2b Length + 32b Hash +- private static final int ENCRYPT_DATA_LEN = 22; // 16b IV + 2b Type + 2b Length + 2b Username length +- private static final int IV_LENGTH = 16; +- private static final int SHA1_LENGTH = 20; ++ private static final int VALUE_COUNT_LEN = UINT16_LEN; ++ private static final int NUMBER_LEN = HEADER_LEN + UINT64_LEN; ++ private static final int SIGNATURE_LEN = 36; // 2b Type + 2b Length + 32b Hash ++ private static final int ENCRYPT_DATA_LEN = ++ 22; // 16b IV + 2b Type + 2b Length + 2b Username length ++ private static final int IV_LENGTH = 16; ++ private static final int SHA1_LENGTH = 20; + +- private static final int VALUE_LEN = 9; +- private static final byte DATA_TYPE_GAUGE = (byte) 1; +- private static final byte NULL = (byte) '\0'; +- private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; +- private static final String AES_CYPHER = "AES_256/OFB/NoPadding"; +- private static final String AES = "AES"; +- private static final String SHA_256_ALGORITHM = "SHA-256"; +- private static final String SHA_1_ALGORITHM = "SHA1"; ++ private static final int VALUE_LEN = 9; ++ private static final byte DATA_TYPE_GAUGE = (byte) 1; ++ private static final byte NULL = (byte) '\0'; ++ private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; ++ private static final String AES_CYPHER = "AES_256/OFB/NoPadding"; ++ private static final String AES = "AES"; ++ private static final String SHA_256_ALGORITHM = "SHA-256"; ++ private static final String SHA_1_ALGORITHM = "SHA1"; + +- private final Sender sender; ++ private final Sender sender; + +- private final SecurityLevel securityLevel; +- private final byte[] username; +- private final byte[] password; ++ private final SecurityLevel securityLevel; ++ private final byte[] username; ++ private final byte[] password; + +- PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { +- this.sender = sender; +- this.securityLevel = securityLevel; +- this.username = username != null ? username.getBytes(StandardCharsets.UTF_8) : null; +- this.password = password != null ? password.getBytes(StandardCharsets.UTF_8) : null; +- } ++ PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { ++ this.sender = sender; ++ this.securityLevel = securityLevel; ++ this.username = username != null ? username.getBytes(UTF_8) : null; ++ this.password = password != null ? password.getBytes(UTF_8) : null; ++ } + +- void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { +- final ByteBuffer packet = ByteBuffer.allocate(BUFFER_SIZE); +- write(packet, metaData); +- write(packet, values); +- packet.flip(); ++ void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { ++ final ByteBuffer packet = ByteBuffer.allocate(BUFFER_SIZE); ++ write(packet, metaData); ++ write(packet, values); ++ packet.flip(); + +- switch (securityLevel) { +- case NONE: +- sender.send(packet); +- break; +- case SIGN: +- sender.send(signPacket(packet)); +- break; +- case ENCRYPT: +- sender.send(encryptPacket(packet)); +- break; +- default: +- throw new IllegalArgumentException("Unsupported security level: " + securityLevel); +- } ++ switch (securityLevel) { ++ case NONE: ++ sender.send(packet); ++ break; ++ case SIGN: ++ sender.send(signPacket(packet)); ++ break; ++ case ENCRYPT: ++ sender.send(encryptPacket(packet)); ++ break; ++ default: ++ throw new IllegalArgumentException("Unsupported security level: " + securityLevel); + } ++ } + ++ private void write(ByteBuffer buffer, MetaData metaData) { ++ writeString(buffer, TYPE_HOST, metaData.getHost()); ++ writeNumber(buffer, TYPE_TIME, metaData.getTimestamp()); ++ writeString(buffer, TYPE_PLUGIN, metaData.getPlugin()); ++ writeString(buffer, TYPE_PLUGIN_INSTANCE, metaData.getPluginInstance()); ++ writeString(buffer, TYPE_TYPE, metaData.getType()); ++ writeString(buffer, TYPE_TYPE_INSTANCE, metaData.getTypeInstance()); ++ writeNumber(buffer, TYPE_INTERVAL, metaData.getPeriod()); ++ } + +- private void write(ByteBuffer buffer, MetaData metaData) { +- writeString(buffer, TYPE_HOST, metaData.getHost()); +- writeNumber(buffer, TYPE_TIME, metaData.getTimestamp()); +- writeString(buffer, TYPE_PLUGIN, metaData.getPlugin()); +- writeString(buffer, TYPE_PLUGIN_INSTANCE, metaData.getPluginInstance()); +- writeString(buffer, TYPE_TYPE, metaData.getType()); +- writeString(buffer, TYPE_TYPE_INSTANCE, metaData.getTypeInstance()); +- writeNumber(buffer, TYPE_INTERVAL, metaData.getPeriod()); ++ private void write(ByteBuffer buffer, Number... values) { ++ final int numValues = values.length; ++ final int length = HEADER_LEN + VALUE_COUNT_LEN + numValues * VALUE_LEN; ++ writeHeader(buffer, TYPE_VALUES, length); ++ buffer.putShort((short) numValues); ++ buffer.put(nCopies(numValues, DATA_TYPE_GAUGE)); ++ buffer.order(ByteOrder.LITTLE_ENDIAN); ++ for (Number value : values) { ++ buffer.putDouble(value.doubleValue()); + } ++ buffer.order(ByteOrder.BIG_ENDIAN); ++ } + +- private void write(ByteBuffer buffer, Number... values) { +- final int numValues = values.length; +- final int length = HEADER_LEN + VALUE_COUNT_LEN + numValues * VALUE_LEN; +- writeHeader(buffer, TYPE_VALUES, length); +- buffer.putShort((short) numValues); +- buffer.put(nCopies(numValues, DATA_TYPE_GAUGE)); +- buffer.order(ByteOrder.LITTLE_ENDIAN); +- for (Number value : values) { +- buffer.putDouble(value.doubleValue()); +- } +- buffer.order(ByteOrder.BIG_ENDIAN); +- } ++ private byte[] nCopies(int n, byte value) { ++ final byte[] array = new byte[n]; ++ Arrays.fill(array, value); ++ return array; ++ } + +- private byte[] nCopies(int n, byte value) { +- final byte[] array = new byte[n]; +- Arrays.fill(array, value); +- return array; ++ private void writeString(ByteBuffer buffer, int type, String val) { ++ if (Strings.isNullOrEmpty(val)) { ++ return; + } ++ int len = HEADER_LEN + val.length() + 1; ++ writeHeader(buffer, type, len); ++ buffer.put(val.getBytes(US_ASCII)).put(NULL); ++ } + +- private void writeString(ByteBuffer buffer, int type, String val) { +- if (val == null || val.length() == 0) { +- return; +- } +- int len = HEADER_LEN + val.length() + 1; +- writeHeader(buffer, type, len); +- buffer.put(val.getBytes(StandardCharsets.US_ASCII)).put(NULL); +- } ++ private void writeNumber(ByteBuffer buffer, int type, long val) { ++ writeHeader(buffer, type, NUMBER_LEN); ++ buffer.putLong(val); ++ } + +- private void writeNumber(ByteBuffer buffer, int type, long val) { +- writeHeader(buffer, type, NUMBER_LEN); +- buffer.putLong(val); +- } ++ private void writeHeader(ByteBuffer buffer, int type, int len) { ++ buffer.putShort((short) type); ++ buffer.putShort((short) len); ++ } + +- private void writeHeader(ByteBuffer buffer, int type, int len) { +- buffer.putShort((short) type); +- buffer.putShort((short) len); +- } ++ /** ++ * Signs the provided packet, so a CollectD server can verify that its authenticity. Wire format: ++ * ++ *
++   * +-------------------------------+-------------------------------+
++   * ! Type (0x0200)                 ! Length                        !
++   * +-------------------------------+-------------------------------+
++   * ! Signature (SHA2(username + packet))                           \
++   * +-------------------------------+-------------------------------+
++   * ! Username                      ! Packet                        \
++   * +---------------------------------------------------------------+
++   * 
++ * ++ * @see Binary ++ * protocol - CollectD | Signature part ++ */ ++ private ByteBuffer signPacket(ByteBuffer packet) { ++ final byte[] signature = ++ sign( ++ password, ++ (ByteBuffer) ++ ByteBuffer.allocate(packet.remaining() + username.length) ++ .put(username) ++ .put(packet) ++ .flip()); ++ return (ByteBuffer) ++ ByteBuffer.allocate(BUFFER_SIZE) ++ .putShort((short) TYPE_SIGN_SHA256) ++ .putShort((short) (username.length + SIGNATURE_LEN)) ++ .put(signature) ++ .put(username) ++ .put((ByteBuffer) packet.flip()) ++ .flip(); ++ } + +- /** +- * Signs the provided packet, so a CollectD server can verify that its authenticity. +- * Wire format: +- *
+-     * +-------------------------------+-------------------------------+
+-     * ! Type (0x0200)                 ! Length                        !
+-     * +-------------------------------+-------------------------------+
+-     * ! Signature (SHA2(username + packet))                           \
+-     * +-------------------------------+-------------------------------+
+-     * ! Username                      ! Packet                        \
+-     * +---------------------------------------------------------------+
+-     * 
+- * +- * @see +- * Binary protocol - CollectD | Signature part +- */ +- private ByteBuffer signPacket(ByteBuffer packet) { +- final byte[] signature = sign(password, (ByteBuffer) ByteBuffer.allocate(packet.remaining() + username.length) +- .put(username) +- .put(packet) +- .flip()); +- return (ByteBuffer) ByteBuffer.allocate(BUFFER_SIZE) +- .putShort((short) TYPE_SIGN_SHA256) +- .putShort((short) (username.length + SIGNATURE_LEN)) +- .put(signature) +- .put(username) +- .put((ByteBuffer) packet.flip()) +- .flip(); +- } +- +- /** +- * Encrypts the provided packet, so it's can't be eavesdropped during a transfer +- * to a CollectD server. Wire format: +- *
+-     * +---------------------------------+-------------------------------+
+-     * ! Type (0x0210)                   ! Length                        !
+-     * +---------------------------------+-------------------------------+
+-     * ! Username length in bytes        ! Username                      \
+-     * +-----------------------------------------------------------------+
+-     * ! Initialization Vector (IV)      !                               \
+-     * +---------------------------------+-------------------------------+
+-     * ! Encrypted bytes (AES (SHA1(packet) + packet))                   \
+-     * +---------------------------------+-------------------------------+
+-     * 
+- * +- * @see +- * Binary protocol - CollectD | Encrypted part +- */ +- private ByteBuffer encryptPacket(ByteBuffer packet) { +- final ByteBuffer payload = (ByteBuffer) ByteBuffer.allocate(SHA1_LENGTH + packet.remaining()) ++ /** ++ * Encrypts the provided packet, so it's can't be eavesdropped during a transfer to a CollectD ++ * server. Wire format: ++ * ++ *
++   * +---------------------------------+-------------------------------+
++   * ! Type (0x0210)                   ! Length                        !
++   * +---------------------------------+-------------------------------+
++   * ! Username length in bytes        ! Username                      \
++   * +-----------------------------------------------------------------+
++   * ! Initialization Vector (IV)      !                               \
++   * +---------------------------------+-------------------------------+
++   * ! Encrypted bytes (AES (SHA1(packet) + packet))                   \
++   * +---------------------------------+-------------------------------+
++   * 
++ * ++ * @see Binary ++ * protocol - CollectD | Encrypted part ++ */ ++ private ByteBuffer encryptPacket(ByteBuffer packet) { ++ final ByteBuffer payload = ++ (ByteBuffer) ++ ByteBuffer.allocate(SHA1_LENGTH + packet.remaining()) + .put(sha1(packet)) + .put((ByteBuffer) packet.flip()) + .flip(); +- final EncryptionResult er = encrypt(password, payload); +- return (ByteBuffer) ByteBuffer.allocate(BUFFER_SIZE) +- .putShort((short) TYPE_ENCR_AES256) +- .putShort((short) (ENCRYPT_DATA_LEN + username.length + er.output.remaining())) +- .putShort((short) username.length) +- .put(username) +- .put(er.iv) +- .put(er.output) +- .flip(); +- } ++ final EncryptionResult er = encrypt(password, payload); ++ return (ByteBuffer) ++ ByteBuffer.allocate(BUFFER_SIZE) ++ .putShort((short) TYPE_ENCR_AES256) ++ .putShort((short) (ENCRYPT_DATA_LEN + username.length + er.output.remaining())) ++ .putShort((short) username.length) ++ .put(username) ++ .put(er.iv) ++ .put(er.output) ++ .flip(); ++ } + +- private static byte[] sign(byte[] secret, ByteBuffer input) { +- final Mac mac; +- try { +- mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); +- mac.init(new SecretKeySpec(secret, HMAC_SHA256_ALGORITHM)); +- } catch (NoSuchAlgorithmException | InvalidKeyException e) { +- throw new RuntimeException(e); +- } +- mac.update(input); +- return mac.doFinal(); ++ private static byte[] sign(byte[] secret, ByteBuffer input) { ++ final Mac mac; ++ try { ++ mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); ++ mac.init(new SecretKeySpec(secret, HMAC_SHA256_ALGORITHM)); ++ } catch (NoSuchAlgorithmException | InvalidKeyException e) { ++ throw new RuntimeException(e); + } ++ mac.update(input); ++ return mac.doFinal(); ++ } + +- private static EncryptionResult encrypt(byte[] password, ByteBuffer input) { +- final Cipher cipher; +- try { +- cipher = Cipher.getInstance(AES_CYPHER); +- cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sha256(password), AES)); +- } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { +- throw new RuntimeException(e); +- } +- final byte[] iv; +- try { +- iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); +- } catch (InvalidParameterSpecException e) { +- throw new RuntimeException(e); +- } +- if (iv.length != IV_LENGTH) { +- throw new IllegalStateException("Bad initialization vector"); +- } +- final ByteBuffer output = ByteBuffer.allocate(input.remaining() * 2); +- try { +- cipher.doFinal(input, output); +- } catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException e) { +- throw new RuntimeException(e); +- } +- return new EncryptionResult(iv, (ByteBuffer) output.flip()); ++ private static EncryptionResult encrypt(byte[] password, ByteBuffer input) { ++ final Cipher cipher; ++ try { ++ cipher = Cipher.getInstance(AES_CYPHER); ++ cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sha256(password), AES)); ++ } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { ++ throw new RuntimeException(e); + } ++ final byte[] iv; ++ try { ++ iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); ++ } catch (InvalidParameterSpecException e) { ++ throw new RuntimeException(e); ++ } ++ checkState(iv.length == IV_LENGTH, "Bad initialization vector"); ++ final ByteBuffer output = ByteBuffer.allocate(input.remaining() * 2); ++ try { ++ cipher.doFinal(input, output); ++ } catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException e) { ++ throw new RuntimeException(e); ++ } ++ return new EncryptionResult(iv, (ByteBuffer) output.flip()); ++ } + +- private static byte[] sha256(byte[] input) { +- try { +- return MessageDigest.getInstance(SHA_256_ALGORITHM).digest(input); +- } catch (NoSuchAlgorithmException e) { +- throw new RuntimeException(e); +- } ++ private static byte[] sha256(byte[] input) { ++ try { ++ return MessageDigest.getInstance(SHA_256_ALGORITHM).digest(input); ++ } catch (NoSuchAlgorithmException e) { ++ throw new RuntimeException(e); + } ++ } + +- private static byte[] sha1(ByteBuffer input) { +- try { +- final MessageDigest digest = MessageDigest.getInstance(SHA_1_ALGORITHM); +- digest.update(input); +- final byte[] output = digest.digest(); +- if (output.length != SHA1_LENGTH) { +- throw new IllegalStateException("Bad SHA1 hash"); +- } +- return output; +- } catch (NoSuchAlgorithmException e) { +- throw new RuntimeException(e); +- } ++ private static byte[] sha1(ByteBuffer input) { ++ try { ++ final MessageDigest digest = MessageDigest.getInstance(SHA_1_ALGORITHM); ++ digest.update(input); ++ final byte[] output = digest.digest(); ++ checkState(output.length == SHA1_LENGTH, "Bad SHA1 hash"); ++ return output; ++ } catch (NoSuchAlgorithmException e) { ++ throw new RuntimeException(e); + } ++ } + +- private static class EncryptionResult { ++ private static class EncryptionResult { + +- private final byte[] iv; +- private final ByteBuffer output; ++ private final byte[] iv; ++ private final ByteBuffer output; + +- private EncryptionResult(byte[] iv, ByteBuffer output) { +- this.iv = iv; +- this.output = output; +- } ++ private EncryptionResult(byte[] iv, ByteBuffer output) { ++ this.iv = iv; ++ this.output = output; + } +- ++ } + } +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sanitize.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sanitize.java +@@ -8,39 +8,38 @@ import java.util.List; + */ + class Sanitize { + +- static final int DEFAULT_MAX_LENGTH = 63; ++ static final int DEFAULT_MAX_LENGTH = 63; + +- private static final char DASH = '-'; +- private static final char SLASH = '/'; +- private static final char NULL = '\0'; +- private static final char UNDERSCORE = '_'; ++ private static final char DASH = '-'; ++ private static final char SLASH = '/'; ++ private static final char NULL = '\0'; ++ private static final char UNDERSCORE = '_'; + +- private static final List INSTANCE_RESERVED = Arrays.asList(SLASH, NULL); +- private static final List NAME_RESERVED = Arrays.asList(DASH, SLASH, NULL); ++ private static final List INSTANCE_RESERVED = Arrays.asList(SLASH, NULL); ++ private static final List NAME_RESERVED = Arrays.asList(DASH, SLASH, NULL); + +- private final int maxLength; ++ private final int maxLength; + +- Sanitize(int maxLength) { +- this.maxLength = maxLength; +- } ++ Sanitize(int maxLength) { ++ this.maxLength = maxLength; ++ } + +- String name(String name) { +- return sanitize(name, NAME_RESERVED); +- } ++ String name(String name) { ++ return sanitize(name, NAME_RESERVED); ++ } + +- String instanceName(String instanceName) { +- return sanitize(instanceName, INSTANCE_RESERVED); +- } ++ String instanceName(String instanceName) { ++ return sanitize(instanceName, INSTANCE_RESERVED); ++ } + +- private String sanitize(String string, List reservedChars) { +- final StringBuilder buffer = new StringBuilder(string.length()); +- final int len = Math.min(string.length(), maxLength); +- for (int i = 0; i < len; i++) { +- final char c = string.charAt(i); +- final boolean legal = ((int) c) < 128 && !reservedChars.contains(c); +- buffer.append(legal ? c : UNDERSCORE); +- } +- return buffer.toString(); ++ private String sanitize(String string, List reservedChars) { ++ final StringBuilder buffer = new StringBuilder(string.length()); ++ final int len = Math.min(string.length(), maxLength); ++ for (int i = 0; i < len; i++) { ++ final char c = string.charAt(i); ++ final boolean legal = ((int) c) < 128 && !reservedChars.contains(c); ++ buffer.append(legal ? c : UNDERSCORE); + } +- ++ return buffer.toString(); ++ } + } +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/SecurityConfiguration.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/SecurityConfiguration.java +@@ -2,29 +2,29 @@ package io.dropwizard.metrics5.collectd; + + public class SecurityConfiguration { + +- private final byte[] username; +- private final byte[] password; +- private final SecurityLevel securityLevel; ++ private final byte[] username; ++ private final byte[] password; ++ private final SecurityLevel securityLevel; + +- public SecurityConfiguration(byte[] username, byte[] password, SecurityLevel securityLevel) { +- this.username = username; +- this.password = password; +- this.securityLevel = securityLevel; +- } ++ public SecurityConfiguration(byte[] username, byte[] password, SecurityLevel securityLevel) { ++ this.username = username; ++ this.password = password; ++ this.securityLevel = securityLevel; ++ } + +- public static SecurityConfiguration none() { +- return new SecurityConfiguration(null, null, SecurityLevel.NONE); +- } ++ public static SecurityConfiguration none() { ++ return new SecurityConfiguration(null, null, SecurityLevel.NONE); ++ } + +- public byte[] getUsername() { +- return username; +- } ++ public byte[] getUsername() { ++ return username; ++ } + +- public byte[] getPassword() { +- return password; +- } ++ public byte[] getPassword() { ++ return password; ++ } + +- public SecurityLevel getSecurityLevel() { +- return securityLevel; +- } ++ public SecurityLevel getSecurityLevel() { ++ return securityLevel; ++ } + } +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/SecurityLevel.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/SecurityLevel.java +@@ -1,8 +1,7 @@ + package io.dropwizard.metrics5.collectd; + + public enum SecurityLevel { +- +- NONE, +- SIGN, +- ENCRYPT ++ NONE, ++ SIGN, ++ ENCRYPT + } +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.collectd; + ++import static com.google.common.base.Preconditions.checkState; ++ + import java.io.IOException; + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; +@@ -7,44 +9,41 @@ import java.nio.channels.DatagramChannel; + + public class Sender { + +- private final String host; +- private final int port; ++ private final String host; ++ private final int port; + +- private InetSocketAddress address; +- private DatagramChannel channel; ++ private InetSocketAddress address; ++ private DatagramChannel channel; + +- public Sender(String host, int port) { +- this.host = host; +- this.port = port; +- } ++ public Sender(String host, int port) { ++ this.host = host; ++ this.port = port; ++ } + +- public void connect() throws IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } +- if (host != null) { +- address = new InetSocketAddress(host, port); +- } +- channel = DatagramChannel.open(); ++ public void connect() throws IOException { ++ checkState(!isConnected(), "Already connected"); ++ if (host != null) { ++ address = new InetSocketAddress(host, port); + } ++ channel = DatagramChannel.open(); ++ } + +- public boolean isConnected() { +- return channel != null && !channel.socket().isClosed(); +- } ++ public boolean isConnected() { ++ return channel != null && !channel.socket().isClosed(); ++ } + +- public void send(ByteBuffer buffer) throws IOException { +- channel.send(buffer, address); +- } ++ public void send(ByteBuffer buffer) throws IOException { ++ channel.send(buffer, address); ++ } + +- public void disconnect() throws IOException { +- if (channel == null) { +- return; +- } +- try { +- channel.close(); +- } finally { +- channel = null; +- } ++ public void disconnect() throws IOException { ++ if (channel == null) { ++ return; + } +- ++ try { ++ channel.close(); ++ } finally { ++ channel = null; ++ } ++ } + } +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java +@@ -1,33 +1,37 @@ + package io.dropwizard.metrics5.collectd; + ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++ + import io.dropwizard.metrics5.MetricRegistry; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +- +-class CollectdReporterSecurityTest { ++final class CollectdReporterSecurityTest { + +- private final MetricRegistry registry = new MetricRegistry(); ++ private final MetricRegistry registry = new MetricRegistry(); + +- @Test +- void testUnableSetSecurityLevelToSignWithoutUsername() { +- assertThatIllegalArgumentException().isThrownBy(() -> ++ @Test ++ void unableSetSecurityLevelToSignWithoutUsername() { ++ assertThatThrownBy( ++ () -> + CollectdReporter.forRegistry(registry) +- .withHostName("eddie") +- .withSecurityLevel(SecurityLevel.SIGN) +- .withPassword("t1_g3r") +- .build(new Sender("localhost", 25826))) +- .withMessage("username is required for securityLevel: SIGN"); +- } ++ .withHostName("eddie") ++ .withSecurityLevel(SecurityLevel.SIGN) ++ .withPassword("t1_g3r") ++ .build(new Sender("localhost", 25826))) ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("username is required for securityLevel: SIGN"); ++ } + +- @Test +- void testUnableSetSecurityLevelToSignWithoutPassword() { +- assertThatIllegalArgumentException().isThrownBy(() -> ++ @Test ++ void unableSetSecurityLevelToSignWithoutPassword() { ++ assertThatThrownBy( ++ () -> + CollectdReporter.forRegistry(registry) +- .withHostName("eddie") +- .withSecurityLevel(SecurityLevel.SIGN) +- .withUsername("scott") +- .build(new Sender("localhost", 25826))) +- .withMessage("password is required for securityLevel: SIGN"); +- } ++ .withHostName("eddie") ++ .withSecurityLevel(SecurityLevel.SIGN) ++ .withUsername("scott") ++ .build(new Sender("localhost", 25826))) ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("password is required for securityLevel: SIGN"); ++ } + } +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java +@@ -1,5 +1,14 @@ + package io.dropwizard.metrics5.collectd; + ++import static java.util.Collections.emptySortedMap; ++import static java.util.concurrent.TimeUnit.MILLISECONDS; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Histogram; + import io.dropwizard.metrics5.Meter; +@@ -8,315 +17,280 @@ import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +-import org.collectd.api.ValueList; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +-import org.junit.jupiter.api.extension.RegisterExtension; +- +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; + import java.util.SortedMap; + import java.util.TreeMap; ++import org.collectd.api.ValueList; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; ++import org.junit.jupiter.api.extension.RegisterExtension; + +-import static java.util.concurrent.TimeUnit.MILLISECONDS; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-public class CollectdReporterTest { +- @RegisterExtension +- public static Receiver receiver = new Receiver(25826); +- +- private final MetricRegistry registry = new MetricRegistry(); +- private CollectdReporter reporter; +- +- @BeforeEach +- void setUp() { +- reporter = CollectdReporter.forRegistry(registry) +- .withHostName("eddie") +- .build(new Sender("localhost", 25826)); +- } +- +- @Test +- void reportsByteGauges() throws Exception { +- reportsGauges((byte) 128); +- } +- +- @Test +- void reportsShortGauges() throws Exception { +- reportsGauges((short) 2048); +- } +- +- @Test +- void reportsIntegerGauges() throws Exception { +- reportsGauges(42); +- } +- +- @Test +- void reportsLongGauges() throws Exception { +- reportsGauges(Long.MAX_VALUE); +- } +- +- @Test +- void reportsFloatGauges() throws Exception { +- reportsGauges(0.25); +- } +- +- @Test +- void reportsDoubleGauges() throws Exception { +- reportsGauges(0.125d); +- } +- +- private void reportsGauges(T value) throws Exception { +- reporter.report( +- map(MetricName.build("gauge"), () -> value), +- map(), +- map(), +- map(), +- map()); +- +- assertThat(nextValues(receiver)).containsExactly(value.doubleValue()); +- } +- +- @Test +- void reportsBooleanGauges() throws Exception { +- reporter.report( +- map(MetricName.build("gauge"), () -> true), +- map(), +- map(), +- map(), +- map()); +- +- assertThat(nextValues(receiver)).containsExactly(1d); +- +- reporter.report( +- map(MetricName.build("gauge"), () -> false), +- map(), +- map(), +- map(), +- map()); +- +- assertThat(nextValues(receiver)).containsExactly(0d); +- } +- +- @Test +- void doesNotReportStringGauges() throws Exception { +- reporter.report( +- map(MetricName.build("unsupported"), () -> "value"), +- map(), +- map(), +- map(), +- map()); +- +- assertThat(receiver.next()).isNull(); +- } +- +- @Test +- void reportsCounters() throws Exception { +- Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(42L); +- +- reporter.report( +- map(), +- map(MetricName.build("api", "rest", "requests", "count"), counter), +- map(), +- map(), +- map()); +- +- assertThat(nextValues(receiver)).containsExactly(42d); +- } +- +- @Test +- void reportsMeters() throws Exception { +- Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getOneMinuteRate()).thenReturn(2.0); +- when(meter.getFiveMinuteRate()).thenReturn(3.0); +- when(meter.getFifteenMinuteRate()).thenReturn(4.0); +- when(meter.getMeanRate()).thenReturn(5.0); +- +- reporter.report( +- map(), +- map(), +- map(), +- map(MetricName.build("api", "rest", "requests"), meter), +- map()); +- +- assertThat(nextValues(receiver)).containsExactly(1d); +- assertThat(nextValues(receiver)).containsExactly(2d); +- assertThat(nextValues(receiver)).containsExactly(3d); +- assertThat(nextValues(receiver)).containsExactly(4d); +- assertThat(nextValues(receiver)).containsExactly(5d); +- } +- +- @Test +- void reportsHistograms() throws Exception { +- Histogram histogram = mock(Histogram.class); +- Snapshot snapshot = mock(Snapshot.class); +- when(histogram.getCount()).thenReturn(1L); +- when(histogram.getSnapshot()).thenReturn(snapshot); +- when(snapshot.getMax()).thenReturn(2L); +- when(snapshot.getMean()).thenReturn(3.0); +- when(snapshot.getMin()).thenReturn(4L); +- when(snapshot.getStdDev()).thenReturn(5.0); +- when(snapshot.getMedian()).thenReturn(6.0); +- when(snapshot.get75thPercentile()).thenReturn(7.0); +- when(snapshot.get95thPercentile()).thenReturn(8.0); +- when(snapshot.get98thPercentile()).thenReturn(9.0); +- when(snapshot.get99thPercentile()).thenReturn(10.0); +- when(snapshot.get999thPercentile()).thenReturn(11.0); +- +- reporter.report( +- map(), +- map(), +- map(MetricName.build("histogram"), histogram), +- map(), +- map()); +- +- for (int i = 1; i <= 11; i++) { +- assertThat(nextValues(receiver)).containsExactly((double) i); +- } +- } +- +- @Test +- void reportsTimers() throws Exception { +- Timer timer = mock(Timer.class); +- Snapshot snapshot = mock(Snapshot.class); +- when(timer.getSnapshot()).thenReturn(snapshot); +- when(timer.getCount()).thenReturn(1L); +- when(timer.getSnapshot()).thenReturn(snapshot); +- when(snapshot.getMax()).thenReturn(MILLISECONDS.toNanos(100)); +- when(snapshot.getMean()).thenReturn((double) MILLISECONDS.toNanos(200)); +- when(snapshot.getMin()).thenReturn(MILLISECONDS.toNanos(300)); +- when(snapshot.getStdDev()).thenReturn((double) MILLISECONDS.toNanos(400)); +- when(snapshot.getMedian()).thenReturn((double) MILLISECONDS.toNanos(500)); +- when(snapshot.get75thPercentile()).thenReturn((double) MILLISECONDS.toNanos(600)); +- when(snapshot.get95thPercentile()).thenReturn((double) MILLISECONDS.toNanos(700)); +- when(snapshot.get98thPercentile()).thenReturn((double) MILLISECONDS.toNanos(800)); +- when(snapshot.get99thPercentile()).thenReturn((double) MILLISECONDS.toNanos(900)); +- when(snapshot.get999thPercentile()).thenReturn((double) MILLISECONDS.toNanos(1000)); +- when(timer.getOneMinuteRate()).thenReturn(11.0); +- when(timer.getFiveMinuteRate()).thenReturn(12.0); +- when(timer.getFifteenMinuteRate()).thenReturn(13.0); +- when(timer.getMeanRate()).thenReturn(14.0); +- +- reporter.report( +- map(), +- map(), +- map(), +- map(), +- map(MetricName.build("timer"), timer)); +- +- assertThat(nextValues(receiver)).containsExactly(1d); +- assertThat(nextValues(receiver)).containsExactly(100d); +- assertThat(nextValues(receiver)).containsExactly(200d); +- assertThat(nextValues(receiver)).containsExactly(300d); +- assertThat(nextValues(receiver)).containsExactly(400d); +- assertThat(nextValues(receiver)).containsExactly(500d); +- assertThat(nextValues(receiver)).containsExactly(600d); +- assertThat(nextValues(receiver)).containsExactly(700d); +- assertThat(nextValues(receiver)).containsExactly(800d); +- assertThat(nextValues(receiver)).containsExactly(900d); +- assertThat(nextValues(receiver)).containsExactly(1000d); +- assertThat(nextValues(receiver)).containsExactly(11d); +- assertThat(nextValues(receiver)).containsExactly(12d); +- assertThat(nextValues(receiver)).containsExactly(13d); +- assertThat(nextValues(receiver)).containsExactly(14d); +- } +- +- @Test +- void doesNotReportDisabledMetricAttributes() throws Exception { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getOneMinuteRate()).thenReturn(2.0); +- when(meter.getFiveMinuteRate()).thenReturn(3.0); +- when(meter.getFifteenMinuteRate()).thenReturn(4.0); +- when(meter.getMeanRate()).thenReturn(5.0); +- +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(11L); +- +- CollectdReporter reporter = CollectdReporter.forRegistry(registry) +- .withHostName("eddie") +- .disabledMetricAttributes(EnumSet.of(MetricAttribute.M5_RATE, MetricAttribute.M15_RATE)) +- .build(new Sender("localhost", 25826)); +- +- reporter.report( +- map(), +- map(MetricName.build("counter"), counter), +- map(), +- map(MetricName.build("meter"), meter), +- map()); +- +- assertThat(nextValues(receiver)).containsExactly(11d); +- assertThat(nextValues(receiver)).containsExactly(1d); +- assertThat(nextValues(receiver)).containsExactly(2d); +- assertThat(nextValues(receiver)).containsExactly(5d); +- } +- +- @Test +- void sanitizesMetricName() throws Exception { +- Counter counter = registry.counter("dash-illegal.slash/illegal"); +- counter.inc(); +- +- reporter.report(); +- +- ValueList values = receiver.next(); +- assertThat(values.getPlugin()).isEqualTo("dash_illegal.slash_illegal"); ++final class CollectdReporterTest { ++ @RegisterExtension public static Receiver receiver = new Receiver(25826); ++ ++ private final MetricRegistry registry = new MetricRegistry(); ++ private CollectdReporter reporter; ++ ++ @BeforeEach ++ void setUp() { ++ reporter = ++ CollectdReporter.forRegistry(registry) ++ .withHostName("eddie") ++ .build(new Sender("localhost", 25826)); ++ } ++ ++ @Test ++ void reportsByteGauges() throws Exception { ++ reportsGauges((byte) 128); ++ } ++ ++ @Test ++ void reportsShortGauges() throws Exception { ++ reportsGauges((short) 2048); ++ } ++ ++ @Test ++ void reportsIntegerGauges() throws Exception { ++ reportsGauges(42); ++ } ++ ++ @Test ++ void reportsLongGauges() throws Exception { ++ reportsGauges(Long.MAX_VALUE); ++ } ++ ++ @Test ++ void reportsFloatGauges() throws Exception { ++ reportsGauges(0.25); ++ } ++ ++ @Test ++ void reportsDoubleGauges() throws Exception { ++ reportsGauges(0.125d); ++ } ++ ++ private void reportsGauges(T value) throws Exception { ++ reporter.report(map(MetricName.build("gauge"), () -> value), map(), map(), map(), map()); ++ ++ assertThat(nextValues(receiver)).containsExactly(value.doubleValue()); ++ } ++ ++ @Test ++ void reportsBooleanGauges() throws Exception { ++ reporter.report(map(MetricName.build("gauge"), () -> true), map(), map(), map(), map()); ++ ++ assertThat(nextValues(receiver)).containsExactly(1d); ++ ++ reporter.report(map(MetricName.build("gauge"), () -> false), map(), map(), map(), map()); ++ ++ assertThat(nextValues(receiver)).containsExactly(0d); ++ } ++ ++ @Test ++ void doesNotReportStringGauges() throws Exception { ++ reporter.report( ++ map(MetricName.build("unsupported"), () -> "value"), map(), map(), map(), map()); ++ ++ assertThat(receiver.next()).isNull(); ++ } ++ ++ @Test ++ void reportsCounters() throws Exception { ++ Counter counter = mock(); ++ when(counter.getCount()).thenReturn(42L); ++ ++ reporter.report( ++ map(), ++ map(MetricName.build("api", "rest", "requests", "count"), counter), ++ map(), ++ map(), ++ map()); ++ ++ assertThat(nextValues(receiver)).containsExactly(42d); ++ } ++ ++ @Test ++ void reportsMeters() throws Exception { ++ Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getOneMinuteRate()).thenReturn(2.0); ++ when(meter.getFiveMinuteRate()).thenReturn(3.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(4.0); ++ when(meter.getMeanRate()).thenReturn(5.0); ++ ++ reporter.report( ++ map(), map(), map(), map(MetricName.build("api", "rest", "requests"), meter), map()); ++ ++ assertThat(nextValues(receiver)).containsExactly(1d); ++ assertThat(nextValues(receiver)).containsExactly(2d); ++ assertThat(nextValues(receiver)).containsExactly(3d); ++ assertThat(nextValues(receiver)).containsExactly(4d); ++ assertThat(nextValues(receiver)).containsExactly(5d); ++ } ++ ++ @Test ++ void reportsHistograms() throws Exception { ++ Histogram histogram = mock(); ++ Snapshot snapshot = mock(); ++ when(histogram.getCount()).thenReturn(1L); ++ when(histogram.getSnapshot()).thenReturn(snapshot); ++ when(snapshot.getMax()).thenReturn(2L); ++ when(snapshot.getMean()).thenReturn(3.0); ++ when(snapshot.getMin()).thenReturn(4L); ++ when(snapshot.getStdDev()).thenReturn(5.0); ++ when(snapshot.getMedian()).thenReturn(6.0); ++ when(snapshot.get75thPercentile()).thenReturn(7.0); ++ when(snapshot.get95thPercentile()).thenReturn(8.0); ++ when(snapshot.get98thPercentile()).thenReturn(9.0); ++ when(snapshot.get99thPercentile()).thenReturn(10.0); ++ when(snapshot.get999thPercentile()).thenReturn(11.0); ++ ++ reporter.report(map(), map(), map(MetricName.build("histogram"), histogram), map(), map()); ++ ++ for (int i = 1; i <= 11; i++) { ++ assertThat(nextValues(receiver)).containsExactly((double) i); + } +- +- @Test +- void testUnableSetSecurityLevelToSignWithoutUsername() { +- assertThatIllegalArgumentException().isThrownBy(() -> ++ } ++ ++ @Test ++ void reportsTimers() throws Exception { ++ Timer timer = mock(); ++ Snapshot snapshot = mock(); ++ when(timer.getSnapshot()).thenReturn(snapshot); ++ when(timer.getCount()).thenReturn(1L); ++ when(timer.getSnapshot()).thenReturn(snapshot); ++ when(snapshot.getMax()).thenReturn(MILLISECONDS.toNanos(100)); ++ when(snapshot.getMean()).thenReturn((double) MILLISECONDS.toNanos(200)); ++ when(snapshot.getMin()).thenReturn(MILLISECONDS.toNanos(300)); ++ when(snapshot.getStdDev()).thenReturn((double) MILLISECONDS.toNanos(400)); ++ when(snapshot.getMedian()).thenReturn((double) MILLISECONDS.toNanos(500)); ++ when(snapshot.get75thPercentile()).thenReturn((double) MILLISECONDS.toNanos(600)); ++ when(snapshot.get95thPercentile()).thenReturn((double) MILLISECONDS.toNanos(700)); ++ when(snapshot.get98thPercentile()).thenReturn((double) MILLISECONDS.toNanos(800)); ++ when(snapshot.get99thPercentile()).thenReturn((double) MILLISECONDS.toNanos(900)); ++ when(snapshot.get999thPercentile()).thenReturn((double) MILLISECONDS.toNanos(1000)); ++ when(timer.getOneMinuteRate()).thenReturn(11.0); ++ when(timer.getFiveMinuteRate()).thenReturn(12.0); ++ when(timer.getFifteenMinuteRate()).thenReturn(13.0); ++ when(timer.getMeanRate()).thenReturn(14.0); ++ ++ reporter.report(map(), map(), map(), map(), map(MetricName.build("timer"), timer)); ++ ++ assertThat(nextValues(receiver)).containsExactly(1d); ++ assertThat(nextValues(receiver)).containsExactly(100d); ++ assertThat(nextValues(receiver)).containsExactly(200d); ++ assertThat(nextValues(receiver)).containsExactly(300d); ++ assertThat(nextValues(receiver)).containsExactly(400d); ++ assertThat(nextValues(receiver)).containsExactly(500d); ++ assertThat(nextValues(receiver)).containsExactly(600d); ++ assertThat(nextValues(receiver)).containsExactly(700d); ++ assertThat(nextValues(receiver)).containsExactly(800d); ++ assertThat(nextValues(receiver)).containsExactly(900d); ++ assertThat(nextValues(receiver)).containsExactly(1000d); ++ assertThat(nextValues(receiver)).containsExactly(11d); ++ assertThat(nextValues(receiver)).containsExactly(12d); ++ assertThat(nextValues(receiver)).containsExactly(13d); ++ assertThat(nextValues(receiver)).containsExactly(14d); ++ } ++ ++ @Test ++ void doesNotReportDisabledMetricAttributes() throws Exception { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getOneMinuteRate()).thenReturn(2.0); ++ when(meter.getFiveMinuteRate()).thenReturn(3.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(4.0); ++ when(meter.getMeanRate()).thenReturn(5.0); ++ ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(11L); ++ ++ CollectdReporter reporter = ++ CollectdReporter.forRegistry(registry) ++ .withHostName("eddie") ++ .disabledMetricAttributes(EnumSet.of(MetricAttribute.M5_RATE, MetricAttribute.M15_RATE)) ++ .build(new Sender("localhost", 25826)); ++ ++ reporter.report( ++ map(), ++ map(MetricName.build("counter"), counter), ++ map(), ++ map(MetricName.build("meter"), meter), ++ map()); ++ ++ assertThat(nextValues(receiver)).containsExactly(11d); ++ assertThat(nextValues(receiver)).containsExactly(1d); ++ assertThat(nextValues(receiver)).containsExactly(2d); ++ assertThat(nextValues(receiver)).containsExactly(5d); ++ } ++ ++ @Test ++ void sanitizesMetricName() throws Exception { ++ Counter counter = registry.counter("dash-illegal.slash/illegal"); ++ counter.inc(); ++ ++ reporter.report(); ++ ++ ValueList values = receiver.next(); ++ assertThat(values.getPlugin()).isEqualTo("dash_illegal.slash_illegal"); ++ } ++ ++ @Test ++ void unableSetSecurityLevelToSignWithoutUsername() { ++ assertThatThrownBy( ++ () -> + CollectdReporter.forRegistry(registry) +- .withHostName("eddie") +- .withSecurityLevel(SecurityLevel.SIGN) +- .withPassword("t1_g3r") +- .build(new Sender("localhost", 25826))) +- .withMessage("username is required for securityLevel: SIGN"); +- } +- +- @Test +- void testUnableSetSecurityLevelToSignWithoutPassword() { +- assertThatIllegalArgumentException().isThrownBy(() -> ++ .withHostName("eddie") ++ .withSecurityLevel(SecurityLevel.SIGN) ++ .withPassword("t1_g3r") ++ .build(new Sender("localhost", 25826))) ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("username is required for securityLevel: SIGN"); ++ } ++ ++ @Test ++ void unableSetSecurityLevelToSignWithoutPassword() { ++ assertThatThrownBy( ++ () -> + CollectdReporter.forRegistry(registry) +- .withHostName("eddie") +- .withSecurityLevel(SecurityLevel.SIGN) +- .withUsername("scott") +- .build(new Sender("localhost", 25826))) +- .withMessage("password is required for securityLevel: SIGN"); +- } +- +- private SortedMap map() { +- return Collections.emptySortedMap(); +- } +- +- private SortedMap map(MetricName name, T metric) { +- final Map map = Collections.singletonMap(name, metric); +- return new TreeMap<>(map); +- } +- +- @Test +- void sanitizesMetricNameWithCustomMaxLength() throws Exception { +- CollectdReporter customReporter = CollectdReporter.forRegistry(registry) +- .withHostName("eddie") +- .withMaxLength(20) +- .build(new Sender("localhost", 25826)); +- +- Counter counter = registry.counter("dash-illegal.slash/illegal"); +- counter.inc(); +- +- customReporter.report(); +- +- ValueList values = receiver.next(); +- assertThat(values.getPlugin()).isEqualTo("dash_illegal.slash_i"); +- } +- +- private List nextValues(Receiver receiver) throws Exception { +- final ValueList valueList = receiver.next(); +- return valueList == null ? Collections.emptyList() : valueList.getValues(); +- } ++ .withHostName("eddie") ++ .withSecurityLevel(SecurityLevel.SIGN) ++ .withUsername("scott") ++ .build(new Sender("localhost", 25826))) ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("password is required for securityLevel: SIGN"); ++ } ++ ++ private SortedMap map() { ++ return emptySortedMap(); ++ } ++ ++ private SortedMap map(MetricName name, T metric) { ++ final Map map = ImmutableMap.of(name, metric); ++ return new TreeMap<>(map); ++ } ++ ++ @Test ++ void sanitizesMetricNameWithCustomMaxLength() throws Exception { ++ CollectdReporter customReporter = ++ CollectdReporter.forRegistry(registry) ++ .withHostName("eddie") ++ .withMaxLength(20) ++ .build(new Sender("localhost", 25826)); ++ ++ Counter counter = registry.counter("dash-illegal.slash/illegal"); ++ counter.inc(); ++ ++ customReporter.report(); ++ ++ ValueList values = receiver.next(); ++ assertThat(values.getPlugin()).isEqualTo("dash_illegal.slash_i"); ++ } ++ ++ private List nextValues(Receiver receiver) throws Exception { ++ final ValueList valueList = receiver.next(); ++ return valueList == null ? ImmutableList.of() : valueList.getValues(); ++ } + } +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java +@@ -1,12 +1,9 @@ + package io.dropwizard.metrics5.collectd; + +-import io.dropwizard.metrics5.collectd.SecurityLevel; +-import org.junit.jupiter.api.Test; ++import static java.nio.charset.StandardCharsets.UTF_8; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + +-import javax.crypto.Cipher; +-import javax.crypto.Mac; +-import javax.crypto.spec.IvParameterSpec; +-import javax.crypto.spec.SecretKeySpec; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.nio.ByteOrder; +@@ -14,182 +11,185 @@ import java.security.InvalidKeyException; + import java.security.MessageDigest; + import java.security.NoSuchAlgorithmException; + import java.util.concurrent.atomic.AtomicBoolean; ++import javax.crypto.Cipher; ++import javax.crypto.Mac; ++import javax.crypto.spec.IvParameterSpec; ++import javax.crypto.spec.SecretKeySpec; ++import org.junit.jupiter.api.Test; + +-import static java.nio.charset.StandardCharsets.UTF_8; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.data.Offset.offset; +- +-class PacketWriterTest { +- +- private MetaData metaData = new MetaData.Builder("nw-1.alpine.example.com", 1520961345L, 100) +- .type("gauge") +- .typeInstance("value") +- .get(); +- private String username = "scott"; +- private String password = "t1_g$r"; +- +- @Test +- void testSignRequest() throws Exception { +- AtomicBoolean packetVerified = new AtomicBoolean(); +- Sender sender = new Sender("localhost", 4009) { +- @Override +- public void send(ByteBuffer buffer) throws IOException { +- short type = buffer.getShort(); +- assertThat(type).isEqualTo((short) 512); +- short length = buffer.getShort(); +- assertThat(length).isEqualTo((short) 41); +- byte[] packetSignature = new byte[32]; +- buffer.get(packetSignature, 0, 32); +- +- byte[] packetUsername = new byte[length - 36]; +- buffer.get(packetUsername, 0, packetUsername.length); +- assertThat(new String(packetUsername, UTF_8)).isEqualTo(username); +- +- byte[] packet = new byte[buffer.remaining()]; +- buffer.get(packet); +- +- byte[] usernameAndPacket = new byte[username.length() + packet.length]; +- System.arraycopy(packetUsername, 0, usernameAndPacket, 0, packetUsername.length); +- System.arraycopy(packet, 0, usernameAndPacket, packetUsername.length, packet.length); +- assertThat(sign(usernameAndPacket, password)).isEqualTo(packetSignature); +- +- verifyPacket(packet); +- packetVerified.set(true); +- } +- +- private byte[] sign(byte[] input, String password) { +- Mac mac; +- try { +- mac = Mac.getInstance("HmacSHA256"); +- mac.init(new SecretKeySpec(password.getBytes(UTF_8), "HmacSHA256")); +- } catch (NoSuchAlgorithmException | InvalidKeyException e) { +- throw new RuntimeException(e); +- } +- return mac.doFinal(input); ++final class PacketWriterTest { ++ ++ private MetaData metaData = ++ new MetaData.Builder("nw-1.alpine.example.com", 1520961345L, 100) ++ .type("gauge") ++ .typeInstance("value") ++ .get(); ++ private String username = "scott"; ++ private String password = "t1_g$r"; ++ ++ @Test ++ void signRequest() throws Exception { ++ AtomicBoolean packetVerified = new AtomicBoolean(); ++ Sender sender = ++ new Sender("localhost", 4009) { ++ @Override ++ public void send(ByteBuffer buffer) throws IOException { ++ short type = buffer.getShort(); ++ assertThat(type).isEqualTo((short) 512); ++ short length = buffer.getShort(); ++ assertThat(length).isEqualTo((short) 41); ++ byte[] packetSignature = new byte[32]; ++ buffer.get(packetSignature, 0, 32); ++ ++ byte[] packetUsername = new byte[length - 36]; ++ buffer.get(packetUsername, 0, packetUsername.length); ++ assertThat(new String(packetUsername, UTF_8)).isEqualTo(username); ++ ++ byte[] packet = new byte[buffer.remaining()]; ++ buffer.get(packet); ++ ++ byte[] usernameAndPacket = new byte[username.length() + packet.length]; ++ System.arraycopy(packetUsername, 0, usernameAndPacket, 0, packetUsername.length); ++ System.arraycopy(packet, 0, usernameAndPacket, packetUsername.length, packet.length); ++ assertThat(sign(usernameAndPacket, password)).isEqualTo(packetSignature); ++ ++ verifyPacket(packet); ++ packetVerified.set(true); ++ } ++ ++ private byte[] sign(byte[] input, String password) { ++ Mac mac; ++ try { ++ mac = Mac.getInstance("HmacSHA256"); ++ mac.init(new SecretKeySpec(password.getBytes(UTF_8), "HmacSHA256")); ++ } catch (NoSuchAlgorithmException | InvalidKeyException e) { ++ throw new RuntimeException(e); + } +- ++ return mac.doFinal(input); ++ } + }; +- PacketWriter packetWriter = new PacketWriter(sender, username, password, SecurityLevel.SIGN); +- packetWriter.write(metaData, 42); +- assertThat(packetVerified).isTrue(); +- } +- +- @Test +- void testEncryptRequest() throws Exception { +- AtomicBoolean packetVerified = new AtomicBoolean(); +- Sender sender = new Sender("localhost", 4009) { +- @Override +- public void send(ByteBuffer buffer) throws IOException { +- short type = buffer.getShort(); +- assertThat(type).isEqualTo((short) 0x0210); +- short length = buffer.getShort(); +- assertThat(length).isEqualTo((short) 134); +- short usernameLength = buffer.getShort(); +- assertThat(usernameLength).isEqualTo((short) 5); +- byte[] packetUsername = new byte[usernameLength]; +- buffer.get(packetUsername, 0, packetUsername.length); +- assertThat(new String(packetUsername, UTF_8)).isEqualTo(username); +- +- byte[] iv = new byte[16]; +- buffer.get(iv, 0, iv.length); +- byte[] encryptedPacket = new byte[buffer.remaining()]; +- buffer.get(encryptedPacket); +- +- byte[] decryptedPacket = decrypt(iv, encryptedPacket); +- byte[] hash = new byte[20]; +- System.arraycopy(decryptedPacket, 0, hash, 0, 20); +- byte[] rawData = new byte[decryptedPacket.length - 20]; +- System.arraycopy(decryptedPacket, 20, rawData, 0, decryptedPacket.length - 20); +- assertThat(sha1(rawData)).isEqualTo(hash); +- +- verifyPacket(rawData); +- packetVerified.set(true); +- } +- +- private byte[] decrypt(byte[] iv, byte[] input) { +- try { +- Cipher cipher = Cipher.getInstance("AES_256/OFB/NoPadding"); +- cipher.init(Cipher.DECRYPT_MODE, +- new SecretKeySpec(sha256(password.getBytes(UTF_8)), "AES"), +- new IvParameterSpec(iv)); +- return cipher.doFinal(input); +- } catch (Exception e) { +- throw new RuntimeException(e); +- } ++ PacketWriter packetWriter = new PacketWriter(sender, username, password, SecurityLevel.SIGN); ++ packetWriter.write(metaData, 42); ++ assertThat(packetVerified).isTrue(); ++ } ++ ++ @Test ++ void encryptRequest() throws Exception { ++ AtomicBoolean packetVerified = new AtomicBoolean(); ++ Sender sender = ++ new Sender("localhost", 4009) { ++ @Override ++ public void send(ByteBuffer buffer) throws IOException { ++ short type = buffer.getShort(); ++ assertThat(type).isEqualTo((short) 0x0210); ++ short length = buffer.getShort(); ++ assertThat(length).isEqualTo((short) 134); ++ short usernameLength = buffer.getShort(); ++ assertThat(usernameLength).isEqualTo((short) 5); ++ byte[] packetUsername = new byte[usernameLength]; ++ buffer.get(packetUsername, 0, packetUsername.length); ++ assertThat(new String(packetUsername, UTF_8)).isEqualTo(username); ++ ++ byte[] iv = new byte[16]; ++ buffer.get(iv, 0, iv.length); ++ byte[] encryptedPacket = new byte[buffer.remaining()]; ++ buffer.get(encryptedPacket); ++ ++ byte[] decryptedPacket = decrypt(iv, encryptedPacket); ++ byte[] hash = new byte[20]; ++ System.arraycopy(decryptedPacket, 0, hash, 0, 20); ++ byte[] rawData = new byte[decryptedPacket.length - 20]; ++ System.arraycopy(decryptedPacket, 20, rawData, 0, decryptedPacket.length - 20); ++ assertThat(sha1(rawData)).isEqualTo(hash); ++ ++ verifyPacket(rawData); ++ packetVerified.set(true); ++ } ++ ++ private byte[] decrypt(byte[] iv, byte[] input) { ++ try { ++ Cipher cipher = Cipher.getInstance("AES_256/OFB/NoPadding"); ++ cipher.init( ++ Cipher.DECRYPT_MODE, ++ new SecretKeySpec(sha256(password.getBytes(UTF_8)), "AES"), ++ new IvParameterSpec(iv)); ++ return cipher.doFinal(input); ++ } catch (Exception e) { ++ throw new RuntimeException(e); + } ++ } + +- private byte[] sha256(byte[] input) { +- try { +- return MessageDigest.getInstance("SHA-256").digest(input); +- } catch (NoSuchAlgorithmException e) { +- throw new RuntimeException(e); +- } ++ private byte[] sha256(byte[] input) { ++ try { ++ return MessageDigest.getInstance("SHA-256").digest(input); ++ } catch (NoSuchAlgorithmException e) { ++ throw new RuntimeException(e); + } ++ } + +- private byte[] sha1(byte[] input) { +- try { +- return MessageDigest.getInstance("SHA-1").digest(input); +- } catch (NoSuchAlgorithmException e) { +- throw new RuntimeException(e); +- } ++ private byte[] sha1(byte[] input) { ++ try { ++ return MessageDigest.getInstance("SHA-1").digest(input); ++ } catch (NoSuchAlgorithmException e) { ++ throw new RuntimeException(e); + } ++ } + }; +- PacketWriter packetWriter = new PacketWriter(sender, username, password, SecurityLevel.ENCRYPT); +- packetWriter.write(metaData, 42); +- assertThat(packetVerified).isTrue(); +- } +- +- private void verifyPacket(byte[] packetArr) { +- ByteBuffer packet = ByteBuffer.wrap(packetArr); +- +- short hostType = packet.getShort(); +- assertThat(hostType).isEqualTo((short) 0); +- short hostLength = packet.getShort(); +- assertThat(hostLength).isEqualTo((short) 28); +- byte[] host = new byte[hostLength - 5]; +- packet.get(host, 0, host.length); +- assertThat(new String(host, UTF_8)).isEqualTo("nw-1.alpine.example.com"); +- assertThat(packet.get()).isEqualTo((byte) 0); +- +- short timestampType = packet.getShort(); +- assertThat(timestampType).isEqualTo((short) 1); +- short timestampLength = packet.getShort(); +- assertThat(timestampLength).isEqualTo((short) 12); +- assertThat(packet.getLong()).isEqualTo(1520961345L); +- +- short typeType = packet.getShort(); +- assertThat(typeType).isEqualTo((short) 4); +- short typeLength = packet.getShort(); +- assertThat(typeLength).isEqualTo((short) 10); +- byte[] type = new byte[typeLength - 5]; +- packet.get(type, 0, type.length); +- assertThat(new String(type, UTF_8)).isEqualTo("gauge"); +- assertThat(packet.get()).isEqualTo((byte) 0); +- +- short typeInstanceType = packet.getShort(); +- assertThat(typeInstanceType).isEqualTo((short) 5); +- short typeInstanceLength = packet.getShort(); +- assertThat(typeInstanceLength).isEqualTo((short) 10); +- byte[] typeInstance = new byte[typeInstanceLength - 5]; +- packet.get(typeInstance, 0, typeInstance.length); +- assertThat(new String(typeInstance, UTF_8)).isEqualTo("value"); +- assertThat(packet.get()).isEqualTo((byte) 0); +- +- short periodType = packet.getShort(); +- assertThat(periodType).isEqualTo((short) 7); +- short periodLength = packet.getShort(); +- assertThat(periodLength).isEqualTo((short) 12); +- assertThat(packet.getLong()).isEqualTo(100); +- +- short valuesType = packet.getShort(); +- assertThat(valuesType).isEqualTo((short) 6); +- short valuesLength = packet.getShort(); +- assertThat(valuesLength).isEqualTo((short) 15); +- short amountOfValues = packet.getShort(); +- assertThat(amountOfValues).isEqualTo((short) 1); +- byte dataType = packet.get(); +- assertThat(dataType).isEqualTo((byte) 1); +- assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isEqualTo(42.0, offset(0.01)); +- } +- +-} +\ No newline at end of file ++ PacketWriter packetWriter = new PacketWriter(sender, username, password, SecurityLevel.ENCRYPT); ++ packetWriter.write(metaData, 42); ++ assertThat(packetVerified).isTrue(); ++ } ++ ++ private void verifyPacket(byte[] packetArr) { ++ ByteBuffer packet = ByteBuffer.wrap(packetArr); ++ ++ short hostType = packet.getShort(); ++ assertThat(hostType).isEqualTo((short) 0); ++ short hostLength = packet.getShort(); ++ assertThat(hostLength).isEqualTo((short) 28); ++ byte[] host = new byte[hostLength - 5]; ++ packet.get(host, 0, host.length); ++ assertThat(new String(host, UTF_8)).isEqualTo("nw-1.alpine.example.com"); ++ assertThat(packet.get()).isEqualTo((byte) 0); ++ ++ short timestampType = packet.getShort(); ++ assertThat(timestampType).isEqualTo((short) 1); ++ short timestampLength = packet.getShort(); ++ assertThat(timestampLength).isEqualTo((short) 12); ++ assertThat(packet.getLong()).isEqualTo(1520961345L); ++ ++ short typeType = packet.getShort(); ++ assertThat(typeType).isEqualTo((short) 4); ++ short typeLength = packet.getShort(); ++ assertThat(typeLength).isEqualTo((short) 10); ++ byte[] type = new byte[typeLength - 5]; ++ packet.get(type, 0, type.length); ++ assertThat(new String(type, UTF_8)).isEqualTo("gauge"); ++ assertThat(packet.get()).isEqualTo((byte) 0); ++ ++ short typeInstanceType = packet.getShort(); ++ assertThat(typeInstanceType).isEqualTo((short) 5); ++ short typeInstanceLength = packet.getShort(); ++ assertThat(typeInstanceLength).isEqualTo((short) 10); ++ byte[] typeInstance = new byte[typeInstanceLength - 5]; ++ packet.get(typeInstance, 0, typeInstance.length); ++ assertThat(new String(typeInstance, UTF_8)).isEqualTo("value"); ++ assertThat(packet.get()).isEqualTo((byte) 0); ++ ++ short periodType = packet.getShort(); ++ assertThat(periodType).isEqualTo((short) 7); ++ short periodLength = packet.getShort(); ++ assertThat(periodLength).isEqualTo((short) 12); ++ assertThat(packet.getLong()).isEqualTo(100); ++ ++ short valuesType = packet.getShort(); ++ assertThat(valuesType).isEqualTo((short) 6); ++ short valuesLength = packet.getShort(); ++ assertThat(valuesLength).isEqualTo((short) 15); ++ short amountOfValues = packet.getShort(); ++ assertThat(amountOfValues).isEqualTo((short) 1); ++ byte dataType = packet.get(); ++ assertThat(dataType).isEqualTo((byte) 1); ++ assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01)); ++ } ++} +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/Receiver.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/Receiver.java +@@ -1,5 +1,11 @@ + package io.dropwizard.metrics5.collectd; + ++import java.net.DatagramSocket; ++import java.net.InetAddress; ++import java.net.InetSocketAddress; ++import java.util.concurrent.BlockingQueue; ++import java.util.concurrent.LinkedBlockingQueue; ++import java.util.concurrent.TimeUnit; + import org.collectd.api.Notification; + import org.collectd.api.ValueList; + import org.collectd.protocol.Dispatcher; +@@ -8,59 +14,55 @@ import org.junit.jupiter.api.extension.AfterAllCallback; + import org.junit.jupiter.api.extension.BeforeAllCallback; + import org.junit.jupiter.api.extension.ExtensionContext; + +-import java.net.DatagramSocket; +-import java.net.InetAddress; +-import java.net.InetSocketAddress; +-import java.util.concurrent.BlockingQueue; +-import java.util.concurrent.LinkedBlockingQueue; +-import java.util.concurrent.TimeUnit; +- + public final class Receiver implements BeforeAllCallback, AfterAllCallback { + +- private final int port; +- +- private UdpReceiver receiver; +- private DatagramSocket socket; +- private final BlockingQueue queue = new LinkedBlockingQueue<>(); ++ private final int port; + +- public Receiver(int port) { +- this.port = port; +- } ++ private UdpReceiver receiver; ++ private DatagramSocket socket; ++ private final BlockingQueue queue = new LinkedBlockingQueue<>(); + ++ public Receiver(int port) { ++ this.port = port; ++ } + +- @Override +- public void afterAll(ExtensionContext context) throws Exception { +- receiver.shutdown(); +- socket.close(); +- } ++ @Override ++ public void afterAll(ExtensionContext context) throws Exception { ++ receiver.shutdown(); ++ socket.close(); ++ } + +- @Override +- public void beforeAll(ExtensionContext context) throws Exception { +- socket = new DatagramSocket(null); +- socket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), port)); ++ @Override ++ public void beforeAll(ExtensionContext context) throws Exception { ++ socket = new DatagramSocket(null); ++ socket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), port)); + +- receiver = new UdpReceiver(new Dispatcher() { +- @Override +- public void dispatch(ValueList values) { ++ receiver = ++ new UdpReceiver( ++ new Dispatcher() { ++ @Override ++ public void dispatch(ValueList values) { + queue.offer(new ValueList(values)); +- } ++ } + +- @Override +- public void dispatch(Notification notification) { ++ @Override ++ public void dispatch(Notification notification) { + throw new UnsupportedOperationException(); +- } +- }); +- receiver.setPort(port); +- new Thread(() -> { +- try { ++ } ++ }); ++ receiver.setPort(port); ++ new Thread( ++ () -> { ++ try { + receiver.listen(socket); +- } catch (Exception e) { ++ } catch (Exception e) { + e.printStackTrace(); +- } +- }).start(); +- } ++ } ++ }) ++ .start(); ++ } + +- public ValueList next() throws InterruptedException { +- return queue.poll(2, TimeUnit.SECONDS); +- } ++ public ValueList next() throws InterruptedException { ++ return queue.poll(2, TimeUnit.SECONDS); ++ } + } +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java +@@ -1,39 +1,41 @@ + package io.dropwizard.metrics5.collectd; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-class SanitizeTest { +- +- private Sanitize sanitize = new Sanitize(Sanitize.DEFAULT_MAX_LENGTH); +- +- @Test +- void replacesIllegalCharactersInName() throws Exception { +- assertThat(sanitize.name("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz_quux"); +- } +- +- @Test +- void replacesIllegalCharactersInInstanceName() throws Exception { +- assertThat(sanitize.instanceName("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz-quux"); +- } +- +- @Test +- void truncatesNamesExceedingMaxLength() throws Exception { +- String longName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; +- assertThat(sanitize.name(longName)).isEqualTo(longName.substring(0, (Sanitize.DEFAULT_MAX_LENGTH))); +- } +- +- @Test +- void truncatesNamesExceedingCustomMaxLength() throws Exception { +- Sanitize customSanitize = new Sanitize(70); +- String longName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; +- assertThat(customSanitize.name(longName)).isEqualTo(longName.substring(0, 70)); +- } +- +- @Test +- void replacesNonASCIICharacters() throws Exception { +- assertThat(sanitize.name("M" + '\u00FC' + "nchen")).isEqualTo("M_nchen"); +- } ++import org.junit.jupiter.api.Test; + ++final class SanitizeTest { ++ ++ private Sanitize sanitize = new Sanitize(Sanitize.DEFAULT_MAX_LENGTH); ++ ++ @Test ++ void replacesIllegalCharactersInName() throws Exception { ++ assertThat(sanitize.name("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz_quux"); ++ } ++ ++ @Test ++ void replacesIllegalCharactersInInstanceName() throws Exception { ++ assertThat(sanitize.instanceName("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz-quux"); ++ } ++ ++ @Test ++ void truncatesNamesExceedingMaxLength() throws Exception { ++ String longName = ++ "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; ++ assertThat(sanitize.name(longName)) ++ .isEqualTo(longName.substring(0, (Sanitize.DEFAULT_MAX_LENGTH))); ++ } ++ ++ @Test ++ void truncatesNamesExceedingCustomMaxLength() throws Exception { ++ Sanitize customSanitize = new Sanitize(70); ++ String longName = ++ "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; ++ assertThat(customSanitize.name(longName)).isEqualTo(longName.substring(0, 70)); ++ } ++ ++ @Test ++ void replacesNonASCIICharacters() throws Exception { ++ assertThat(sanitize.name("M" + '\u00FC' + "nchen")).isEqualTo("M_nchen"); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/CachedGauge.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/CachedGauge.java +@@ -10,65 +10,65 @@ import java.util.concurrent.atomic.AtomicReference; + * @param the type of the gauge's value + */ + public abstract class CachedGauge implements Gauge { +- private final Clock clock; +- private final AtomicLong reloadAt; +- private final long timeoutNS; +- private final AtomicReference value; ++ private final Clock clock; ++ private final AtomicLong reloadAt; ++ private final long timeoutNS; ++ private final AtomicReference value; + +- /** +- * Creates a new cached gauge with the given timeout period. +- * +- * @param timeout the timeout +- * @param timeoutUnit the unit of {@code timeout} +- */ +- protected CachedGauge(long timeout, TimeUnit timeoutUnit) { +- this(Clock.defaultClock(), timeout, timeoutUnit); +- } ++ /** ++ * Creates a new cached gauge with the given timeout period. ++ * ++ * @param timeout the timeout ++ * @param timeoutUnit the unit of {@code timeout} ++ */ ++ protected CachedGauge(long timeout, TimeUnit timeoutUnit) { ++ this(Clock.defaultClock(), timeout, timeoutUnit); ++ } + +- /** +- * Creates a new cached gauge with the given clock and timeout period. +- * +- * @param clock the clock used to calculate the timeout +- * @param timeout the timeout +- * @param timeoutUnit the unit of {@code timeout} +- */ +- protected CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit) { +- this.clock = clock; +- this.reloadAt = new AtomicLong(clock.getTick()); +- this.timeoutNS = timeoutUnit.toNanos(timeout); +- this.value = new AtomicReference<>(); +- } ++ /** ++ * Creates a new cached gauge with the given clock and timeout period. ++ * ++ * @param clock the clock used to calculate the timeout ++ * @param timeout the timeout ++ * @param timeoutUnit the unit of {@code timeout} ++ */ ++ protected CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit) { ++ this.clock = clock; ++ this.reloadAt = new AtomicLong(clock.getTick()); ++ this.timeoutNS = timeoutUnit.toNanos(timeout); ++ this.value = new AtomicReference<>(); ++ } + +- /** +- * Loads the value and returns it. +- * +- * @return the new value +- */ +- protected abstract T loadValue(); ++ /** ++ * Loads the value and returns it. ++ * ++ * @return the new value ++ */ ++ protected abstract T loadValue(); + +- @Override +- public T getValue() { +- T currentValue = this.value.get(); +- if (shouldLoad() || currentValue == null) { +- T newValue = loadValue(); +- if (!this.value.compareAndSet(currentValue, newValue)) { +- return this.value.get(); +- } +- return newValue; +- } +- return currentValue; ++ @Override ++ public T getValue() { ++ T currentValue = this.value.get(); ++ if (shouldLoad() || currentValue == null) { ++ T newValue = loadValue(); ++ if (!this.value.compareAndSet(currentValue, newValue)) { ++ return this.value.get(); ++ } ++ return newValue; + } ++ return currentValue; ++ } + +- private boolean shouldLoad() { +- for ( ;; ) { +- final long time = clock.getTick(); +- final long current = reloadAt.get(); +- if (current > time) { +- return false; +- } +- if (reloadAt.compareAndSet(current, time + timeoutNS)) { +- return true; +- } +- } ++ private boolean shouldLoad() { ++ for (; ; ) { ++ final long time = clock.getTick(); ++ final long current = reloadAt.get(); ++ if (current > time) { ++ return false; ++ } ++ if (reloadAt.compareAndSet(current, time + timeoutNS)) { ++ return true; ++ } + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ChunkedAssociativeLongArray.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ChunkedAssociativeLongArray.java +@@ -1,200 +1,211 @@ + package io.dropwizard.metrics5; + ++import static java.lang.System.arraycopy; ++import static java.util.Arrays.binarySearch; ++ + import java.lang.ref.SoftReference; + import java.util.ArrayDeque; + import java.util.Deque; + import java.util.Iterator; + +-import static java.lang.System.arraycopy; +-import static java.util.Arrays.binarySearch; +- + class ChunkedAssociativeLongArray { +- private static final long[] EMPTY = new long[0]; +- private static final int DEFAULT_CHUNK_SIZE = 512; +- private static final int MAX_CACHE_SIZE = 128; +- +- private final int defaultChunkSize; +- +- /* +- * We use this ArrayDeque as cache to store chunks that are expired and removed from main data structure. +- * Then instead of allocating new Chunk immediately we are trying to poll one from this deque. +- * So if you have constant or slowly changing load ChunkedAssociativeLongArray will never +- * throw away old chunks or allocate new ones which makes this data structure almost garbage free. +- */ +- private final ArrayDeque> chunksCache = new ArrayDeque<>(); +- +- private final Deque chunks = new ArrayDeque<>(); +- +- ChunkedAssociativeLongArray() { +- this(DEFAULT_CHUNK_SIZE); ++ private static final long[] EMPTY = new long[0]; ++ private static final int DEFAULT_CHUNK_SIZE = 512; ++ private static final int MAX_CACHE_SIZE = 128; ++ ++ private final int defaultChunkSize; ++ ++ /* ++ * We use this ArrayDeque as cache to store chunks that are expired and removed from main data structure. ++ * Then instead of allocating new Chunk immediately we are trying to poll one from this deque. ++ * So if you have constant or slowly changing load ChunkedAssociativeLongArray will never ++ * throw away old chunks or allocate new ones which makes this data structure almost garbage free. ++ */ ++ private final ArrayDeque> chunksCache = new ArrayDeque<>(); ++ ++ private final Deque chunks = new ArrayDeque<>(); ++ ++ ChunkedAssociativeLongArray() { ++ this(DEFAULT_CHUNK_SIZE); ++ } ++ ++ ChunkedAssociativeLongArray(int chunkSize) { ++ this.defaultChunkSize = chunkSize; ++ } ++ ++ private Chunk allocateChunk() { ++ while (true) { ++ final SoftReference chunkRef = chunksCache.pollLast(); ++ if (chunkRef == null) { ++ return new Chunk(defaultChunkSize); ++ } ++ final Chunk chunk = chunkRef.get(); ++ if (chunk != null) { ++ chunk.cursor = 0; ++ chunk.startIndex = 0; ++ chunk.chunkSize = chunk.keys.length; ++ return chunk; ++ } + } ++ } + +- ChunkedAssociativeLongArray(int chunkSize) { +- this.defaultChunkSize = chunkSize; ++ private void freeChunk(Chunk chunk) { ++ if (chunksCache.size() < MAX_CACHE_SIZE) { ++ chunksCache.add(new SoftReference<>(chunk)); + } +- +- private Chunk allocateChunk() { +- while (true) { +- final SoftReference chunkRef = chunksCache.pollLast(); +- if (chunkRef == null) { +- return new Chunk(defaultChunkSize); +- } +- final Chunk chunk = chunkRef.get(); +- if (chunk != null) { +- chunk.cursor = 0; +- chunk.startIndex = 0; +- chunk.chunkSize = chunk.keys.length; +- return chunk; +- } +- } ++ } ++ ++ synchronized boolean put(long key, long value) { ++ Chunk activeChunk = chunks.peekLast(); ++ if (activeChunk != null ++ && activeChunk.cursor != 0 ++ && activeChunk.keys[activeChunk.cursor - 1] > key) { ++ // key should be the same as last inserted or bigger ++ return false; + } +- +- private void freeChunk(Chunk chunk) { +- if (chunksCache.size() < MAX_CACHE_SIZE) { +- chunksCache.add(new SoftReference<>(chunk)); +- } ++ if (activeChunk == null ++ || activeChunk.cursor - activeChunk.startIndex == activeChunk.chunkSize) { ++ // The last chunk doesn't exist or full ++ activeChunk = allocateChunk(); ++ chunks.add(activeChunk); + } +- +- synchronized boolean put(long key, long value) { +- Chunk activeChunk = chunks.peekLast(); +- if (activeChunk != null && activeChunk.cursor != 0 && activeChunk.keys[activeChunk.cursor - 1] > key) { +- // key should be the same as last inserted or bigger +- return false; +- } +- if (activeChunk == null || activeChunk.cursor - activeChunk.startIndex == activeChunk.chunkSize) { +- // The last chunk doesn't exist or full +- activeChunk = allocateChunk(); +- chunks.add(activeChunk); +- } +- activeChunk.append(key, value); +- return true; ++ activeChunk.append(key, value); ++ return true; ++ } ++ ++ synchronized long[] values() { ++ final int valuesSize = size(); ++ if (valuesSize == 0) { ++ return EMPTY; + } + +- synchronized long[] values() { +- final int valuesSize = size(); +- if (valuesSize == 0) { +- return EMPTY; +- } +- +- final long[] values = new long[valuesSize]; +- int valuesIndex = 0; +- for (Chunk chunk : chunks) { +- int length = chunk.cursor - chunk.startIndex; +- int itemsToCopy = Math.min(valuesSize - valuesIndex, length); +- arraycopy(chunk.values, chunk.startIndex, values, valuesIndex, itemsToCopy); +- valuesIndex += length; +- } +- return values; ++ final long[] values = new long[valuesSize]; ++ int valuesIndex = 0; ++ for (Chunk chunk : chunks) { ++ int length = chunk.cursor - chunk.startIndex; ++ int itemsToCopy = Math.min(valuesSize - valuesIndex, length); ++ arraycopy(chunk.values, chunk.startIndex, values, valuesIndex, itemsToCopy); ++ valuesIndex += length; + } ++ return values; ++ } + +- synchronized int size() { +- int result = 0; +- for (Chunk chunk : chunks) { +- result += chunk.cursor - chunk.startIndex; +- } +- return result; ++ synchronized int size() { ++ int result = 0; ++ for (Chunk chunk : chunks) { ++ result += chunk.cursor - chunk.startIndex; + } +- +- synchronized String out() { +- final StringBuilder builder = new StringBuilder(); +- final Iterator iterator = chunks.iterator(); +- while (iterator.hasNext()) { +- final Chunk chunk = iterator.next(); +- builder.append('['); +- for (int i = chunk.startIndex; i < chunk.cursor; i++) { +- builder.append('(').append(chunk.keys[i]).append(": ") +- .append(chunk.values[i]).append(')').append(' '); +- } +- builder.append(']'); +- if (iterator.hasNext()) { +- builder.append("->"); +- } +- } +- return builder.toString(); ++ return result; ++ } ++ ++ synchronized String out() { ++ final StringBuilder builder = new StringBuilder(); ++ final Iterator iterator = chunks.iterator(); ++ while (iterator.hasNext()) { ++ final Chunk chunk = iterator.next(); ++ builder.append('['); ++ for (int i = chunk.startIndex; i < chunk.cursor; i++) { ++ builder ++ .append('(') ++ .append(chunk.keys[i]) ++ .append(": ") ++ .append(chunk.values[i]) ++ .append(')') ++ .append(' '); ++ } ++ builder.append(']'); ++ if (iterator.hasNext()) { ++ builder.append("->"); ++ } + } +- +- /** +- * Try to trim all beyond specified boundaries. +- * +- * @param startKey the start value for which all elements less than it should be removed. +- * @param endKey the end value for which all elements greater/equals than it should be removed. ++ return builder.toString(); ++ } ++ ++ /** ++ * Try to trim all beyond specified boundaries. ++ * ++ * @param startKey the start value for which all elements less than it should be removed. ++ * @param endKey the end value for which all elements greater/equals than it should be removed. ++ */ ++ synchronized void trim(long startKey, long endKey) { ++ /* ++ * [3, 4, 5, 9] -> [10, 13, 14, 15] -> [21, 24, 29, 30] -> [31] :: start layout ++ * |5______________________________23| :: trim(5, 23) ++ * [5, 9] -> [10, 13, 14, 15] -> [21] :: result layout + */ +- synchronized void trim(long startKey, long endKey) { +- /* +- * [3, 4, 5, 9] -> [10, 13, 14, 15] -> [21, 24, 29, 30] -> [31] :: start layout +- * |5______________________________23| :: trim(5, 23) +- * [5, 9] -> [10, 13, 14, 15] -> [21] :: result layout +- */ +- final Iterator descendingIterator = chunks.descendingIterator(); +- while (descendingIterator.hasNext()) { +- final Chunk currentTail = descendingIterator.next(); +- if (isFirstElementIsEmptyOrGreaterEqualThanKey(currentTail, endKey)) { +- freeChunk(currentTail); +- descendingIterator.remove(); +- } else { +- currentTail.cursor = findFirstIndexOfGreaterEqualElements(currentTail.keys, currentTail.startIndex, +- currentTail.cursor, endKey); +- break; +- } +- } ++ final Iterator descendingIterator = chunks.descendingIterator(); ++ while (descendingIterator.hasNext()) { ++ final Chunk currentTail = descendingIterator.next(); ++ if (isFirstElementIsEmptyOrGreaterEqualThanKey(currentTail, endKey)) { ++ freeChunk(currentTail); ++ descendingIterator.remove(); ++ } else { ++ currentTail.cursor = ++ findFirstIndexOfGreaterEqualElements( ++ currentTail.keys, currentTail.startIndex, currentTail.cursor, endKey); ++ break; ++ } ++ } + +- final Iterator iterator = chunks.iterator(); +- while (iterator.hasNext()) { +- final Chunk currentHead = iterator.next(); +- if (isLastElementIsLessThanKey(currentHead, startKey)) { +- freeChunk(currentHead); +- iterator.remove(); +- } else { +- final int newStartIndex = findFirstIndexOfGreaterEqualElements(currentHead.keys, currentHead.startIndex, +- currentHead.cursor, startKey); +- if (currentHead.startIndex != newStartIndex) { +- currentHead.startIndex = newStartIndex; +- currentHead.chunkSize = currentHead.cursor - currentHead.startIndex; +- } +- break; +- } ++ final Iterator iterator = chunks.iterator(); ++ while (iterator.hasNext()) { ++ final Chunk currentHead = iterator.next(); ++ if (isLastElementIsLessThanKey(currentHead, startKey)) { ++ freeChunk(currentHead); ++ iterator.remove(); ++ } else { ++ final int newStartIndex = ++ findFirstIndexOfGreaterEqualElements( ++ currentHead.keys, currentHead.startIndex, currentHead.cursor, startKey); ++ if (currentHead.startIndex != newStartIndex) { ++ currentHead.startIndex = newStartIndex; ++ currentHead.chunkSize = currentHead.cursor - currentHead.startIndex; + } ++ break; ++ } + } ++ } + +- synchronized void clear() { +- chunks.clear(); +- } ++ synchronized void clear() { ++ chunks.clear(); ++ } + +- private boolean isFirstElementIsEmptyOrGreaterEqualThanKey(Chunk chunk, long key) { +- return chunk.cursor == chunk.startIndex || chunk.keys[chunk.startIndex] >= key; +- } ++ private boolean isFirstElementIsEmptyOrGreaterEqualThanKey(Chunk chunk, long key) { ++ return chunk.cursor == chunk.startIndex || chunk.keys[chunk.startIndex] >= key; ++ } + +- private boolean isLastElementIsLessThanKey(Chunk chunk, long key) { +- return chunk.cursor == chunk.startIndex || chunk.keys[chunk.cursor - 1] < key; +- } ++ private boolean isLastElementIsLessThanKey(Chunk chunk, long key) { ++ return chunk.cursor == chunk.startIndex || chunk.keys[chunk.cursor - 1] < key; ++ } + +- private int findFirstIndexOfGreaterEqualElements(long[] array, int startIndex, int endIndex, long minKey) { +- if (endIndex == startIndex || array[startIndex] >= minKey) { +- return startIndex; +- } +- final int keyIndex = binarySearch(array, startIndex, endIndex, minKey); +- return keyIndex < 0 ? -(keyIndex + 1) : keyIndex; ++ private int findFirstIndexOfGreaterEqualElements( ++ long[] array, int startIndex, int endIndex, long minKey) { ++ if (endIndex == startIndex || array[startIndex] >= minKey) { ++ return startIndex; + } ++ final int keyIndex = binarySearch(array, startIndex, endIndex, minKey); ++ return keyIndex < 0 ? -(keyIndex + 1) : keyIndex; ++ } + +- private static class Chunk { ++ private static class Chunk { + +- private final long[] keys; +- private final long[] values; ++ private final long[] keys; ++ private final long[] values; + +- private int chunkSize; // can differ from keys.length after half clear() +- private int startIndex = 0; +- private int cursor = 0; ++ private int chunkSize; // can differ from keys.length after half clear() ++ private int startIndex = 0; ++ private int cursor = 0; + +- private Chunk(int chunkSize) { +- this.chunkSize = chunkSize; +- this.keys = new long[chunkSize]; +- this.values = new long[chunkSize]; +- } ++ private Chunk(int chunkSize) { ++ this.chunkSize = chunkSize; ++ this.keys = new long[chunkSize]; ++ this.values = new long[chunkSize]; ++ } + +- private void append(long key, long value) { +- keys[cursor] = key; +- values[cursor] = value; +- cursor++; +- } ++ private void append(long key, long value) { ++ keys[cursor] = key; ++ values[cursor] = value; ++ cursor++; + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Clock.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Clock.java +@@ -1,46 +1,42 @@ + package io.dropwizard.metrics5; + +-/** +- * An abstraction for how time passes. It is passed to {@link Timer} to track timing. +- */ ++/** An abstraction for how time passes. It is passed to {@link Timer} to track timing. */ + public abstract class Clock { +- /** +- * Returns the current time tick. +- * +- * @return time tick in nanoseconds +- */ +- public abstract long getTick(); ++ /** ++ * Returns the current time tick. ++ * ++ * @return time tick in nanoseconds ++ */ ++ public abstract long getTick(); + +- /** +- * Returns the current time in milliseconds. +- * +- * @return time in milliseconds +- */ +- public long getTime() { +- return System.currentTimeMillis(); +- } ++ /** ++ * Returns the current time in milliseconds. ++ * ++ * @return time in milliseconds ++ */ ++ public long getTime() { ++ return System.currentTimeMillis(); ++ } + +- /** +- * The default clock to use. +- * +- * @return the default {@link Clock} instance +- * @see Clock.UserTimeClock +- */ +- public static Clock defaultClock() { +- return UserTimeClockHolder.DEFAULT; +- } ++ /** ++ * The default clock to use. ++ * ++ * @return the default {@link Clock} instance ++ * @see Clock.UserTimeClock ++ */ ++ public static Clock defaultClock() { ++ return UserTimeClockHolder.DEFAULT; ++ } + +- /** +- * A clock implementation which returns the current time in epoch nanoseconds. +- */ +- public static class UserTimeClock extends Clock { +- @Override +- public long getTick() { +- return System.nanoTime(); +- } ++ /** A clock implementation which returns the current time in epoch nanoseconds. */ ++ public static class UserTimeClock extends Clock { ++ @Override ++ public long getTick() { ++ return System.nanoTime(); + } ++ } + +- private static class UserTimeClockHolder { +- private static final Clock DEFAULT = new UserTimeClock(); +- } ++ private static class UserTimeClockHolder { ++ private static final Clock DEFAULT = new UserTimeClock(); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java +@@ -1,8 +1,8 @@ + package io.dropwizard.metrics5; + ++import com.google.common.collect.ImmutableSet; + import java.io.PrintStream; + import java.text.DateFormat; +-import java.util.Collections; + import java.util.Date; + import java.util.Locale; + import java.util.Map; +@@ -12,349 +12,491 @@ import java.util.TimeZone; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; + +-/** +- * A reporter which outputs measurements to a {@link PrintStream}, like {@code System.out}. +- */ ++/** A reporter which outputs measurements to a {@link PrintStream}, like {@code System.out}. */ + public class ConsoleReporter extends ScheduledReporter { ++ /** ++ * Returns a new {@link Builder} for {@link ConsoleReporter}. ++ * ++ * @param registry the registry to report ++ * @return a {@link Builder} instance for a {@link ConsoleReporter} ++ */ ++ public static Builder forRegistry(MetricRegistry registry) { ++ return new Builder(registry); ++ } ++ ++ /** ++ * A builder for {@link ConsoleReporter} instances. Defaults to using the default locale and time ++ * zone, writing to {@code System.out}, converting rates to events/second, converting durations to ++ * milliseconds, and not filtering metrics. ++ */ ++ public static class Builder { ++ private final MetricRegistry registry; ++ private PrintStream output; ++ private Locale locale; ++ private Clock clock; ++ private TimeZone timeZone; ++ private TimeUnit rateUnit; ++ private TimeUnit durationUnit; ++ private MetricFilter filter; ++ private ScheduledExecutorService executor; ++ private boolean shutdownExecutorOnStop; ++ private Set disabledMetricAttributes; ++ ++ private Builder(MetricRegistry registry) { ++ this.registry = registry; ++ this.output = System.out; ++ this.locale = Locale.getDefault(); ++ this.clock = Clock.defaultClock(); ++ this.timeZone = TimeZone.getDefault(); ++ this.rateUnit = TimeUnit.SECONDS; ++ this.durationUnit = TimeUnit.MILLISECONDS; ++ this.filter = MetricFilter.ALL; ++ this.executor = null; ++ this.shutdownExecutorOnStop = true; ++ disabledMetricAttributes = ImmutableSet.of(); ++ } ++ + /** +- * Returns a new {@link Builder} for {@link ConsoleReporter}. ++ * Specifies whether or not, the executor (used for reporting) will be stopped with same time ++ * with reporter. Default value is true. Setting this parameter to false, has the sense in ++ * combining with providing external managed executor via {@link ++ * #scheduleOn(ScheduledExecutorService)}. + * +- * @param registry the registry to report +- * @return a {@link Builder} instance for a {@link ConsoleReporter} ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ * @return {@code this} + */ +- public static Builder forRegistry(MetricRegistry registry) { +- return new Builder(registry); ++ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { ++ this.shutdownExecutorOnStop = shutdownExecutorOnStop; ++ return this; + } + + /** +- * A builder for {@link ConsoleReporter} instances. Defaults to using the default locale and +- * time zone, writing to {@code System.out}, converting rates to events/second, converting +- * durations to milliseconds, and not filtering metrics. ++ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. ++ * Null value leads to executor will be auto created on start. ++ * ++ * @param executor the executor to use while scheduling reporting of metrics. ++ * @return {@code this} + */ +- public static class Builder { +- private final MetricRegistry registry; +- private PrintStream output; +- private Locale locale; +- private Clock clock; +- private TimeZone timeZone; +- private TimeUnit rateUnit; +- private TimeUnit durationUnit; +- private MetricFilter filter; +- private ScheduledExecutorService executor; +- private boolean shutdownExecutorOnStop; +- private Set disabledMetricAttributes; +- +- private Builder(MetricRegistry registry) { +- this.registry = registry; +- this.output = System.out; +- this.locale = Locale.getDefault(); +- this.clock = Clock.defaultClock(); +- this.timeZone = TimeZone.getDefault(); +- this.rateUnit = TimeUnit.SECONDS; +- this.durationUnit = TimeUnit.MILLISECONDS; +- this.filter = MetricFilter.ALL; +- this.executor = null; +- this.shutdownExecutorOnStop = true; +- disabledMetricAttributes = Collections.emptySet(); +- } +- +- /** +- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. +- * Default value is true. +- * Setting this parameter to false, has the sense in combining with providing external managed executor via {@link #scheduleOn(ScheduledExecutorService)}. +- * +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- * @return {@code this} +- */ +- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { +- this.shutdownExecutorOnStop = shutdownExecutorOnStop; +- return this; +- } +- +- /** +- * Specifies the executor to use while scheduling reporting of metrics. +- * Default value is null. +- * Null value leads to executor will be auto created on start. +- * +- * @param executor the executor to use while scheduling reporting of metrics. +- * @return {@code this} +- */ +- public Builder scheduleOn(ScheduledExecutorService executor) { +- this.executor = executor; +- return this; +- } +- +- /** +- * Write to the given {@link PrintStream}. +- * +- * @param output a {@link PrintStream} instance. +- * @return {@code this} +- */ +- public Builder outputTo(PrintStream output) { +- this.output = output; +- return this; +- } +- +- /** +- * Format numbers for the given {@link Locale}. +- * +- * @param locale a {@link Locale} +- * @return {@code this} +- */ +- public Builder formattedFor(Locale locale) { +- this.locale = locale; +- return this; +- } +- +- /** +- * Use the given {@link Clock} instance for the time. +- * +- * @param clock a {@link Clock} instance +- * @return {@code this} +- */ +- public Builder withClock(Clock clock) { +- this.clock = clock; +- return this; +- } +- +- /** +- * Use the given {@link TimeZone} for the time. +- * +- * @param timeZone a {@link TimeZone} +- * @return {@code this} +- */ +- public Builder formattedFor(TimeZone timeZone) { +- this.timeZone = timeZone; +- return this; +- } +- +- /** +- * Convert rates to the given time unit. +- * +- * @param rateUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertRatesTo(TimeUnit rateUnit) { +- this.rateUnit = rateUnit; +- return this; +- } +- +- /** +- * Convert durations to the given time unit. +- * +- * @param durationUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertDurationsTo(TimeUnit durationUnit) { +- this.durationUnit = durationUnit; +- return this; +- } +- +- /** +- * Only report metrics which match the given filter. +- * +- * @param filter a {@link MetricFilter} +- * @return {@code this} +- */ +- public Builder filter(MetricFilter filter) { +- this.filter = filter; +- return this; +- } +- +- /** +- * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). +- * See {@link MetricAttribute}. +- * +- * @param disabledMetricAttributes a {@link MetricFilter} +- * @return {@code this} +- */ +- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { +- this.disabledMetricAttributes = disabledMetricAttributes; +- return this; +- } +- +- /** +- * Builds a {@link ConsoleReporter} with the given properties. +- * +- * @return a {@link ConsoleReporter} +- */ +- public ConsoleReporter build() { +- return new ConsoleReporter(registry, +- output, +- locale, +- clock, +- timeZone, +- rateUnit, +- durationUnit, +- filter, +- executor, +- shutdownExecutorOnStop, +- disabledMetricAttributes); +- } ++ public Builder scheduleOn(ScheduledExecutorService executor) { ++ this.executor = executor; ++ return this; + } + +- private static final int CONSOLE_WIDTH = 80; +- +- private final PrintStream output; +- private final Locale locale; +- private final Clock clock; +- private final DateFormat dateFormat; +- +- private ConsoleReporter(MetricRegistry registry, +- PrintStream output, +- Locale locale, +- Clock clock, +- TimeZone timeZone, +- TimeUnit rateUnit, +- TimeUnit durationUnit, +- MetricFilter filter, +- ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop, +- Set disabledMetricAttributes) { +- super(registry, "console-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, disabledMetricAttributes); +- this.output = output; +- this.locale = locale; +- this.clock = clock; +- this.dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, +- DateFormat.MEDIUM, +- locale); +- dateFormat.setTimeZone(timeZone); ++ /** ++ * Write to the given {@link PrintStream}. ++ * ++ * @param output a {@link PrintStream} instance. ++ * @return {@code this} ++ */ ++ public Builder outputTo(PrintStream output) { ++ this.output = output; ++ return this; + } + +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap> gauges, +- SortedMap counters, +- SortedMap histograms, +- SortedMap meters, +- SortedMap timers) { +- final String dateTime = dateFormat.format(new Date(clock.getTime())); +- printWithBanner(dateTime, '='); +- output.println(); +- +- if (!gauges.isEmpty()) { +- printWithBanner("-- Gauges", '-'); +- for (Map.Entry> entry : gauges.entrySet()) { +- output.println(entry.getKey()); +- printGauge(entry.getValue()); +- } +- output.println(); +- } +- +- if (!counters.isEmpty()) { +- printWithBanner("-- Counters", '-'); +- for (Map.Entry entry : counters.entrySet()) { +- output.println(entry.getKey()); +- printCounter(entry); +- } +- output.println(); +- } +- +- if (!histograms.isEmpty()) { +- printWithBanner("-- Histograms", '-'); +- for (Map.Entry entry : histograms.entrySet()) { +- output.println(entry.getKey()); +- printHistogram(entry.getValue()); +- } +- output.println(); +- } +- +- if (!meters.isEmpty()) { +- printWithBanner("-- Meters", '-'); +- for (Map.Entry entry : meters.entrySet()) { +- output.println(entry.getKey()); +- printMeter(entry.getValue()); +- } +- output.println(); +- } +- +- if (!timers.isEmpty()) { +- printWithBanner("-- Timers", '-'); +- for (Map.Entry entry : timers.entrySet()) { +- output.println(entry.getKey()); +- printTimer(entry.getValue()); +- } +- output.println(); +- } +- +- output.println(); +- output.flush(); ++ /** ++ * Format numbers for the given {@link Locale}. ++ * ++ * @param locale a {@link Locale} ++ * @return {@code this} ++ */ ++ public Builder formattedFor(Locale locale) { ++ this.locale = locale; ++ return this; + } + +- private void printMeter(Meter meter) { +- printIfEnabled(MetricAttribute.COUNT, String.format(locale, " count = %d", meter.getCount())); +- printIfEnabled(MetricAttribute.SUM, String.format(locale, " sum = %d", meter.getSum())); +- printIfEnabled(MetricAttribute.MEAN_RATE, String.format(locale, " mean rate = %2.2f events/%s", convertRate(meter.getMeanRate()), getRateUnit())); +- printIfEnabled(MetricAttribute.M1_RATE, String.format(locale, " 1-minute rate = %2.2f events/%s", convertRate(meter.getOneMinuteRate()), getRateUnit())); +- printIfEnabled(MetricAttribute.M5_RATE, String.format(locale, " 5-minute rate = %2.2f events/%s", convertRate(meter.getFiveMinuteRate()), getRateUnit())); +- printIfEnabled(MetricAttribute.M15_RATE, String.format(locale, " 15-minute rate = %2.2f events/%s", convertRate(meter.getFifteenMinuteRate()), getRateUnit())); ++ /** ++ * Use the given {@link Clock} instance for the time. ++ * ++ * @param clock a {@link Clock} instance ++ * @return {@code this} ++ */ ++ public Builder withClock(Clock clock) { ++ this.clock = clock; ++ return this; + } + +- private void printCounter(Map.Entry entry) { +- output.printf(locale, " count = %d%n", entry.getValue().getCount()); ++ /** ++ * Use the given {@link TimeZone} for the time. ++ * ++ * @param timeZone a {@link TimeZone} ++ * @return {@code this} ++ */ ++ public Builder formattedFor(TimeZone timeZone) { ++ this.timeZone = timeZone; ++ return this; + } + +- private void printGauge(Gauge gauge) { +- output.printf(locale, " value = %s%n", gauge.getValue()); ++ /** ++ * Convert rates to the given time unit. ++ * ++ * @param rateUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertRatesTo(TimeUnit rateUnit) { ++ this.rateUnit = rateUnit; ++ return this; + } + +- private void printHistogram(Histogram histogram) { +- printIfEnabled(MetricAttribute.COUNT, String.format(locale, " count = %d", histogram.getCount())); +- printIfEnabled(MetricAttribute.SUM, String.format(locale, " sum = %d", histogram.getSum())); +- Snapshot snapshot = histogram.getSnapshot(); +- printIfEnabled(MetricAttribute.MIN, String.format(locale, " min = %d", snapshot.getMin())); +- printIfEnabled(MetricAttribute.MAX, String.format(locale, " max = %d", snapshot.getMax())); +- printIfEnabled(MetricAttribute.MEAN, String.format(locale, " mean = %2.2f", snapshot.getMean())); +- printIfEnabled(MetricAttribute.STDDEV, String.format(locale, " stddev = %2.2f", snapshot.getStdDev())); +- printIfEnabled(MetricAttribute.P50, String.format(locale, " median = %2.2f", snapshot.getMedian())); +- printIfEnabled(MetricAttribute.P75, String.format(locale, " 75%% <= %2.2f", snapshot.get75thPercentile())); +- printIfEnabled(MetricAttribute.P95, String.format(locale, " 95%% <= %2.2f", snapshot.get95thPercentile())); +- printIfEnabled(MetricAttribute.P98, String.format(locale, " 98%% <= %2.2f", snapshot.get98thPercentile())); +- printIfEnabled(MetricAttribute.P99, String.format(locale, " 99%% <= %2.2f", snapshot.get99thPercentile())); +- printIfEnabled(MetricAttribute.P999, String.format(locale, " 99.9%% <= %2.2f", snapshot.get999thPercentile())); ++ /** ++ * Convert durations to the given time unit. ++ * ++ * @param durationUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertDurationsTo(TimeUnit durationUnit) { ++ this.durationUnit = durationUnit; ++ return this; + } + +- private void printTimer(Timer timer) { +- final Snapshot snapshot = timer.getSnapshot(); +- printIfEnabled(MetricAttribute.COUNT, String.format(locale, " count = %d", timer.getCount())); +- printIfEnabled(MetricAttribute.SUM, String.format(locale, " sum = %2.2f", convertDuration(timer.getSum()))); +- printIfEnabled(MetricAttribute.MEAN_RATE, String.format(locale, " mean rate = %2.2f calls/%s", convertRate(timer.getMeanRate()), getRateUnit())); +- printIfEnabled(MetricAttribute.M1_RATE, String.format(locale, " 1-minute rate = %2.2f calls/%s", convertRate(timer.getOneMinuteRate()), getRateUnit())); +- printIfEnabled(MetricAttribute.M5_RATE, String.format(locale, " 5-minute rate = %2.2f calls/%s", convertRate(timer.getFiveMinuteRate()), getRateUnit())); +- printIfEnabled(MetricAttribute.M15_RATE, String.format(locale, " 15-minute rate = %2.2f calls/%s", convertRate(timer.getFifteenMinuteRate()), getRateUnit())); +- +- printIfEnabled(MetricAttribute.MIN, String.format(locale, " min = %2.2f %s", convertDuration(snapshot.getMin()), getDurationUnit())); +- printIfEnabled(MetricAttribute.MAX, String.format(locale, " max = %2.2f %s", convertDuration(snapshot.getMax()), getDurationUnit())); +- printIfEnabled(MetricAttribute.MEAN, String.format(locale, " mean = %2.2f %s", convertDuration(snapshot.getMean()), getDurationUnit())); +- printIfEnabled(MetricAttribute.STDDEV, String.format(locale, " stddev = %2.2f %s", convertDuration(snapshot.getStdDev()), getDurationUnit())); +- printIfEnabled(MetricAttribute.P50, String.format(locale, " median = %2.2f %s", convertDuration(snapshot.getMedian()), getDurationUnit())); +- printIfEnabled(MetricAttribute.P75, String.format(locale, " 75%% <= %2.2f %s", convertDuration(snapshot.get75thPercentile()), getDurationUnit())); +- printIfEnabled(MetricAttribute.P95, String.format(locale, " 95%% <= %2.2f %s", convertDuration(snapshot.get95thPercentile()), getDurationUnit())); +- printIfEnabled(MetricAttribute.P98, String.format(locale, " 98%% <= %2.2f %s", convertDuration(snapshot.get98thPercentile()), getDurationUnit())); +- printIfEnabled(MetricAttribute.P99, String.format(locale, " 99%% <= %2.2f %s", convertDuration(snapshot.get99thPercentile()), getDurationUnit())); +- printIfEnabled(MetricAttribute.P999, String.format(locale, " 99.9%% <= %2.2f %s", convertDuration(snapshot.get999thPercentile()), getDurationUnit())); ++ /** ++ * Only report metrics which match the given filter. ++ * ++ * @param filter a {@link MetricFilter} ++ * @return {@code this} ++ */ ++ public Builder filter(MetricFilter filter) { ++ this.filter = filter; ++ return this; + } + +- private void printWithBanner(String s, char c) { +- output.print(s); +- output.print(' '); +- for (int i = 0; i < (CONSOLE_WIDTH - s.length() - 1); i++) { +- output.print(c); +- } +- output.println(); ++ /** ++ * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). ++ * See {@link MetricAttribute}. ++ * ++ * @param disabledMetricAttributes a {@link MetricFilter} ++ * @return {@code this} ++ */ ++ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { ++ this.disabledMetricAttributes = disabledMetricAttributes; ++ return this; + } + + /** +- * Print only if the attribute is enabled ++ * Builds a {@link ConsoleReporter} with the given properties. + * +- * @param type Metric attribute +- * @param status Status to be logged ++ * @return a {@link ConsoleReporter} + */ +- private void printIfEnabled(MetricAttribute type, String status) { +- if (getDisabledMetricAttributes().contains(type)) { +- return; +- } ++ public ConsoleReporter build() { ++ return new ConsoleReporter( ++ registry, ++ output, ++ locale, ++ clock, ++ timeZone, ++ rateUnit, ++ durationUnit, ++ filter, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes); ++ } ++ } ++ ++ private static final int CONSOLE_WIDTH = 80; ++ ++ private final PrintStream output; ++ private final Locale locale; ++ private final Clock clock; ++ private final DateFormat dateFormat; ++ ++ private ConsoleReporter( ++ MetricRegistry registry, ++ PrintStream output, ++ Locale locale, ++ Clock clock, ++ TimeZone timeZone, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ MetricFilter filter, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes) { ++ super( ++ registry, ++ "console-reporter", ++ filter, ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes); ++ this.output = output; ++ this.locale = locale; ++ this.clock = clock; ++ this.dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale); ++ dateFormat.setTimeZone(timeZone); ++ } ++ ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap> gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ final String dateTime = dateFormat.format(new Date(clock.getTime())); ++ printWithBanner(dateTime, '='); ++ output.println(); ++ ++ if (!gauges.isEmpty()) { ++ printWithBanner("-- Gauges", '-'); ++ for (Map.Entry> entry : gauges.entrySet()) { ++ output.println(entry.getKey()); ++ printGauge(entry.getValue()); ++ } ++ output.println(); ++ } + +- output.println(status); ++ if (!counters.isEmpty()) { ++ printWithBanner("-- Counters", '-'); ++ for (Map.Entry entry : counters.entrySet()) { ++ output.println(entry.getKey()); ++ printCounter(entry); ++ } ++ output.println(); + } ++ ++ if (!histograms.isEmpty()) { ++ printWithBanner("-- Histograms", '-'); ++ for (Map.Entry entry : histograms.entrySet()) { ++ output.println(entry.getKey()); ++ printHistogram(entry.getValue()); ++ } ++ output.println(); ++ } ++ ++ if (!meters.isEmpty()) { ++ printWithBanner("-- Meters", '-'); ++ for (Map.Entry entry : meters.entrySet()) { ++ output.println(entry.getKey()); ++ printMeter(entry.getValue()); ++ } ++ output.println(); ++ } ++ ++ if (!timers.isEmpty()) { ++ printWithBanner("-- Timers", '-'); ++ for (Map.Entry entry : timers.entrySet()) { ++ output.println(entry.getKey()); ++ printTimer(entry.getValue()); ++ } ++ output.println(); ++ } ++ ++ output.println(); ++ output.flush(); ++ } ++ ++ private void printMeter(Meter meter) { ++ printIfEnabled( ++ MetricAttribute.COUNT, String.format(locale, " count = %d", meter.getCount())); ++ printIfEnabled( ++ MetricAttribute.SUM, String.format(locale, " sum = %d", meter.getSum())); ++ printIfEnabled( ++ MetricAttribute.MEAN_RATE, ++ String.format( ++ locale, ++ " mean rate = %2.2f events/%s", ++ convertRate(meter.getMeanRate()), ++ getRateUnit())); ++ printIfEnabled( ++ MetricAttribute.M1_RATE, ++ String.format( ++ locale, ++ " 1-minute rate = %2.2f events/%s", ++ convertRate(meter.getOneMinuteRate()), ++ getRateUnit())); ++ printIfEnabled( ++ MetricAttribute.M5_RATE, ++ String.format( ++ locale, ++ " 5-minute rate = %2.2f events/%s", ++ convertRate(meter.getFiveMinuteRate()), ++ getRateUnit())); ++ printIfEnabled( ++ MetricAttribute.M15_RATE, ++ String.format( ++ locale, ++ " 15-minute rate = %2.2f events/%s", ++ convertRate(meter.getFifteenMinuteRate()), ++ getRateUnit())); ++ } ++ ++ private void printCounter(Map.Entry entry) { ++ output.printf(locale, " count = %d%n", entry.getValue().getCount()); ++ } ++ ++ private void printGauge(Gauge gauge) { ++ output.printf(locale, " value = %s%n", gauge.getValue()); ++ } ++ ++ private void printHistogram(Histogram histogram) { ++ printIfEnabled( ++ MetricAttribute.COUNT, ++ String.format(locale, " count = %d", histogram.getCount())); ++ printIfEnabled( ++ MetricAttribute.SUM, String.format(locale, " sum = %d", histogram.getSum())); ++ Snapshot snapshot = histogram.getSnapshot(); ++ printIfEnabled( ++ MetricAttribute.MIN, String.format(locale, " min = %d", snapshot.getMin())); ++ printIfEnabled( ++ MetricAttribute.MAX, String.format(locale, " max = %d", snapshot.getMax())); ++ printIfEnabled( ++ MetricAttribute.MEAN, ++ String.format(locale, " mean = %2.2f", snapshot.getMean())); ++ printIfEnabled( ++ MetricAttribute.STDDEV, ++ String.format(locale, " stddev = %2.2f", snapshot.getStdDev())); ++ printIfEnabled( ++ MetricAttribute.P50, ++ String.format(locale, " median = %2.2f", snapshot.getMedian())); ++ printIfEnabled( ++ MetricAttribute.P75, ++ String.format(locale, " 75%% <= %2.2f", snapshot.get75thPercentile())); ++ printIfEnabled( ++ MetricAttribute.P95, ++ String.format(locale, " 95%% <= %2.2f", snapshot.get95thPercentile())); ++ printIfEnabled( ++ MetricAttribute.P98, ++ String.format(locale, " 98%% <= %2.2f", snapshot.get98thPercentile())); ++ printIfEnabled( ++ MetricAttribute.P99, ++ String.format(locale, " 99%% <= %2.2f", snapshot.get99thPercentile())); ++ printIfEnabled( ++ MetricAttribute.P999, ++ String.format(locale, " 99.9%% <= %2.2f", snapshot.get999thPercentile())); ++ } ++ ++ private void printTimer(Timer timer) { ++ final Snapshot snapshot = timer.getSnapshot(); ++ printIfEnabled( ++ MetricAttribute.COUNT, String.format(locale, " count = %d", timer.getCount())); ++ printIfEnabled( ++ MetricAttribute.SUM, ++ String.format(locale, " sum = %2.2f", convertDuration(timer.getSum()))); ++ printIfEnabled( ++ MetricAttribute.MEAN_RATE, ++ String.format( ++ locale, ++ " mean rate = %2.2f calls/%s", ++ convertRate(timer.getMeanRate()), ++ getRateUnit())); ++ printIfEnabled( ++ MetricAttribute.M1_RATE, ++ String.format( ++ locale, ++ " 1-minute rate = %2.2f calls/%s", ++ convertRate(timer.getOneMinuteRate()), ++ getRateUnit())); ++ printIfEnabled( ++ MetricAttribute.M5_RATE, ++ String.format( ++ locale, ++ " 5-minute rate = %2.2f calls/%s", ++ convertRate(timer.getFiveMinuteRate()), ++ getRateUnit())); ++ printIfEnabled( ++ MetricAttribute.M15_RATE, ++ String.format( ++ locale, ++ " 15-minute rate = %2.2f calls/%s", ++ convertRate(timer.getFifteenMinuteRate()), ++ getRateUnit())); ++ ++ printIfEnabled( ++ MetricAttribute.MIN, ++ String.format( ++ locale, ++ " min = %2.2f %s", ++ convertDuration(snapshot.getMin()), ++ getDurationUnit())); ++ printIfEnabled( ++ MetricAttribute.MAX, ++ String.format( ++ locale, ++ " max = %2.2f %s", ++ convertDuration(snapshot.getMax()), ++ getDurationUnit())); ++ printIfEnabled( ++ MetricAttribute.MEAN, ++ String.format( ++ locale, ++ " mean = %2.2f %s", ++ convertDuration(snapshot.getMean()), ++ getDurationUnit())); ++ printIfEnabled( ++ MetricAttribute.STDDEV, ++ String.format( ++ locale, ++ " stddev = %2.2f %s", ++ convertDuration(snapshot.getStdDev()), ++ getDurationUnit())); ++ printIfEnabled( ++ MetricAttribute.P50, ++ String.format( ++ locale, ++ " median = %2.2f %s", ++ convertDuration(snapshot.getMedian()), ++ getDurationUnit())); ++ printIfEnabled( ++ MetricAttribute.P75, ++ String.format( ++ locale, ++ " 75%% <= %2.2f %s", ++ convertDuration(snapshot.get75thPercentile()), ++ getDurationUnit())); ++ printIfEnabled( ++ MetricAttribute.P95, ++ String.format( ++ locale, ++ " 95%% <= %2.2f %s", ++ convertDuration(snapshot.get95thPercentile()), ++ getDurationUnit())); ++ printIfEnabled( ++ MetricAttribute.P98, ++ String.format( ++ locale, ++ " 98%% <= %2.2f %s", ++ convertDuration(snapshot.get98thPercentile()), ++ getDurationUnit())); ++ printIfEnabled( ++ MetricAttribute.P99, ++ String.format( ++ locale, ++ " 99%% <= %2.2f %s", ++ convertDuration(snapshot.get99thPercentile()), ++ getDurationUnit())); ++ printIfEnabled( ++ MetricAttribute.P999, ++ String.format( ++ locale, ++ " 99.9%% <= %2.2f %s", ++ convertDuration(snapshot.get999thPercentile()), ++ getDurationUnit())); ++ } ++ ++ private void printWithBanner(String s, char c) { ++ output.print(s); ++ output.print(' '); ++ for (int i = 0; i < (CONSOLE_WIDTH - s.length() - 1); i++) { ++ output.print(c); ++ } ++ output.println(); ++ } ++ ++ /** ++ * Print only if the attribute is enabled ++ * ++ * @param type Metric attribute ++ * @param status Status to be logged ++ */ ++ private void printIfEnabled(MetricAttribute type, String status) { ++ if (getDisabledMetricAttributes().contains(type)) { ++ return; ++ } ++ ++ output.println(status); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Counter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Counter.java +@@ -2,55 +2,49 @@ package io.dropwizard.metrics5; + + import java.util.concurrent.atomic.LongAdder; + +-/** +- * An incrementing and decrementing counter metric. +- */ ++/** An incrementing and decrementing counter metric. */ + public class Counter implements Metric, Counting { +- private final LongAdder count; +- +- public Counter() { +- this.count = new LongAdder(); +- } +- +- /** +- * Increment the counter by one. +- */ +- public void inc() { +- inc(1); +- } +- +- /** +- * Increment the counter by {@code n}. +- * +- * @param n the amount by which the counter will be increased +- */ +- public void inc(long n) { +- count.add(n); +- } +- +- /** +- * Decrement the counter by one. +- */ +- public void dec() { +- dec(1); +- } +- +- /** +- * Decrement the counter by {@code n}. +- * +- * @param n the amount by which the counter will be decreased +- */ +- public void dec(long n) { +- count.add(-n); +- } +- +- /** +- * Returns the counter's current value. +- * +- * @return the counter's current value +- */ +- @Override +- public long getCount() { +- return count.sum(); +- } ++ private final LongAdder count; ++ ++ public Counter() { ++ this.count = new LongAdder(); ++ } ++ ++ /** Increment the counter by one. */ ++ public void inc() { ++ inc(1); ++ } ++ ++ /** ++ * Increment the counter by {@code n}. ++ * ++ * @param n the amount by which the counter will be increased ++ */ ++ public void inc(long n) { ++ count.add(n); ++ } ++ ++ /** Decrement the counter by one. */ ++ public void dec() { ++ dec(1); ++ } ++ ++ /** ++ * Decrement the counter by {@code n}. ++ * ++ * @param n the amount by which the counter will be decreased ++ */ ++ public void dec(long n) { ++ count.add(-n); ++ } ++ ++ /** ++ * Returns the counter's current value. ++ * ++ * @return the counter's current value ++ */ ++ @Override ++ public long getCount() { ++ return count.sum(); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Counting.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Counting.java +@@ -1,13 +1,11 @@ + package io.dropwizard.metrics5; + +-/** +- * An interface for metric types which have counts. +- */ ++/** An interface for metric types which have counts. */ + public interface Counting { +- /** +- * Returns the current count. +- * +- * @return the current count +- */ +- long getCount(); ++ /** ++ * Returns the current count. ++ * ++ * @return the current count ++ */ ++ long getCount(); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/CsvFileProvider.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/CsvFileProvider.java +@@ -3,10 +3,10 @@ package io.dropwizard.metrics5; + import java.io.File; + + /** +- * This interface allows a pluggable implementation of what file names +- * the {@link CsvReporter} will write to. ++ * This interface allows a pluggable implementation of what file names the {@link CsvReporter} will ++ * write to. + */ + public interface CsvFileProvider { + +- File getFile(File directory, String metricName); ++ File getFile(File directory, String metricName); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5; + +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; ++import static java.nio.charset.StandardCharsets.UTF_8; + + import java.io.File; + import java.io.FileOutputStream; +@@ -13,335 +12,390 @@ import java.util.Map; + import java.util.SortedMap; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + +-import static java.nio.charset.StandardCharsets.UTF_8; +- +-/** +- * A reporter which creates a comma-separated values file of the measurements for each metric. +- */ ++/** A reporter which creates a comma-separated values file of the measurements for each metric. */ + public class CsvReporter extends ScheduledReporter { +- private static final String DEFAULT_SEPARATOR = ","; ++ private static final String DEFAULT_SEPARATOR = ","; ++ ++ /** ++ * Returns a new {@link Builder} for {@link CsvReporter}. ++ * ++ * @param registry the registry to report ++ * @return a {@link Builder} instance for a {@link CsvReporter} ++ */ ++ public static Builder forRegistry(MetricRegistry registry) { ++ return new Builder(registry); ++ } ++ ++ /** ++ * A builder for {@link CsvReporter} instances. Defaults to using the default locale, converting ++ * rates to events/second, converting durations to milliseconds, and not filtering metrics. ++ */ ++ public static class Builder { ++ private final MetricRegistry registry; ++ private Locale locale; ++ private String separator; ++ private TimeUnit rateUnit; ++ private TimeUnit durationUnit; ++ private Clock clock; ++ private MetricFilter filter; ++ private ScheduledExecutorService executor; ++ private boolean shutdownExecutorOnStop; ++ private CsvFileProvider csvFileProvider; ++ ++ private Builder(MetricRegistry registry) { ++ this.registry = registry; ++ this.locale = Locale.getDefault(); ++ this.separator = DEFAULT_SEPARATOR; ++ this.rateUnit = TimeUnit.SECONDS; ++ this.durationUnit = TimeUnit.MILLISECONDS; ++ this.clock = Clock.defaultClock(); ++ this.filter = MetricFilter.ALL; ++ this.executor = null; ++ this.shutdownExecutorOnStop = true; ++ this.csvFileProvider = new FixedNameCsvFileProvider(); ++ } + + /** +- * Returns a new {@link Builder} for {@link CsvReporter}. ++ * Specifies whether or not, the executor (used for reporting) will be stopped with same time ++ * with reporter. Default value is true. Setting this parameter to false, has the sense in ++ * combining with providing external managed executor via {@link ++ * #scheduleOn(ScheduledExecutorService)}. + * +- * @param registry the registry to report +- * @return a {@link Builder} instance for a {@link CsvReporter} ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ * @return {@code this} + */ +- public static Builder forRegistry(MetricRegistry registry) { +- return new Builder(registry); ++ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { ++ this.shutdownExecutorOnStop = shutdownExecutorOnStop; ++ return this; + } + + /** +- * A builder for {@link CsvReporter} instances. Defaults to using the default locale, converting +- * rates to events/second, converting durations to milliseconds, and not filtering metrics. ++ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. ++ * Null value leads to executor will be auto created on start. ++ * ++ * @param executor the executor to use while scheduling reporting of metrics. ++ * @return {@code this} + */ +- public static class Builder { +- private final MetricRegistry registry; +- private Locale locale; +- private String separator; +- private TimeUnit rateUnit; +- private TimeUnit durationUnit; +- private Clock clock; +- private MetricFilter filter; +- private ScheduledExecutorService executor; +- private boolean shutdownExecutorOnStop; +- private CsvFileProvider csvFileProvider; +- +- private Builder(MetricRegistry registry) { +- this.registry = registry; +- this.locale = Locale.getDefault(); +- this.separator = DEFAULT_SEPARATOR; +- this.rateUnit = TimeUnit.SECONDS; +- this.durationUnit = TimeUnit.MILLISECONDS; +- this.clock = Clock.defaultClock(); +- this.filter = MetricFilter.ALL; +- this.executor = null; +- this.shutdownExecutorOnStop = true; +- this.csvFileProvider = new FixedNameCsvFileProvider(); +- } +- +- /** +- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. +- * Default value is true. +- * Setting this parameter to false, has the sense in combining with providing external managed executor via {@link #scheduleOn(ScheduledExecutorService)}. +- * +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- * @return {@code this} +- */ +- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { +- this.shutdownExecutorOnStop = shutdownExecutorOnStop; +- return this; +- } +- +- /** +- * Specifies the executor to use while scheduling reporting of metrics. +- * Default value is null. +- * Null value leads to executor will be auto created on start. +- * +- * @param executor the executor to use while scheduling reporting of metrics. +- * @return {@code this} +- */ +- public Builder scheduleOn(ScheduledExecutorService executor) { +- this.executor = executor; +- return this; +- } +- +- /** +- * Format numbers for the given {@link Locale}. +- * +- * @param locale a {@link Locale} +- * @return {@code this} +- */ +- public Builder formatFor(Locale locale) { +- this.locale = locale; +- return this; +- } +- +- /** +- * Convert rates to the given time unit. +- * +- * @param rateUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertRatesTo(TimeUnit rateUnit) { +- this.rateUnit = rateUnit; +- return this; +- } +- +- /** +- * Convert durations to the given time unit. +- * +- * @param durationUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertDurationsTo(TimeUnit durationUnit) { +- this.durationUnit = durationUnit; +- return this; +- } +- +- /** +- * Use the given string to use as the separator for values. +- * +- * @param separator the string to use for the separator. +- * @return {@code this} +- */ +- public Builder withSeparator(String separator) { +- this.separator = separator; +- return this; +- } +- +- /** +- * Use the given {@link Clock} instance for the time. +- * +- * @param clock a {@link Clock} instance +- * @return {@code this} +- */ +- public Builder withClock(Clock clock) { +- this.clock = clock; +- return this; +- } +- +- /** +- * Only report metrics which match the given filter. +- * +- * @param filter a {@link MetricFilter} +- * @return {@code this} +- */ +- public Builder filter(MetricFilter filter) { +- this.filter = filter; +- return this; +- } +- +- public Builder withCsvFileProvider(CsvFileProvider csvFileProvider) { +- this.csvFileProvider = csvFileProvider; +- return this; +- } +- +- /** +- * Builds a {@link CsvReporter} with the given properties, writing {@code .csv} files to the +- * given directory. +- * +- * @param directory the directory in which the {@code .csv} files will be created +- * @return a {@link CsvReporter} +- */ +- public CsvReporter build(File directory) { +- return new CsvReporter(registry, +- directory, +- locale, +- separator, +- rateUnit, +- durationUnit, +- clock, +- filter, +- executor, +- shutdownExecutorOnStop, +- csvFileProvider); +- } ++ public Builder scheduleOn(ScheduledExecutorService executor) { ++ this.executor = executor; ++ return this; + } + +- private static final Logger LOGGER = LoggerFactory.getLogger(CsvReporter.class); +- +- private final File directory; +- private final Locale locale; +- private final String separator; +- private final Clock clock; +- private final CsvFileProvider csvFileProvider; +- +- private final String histogramFormat; +- private final String meterFormat; +- private final String timerFormat; +- +- private final String timerHeader; +- private final String meterHeader; +- private final String histogramHeader; +- +- private CsvReporter(MetricRegistry registry, +- File directory, +- Locale locale, +- String separator, +- TimeUnit rateUnit, +- TimeUnit durationUnit, +- Clock clock, +- MetricFilter filter, +- ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop, +- CsvFileProvider csvFileProvider) { +- super(registry, "csv-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop); +- this.directory = directory; +- this.locale = locale; +- this.separator = separator; +- this.clock = clock; +- this.csvFileProvider = csvFileProvider; +- +- this.histogramFormat = String.join(separator, "%d", "%d", "%d", "%f", "%d", "%f", "%f", "%f", "%f", "%f", "%f", "%f"); +- this.meterFormat = String.join(separator, "%d", "%d", "%f", "%f", "%f", "%f", "events/%s"); +- this.timerFormat = String.join(separator, "%d", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "calls/%s", "%s"); +- +- this.timerHeader = String.join(separator, "count", "sum", "max", "mean", "min", "stddev", "p50", "p75", "p95", "p98", "p99", "p999", "mean_rate", "m1_rate", "m5_rate", "m15_rate", "rate_unit", "duration_unit"); +- this.meterHeader = String.join(separator, "count", "sum", "mean_rate", "m1_rate", "m5_rate", "m15_rate", "rate_unit"); +- this.histogramHeader = String.join(separator, "count", "sum", "max", "mean", "min", "stddev", "p50", "p75", "p95", "p98", "p99", "p999"); ++ /** ++ * Format numbers for the given {@link Locale}. ++ * ++ * @param locale a {@link Locale} ++ * @return {@code this} ++ */ ++ public Builder formatFor(Locale locale) { ++ this.locale = locale; ++ return this; + } + +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap> gauges, +- SortedMap counters, +- SortedMap histograms, +- SortedMap meters, +- SortedMap timers) { +- final long timestamp = TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); +- +- for (Map.Entry> entry : gauges.entrySet()) { +- reportGauge(timestamp, entry.getKey(), entry.getValue()); +- } ++ /** ++ * Convert rates to the given time unit. ++ * ++ * @param rateUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertRatesTo(TimeUnit rateUnit) { ++ this.rateUnit = rateUnit; ++ return this; ++ } + +- for (Map.Entry entry : counters.entrySet()) { +- reportCounter(timestamp, entry.getKey(), entry.getValue()); +- } ++ /** ++ * Convert durations to the given time unit. ++ * ++ * @param durationUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertDurationsTo(TimeUnit durationUnit) { ++ this.durationUnit = durationUnit; ++ return this; ++ } + +- for (Map.Entry entry : histograms.entrySet()) { +- reportHistogram(timestamp, entry.getKey(), entry.getValue()); +- } ++ /** ++ * Use the given string to use as the separator for values. ++ * ++ * @param separator the string to use for the separator. ++ * @return {@code this} ++ */ ++ public Builder withSeparator(String separator) { ++ this.separator = separator; ++ return this; ++ } + +- for (Map.Entry entry : meters.entrySet()) { +- reportMeter(timestamp, entry.getKey(), entry.getValue()); +- } ++ /** ++ * Use the given {@link Clock} instance for the time. ++ * ++ * @param clock a {@link Clock} instance ++ * @return {@code this} ++ */ ++ public Builder withClock(Clock clock) { ++ this.clock = clock; ++ return this; ++ } + +- for (Map.Entry entry : timers.entrySet()) { +- reportTimer(timestamp, entry.getKey(), entry.getValue()); +- } ++ /** ++ * Only report metrics which match the given filter. ++ * ++ * @param filter a {@link MetricFilter} ++ * @return {@code this} ++ */ ++ public Builder filter(MetricFilter filter) { ++ this.filter = filter; ++ return this; + } + +- private void reportTimer(long timestamp, MetricName name, Timer timer) { +- final Snapshot snapshot = timer.getSnapshot(); +- +- report(timestamp, +- name, +- timerHeader, +- timerFormat, +- timer.getCount(), +- convertDuration(timer.getSum()), +- convertDuration(snapshot.getMax()), +- convertDuration(snapshot.getMean()), +- convertDuration(snapshot.getMin()), +- convertDuration(snapshot.getStdDev()), +- convertDuration(snapshot.getMedian()), +- convertDuration(snapshot.get75thPercentile()), +- convertDuration(snapshot.get95thPercentile()), +- convertDuration(snapshot.get98thPercentile()), +- convertDuration(snapshot.get99thPercentile()), +- convertDuration(snapshot.get999thPercentile()), +- convertRate(timer.getMeanRate()), +- convertRate(timer.getOneMinuteRate()), +- convertRate(timer.getFiveMinuteRate()), +- convertRate(timer.getFifteenMinuteRate()), +- getRateUnit(), +- getDurationUnit()); ++ public Builder withCsvFileProvider(CsvFileProvider csvFileProvider) { ++ this.csvFileProvider = csvFileProvider; ++ return this; + } + +- private void reportMeter(long timestamp, MetricName name, Meter meter) { +- report(timestamp, +- name, +- meterHeader, +- meterFormat, +- meter.getCount(), +- meter.getSum(), +- convertRate(meter.getMeanRate()), +- convertRate(meter.getOneMinuteRate()), +- convertRate(meter.getFiveMinuteRate()), +- convertRate(meter.getFifteenMinuteRate()), +- getRateUnit()); ++ /** ++ * Builds a {@link CsvReporter} with the given properties, writing {@code .csv} files to the ++ * given directory. ++ * ++ * @param directory the directory in which the {@code .csv} files will be created ++ * @return a {@link CsvReporter} ++ */ ++ public CsvReporter build(File directory) { ++ return new CsvReporter( ++ registry, ++ directory, ++ locale, ++ separator, ++ rateUnit, ++ durationUnit, ++ clock, ++ filter, ++ executor, ++ shutdownExecutorOnStop, ++ csvFileProvider); ++ } ++ } ++ ++ private static final Logger LOG = LoggerFactory.getLogger(CsvReporter.class); ++ ++ private final File directory; ++ private final Locale locale; ++ private final String separator; ++ private final Clock clock; ++ private final CsvFileProvider csvFileProvider; ++ ++ private final String histogramFormat; ++ private final String meterFormat; ++ private final String timerFormat; ++ ++ private final String timerHeader; ++ private final String meterHeader; ++ private final String histogramHeader; ++ ++ private CsvReporter( ++ MetricRegistry registry, ++ File directory, ++ Locale locale, ++ String separator, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ Clock clock, ++ MetricFilter filter, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ CsvFileProvider csvFileProvider) { ++ super( ++ registry, "csv-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop); ++ this.directory = directory; ++ this.locale = locale; ++ this.separator = separator; ++ this.clock = clock; ++ this.csvFileProvider = csvFileProvider; ++ ++ this.histogramFormat = ++ String.join( ++ separator, "%d", "%d", "%d", "%f", "%d", "%f", "%f", "%f", "%f", "%f", "%f", "%f"); ++ this.meterFormat = String.join(separator, "%d", "%d", "%f", "%f", "%f", "%f", "events/%s"); ++ this.timerFormat = ++ String.join( ++ separator, ++ "%d", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "%f", ++ "calls/%s", ++ "%s"); ++ ++ this.timerHeader = ++ String.join( ++ separator, ++ "count", ++ "sum", ++ "max", ++ "mean", ++ "min", ++ "stddev", ++ "p50", ++ "p75", ++ "p95", ++ "p98", ++ "p99", ++ "p999", ++ "mean_rate", ++ "m1_rate", ++ "m5_rate", ++ "m15_rate", ++ "rate_unit", ++ "duration_unit"); ++ this.meterHeader = ++ String.join( ++ separator, "count", "sum", "mean_rate", "m1_rate", "m5_rate", "m15_rate", "rate_unit"); ++ this.histogramHeader = ++ String.join( ++ separator, "count", "sum", "max", "mean", "min", "stddev", "p50", "p75", "p95", "p98", ++ "p99", "p999"); ++ } ++ ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap> gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ final long timestamp = TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); ++ ++ for (Map.Entry> entry : gauges.entrySet()) { ++ reportGauge(timestamp, entry.getKey(), entry.getValue()); + } + +- private void reportHistogram(long timestamp, MetricName name, Histogram histogram) { +- final Snapshot snapshot = histogram.getSnapshot(); +- +- report(timestamp, +- name, +- histogramHeader, +- histogramFormat, +- histogram.getCount(), +- histogram.getSum(), +- snapshot.getMax(), +- snapshot.getMean(), +- snapshot.getMin(), +- snapshot.getStdDev(), +- snapshot.getMedian(), +- snapshot.get75thPercentile(), +- snapshot.get95thPercentile(), +- snapshot.get98thPercentile(), +- snapshot.get99thPercentile(), +- snapshot.get999thPercentile()); ++ for (Map.Entry entry : counters.entrySet()) { ++ reportCounter(timestamp, entry.getKey(), entry.getValue()); + } + +- private void reportCounter(long timestamp, MetricName name, Counter counter) { +- report(timestamp, name, "count", "%d", counter.getCount()); ++ for (Map.Entry entry : histograms.entrySet()) { ++ reportHistogram(timestamp, entry.getKey(), entry.getValue()); + } + +- private void reportGauge(long timestamp, MetricName name, Gauge gauge) { +- report(timestamp, name, "value", "%s", gauge.getValue()); ++ for (Map.Entry entry : meters.entrySet()) { ++ reportMeter(timestamp, entry.getKey(), entry.getValue()); + } + +- private void report(long timestamp, MetricName name, String header, String line, Object... values) { +- try { +- final File file = csvFileProvider.getFile(directory, name.getKey()); +- final boolean fileAlreadyExists = file.exists(); +- if (fileAlreadyExists || file.createNewFile()) { +- try (PrintWriter out = new PrintWriter(new OutputStreamWriter( +- new FileOutputStream(file, true), UTF_8))) { +- if (!fileAlreadyExists) { +- out.println("t" + separator + header); +- } +- out.printf(locale, String.format(locale, "%d" + separator + "%s%n", timestamp, line), values); +- } +- } +- } catch (IOException e) { +- LOGGER.warn("Error writing to {}", name, e); ++ for (Map.Entry entry : timers.entrySet()) { ++ reportTimer(timestamp, entry.getKey(), entry.getValue()); ++ } ++ } ++ ++ private void reportTimer(long timestamp, MetricName name, Timer timer) { ++ final Snapshot snapshot = timer.getSnapshot(); ++ ++ report( ++ timestamp, ++ name, ++ timerHeader, ++ timerFormat, ++ timer.getCount(), ++ convertDuration(timer.getSum()), ++ convertDuration(snapshot.getMax()), ++ convertDuration(snapshot.getMean()), ++ convertDuration(snapshot.getMin()), ++ convertDuration(snapshot.getStdDev()), ++ convertDuration(snapshot.getMedian()), ++ convertDuration(snapshot.get75thPercentile()), ++ convertDuration(snapshot.get95thPercentile()), ++ convertDuration(snapshot.get98thPercentile()), ++ convertDuration(snapshot.get99thPercentile()), ++ convertDuration(snapshot.get999thPercentile()), ++ convertRate(timer.getMeanRate()), ++ convertRate(timer.getOneMinuteRate()), ++ convertRate(timer.getFiveMinuteRate()), ++ convertRate(timer.getFifteenMinuteRate()), ++ getRateUnit(), ++ getDurationUnit()); ++ } ++ ++ private void reportMeter(long timestamp, MetricName name, Meter meter) { ++ report( ++ timestamp, ++ name, ++ meterHeader, ++ meterFormat, ++ meter.getCount(), ++ meter.getSum(), ++ convertRate(meter.getMeanRate()), ++ convertRate(meter.getOneMinuteRate()), ++ convertRate(meter.getFiveMinuteRate()), ++ convertRate(meter.getFifteenMinuteRate()), ++ getRateUnit()); ++ } ++ ++ private void reportHistogram(long timestamp, MetricName name, Histogram histogram) { ++ final Snapshot snapshot = histogram.getSnapshot(); ++ ++ report( ++ timestamp, ++ name, ++ histogramHeader, ++ histogramFormat, ++ histogram.getCount(), ++ histogram.getSum(), ++ snapshot.getMax(), ++ snapshot.getMean(), ++ snapshot.getMin(), ++ snapshot.getStdDev(), ++ snapshot.getMedian(), ++ snapshot.get75thPercentile(), ++ snapshot.get95thPercentile(), ++ snapshot.get98thPercentile(), ++ snapshot.get99thPercentile(), ++ snapshot.get999thPercentile()); ++ } ++ ++ private void reportCounter(long timestamp, MetricName name, Counter counter) { ++ report(timestamp, name, "count", "%d", counter.getCount()); ++ } ++ ++ private void reportGauge(long timestamp, MetricName name, Gauge gauge) { ++ report(timestamp, name, "value", "%s", gauge.getValue()); ++ } ++ ++ private void report( ++ long timestamp, MetricName name, String header, String line, Object... values) { ++ try { ++ final File file = csvFileProvider.getFile(directory, name.getKey()); ++ final boolean fileAlreadyExists = file.exists(); ++ if (fileAlreadyExists || file.createNewFile()) { ++ try (PrintWriter out = ++ new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, true), UTF_8))) { ++ if (!fileAlreadyExists) { ++ out.println("t" + separator + header); ++ } ++ out.printf( ++ locale, String.format(locale, "%d" + separator + "%s%n", timestamp, line), values); + } ++ } ++ } catch (IOException e) { ++ LOG.warn("Error writing to {}", name, e); + } ++ } + +- protected String sanitize(MetricName name) { +- return name.getKey(); +- } ++ protected String sanitize(MetricName name) { ++ return name.getKey(); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/DefaultSettableGauge.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/DefaultSettableGauge.java +@@ -4,40 +4,35 @@ package io.dropwizard.metrics5; + * Similar to {@link Gauge}, but metric value is updated via calling {@link #setValue(T)} instead. + */ + public class DefaultSettableGauge implements SettableGauge { +- private volatile T value; ++ private volatile T value; + +- /** +- * Create an instance with no default value. +- */ +- public DefaultSettableGauge() { +- this(null); +- } ++ /** Create an instance with no default value. */ ++ public DefaultSettableGauge() { ++ this(null); ++ } + +- /** +- * Create an instance with a default value. +- * +- * @param defaultValue default value +- */ +- public DefaultSettableGauge(T defaultValue) { +- this.value = defaultValue; +- } ++ /** ++ * Create an instance with a default value. ++ * ++ * @param defaultValue default value ++ */ ++ public DefaultSettableGauge(T defaultValue) { ++ this.value = defaultValue; ++ } + +- /** +- * Set the metric to a new value. +- */ +- @Override +- public void setValue(T value) { +- this.value = value; +- } +- +- /** +- * Returns the current value. +- * +- * @return the current value +- */ +- @Override +- public T getValue() { +- return value; +- } ++ /** Set the metric to a new value. */ ++ @Override ++ public void setValue(T value) { ++ this.value = value; ++ } + ++ /** ++ * Returns the current value. ++ * ++ * @return the current value ++ */ ++ @Override ++ public T getValue() { ++ return value; ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/DerivativeGauge.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/DerivativeGauge.java +@@ -7,27 +7,27 @@ package io.dropwizard.metrics5; + * @param the derivative type + */ + public abstract class DerivativeGauge implements Gauge { +- private final Gauge base; ++ private final Gauge base; + +- /** +- * Creates a new derivative with the given base gauge. +- * +- * @param base the gauge from which to derive this gauge's value +- */ +- protected DerivativeGauge(Gauge base) { +- this.base = base; +- } ++ /** ++ * Creates a new derivative with the given base gauge. ++ * ++ * @param base the gauge from which to derive this gauge's value ++ */ ++ protected DerivativeGauge(Gauge base) { ++ this.base = base; ++ } + +- @Override +- public T getValue() { +- return transform(base.getValue()); +- } ++ @Override ++ public T getValue() { ++ return transform(base.getValue()); ++ } + +- /** +- * Transforms the value of the base gauge to the value of this gauge. +- * +- * @param value the value of the base gauge +- * @return this gauge's value +- */ +- protected abstract T transform(F value); ++ /** ++ * Transforms the value of the base gauge to the value of this gauge. ++ * ++ * @param value the value of the base gauge ++ * @return this gauge's value ++ */ ++ protected abstract T transform(F value); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/EWMA.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/EWMA.java +@@ -1,116 +1,115 @@ + package io.dropwizard.metrics5; + ++import static java.lang.Math.exp; ++ + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.LongAdder; + +-import static java.lang.Math.exp; +- + /** + * An exponentially-weighted moving average. + * + * @see UNIX Load Average Part 1: How +- * It Works ++ * It Works + * @see UNIX Load Average Part 2: Not +- * Your Average Average ++ * Your Average Average + * @see EMA + */ + public class EWMA { +- private static final int INTERVAL = 5; +- private static final double SECONDS_PER_MINUTE = 60.0; +- private static final int ONE_MINUTE = 1; +- private static final int FIVE_MINUTES = 5; +- private static final int FIFTEEN_MINUTES = 15; +- private static final double M1_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / ONE_MINUTE); +- private static final double M5_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIVE_MINUTES); +- private static final double M15_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIFTEEN_MINUTES); ++ private static final int INTERVAL = 5; ++ private static final double SECONDS_PER_MINUTE = 60.0; ++ private static final int ONE_MINUTE = 1; ++ private static final int FIVE_MINUTES = 5; ++ private static final int FIFTEEN_MINUTES = 15; ++ private static final double M1_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / ONE_MINUTE); ++ private static final double M5_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIVE_MINUTES); ++ private static final double M15_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIFTEEN_MINUTES); + +- private volatile boolean initialized = false; +- private volatile double rate = 0.0; ++ private volatile boolean initialized = false; ++ private volatile double rate = 0.0; + +- private final LongAdder uncounted = new LongAdder(); +- private final double alpha, interval; ++ private final LongAdder uncounted = new LongAdder(); ++ private final double alpha, interval; + +- /** +- * Creates a new EWMA which is equivalent to the UNIX one minute load average and which expects +- * to be ticked every 5 seconds. +- * +- * @return a one-minute EWMA +- */ +- public static EWMA oneMinuteEWMA() { +- return new EWMA(M1_ALPHA, INTERVAL, TimeUnit.SECONDS); +- } ++ /** ++ * Creates a new EWMA which is equivalent to the UNIX one minute load average and which expects to ++ * be ticked every 5 seconds. ++ * ++ * @return a one-minute EWMA ++ */ ++ public static EWMA oneMinuteEWMA() { ++ return new EWMA(M1_ALPHA, INTERVAL, TimeUnit.SECONDS); ++ } + +- /** +- * Creates a new EWMA which is equivalent to the UNIX five minute load average and which expects +- * to be ticked every 5 seconds. +- * +- * @return a five-minute EWMA +- */ +- public static EWMA fiveMinuteEWMA() { +- return new EWMA(M5_ALPHA, INTERVAL, TimeUnit.SECONDS); +- } ++ /** ++ * Creates a new EWMA which is equivalent to the UNIX five minute load average and which expects ++ * to be ticked every 5 seconds. ++ * ++ * @return a five-minute EWMA ++ */ ++ public static EWMA fiveMinuteEWMA() { ++ return new EWMA(M5_ALPHA, INTERVAL, TimeUnit.SECONDS); ++ } + +- /** +- * Creates a new EWMA which is equivalent to the UNIX fifteen minute load average and which +- * expects to be ticked every 5 seconds. +- * +- * @return a fifteen-minute EWMA +- */ +- public static EWMA fifteenMinuteEWMA() { +- return new EWMA(M15_ALPHA, INTERVAL, TimeUnit.SECONDS); +- } ++ /** ++ * Creates a new EWMA which is equivalent to the UNIX fifteen minute load average and which ++ * expects to be ticked every 5 seconds. ++ * ++ * @return a fifteen-minute EWMA ++ */ ++ public static EWMA fifteenMinuteEWMA() { ++ return new EWMA(M15_ALPHA, INTERVAL, TimeUnit.SECONDS); ++ } + +- /** +- * Create a new EWMA with a specific smoothing constant. +- * +- * @param alpha the smoothing constant +- * @param interval the expected tick interval +- * @param intervalUnit the time unit of the tick interval +- */ +- public EWMA(double alpha, long interval, TimeUnit intervalUnit) { +- this.interval = intervalUnit.toNanos(interval); +- this.alpha = alpha; +- } ++ /** ++ * Create a new EWMA with a specific smoothing constant. ++ * ++ * @param alpha the smoothing constant ++ * @param interval the expected tick interval ++ * @param intervalUnit the time unit of the tick interval ++ */ ++ public EWMA(double alpha, long interval, TimeUnit intervalUnit) { ++ this.interval = intervalUnit.toNanos(interval); ++ this.alpha = alpha; ++ } + +- /** +- * Update the moving average with a new value. +- * +- * @param n the new value +- */ +- public void update(long n) { +- uncounted.add(n); +- } ++ /** ++ * Update the moving average with a new value. ++ * ++ * @param n the new value ++ */ ++ public void update(long n) { ++ uncounted.add(n); ++ } + +- /** +- * Set the rate to the smallest possible positive value. Used to avoid calling tick a large number of times. +- */ +- public void reset() { +- uncounted.reset(); +- rate = Double.MIN_NORMAL; +- } ++ /** ++ * Set the rate to the smallest possible positive value. Used to avoid calling tick a large number ++ * of times. ++ */ ++ public void reset() { ++ uncounted.reset(); ++ rate = Double.MIN_NORMAL; ++ } + +- /** +- * Mark the passage of time and decay the current rate accordingly. +- */ +- public void tick() { +- final long count = uncounted.sumThenReset(); +- final double instantRate = count / interval; +- if (initialized) { +- final double oldRate = this.rate; +- rate = oldRate + (alpha * (instantRate - oldRate)); +- } else { +- rate = instantRate; +- initialized = true; +- } ++ /** Mark the passage of time and decay the current rate accordingly. */ ++ public void tick() { ++ final long count = uncounted.sumThenReset(); ++ final double instantRate = count / interval; ++ if (initialized) { ++ final double oldRate = this.rate; ++ rate = oldRate + (alpha * (instantRate - oldRate)); ++ } else { ++ rate = instantRate; ++ initialized = true; + } ++ } + +- /** +- * Returns the rate in the given units of time. +- * +- * @param rateUnit the unit of time +- * @return the rate +- */ +- public double getRate(TimeUnit rateUnit) { +- return rate * (double) rateUnit.toNanos(1); +- } ++ /** ++ * Returns the rate in the given units of time. ++ * ++ * @param rateUnit the unit of time ++ * @return the rate ++ */ ++ public double getRate(TimeUnit rateUnit) { ++ return rate * (double) rateUnit.toNanos(1); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java +@@ -5,110 +5,102 @@ import java.util.concurrent.atomic.AtomicLong; + import java.util.concurrent.atomic.LongAdder; + + /** +- * A triple (one, five and fifteen minutes) of exponentially-weighted moving average rates as needed by {@link Meter}. +- *

+- * The rates have the same exponential decay factor as the fifteen-minute load average in the ++ * A triple (one, five and fifteen minutes) of exponentially-weighted moving average rates as needed ++ * by {@link Meter}. ++ * ++ *

The rates have the same exponential decay factor as the fifteen-minute load average in the + * {@code top} Unix command. + */ + public class ExponentialMovingAverages implements MovingAverages { + +- /** +- * If ticking would reduce even Long.MAX_VALUE in the 15 minute EWMA below this target then don't bother +- * ticking in a loop and instead reset all the EWMAs. +- */ +- private static final double maxTickZeroTarget = 0.0001; +- private static final int maxTicks; +- private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5); ++ /** ++ * If ticking would reduce even Long.MAX_VALUE in the 15 minute EWMA below this target then don't ++ * bother ticking in a loop and instead reset all the EWMAs. ++ */ ++ private static final double MAX_TICK_ZERO_TARGET = 0.0001; + +- static +- { +- int m3Ticks = 1; +- final EWMA m3 = EWMA.fifteenMinuteEWMA(); +- m3.update(Long.MAX_VALUE); +- do +- { +- m3.tick(); +- m3Ticks++; +- } +- while (m3.getRate(TimeUnit.SECONDS) > maxTickZeroTarget); +- maxTicks = m3Ticks; +- } ++ private static final int MAX_TICKS; ++ private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5); + +- private final EWMA m1Rate = EWMA.oneMinuteEWMA(); +- private final EWMA m5Rate = EWMA.fiveMinuteEWMA(); +- private final EWMA m15Rate = EWMA.fifteenMinuteEWMA(); +- private final LongAdder sum = new LongAdder(); ++ static { ++ int m3Ticks = 1; ++ final EWMA m3 = EWMA.fifteenMinuteEWMA(); ++ m3.update(Long.MAX_VALUE); ++ do { ++ m3.tick(); ++ m3Ticks++; ++ } while (m3.getRate(TimeUnit.SECONDS) > MAX_TICK_ZERO_TARGET); ++ MAX_TICKS = m3Ticks; ++ } + +- private final AtomicLong lastTick; +- private final Clock clock; ++ private final EWMA m1Rate = EWMA.oneMinuteEWMA(); ++ private final EWMA m5Rate = EWMA.fiveMinuteEWMA(); ++ private final EWMA m15Rate = EWMA.fifteenMinuteEWMA(); ++ private final LongAdder sum = new LongAdder(); + +- /** +- * Creates a new {@link ExponentialMovingAverages}. +- */ +- public ExponentialMovingAverages() { +- this(Clock.defaultClock()); +- } ++ private final AtomicLong lastTick; ++ private final Clock clock; + +- /** +- * Creates a new {@link ExponentialMovingAverages}. +- */ +- public ExponentialMovingAverages(Clock clock) { +- this.clock = clock; +- this.lastTick = new AtomicLong(this.clock.getTick()); +- } ++ /** Creates a new {@link ExponentialMovingAverages}. */ ++ public ExponentialMovingAverages() { ++ this(Clock.defaultClock()); ++ } + +- @Override +- public void update(long n) { +- m1Rate.update(n); +- m5Rate.update(n); +- m15Rate.update(n); +- } ++ /** Creates a new {@link ExponentialMovingAverages}. */ ++ public ExponentialMovingAverages(Clock clock) { ++ this.clock = clock; ++ this.lastTick = new AtomicLong(this.clock.getTick()); ++ } + +- @Override +- public void tickIfNecessary() { +- final long oldTick = lastTick.get(); +- final long newTick = clock.getTick(); +- final long age = newTick - oldTick; +- if (age > TICK_INTERVAL) { +- final long newIntervalStartTick = newTick - age % TICK_INTERVAL; +- if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) { +- sum.add(age); +- final long requiredTicks = age / TICK_INTERVAL; +- if (requiredTicks >= maxTicks) { +- m1Rate.reset(); +- m5Rate.reset(); +- m15Rate.reset(); +- } +- else +- { +- for (long i = 0; i < requiredTicks; i++) +- { +- m1Rate.tick(); +- m5Rate.tick(); +- m15Rate.tick(); +- } +- } +- } ++ @Override ++ public void update(long n) { ++ m1Rate.update(n); ++ m5Rate.update(n); ++ m15Rate.update(n); ++ } ++ ++ @Override ++ public void tickIfNecessary() { ++ final long oldTick = lastTick.get(); ++ final long newTick = clock.getTick(); ++ final long age = newTick - oldTick; ++ if (age > TICK_INTERVAL) { ++ final long newIntervalStartTick = newTick - age % TICK_INTERVAL; ++ if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) { ++ sum.add(age); ++ final long requiredTicks = age / TICK_INTERVAL; ++ if (requiredTicks >= MAX_TICKS) { ++ m1Rate.reset(); ++ m5Rate.reset(); ++ m15Rate.reset(); ++ } else { ++ for (long i = 0; i < requiredTicks; i++) { ++ m1Rate.tick(); ++ m5Rate.tick(); ++ m15Rate.tick(); ++ } + } ++ } + } ++ } + +- @Override +- public double getM1Rate() { +- return m1Rate.getRate(TimeUnit.SECONDS); +- } ++ @Override ++ public double getM1Rate() { ++ return m1Rate.getRate(TimeUnit.SECONDS); ++ } + +- @Override +- public double getM5Rate() { +- return m5Rate.getRate(TimeUnit.SECONDS); +- } ++ @Override ++ public double getM5Rate() { ++ return m5Rate.getRate(TimeUnit.SECONDS); ++ } + +- @Override +- public double getM15Rate() { +- return m15Rate.getRate(TimeUnit.SECONDS); +- } ++ @Override ++ public double getM15Rate() { ++ return m15Rate.getRate(TimeUnit.SECONDS); ++ } + +- @Override +- public long getSum() { +- return sum.sum(); +- } ++ @Override ++ public long getSum() { ++ return sum.sum(); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoir.java +@@ -1,6 +1,9 @@ + package io.dropwizard.metrics5; + ++import static java.lang.Math.exp; ++import static java.lang.Math.min; + ++import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; + import java.util.ArrayList; + import java.util.concurrent.ConcurrentSkipListMap; + import java.util.concurrent.ThreadLocalRandom; +@@ -8,201 +11,197 @@ import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicLong; + import java.util.concurrent.locks.ReentrantReadWriteLock; + +-import static java.lang.Math.exp; +-import static java.lang.Math.min; +- +-import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; +- + /** + * An exponentially-decaying random reservoir of {@code long}s. Uses Cormode et al's + * forward-decaying priority reservoir sampling method to produce a statistically representative + * sampling reservoir, exponentially biased towards newer entries. + * +- * @see +- * Cormode et al. Forward Decay: A Practical Time Decay Model for Streaming Systems. ICDE '09: +- * Proceedings of the 2009 IEEE International Conference on Data Engineering (2009) ++ * @see Cormode et al. Forward ++ * Decay: A Practical Time Decay Model for Streaming Systems. ICDE '09: Proceedings of the 2009 ++ * IEEE International Conference on Data Engineering (2009) + */ + public class ExponentiallyDecayingReservoir implements Reservoir { +- private static final int DEFAULT_SIZE = 1028; +- private static final double DEFAULT_ALPHA = 0.015; +- private static final long RESCALE_THRESHOLD = TimeUnit.HOURS.toNanos(1); +- +- private final ConcurrentSkipListMap values; +- private final ReentrantReadWriteLock lock; +- private final double alpha; +- private final int size; +- private final AtomicLong count; +- private volatile long startTime; +- private final AtomicLong lastScaleTick; +- private final Clock clock; +- +- /** +- * Creates a new {@link ExponentiallyDecayingReservoir} of 1028 elements, which offers a 99.9% +- * confidence level with a 5% margin of error assuming a normal distribution, and an alpha +- * factor of 0.015, which heavily biases the reservoir to the past 5 minutes of measurements. +- */ +- public ExponentiallyDecayingReservoir() { +- this(DEFAULT_SIZE, DEFAULT_ALPHA); +- } +- +- /** +- * Creates a new {@link ExponentiallyDecayingReservoir}. +- * +- * @param size the number of samples to keep in the sampling reservoir +- * @param alpha the exponential decay factor; the higher this is, the more biased the reservoir +- * will be towards newer values +- */ +- public ExponentiallyDecayingReservoir(int size, double alpha) { +- this(size, alpha, Clock.defaultClock()); +- } +- +- /** +- * Creates a new {@link ExponentiallyDecayingReservoir}. +- * +- * @param size the number of samples to keep in the sampling reservoir +- * @param alpha the exponential decay factor; the higher this is, the more biased the reservoir +- * will be towards newer values +- * @param clock the clock used to timestamp samples and track rescaling +- */ +- public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock) { +- this.values = new ConcurrentSkipListMap<>(); +- this.lock = new ReentrantReadWriteLock(); +- this.alpha = alpha; +- this.size = size; +- this.clock = clock; +- this.count = new AtomicLong(0); +- this.startTime = currentTimeInSeconds(); +- this.lastScaleTick = new AtomicLong(clock.getTick()); +- } +- +- @Override +- public int size() { +- return (int) min(size, count.get()); +- } +- +- @Override +- public void update(long value) { +- update(value, currentTimeInSeconds()); +- } +- +- /** +- * Adds an old value with a fixed timestamp to the reservoir. +- * +- * @param value the value to be added +- * @param timestamp the epoch timestamp of {@code value} in seconds +- */ +- public void update(long value, long timestamp) { +- rescaleIfNeeded(); +- lockForRegularUsage(); +- try { +- final double itemWeight = weight(timestamp - startTime); +- final WeightedSample sample = new WeightedSample(value, itemWeight); +- final double priority = itemWeight / ThreadLocalRandom.current().nextDouble(); +- +- final long newCount = count.incrementAndGet(); +- if (newCount <= size || values.isEmpty()) { +- values.put(priority, sample); +- } else { +- Double first = values.firstKey(); +- if (first < priority && values.putIfAbsent(priority, sample) == null) { +- // ensure we always remove an item +- while (values.remove(first) == null) { +- first = values.firstKey(); +- } +- } +- } +- } finally { +- unlockForRegularUsage(); ++ private static final int DEFAULT_SIZE = 1028; ++ private static final double DEFAULT_ALPHA = 0.015; ++ private static final long RESCALE_THRESHOLD = TimeUnit.HOURS.toNanos(1); ++ ++ private final ConcurrentSkipListMap values; ++ private final ReentrantReadWriteLock lock; ++ private final double alpha; ++ private final int size; ++ private final AtomicLong count; ++ private volatile long startTime; ++ private final AtomicLong lastScaleTick; ++ private final Clock clock; ++ ++ /** ++ * Creates a new {@link ExponentiallyDecayingReservoir} of 1028 elements, which offers a 99.9% ++ * confidence level with a 5% margin of error assuming a normal distribution, and an alpha factor ++ * of 0.015, which heavily biases the reservoir to the past 5 minutes of measurements. ++ */ ++ public ExponentiallyDecayingReservoir() { ++ this(DEFAULT_SIZE, DEFAULT_ALPHA); ++ } ++ ++ /** ++ * Creates a new {@link ExponentiallyDecayingReservoir}. ++ * ++ * @param size the number of samples to keep in the sampling reservoir ++ * @param alpha the exponential decay factor; the higher this is, the more biased the reservoir ++ * will be towards newer values ++ */ ++ public ExponentiallyDecayingReservoir(int size, double alpha) { ++ this(size, alpha, Clock.defaultClock()); ++ } ++ ++ /** ++ * Creates a new {@link ExponentiallyDecayingReservoir}. ++ * ++ * @param size the number of samples to keep in the sampling reservoir ++ * @param alpha the exponential decay factor; the higher this is, the more biased the reservoir ++ * will be towards newer values ++ * @param clock the clock used to timestamp samples and track rescaling ++ */ ++ public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock) { ++ this.values = new ConcurrentSkipListMap<>(); ++ this.lock = new ReentrantReadWriteLock(); ++ this.alpha = alpha; ++ this.size = size; ++ this.clock = clock; ++ this.count = new AtomicLong(0); ++ this.startTime = currentTimeInSeconds(); ++ this.lastScaleTick = new AtomicLong(clock.getTick()); ++ } ++ ++ @Override ++ public int size() { ++ return (int) min(size, count.get()); ++ } ++ ++ @Override ++ public void update(long value) { ++ update(value, currentTimeInSeconds()); ++ } ++ ++ /** ++ * Adds an old value with a fixed timestamp to the reservoir. ++ * ++ * @param value the value to be added ++ * @param timestamp the epoch timestamp of {@code value} in seconds ++ */ ++ public void update(long value, long timestamp) { ++ rescaleIfNeeded(); ++ lockForRegularUsage(); ++ try { ++ final double itemWeight = weight(timestamp - startTime); ++ final WeightedSample sample = new WeightedSample(value, itemWeight); ++ final double priority = itemWeight / ThreadLocalRandom.current().nextDouble(); ++ ++ final long newCount = count.incrementAndGet(); ++ if (newCount <= size || values.isEmpty()) { ++ values.put(priority, sample); ++ } else { ++ Double first = values.firstKey(); ++ if (first < priority && values.putIfAbsent(priority, sample) == null) { ++ // ensure we always remove an item ++ while (values.remove(first) == null) { ++ first = values.firstKey(); ++ } + } ++ } ++ } finally { ++ unlockForRegularUsage(); + } ++ } + +- private void rescaleIfNeeded() { +- final long now = clock.getTick(); +- final long lastScaleTickSnapshot = lastScaleTick.get(); +- if (now - lastScaleTickSnapshot >= RESCALE_THRESHOLD) { +- rescale(now, lastScaleTickSnapshot); +- } ++ private void rescaleIfNeeded() { ++ final long now = clock.getTick(); ++ final long lastScaleTickSnapshot = lastScaleTick.get(); ++ if (now - lastScaleTickSnapshot >= RESCALE_THRESHOLD) { ++ rescale(now, lastScaleTickSnapshot); + } +- +- @Override +- public Snapshot getSnapshot() { +- rescaleIfNeeded(); +- lockForRegularUsage(); +- try { +- return new WeightedSnapshot(values.values()); +- } finally { +- unlockForRegularUsage(); +- } +- } +- +- private long currentTimeInSeconds() { +- return TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ rescaleIfNeeded(); ++ lockForRegularUsage(); ++ try { ++ return new WeightedSnapshot(values.values()); ++ } finally { ++ unlockForRegularUsage(); + } +- +- private double weight(long t) { +- return exp(alpha * t); +- } +- +- /* "A common feature of the above techniques—indeed, the key technique that +- * allows us to track the decayed weights efficiently—is that they maintain +- * counts and other quantities based on g(ti − L), and only scale by g(t − L) +- * at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero +- * and one, the intermediate values of g(ti − L) could become very large. For +- * polynomial functions, these values should not grow too large, and should be +- * effectively represented in practice by floating point values without loss of +- * precision. For exponential functions, these values could grow quite large as +- * new values of (ti − L) become large, and potentially exceed the capacity of +- * common floating point types. However, since the values stored by the +- * algorithms are linear combinations of g values (scaled sums), they can be +- * rescaled relative to a new landmark. That is, by the analysis of exponential +- * decay in Section III-A, the choice of L does not affect the final result. We +- * can therefore multiply each value based on L by a factor of exp(−α(L′ − L)), +- * and obtain the correct value as if we had instead computed relative to a new +- * landmark L′ (and then use this new L′ at query time). This can be done with +- * a linear pass over whatever data structure is being used." +- */ +- private void rescale(long now, long lastTick) { +- lockForRescale(); +- try { +- if (lastScaleTick.compareAndSet(lastTick, now)) { +- final long oldStartTime = startTime; +- this.startTime = currentTimeInSeconds(); +- final double scalingFactor = exp(-alpha * (startTime - oldStartTime)); +- if (Double.compare(scalingFactor, 0) == 0) { +- values.clear(); +- } else { +- final ArrayList keys = new ArrayList<>(values.keySet()); +- for (Double key : keys) { +- final WeightedSample sample = values.remove(key); +- final WeightedSample newSample = new WeightedSample(sample.value, sample.weight * scalingFactor); +- if (Double.compare(newSample.weight, 0) == 0) { +- continue; +- } +- values.put(key * scalingFactor, newSample); +- } +- } +- +- // make sure the counter is in sync with the number of stored samples. +- count.set(values.size()); ++ } ++ ++ private long currentTimeInSeconds() { ++ return TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); ++ } ++ ++ private double weight(long t) { ++ return exp(alpha * t); ++ } ++ ++ /* "A common feature of the above techniques—indeed, the key technique that ++ * allows us to track the decayed weights efficiently—is that they maintain ++ * counts and other quantities based on g(ti − L), and only scale by g(t − L) ++ * at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero ++ * and one, the intermediate values of g(ti − L) could become very large. For ++ * polynomial functions, these values should not grow too large, and should be ++ * effectively represented in practice by floating point values without loss of ++ * precision. For exponential functions, these values could grow quite large as ++ * new values of (ti − L) become large, and potentially exceed the capacity of ++ * common floating point types. However, since the values stored by the ++ * algorithms are linear combinations of g values (scaled sums), they can be ++ * rescaled relative to a new landmark. That is, by the analysis of exponential ++ * decay in Section III-A, the choice of L does not affect the final result. We ++ * can therefore multiply each value based on L by a factor of exp(−α(L′ − L)), ++ * and obtain the correct value as if we had instead computed relative to a new ++ * landmark L′ (and then use this new L′ at query time). This can be done with ++ * a linear pass over whatever data structure is being used." ++ */ ++ private void rescale(long now, long lastTick) { ++ lockForRescale(); ++ try { ++ if (lastScaleTick.compareAndSet(lastTick, now)) { ++ final long oldStartTime = startTime; ++ this.startTime = currentTimeInSeconds(); ++ final double scalingFactor = exp(-alpha * (startTime - oldStartTime)); ++ if (Double.compare(scalingFactor, 0) == 0) { ++ values.clear(); ++ } else { ++ final ArrayList keys = new ArrayList<>(values.keySet()); ++ for (Double key : keys) { ++ final WeightedSample sample = values.remove(key); ++ final WeightedSample newSample = ++ new WeightedSample(sample.value, sample.weight * scalingFactor); ++ if (Double.compare(newSample.weight, 0) == 0) { ++ continue; + } +- } finally { +- unlockForRescale(); ++ values.put(key * scalingFactor, newSample); ++ } + } +- } + +- private void unlockForRescale() { +- lock.writeLock().unlock(); ++ // make sure the counter is in sync with the number of stored samples. ++ count.set(values.size()); ++ } ++ } finally { ++ unlockForRescale(); + } ++ } + +- private void lockForRescale() { +- lock.writeLock().lock(); +- } ++ private void unlockForRescale() { ++ lock.writeLock().unlock(); ++ } + +- private void lockForRegularUsage() { +- lock.readLock().lock(); +- } ++ private void lockForRescale() { ++ lock.writeLock().lock(); ++ } + +- private void unlockForRegularUsage() { +- lock.readLock().unlock(); +- } ++ private void lockForRegularUsage() { ++ lock.readLock().lock(); ++ } ++ ++ private void unlockForRegularUsage() { ++ lock.readLock().unlock(); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/FixedNameCsvFileProvider.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/FixedNameCsvFileProvider.java +@@ -3,19 +3,19 @@ package io.dropwizard.metrics5; + import java.io.File; + + /** +- * This implementation of the {@link CsvFileProvider} will always return the same name +- * for the same metric. This means the CSV file will grow indefinitely. ++ * This implementation of the {@link CsvFileProvider} will always return the same name for the same ++ * metric. This means the CSV file will grow indefinitely. + */ + public class FixedNameCsvFileProvider implements CsvFileProvider { + +- @Override +- public File getFile(File directory, String metricName) { +- return new File(directory, sanitize(metricName) + ".csv"); +- } ++ @Override ++ public File getFile(File directory, String metricName) { ++ return new File(directory, sanitize(metricName) + ".csv"); ++ } + +- protected String sanitize(String metricName) { +- //Forward slash character is definitely illegal in both Windows and Linux +- //https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx +- return metricName.replaceFirst("^/", "").replaceAll("/", "."); +- } ++ protected String sanitize(String metricName) { ++ // Forward slash character is definitely illegal in both Windows and Linux ++ // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx ++ return metricName.replaceFirst("^/", "").replaceAll("/", "."); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Gauge.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Gauge.java +@@ -1,9 +1,9 @@ + package io.dropwizard.metrics5; + +- + /** + * A gauge metric is an instantaneous reading of a particular value. To instrument a queue's depth, + * for example:
++ * + *


+  * final Queue<String> queue = new ConcurrentLinkedQueue<String>();
+  * final Gauge<Integer> queueDepth = new Gauge<Integer>() {
+@@ -17,10 +17,10 @@ package io.dropwizard.metrics5;
+  */
+ @FunctionalInterface
+ public interface Gauge extends Metric {
+-    /**
+-     * Returns the metric's current value.
+-     *
+-     * @return the metric's current value
+-     */
+-    T getValue();
++  /**
++   * Returns the metric's current value.
++   *
++   * @return the metric's current value
++   */
++  T getValue();
+ }
+--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Histogram.java
++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Histogram.java
+@@ -6,66 +6,66 @@ import java.util.concurrent.atomic.LongAdder;
+  * A metric which calculates the distribution of a value.
+  *
+  * @see Accurately computing running
+- * variance
++ *     variance
+  */
+ public class Histogram implements Metric, Sampling, Counting, Summing {
+-    private final Reservoir reservoir;
+-    private final LongAdder count;
+-    private final LongAdder sum;
++  private final Reservoir reservoir;
++  private final LongAdder count;
++  private final LongAdder sum;
+ 
+-    /**
+-     * Creates a new {@link Histogram} with the given reservoir.
+-     *
+-     * @param reservoir the reservoir to create a histogram from
+-     */
+-    public Histogram(Reservoir reservoir) {
+-        this.reservoir = reservoir;
+-        this.count = new LongAdder();
+-        this.sum = new LongAdder();
+-    }
++  /**
++   * Creates a new {@link Histogram} with the given reservoir.
++   *
++   * @param reservoir the reservoir to create a histogram from
++   */
++  public Histogram(Reservoir reservoir) {
++    this.reservoir = reservoir;
++    this.count = new LongAdder();
++    this.sum = new LongAdder();
++  }
+ 
+-    /**
+-     * Adds a recorded value.
+-     *
+-     * @param value the length of the value
+-     */
+-    public void update(int value) {
+-        update((long) value);
+-    }
++  /**
++   * Adds a recorded value.
++   *
++   * @param value the length of the value
++   */
++  public void update(int value) {
++    update((long) value);
++  }
+ 
+-    /**
+-     * Adds a recorded value.
+-     *
+-     * @param value the length of the value
+-     */
+-    public void update(long value) {
+-        count.increment();
+-        sum.add(value);
+-        reservoir.update(value);
+-    }
++  /**
++   * Adds a recorded value.
++   *
++   * @param value the length of the value
++   */
++  public void update(long value) {
++    count.increment();
++    sum.add(value);
++    reservoir.update(value);
++  }
+ 
+-    /**
+-     * Returns the number of values recorded.
+-     *
+-     * @return the number of values recorded
+-     */
+-    @Override
+-    public long getCount() {
+-        return count.sum();
+-    }
++  /**
++   * Returns the number of values recorded.
++   *
++   * @return the number of values recorded
++   */
++  @Override
++  public long getCount() {
++    return count.sum();
++  }
+ 
+-    /**
+-     * Returns the sum of values recorded.
+-     *
+-     * @return the sum of values recorded
+-     */
+-    @Override
+-    public long getSum() {
+-        return sum.sum();
+-    }
++  /**
++   * Returns the sum of values recorded.
++   *
++   * @return the sum of values recorded
++   */
++  @Override
++  public long getSum() {
++    return sum.sum();
++  }
+ 
+-    @Override
+-    public Snapshot getSnapshot() {
+-        return reservoir.getSnapshot();
+-    }
++  @Override
++  public Snapshot getSnapshot() {
++    return reservoir.getSnapshot();
++  }
+ }
+--- a/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java
++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java
+@@ -16,273 +16,259 @@ import java.util.concurrent.TimeoutException;
+ import java.util.concurrent.atomic.AtomicLong;
+ 
+ /**
+- * An {@link ExecutorService} that monitors the number of tasks submitted, running,
+- * completed and also keeps a {@link Timer} for the task duration.
+- * 

+- * It will register the metrics using the given (or auto-generated) name as classifier, e.g: ++ * An {@link ExecutorService} that monitors the number of tasks submitted, running, completed and ++ * also keeps a {@link Timer} for the task duration. ++ * ++ *

It will register the metrics using the given (or auto-generated) name as classifier, e.g: + * "your-executor-service.submitted", "your-executor-service.running", etc. + */ + public class InstrumentedExecutorService implements ExecutorService { +- private static final AtomicLong NAME_COUNTER = new AtomicLong(); ++ private static final AtomicLong NAME_COUNTER = new AtomicLong(); + +- private final ExecutorService delegate; +- private final MetricRegistry registry; +- private final String name; +- private final Meter submitted; +- private final Counter running; +- private final Meter completed; +- private final Counter rejected; +- private final Timer idle; +- private final Timer duration; ++ private final ExecutorService delegate; ++ private final MetricRegistry registry; ++ private final String name; ++ private final Meter submitted; ++ private final Counter running; ++ private final Meter completed; ++ private final Counter rejected; ++ private final Timer idle; ++ private final Timer duration; + +- /** +- * Wraps an {@link ExecutorService} uses an auto-generated default name. +- * +- * @param delegate {@link ExecutorService} to wrap. +- * @param registry {@link MetricRegistry} that will contain the metrics. +- */ +- public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) { +- this(delegate, registry, "instrumented-delegate-" + NAME_COUNTER.incrementAndGet()); +- } ++ /** ++ * Wraps an {@link ExecutorService} uses an auto-generated default name. ++ * ++ * @param delegate {@link ExecutorService} to wrap. ++ * @param registry {@link MetricRegistry} that will contain the metrics. ++ */ ++ public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) { ++ this(delegate, registry, "instrumented-delegate-" + NAME_COUNTER.incrementAndGet()); ++ } + +- /** +- * Wraps an {@link ExecutorService} with an explicit name. +- * +- * @param delegate {@link ExecutorService} to wrap. +- * @param registry {@link MetricRegistry} that will contain the metrics. +- * @param name name for this executor service. +- */ +- public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry, String name) { +- this.delegate = delegate; +- this.registry = registry; +- this.name = name; +- this.submitted = registry.meter(MetricRegistry.name(name, "submitted")); +- this.running = registry.counter(MetricRegistry.name(name, "running")); +- this.completed = registry.meter(MetricRegistry.name(name, "completed")); +- this.rejected = registry.counter(MetricRegistry.name(name, "rejected")); +- this.idle = registry.timer(MetricRegistry.name(name, "idle")); +- this.duration = registry.timer(MetricRegistry.name(name, "duration")); ++ /** ++ * Wraps an {@link ExecutorService} with an explicit name. ++ * ++ * @param delegate {@link ExecutorService} to wrap. ++ * @param registry {@link MetricRegistry} that will contain the metrics. ++ * @param name name for this executor service. ++ */ ++ public InstrumentedExecutorService( ++ ExecutorService delegate, MetricRegistry registry, String name) { ++ this.delegate = delegate; ++ this.registry = registry; ++ this.name = name; ++ this.submitted = registry.meter(MetricRegistry.name(name, "submitted")); ++ this.running = registry.counter(MetricRegistry.name(name, "running")); ++ this.completed = registry.meter(MetricRegistry.name(name, "completed")); ++ this.rejected = registry.counter(MetricRegistry.name(name, "rejected")); ++ this.idle = registry.timer(MetricRegistry.name(name, "idle")); ++ this.duration = registry.timer(MetricRegistry.name(name, "duration")); + +- registerInternalMetrics(); +- } ++ registerInternalMetrics(); ++ } + +- private void registerInternalMetrics() { +- if (delegate instanceof ThreadPoolExecutor) { +- ThreadPoolExecutor executor = (ThreadPoolExecutor) delegate; +- registry.registerGauge(MetricRegistry.name(name, "pool.size"), +- executor::getPoolSize); +- registry.registerGauge(MetricRegistry.name(name, "pool.core"), +- executor::getCorePoolSize); +- registry.registerGauge(MetricRegistry.name(name, "pool.max"), +- executor::getMaximumPoolSize); +- final BlockingQueue queue = executor.getQueue(); +- registry.registerGauge(MetricRegistry.name(name, "tasks.active"), +- executor::getActiveCount); +- registry.registerGauge(MetricRegistry.name(name, "tasks.completed"), +- executor::getCompletedTaskCount); +- registry.registerGauge(MetricRegistry.name(name, "tasks.queued"), +- queue::size); +- registry.registerGauge(MetricRegistry.name(name, "tasks.capacity"), +- queue::remainingCapacity); +- RejectedExecutionHandler delegateHandler = executor.getRejectedExecutionHandler(); +- executor.setRejectedExecutionHandler(new InstrumentedRejectedExecutionHandler(delegateHandler)); +- } else if (delegate instanceof ForkJoinPool) { +- ForkJoinPool forkJoinPool = (ForkJoinPool) delegate; +- registry.registerGauge(MetricRegistry.name(name, "tasks.stolen"), +- forkJoinPool::getStealCount); +- registry.registerGauge(MetricRegistry.name(name, "tasks.queued"), +- forkJoinPool::getQueuedTaskCount); +- registry.registerGauge(MetricRegistry.name(name, "threads.active"), +- forkJoinPool::getActiveThreadCount); +- registry.registerGauge(MetricRegistry.name(name, "threads.running"), +- forkJoinPool::getRunningThreadCount); +- } ++ private void registerInternalMetrics() { ++ if (delegate instanceof ThreadPoolExecutor) { ++ ThreadPoolExecutor executor = (ThreadPoolExecutor) delegate; ++ registry.registerGauge(MetricRegistry.name(name, "pool.size"), executor::getPoolSize); ++ registry.registerGauge(MetricRegistry.name(name, "pool.core"), executor::getCorePoolSize); ++ registry.registerGauge(MetricRegistry.name(name, "pool.max"), executor::getMaximumPoolSize); ++ final BlockingQueue queue = executor.getQueue(); ++ registry.registerGauge(MetricRegistry.name(name, "tasks.active"), executor::getActiveCount); ++ registry.registerGauge( ++ MetricRegistry.name(name, "tasks.completed"), executor::getCompletedTaskCount); ++ registry.registerGauge(MetricRegistry.name(name, "tasks.queued"), queue::size); ++ registry.registerGauge(MetricRegistry.name(name, "tasks.capacity"), queue::remainingCapacity); ++ RejectedExecutionHandler delegateHandler = executor.getRejectedExecutionHandler(); ++ executor.setRejectedExecutionHandler( ++ new InstrumentedRejectedExecutionHandler(delegateHandler)); ++ } else if (delegate instanceof ForkJoinPool) { ++ ForkJoinPool forkJoinPool = (ForkJoinPool) delegate; ++ registry.registerGauge( ++ MetricRegistry.name(name, "tasks.stolen"), forkJoinPool::getStealCount); ++ registry.registerGauge( ++ MetricRegistry.name(name, "tasks.queued"), forkJoinPool::getQueuedTaskCount); ++ registry.registerGauge( ++ MetricRegistry.name(name, "threads.active"), forkJoinPool::getActiveThreadCount); ++ registry.registerGauge( ++ MetricRegistry.name(name, "threads.running"), forkJoinPool::getRunningThreadCount); + } ++ } + +- private void removeInternalMetrics() { +- if (delegate instanceof ThreadPoolExecutor) { +- registry.remove(MetricRegistry.name(name, "pool.size")); +- registry.remove(MetricRegistry.name(name, "pool.core")); +- registry.remove(MetricRegistry.name(name, "pool.max")); +- registry.remove(MetricRegistry.name(name, "tasks.active")); +- registry.remove(MetricRegistry.name(name, "tasks.completed")); +- registry.remove(MetricRegistry.name(name, "tasks.queued")); +- registry.remove(MetricRegistry.name(name, "tasks.capacity")); +- } else if (delegate instanceof ForkJoinPool) { +- registry.remove(MetricRegistry.name(name, "tasks.stolen")); +- registry.remove(MetricRegistry.name(name, "tasks.queued")); +- registry.remove(MetricRegistry.name(name, "threads.active")); +- registry.remove(MetricRegistry.name(name, "threads.running")); +- } ++ private void removeInternalMetrics() { ++ if (delegate instanceof ThreadPoolExecutor) { ++ registry.remove(MetricRegistry.name(name, "pool.size")); ++ registry.remove(MetricRegistry.name(name, "pool.core")); ++ registry.remove(MetricRegistry.name(name, "pool.max")); ++ registry.remove(MetricRegistry.name(name, "tasks.active")); ++ registry.remove(MetricRegistry.name(name, "tasks.completed")); ++ registry.remove(MetricRegistry.name(name, "tasks.queued")); ++ registry.remove(MetricRegistry.name(name, "tasks.capacity")); ++ } else if (delegate instanceof ForkJoinPool) { ++ registry.remove(MetricRegistry.name(name, "tasks.stolen")); ++ registry.remove(MetricRegistry.name(name, "tasks.queued")); ++ registry.remove(MetricRegistry.name(name, "threads.active")); ++ registry.remove(MetricRegistry.name(name, "threads.running")); + } ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void execute(Runnable runnable) { +- submitted.mark(); +- delegate.execute(new InstrumentedRunnable(runnable)); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public void execute(Runnable runnable) { ++ submitted.mark(); ++ delegate.execute(new InstrumentedRunnable(runnable)); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public Future submit(Runnable runnable) { +- submitted.mark(); +- return delegate.submit(new InstrumentedRunnable(runnable)); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public Future submit(Runnable runnable) { ++ submitted.mark(); ++ return delegate.submit(new InstrumentedRunnable(runnable)); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public Future submit(Runnable runnable, T result) { +- submitted.mark(); +- return delegate.submit(new InstrumentedRunnable(runnable), result); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public Future submit(Runnable runnable, T result) { ++ submitted.mark(); ++ return delegate.submit(new InstrumentedRunnable(runnable), result); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public Future submit(Callable task) { +- submitted.mark(); +- return delegate.submit(new InstrumentedCallable<>(task)); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public Future submit(Callable task) { ++ submitted.mark(); ++ return delegate.submit(new InstrumentedCallable<>(task)); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public List> invokeAll(Collection> tasks) throws InterruptedException { +- submitted.mark(tasks.size()); +- Collection> instrumented = instrument(tasks); +- return delegate.invokeAll(instrumented); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public List> invokeAll(Collection> tasks) ++ throws InterruptedException { ++ submitted.mark(tasks.size()); ++ Collection> instrumented = instrument(tasks); ++ return delegate.invokeAll(instrumented); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { +- submitted.mark(tasks.size()); +- Collection> instrumented = instrument(tasks); +- return delegate.invokeAll(instrumented, timeout, unit); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public List> invokeAll( ++ Collection> tasks, long timeout, TimeUnit unit) ++ throws InterruptedException { ++ submitted.mark(tasks.size()); ++ Collection> instrumented = instrument(tasks); ++ return delegate.invokeAll(instrumented, timeout, unit); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public T invokeAny(Collection> tasks) throws ExecutionException, InterruptedException { +- submitted.mark(tasks.size()); +- Collection> instrumented = instrument(tasks); +- return delegate.invokeAny(instrumented); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public T invokeAny(Collection> tasks) ++ throws ExecutionException, InterruptedException { ++ submitted.mark(tasks.size()); ++ Collection> instrumented = instrument(tasks); ++ return delegate.invokeAny(instrumented); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException { +- submitted.mark(tasks.size()); +- Collection> instrumented = instrument(tasks); +- return delegate.invokeAny(instrumented, timeout, unit); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) ++ throws ExecutionException, InterruptedException, TimeoutException { ++ submitted.mark(tasks.size()); ++ Collection> instrumented = instrument(tasks); ++ return delegate.invokeAny(instrumented, timeout, unit); ++ } + +- private Collection> instrument(Collection> tasks) { +- final List> instrumented = new ArrayList<>(tasks.size()); +- for (Callable task : tasks) { +- instrumented.add(new InstrumentedCallable<>(task)); +- } +- return instrumented; ++ private Collection> instrument( ++ Collection> tasks) { ++ final List> instrumented = new ArrayList<>(tasks.size()); ++ for (Callable task : tasks) { ++ instrumented.add(new InstrumentedCallable<>(task)); + } ++ return instrumented; ++ } + +- @Override +- public void shutdown() { +- delegate.shutdown(); +- removeInternalMetrics(); +- } ++ @Override ++ public void shutdown() { ++ delegate.shutdown(); ++ removeInternalMetrics(); ++ } + +- @Override +- public List shutdownNow() { +- List remainingTasks = delegate.shutdownNow(); +- removeInternalMetrics(); +- return remainingTasks; +- } ++ @Override ++ public List shutdownNow() { ++ List remainingTasks = delegate.shutdownNow(); ++ removeInternalMetrics(); ++ return remainingTasks; ++ } + +- @Override +- public boolean isShutdown() { +- return delegate.isShutdown(); +- } ++ @Override ++ public boolean isShutdown() { ++ return delegate.isShutdown(); ++ } + +- @Override +- public boolean isTerminated() { +- return delegate.isTerminated(); +- } ++ @Override ++ public boolean isTerminated() { ++ return delegate.isTerminated(); ++ } + +- @Override +- public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException { +- return delegate.awaitTermination(l, timeUnit); +- } ++ @Override ++ public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException { ++ return delegate.awaitTermination(l, timeUnit); ++ } + +- private class InstrumentedRejectedExecutionHandler implements RejectedExecutionHandler { +- private final RejectedExecutionHandler delegateHandler; ++ private class InstrumentedRejectedExecutionHandler implements RejectedExecutionHandler { ++ private final RejectedExecutionHandler delegateHandler; + +- public InstrumentedRejectedExecutionHandler(RejectedExecutionHandler delegateHandler) { +- this.delegateHandler = delegateHandler; +- } ++ public InstrumentedRejectedExecutionHandler(RejectedExecutionHandler delegateHandler) { ++ this.delegateHandler = delegateHandler; ++ } + +- @Override +- public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { +- rejected.inc(); +- this.delegateHandler.rejectedExecution(r, executor); +- } ++ @Override ++ public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { ++ rejected.inc(); ++ this.delegateHandler.rejectedExecution(r, executor); + } ++ } + +- private class InstrumentedRunnable implements Runnable { +- private final Runnable task; +- private final Timer.Context idleContext; ++ private class InstrumentedRunnable implements Runnable { ++ private final Runnable task; ++ private final Timer.Context idleContext; + +- InstrumentedRunnable(Runnable task) { +- this.task = task; +- this.idleContext = idle.time(); +- } ++ InstrumentedRunnable(Runnable task) { ++ this.task = task; ++ this.idleContext = idle.time(); ++ } + +- @Override +- public void run() { +- idleContext.stop(); +- running.inc(); +- try (Timer.Context durationContext = duration.time()) { +- task.run(); +- } finally { +- running.dec(); +- completed.mark(); +- } +- } ++ @Override ++ public void run() { ++ idleContext.stop(); ++ running.inc(); ++ try (Timer.Context durationContext = duration.time()) { ++ task.run(); ++ } finally { ++ running.dec(); ++ completed.mark(); ++ } + } ++ } + +- private class InstrumentedCallable implements Callable { +- private final Callable callable; +- private final Timer.Context idleContext; ++ private class InstrumentedCallable implements Callable { ++ private final Callable callable; ++ private final Timer.Context idleContext; + +- InstrumentedCallable(Callable callable) { +- this.callable = callable; +- this.idleContext = idle.time(); +- } ++ InstrumentedCallable(Callable callable) { ++ this.callable = callable; ++ this.idleContext = idle.time(); ++ } + +- @Override +- public T call() throws Exception { +- idleContext.stop(); +- running.inc(); +- try (Timer.Context context = duration.time()) { +- return callable.call(); +- } finally { +- running.dec(); +- completed.mark(); +- } +- } ++ @Override ++ public T call() throws Exception { ++ idleContext.stop(); ++ running.inc(); ++ try (Timer.Context context = duration.time()) { ++ return callable.call(); ++ } finally { ++ running.dec(); ++ completed.mark(); ++ } + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorService.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorService.java +@@ -15,283 +15,266 @@ import java.util.concurrent.atomic.AtomicLong; + /** + * An {@link ScheduledExecutorService} that monitors the number of tasks submitted, running, + * completed and also keeps a {@link Timer} for the task duration. +- *

+- * It will register the metrics using the given (or auto-generated) name as classifier, e.g: ++ * ++ *

It will register the metrics using the given (or auto-generated) name as classifier, e.g: + * "your-executor-service.submitted", "your-executor-service.running", etc. + */ + public class InstrumentedScheduledExecutorService implements ScheduledExecutorService { +- private static final AtomicLong NAME_COUNTER = new AtomicLong(); +- +- private final ScheduledExecutorService delegate; +- +- private final Meter submitted; +- private final Counter running; +- private final Meter completed; +- private final Timer duration; +- +- private final Meter scheduledOnce; +- private final Meter scheduledRepetitively; +- private final Counter scheduledOverrun; +- private final Histogram percentOfPeriod; +- +- /** +- * Wraps an {@link ScheduledExecutorService} uses an auto-generated default name. +- * +- * @param delegate {@link ScheduledExecutorService} to wrap. +- * @param registry {@link MetricRegistry} that will contain the metrics. +- */ +- public InstrumentedScheduledExecutorService(ScheduledExecutorService delegate, MetricRegistry registry) { +- this(delegate, registry, "instrumented-scheduled-executor-service-" + NAME_COUNTER.incrementAndGet()); ++ private static final AtomicLong NAME_COUNTER = new AtomicLong(); ++ ++ private final ScheduledExecutorService delegate; ++ ++ private final Meter submitted; ++ private final Counter running; ++ private final Meter completed; ++ private final Timer duration; ++ ++ private final Meter scheduledOnce; ++ private final Meter scheduledRepetitively; ++ private final Counter scheduledOverrun; ++ private final Histogram percentOfPeriod; ++ ++ /** ++ * Wraps an {@link ScheduledExecutorService} uses an auto-generated default name. ++ * ++ * @param delegate {@link ScheduledExecutorService} to wrap. ++ * @param registry {@link MetricRegistry} that will contain the metrics. ++ */ ++ public InstrumentedScheduledExecutorService( ++ ScheduledExecutorService delegate, MetricRegistry registry) { ++ this( ++ delegate, ++ registry, ++ "instrumented-scheduled-executor-service-" + NAME_COUNTER.incrementAndGet()); ++ } ++ ++ /** ++ * Wraps an {@link ScheduledExecutorService} with an explicit name. ++ * ++ * @param delegate {@link ScheduledExecutorService} to wrap. ++ * @param registry {@link MetricRegistry} that will contain the metrics. ++ * @param name name for this executor service. ++ */ ++ public InstrumentedScheduledExecutorService( ++ ScheduledExecutorService delegate, MetricRegistry registry, String name) { ++ this.delegate = delegate; ++ ++ this.submitted = registry.meter(MetricRegistry.name(name, "submitted")); ++ ++ this.running = registry.counter(MetricRegistry.name(name, "running")); ++ this.completed = registry.meter(MetricRegistry.name(name, "completed")); ++ this.duration = registry.timer(MetricRegistry.name(name, "duration")); ++ ++ this.scheduledOnce = registry.meter(MetricRegistry.name(name, "scheduled.once")); ++ this.scheduledRepetitively = ++ registry.meter(MetricRegistry.name(name, "scheduled.repetitively")); ++ this.scheduledOverrun = registry.counter(MetricRegistry.name(name, "scheduled.overrun")); ++ this.percentOfPeriod = ++ registry.histogram(MetricRegistry.name(name, "scheduled.percent-of-period")); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { ++ scheduledOnce.mark(); ++ return delegate.schedule(new InstrumentedRunnable(command), delay, unit); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { ++ scheduledOnce.mark(); ++ return delegate.schedule(new InstrumentedCallable<>(callable), delay, unit); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public ScheduledFuture scheduleAtFixedRate( ++ Runnable command, long initialDelay, long period, TimeUnit unit) { ++ scheduledRepetitively.mark(); ++ return delegate.scheduleAtFixedRate( ++ new InstrumentedPeriodicRunnable(command, period, unit), initialDelay, period, unit); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public ScheduledFuture scheduleWithFixedDelay( ++ Runnable command, long initialDelay, long delay, TimeUnit unit) { ++ scheduledRepetitively.mark(); ++ return delegate.scheduleWithFixedDelay( ++ new InstrumentedRunnable(command), initialDelay, delay, unit); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void shutdown() { ++ delegate.shutdown(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public List shutdownNow() { ++ return delegate.shutdownNow(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public boolean isShutdown() { ++ return delegate.isShutdown(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public boolean isTerminated() { ++ return delegate.isTerminated(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { ++ return delegate.awaitTermination(timeout, unit); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Future submit(Callable task) { ++ submitted.mark(); ++ return delegate.submit(new InstrumentedCallable<>(task)); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Future submit(Runnable task, T result) { ++ submitted.mark(); ++ return delegate.submit(new InstrumentedRunnable(task), result); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Future submit(Runnable task) { ++ submitted.mark(); ++ return delegate.submit(new InstrumentedRunnable(task)); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public List> invokeAll(Collection> tasks) ++ throws InterruptedException { ++ submitted.mark(tasks.size()); ++ Collection> instrumented = instrument(tasks); ++ return delegate.invokeAll(instrumented); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public List> invokeAll( ++ Collection> tasks, long timeout, TimeUnit unit) ++ throws InterruptedException { ++ submitted.mark(tasks.size()); ++ Collection> instrumented = instrument(tasks); ++ return delegate.invokeAll(instrumented, timeout, unit); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public T invokeAny(Collection> tasks) ++ throws InterruptedException, ExecutionException { ++ submitted.mark(tasks.size()); ++ Collection> instrumented = instrument(tasks); ++ return delegate.invokeAny(instrumented); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) ++ throws InterruptedException, ExecutionException, TimeoutException { ++ submitted.mark(tasks.size()); ++ Collection> instrumented = instrument(tasks); ++ return delegate.invokeAny(instrumented, timeout, unit); ++ } ++ ++ private Collection> instrument( ++ Collection> tasks) { ++ final List> instrumented = new ArrayList<>(tasks.size()); ++ for (Callable task : tasks) { ++ instrumented.add(new InstrumentedCallable<>(task)); + } ++ return instrumented; ++ } + +- /** +- * Wraps an {@link ScheduledExecutorService} with an explicit name. +- * +- * @param delegate {@link ScheduledExecutorService} to wrap. +- * @param registry {@link MetricRegistry} that will contain the metrics. +- * @param name name for this executor service. +- */ +- public InstrumentedScheduledExecutorService(ScheduledExecutorService delegate, MetricRegistry registry, String name) { +- this.delegate = delegate; +- +- this.submitted = registry.meter(MetricRegistry.name(name, "submitted")); +- +- this.running = registry.counter(MetricRegistry.name(name, "running")); +- this.completed = registry.meter(MetricRegistry.name(name, "completed")); +- this.duration = registry.timer(MetricRegistry.name(name, "duration")); +- +- this.scheduledOnce = registry.meter(MetricRegistry.name(name, "scheduled.once")); +- this.scheduledRepetitively = registry.meter(MetricRegistry.name(name, "scheduled.repetitively")); +- this.scheduledOverrun = registry.counter(MetricRegistry.name(name, "scheduled.overrun")); +- this.percentOfPeriod = registry.histogram(MetricRegistry.name(name, "scheduled.percent-of-period")); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { +- scheduledOnce.mark(); +- return delegate.schedule(new InstrumentedRunnable(command), delay, unit); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { +- scheduledOnce.mark(); +- return delegate.schedule(new InstrumentedCallable<>(callable), delay, unit); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { +- scheduledRepetitively.mark(); +- return delegate.scheduleAtFixedRate(new InstrumentedPeriodicRunnable(command, period, unit), initialDelay, period, unit); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { +- scheduledRepetitively.mark(); +- return delegate.scheduleWithFixedDelay(new InstrumentedRunnable(command), initialDelay, delay, unit); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public void shutdown() { +- delegate.shutdown(); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public List shutdownNow() { +- return delegate.shutdownNow(); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public boolean isShutdown() { +- return delegate.isShutdown(); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public boolean isTerminated() { +- return delegate.isTerminated(); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { +- return delegate.awaitTermination(timeout, unit); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public void execute(Runnable command) { ++ submitted.mark(); ++ delegate.execute(new InstrumentedRunnable(command)); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public Future submit(Callable task) { +- submitted.mark(); +- return delegate.submit(new InstrumentedCallable<>(task)); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public Future submit(Runnable task, T result) { +- submitted.mark(); +- return delegate.submit(new InstrumentedRunnable(task), result); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public Future submit(Runnable task) { +- submitted.mark(); +- return delegate.submit(new InstrumentedRunnable(task)); +- } ++ private class InstrumentedRunnable implements Runnable { ++ private final Runnable command; + +- /** +- * {@inheritDoc} +- */ +- @Override +- public List> invokeAll(Collection> tasks) throws InterruptedException { +- submitted.mark(tasks.size()); +- Collection> instrumented = instrument(tasks); +- return delegate.invokeAll(instrumented); ++ InstrumentedRunnable(Runnable command) { ++ this.command = command; + } + +- /** +- * {@inheritDoc} +- */ + @Override +- public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { +- submitted.mark(tasks.size()); +- Collection> instrumented = instrument(tasks); +- return delegate.invokeAll(instrumented, timeout, unit); ++ public void run() { ++ running.inc(); ++ final Timer.Context context = duration.time(); ++ try { ++ command.run(); ++ } finally { ++ context.stop(); ++ running.dec(); ++ completed.mark(); ++ } + } ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { +- submitted.mark(tasks.size()); +- Collection> instrumented = instrument(tasks); +- return delegate.invokeAny(instrumented); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { +- submitted.mark(tasks.size()); +- Collection> instrumented = instrument(tasks); +- return delegate.invokeAny(instrumented, timeout, unit); +- } ++ private class InstrumentedPeriodicRunnable implements Runnable { ++ private final Runnable command; ++ private final long periodInNanos; + +- private Collection> instrument(Collection> tasks) { +- final List> instrumented = new ArrayList<>(tasks.size()); +- for (Callable task : tasks) { +- instrumented.add(new InstrumentedCallable<>(task)); +- } +- return instrumented; ++ InstrumentedPeriodicRunnable(Runnable command, long period, TimeUnit unit) { ++ this.command = command; ++ this.periodInNanos = unit.toNanos(period); + } + +- /** +- * {@inheritDoc} +- */ + @Override +- public void execute(Runnable command) { +- submitted.mark(); +- delegate.execute(new InstrumentedRunnable(command)); +- } +- +- private class InstrumentedRunnable implements Runnable { +- private final Runnable command; +- +- InstrumentedRunnable(Runnable command) { +- this.command = command; +- } +- +- @Override +- public void run() { +- running.inc(); +- final Timer.Context context = duration.time(); +- try { +- command.run(); +- } finally { +- context.stop(); +- running.dec(); +- completed.mark(); +- } ++ public void run() { ++ running.inc(); ++ final Timer.Context context = duration.time(); ++ try { ++ command.run(); ++ } finally { ++ final long elapsed = context.stop(); ++ running.dec(); ++ completed.mark(); ++ if (elapsed > periodInNanos) { ++ scheduledOverrun.inc(); + } ++ percentOfPeriod.update((100L * elapsed) / periodInNanos); ++ } + } ++ } + +- private class InstrumentedPeriodicRunnable implements Runnable { +- private final Runnable command; +- private final long periodInNanos; +- +- InstrumentedPeriodicRunnable(Runnable command, long period, TimeUnit unit) { +- this.command = command; +- this.periodInNanos = unit.toNanos(period); +- } ++ private class InstrumentedCallable implements Callable { ++ private final Callable task; + +- @Override +- public void run() { +- running.inc(); +- final Timer.Context context = duration.time(); +- try { +- command.run(); +- } finally { +- final long elapsed = context.stop(); +- running.dec(); +- completed.mark(); +- if (elapsed > periodInNanos) { +- scheduledOverrun.inc(); +- } +- percentOfPeriod.update((100L * elapsed) / periodInNanos); +- } +- } ++ InstrumentedCallable(Callable task) { ++ this.task = task; + } + +- private class InstrumentedCallable implements Callable { +- private final Callable task; +- +- InstrumentedCallable(Callable task) { +- this.task = task; +- } +- +- @Override +- public T call() throws Exception { +- running.inc(); +- final Timer.Context context = duration.time(); +- try { +- return task.call(); +- } finally { +- context.stop(); +- running.dec(); +- completed.mark(); +- } +- } ++ @Override ++ public T call() throws Exception { ++ running.inc(); ++ final Timer.Context context = duration.time(); ++ try { ++ return task.call(); ++ } finally { ++ context.stop(); ++ running.dec(); ++ completed.mark(); ++ } + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedThreadFactory.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedThreadFactory.java +@@ -5,69 +5,67 @@ import java.util.concurrent.atomic.AtomicLong; + + /** + * A {@link ThreadFactory} that monitors the number of threads created, running and terminated. +- *

+- * It will register the metrics using the given (or auto-generated) name as classifier, e.g: ++ * ++ *

It will register the metrics using the given (or auto-generated) name as classifier, e.g: + * "your-thread-delegate.created", "your-thread-delegate.running", etc. + */ + public class InstrumentedThreadFactory implements ThreadFactory { +- private static final AtomicLong NAME_COUNTER = new AtomicLong(); ++ private static final AtomicLong NAME_COUNTER = new AtomicLong(); + +- private final ThreadFactory delegate; +- private final Meter created; +- private final Counter running; +- private final Meter terminated; ++ private final ThreadFactory delegate; ++ private final Meter created; ++ private final Counter running; ++ private final Meter terminated; + +- /** +- * Wraps a {@link ThreadFactory}, uses a default auto-generated name. +- * +- * @param delegate {@link ThreadFactory} to wrap. +- * @param registry {@link MetricRegistry} that will contain the metrics. +- */ +- public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry) { +- this(delegate, registry, "instrumented-thread-delegate-" + NAME_COUNTER.incrementAndGet()); +- } ++ /** ++ * Wraps a {@link ThreadFactory}, uses a default auto-generated name. ++ * ++ * @param delegate {@link ThreadFactory} to wrap. ++ * @param registry {@link MetricRegistry} that will contain the metrics. ++ */ ++ public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry) { ++ this(delegate, registry, "instrumented-thread-delegate-" + NAME_COUNTER.incrementAndGet()); ++ } + +- /** +- * Wraps a {@link ThreadFactory} with an explicit name. +- * +- * @param delegate {@link ThreadFactory} to wrap. +- * @param registry {@link MetricRegistry} that will contain the metrics. +- * @param name name for this delegate. +- */ +- public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry, String name) { +- this.delegate = delegate; +- this.created = registry.meter(MetricRegistry.name(name, "created")); +- this.running = registry.counter(MetricRegistry.name(name, "running")); +- this.terminated = registry.meter(MetricRegistry.name(name, "terminated")); +- } ++ /** ++ * Wraps a {@link ThreadFactory} with an explicit name. ++ * ++ * @param delegate {@link ThreadFactory} to wrap. ++ * @param registry {@link MetricRegistry} that will contain the metrics. ++ * @param name name for this delegate. ++ */ ++ public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry, String name) { ++ this.delegate = delegate; ++ this.created = registry.meter(MetricRegistry.name(name, "created")); ++ this.running = registry.counter(MetricRegistry.name(name, "running")); ++ this.terminated = registry.meter(MetricRegistry.name(name, "terminated")); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public Thread newThread(Runnable runnable) { +- Runnable wrappedRunnable = new InstrumentedRunnable(runnable); +- Thread thread = delegate.newThread(wrappedRunnable); +- created.mark(); +- return thread; +- } ++ /** {@inheritDoc} */ ++ @Override ++ public Thread newThread(Runnable runnable) { ++ Runnable wrappedRunnable = new InstrumentedRunnable(runnable); ++ Thread thread = delegate.newThread(wrappedRunnable); ++ created.mark(); ++ return thread; ++ } + +- private class InstrumentedRunnable implements Runnable { +- private final Runnable task; ++ private class InstrumentedRunnable implements Runnable { ++ private final Runnable task; + +- InstrumentedRunnable(Runnable task) { +- this.task = task; +- } ++ InstrumentedRunnable(Runnable task) { ++ this.task = task; ++ } + +- @Override +- public void run() { +- running.inc(); +- try { +- task.run(); +- } finally { +- running.dec(); +- terminated.mark(); +- } +- } ++ @Override ++ public void run() { ++ running.inc(); ++ try { ++ task.run(); ++ } finally { ++ running.dec(); ++ terminated.mark(); ++ } + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java +@@ -1,9 +1,10 @@ + package io.dropwizard.metrics5; + +-import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Objects.requireNonNull; + ++import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; + import java.time.Duration; +-import java.util.Objects; + import java.util.concurrent.ConcurrentSkipListMap; + import java.util.concurrent.ThreadLocalRandom; + import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +@@ -16,255 +17,255 @@ import java.util.function.BiConsumer; + * sampling reservoir, exponentially biased towards newer entries. + * + * @author Carter Kozak +- * @see +- * Cormode et al. Forward Decay: A Practical Time Decay Model for Streaming Systems. ICDE '09: +- * Proceedings of the 2009 IEEE International Conference on Data Engineering (2009) +- *

+- * {@link LockFreeExponentiallyDecayingReservoir} is based closely on the {@link ExponentiallyDecayingReservoir}, +- * however it provides looser guarantees while completely avoiding locks. +- *

+- * Looser guarantees: +- *

    +- *
  • Updates which occur concurrently with rescaling may be discarded if the orphaned state node is updated after +- * rescale has replaced it. This condition has a greater probability as the rescale interval is reduced due to the +- * increased frequency of rescaling. {@link #rescaleThresholdNanos} values below 30 seconds are not recommended. +- *
  • Given a small rescale threshold, updates may attempt to rescale into a new bucket, but lose the CAS race +- * and update into a newer bucket than expected. In these cases the measurement weight is reduced accordingly. +- *
  • In the worst case, all concurrent threads updating the reservoir may attempt to rescale rather than +- * a single thread holding an exclusive write lock. It's expected that the configuration is set such that +- * rescaling is substantially less common than updating at peak load. Even so, when size is reasonably small +- * it can be more efficient to rescale than to park and context switch. +- *
++ * @see Cormode et al. Forward ++ * Decay: A Practical Time Decay Model for Streaming Systems. ICDE '09: Proceedings of the 2009 ++ * IEEE International Conference on Data Engineering (2009) ++ *

{@link LockFreeExponentiallyDecayingReservoir} is based closely on the {@link ++ * ExponentiallyDecayingReservoir}, however it provides looser guarantees while completely ++ * avoiding locks. ++ *

Looser guarantees: ++ *

    ++ *
  • Updates which occur concurrently with rescaling may be discarded if the orphaned state ++ * node is updated after rescale has replaced it. This condition has a greater probability ++ * as the rescale interval is reduced due to the increased frequency of rescaling. {@link ++ * #rescaleThresholdNanos} values below 30 seconds are not recommended. ++ *
  • Given a small rescale threshold, updates may attempt to rescale into a new bucket, but ++ * lose the CAS race and update into a newer bucket than expected. In these cases the ++ * measurement weight is reduced accordingly. ++ *
  • In the worst case, all concurrent threads updating the reservoir may attempt to rescale ++ * rather than a single thread holding an exclusive write lock. It's expected that the ++ * configuration is set such that rescaling is substantially less common than updating at ++ * peak load. Even so, when size is reasonably small it can be more efficient to rescale ++ * than to park and context switch. ++ *
+ */ + public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + +- private static final double SECONDS_PER_NANO = .000_000_001D; +- private static final AtomicReferenceFieldUpdater stateUpdater = +- AtomicReferenceFieldUpdater.newUpdater(LockFreeExponentiallyDecayingReservoir.class, State.class, "state"); ++ private static final double SECONDS_PER_NANO = .000_000_001D; ++ private static final AtomicReferenceFieldUpdater ++ STATE_UPDATER = ++ AtomicReferenceFieldUpdater.newUpdater( ++ LockFreeExponentiallyDecayingReservoir.class, State.class, "state"); ++ ++ private final int size; ++ private final long rescaleThresholdNanos; ++ private final Clock clock; ++ ++ private volatile State state; ++ ++ private static final class State { + ++ private static final AtomicIntegerFieldUpdater COUNT_UPDATER = ++ AtomicIntegerFieldUpdater.newUpdater(State.class, "count"); ++ ++ private final double alphaNanos; + private final int size; +- private final long rescaleThresholdNanos; +- private final Clock clock; +- +- private volatile State state; +- +- private static final class State { +- +- private static final AtomicIntegerFieldUpdater countUpdater = +- AtomicIntegerFieldUpdater.newUpdater(State.class, "count"); +- +- private final double alphaNanos; +- private final int size; +- private final long startTick; +- // Count is updated after samples are successfully added to the map. +- private final ConcurrentSkipListMap values; +- +- private volatile int count; +- +- State( +- double alphaNanos, +- int size, +- long startTick, +- int count, +- ConcurrentSkipListMap values) { +- this.alphaNanos = alphaNanos; +- this.size = size; +- this.startTick = startTick; +- this.values = values; +- this.count = count; +- } +- +- private void update(long value, long timestampNanos) { +- double itemWeight = weight(timestampNanos - startTick); +- double priority = itemWeight / ThreadLocalRandom.current().nextDouble(); +- boolean mapIsFull = count >= size; +- if (!mapIsFull || values.firstKey() < priority) { +- addSample(priority, value, itemWeight, mapIsFull); +- } +- } +- +- private void addSample(double priority, long value, double itemWeight, boolean bypassIncrement) { +- if (values.putIfAbsent(priority, new WeightedSample(value, itemWeight)) == null +- && (bypassIncrement || countUpdater.incrementAndGet(this) > size)) { +- values.pollFirstEntry(); +- } +- } +- +- /* "A common feature of the above techniques—indeed, the key technique that +- * allows us to track the decayed weights efficiently—is that they maintain +- * counts and other quantities based on g(ti − L), and only scale by g(t − L) +- * at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero +- * and one, the intermediate values of g(ti − L) could become very large. For +- * polynomial functions, these values should not grow too large, and should be +- * effectively represented in practice by floating point values without loss of +- * precision. For exponential functions, these values could grow quite large as +- * new values of (ti − L) become large, and potentially exceed the capacity of +- * common floating point types. However, since the values stored by the +- * algorithms are linear combinations of g values (scaled sums), they can be +- * rescaled relative to a new landmark. That is, by the analysis of exponential +- * decay in Section III-A, the choice of L does not affect the final result. We +- * can therefore multiply each value based on L by a factor of exp(−α(L′ − L)), +- * and obtain the correct value as if we had instead computed relative to a new +- * landmark L′ (and then use this new L′ at query time). This can be done with +- * a linear pass over whatever data structure is being used." +- */ +- State rescale(long newTick) { +- long durationNanos = newTick - startTick; +- double scalingFactor = Math.exp(-alphaNanos * durationNanos); +- int newCount = 0; +- ConcurrentSkipListMap newValues = new ConcurrentSkipListMap<>(); +- if (Double.compare(scalingFactor, 0) != 0) { +- RescalingConsumer consumer = new RescalingConsumer(scalingFactor, newValues); +- values.forEach(consumer); +- // make sure the counter is in sync with the number of stored samples. +- newCount = consumer.count; +- } +- // It's possible that more values were added while the map was scanned, those with the +- // minimum priorities are removed. +- while (newCount > size) { +- Objects.requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); +- newCount--; +- } +- return new State(alphaNanos, size, newTick, newCount, newValues); +- } +- +- private double weight(long durationNanos) { +- return Math.exp(alphaNanos * durationNanos); +- } ++ private final long startTick; ++ // Count is updated after samples are successfully added to the map. ++ private final ConcurrentSkipListMap values; ++ ++ private volatile int count; ++ ++ State( ++ double alphaNanos, ++ int size, ++ long startTick, ++ int count, ++ ConcurrentSkipListMap values) { ++ this.alphaNanos = alphaNanos; ++ this.size = size; ++ this.startTick = startTick; ++ this.values = values; ++ this.count = count; + } + +- private static final class RescalingConsumer implements BiConsumer { +- private final double scalingFactor; +- private final ConcurrentSkipListMap values; +- private int count; +- +- RescalingConsumer(double scalingFactor, ConcurrentSkipListMap values) { +- this.scalingFactor = scalingFactor; +- this.values = values; +- } +- +- @Override +- public void accept(Double priority, WeightedSample sample) { +- double newWeight = sample.weight * scalingFactor; +- if (Double.compare(newWeight, 0) == 0) { +- return; +- } +- WeightedSample newSample = new WeightedSample(sample.value, newWeight); +- if (values.put(priority * scalingFactor, newSample) == null) { +- count++; +- } +- } ++ private void update(long value, long timestampNanos) { ++ double itemWeight = weight(timestampNanos - startTick); ++ double priority = itemWeight / ThreadLocalRandom.current().nextDouble(); ++ boolean mapIsFull = count >= size; ++ if (!mapIsFull || values.firstKey() < priority) { ++ addSample(priority, value, itemWeight, mapIsFull); ++ } + } + +- private LockFreeExponentiallyDecayingReservoir(int size, double alpha, Duration rescaleThreshold, Clock clock) { +- // Scale alpha to nanoseconds +- double alphaNanos = alpha * SECONDS_PER_NANO; +- this.size = size; +- this.clock = clock; +- this.rescaleThresholdNanos = rescaleThreshold.toNanos(); +- this.state = new State(alphaNanos, size, clock.getTick(), 0, new ConcurrentSkipListMap<>()); ++ private void addSample( ++ double priority, long value, double itemWeight, boolean bypassIncrement) { ++ if (values.putIfAbsent(priority, new WeightedSample(value, itemWeight)) == null ++ && (bypassIncrement || COUNT_UPDATER.incrementAndGet(this) > size)) { ++ values.pollFirstEntry(); ++ } + } + +- @Override +- public int size() { +- return Math.min(size, state.count); ++ /* "A common feature of the above techniques—indeed, the key technique that ++ * allows us to track the decayed weights efficiently—is that they maintain ++ * counts and other quantities based on g(ti − L), and only scale by g(t − L) ++ * at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero ++ * and one, the intermediate values of g(ti − L) could become very large. For ++ * polynomial functions, these values should not grow too large, and should be ++ * effectively represented in practice by floating point values without loss of ++ * precision. For exponential functions, these values could grow quite large as ++ * new values of (ti − L) become large, and potentially exceed the capacity of ++ * common floating point types. However, since the values stored by the ++ * algorithms are linear combinations of g values (scaled sums), they can be ++ * rescaled relative to a new landmark. That is, by the analysis of exponential ++ * decay in Section III-A, the choice of L does not affect the final result. We ++ * can therefore multiply each value based on L by a factor of exp(−α(L′ − L)), ++ * and obtain the correct value as if we had instead computed relative to a new ++ * landmark L′ (and then use this new L′ at query time). This can be done with ++ * a linear pass over whatever data structure is being used." ++ */ ++ State rescale(long newTick) { ++ long durationNanos = newTick - startTick; ++ double scalingFactor = Math.exp(-alphaNanos * durationNanos); ++ int newCount = 0; ++ ConcurrentSkipListMap newValues = new ConcurrentSkipListMap<>(); ++ if (Double.compare(scalingFactor, 0) != 0) { ++ RescalingConsumer consumer = new RescalingConsumer(scalingFactor, newValues); ++ values.forEach(consumer); ++ // make sure the counter is in sync with the number of stored samples. ++ newCount = consumer.count; ++ } ++ // It's possible that more values were added while the map was scanned, those with the ++ // minimum priorities are removed. ++ while (newCount > size) { ++ requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); ++ newCount--; ++ } ++ return new State(alphaNanos, size, newTick, newCount, newValues); + } + +- @Override +- public void update(long value) { +- long now = clock.getTick(); +- rescaleIfNeeded(now).update(value, now); ++ private double weight(long durationNanos) { ++ return Math.exp(alphaNanos * durationNanos); + } ++ } + +- private State rescaleIfNeeded(long currentTick) { +- // This method is optimized for size so the check may be quickly inlined. +- // Rescaling occurs substantially less frequently than the check itself. +- State stateSnapshot = this.state; +- if (currentTick - stateSnapshot.startTick >= rescaleThresholdNanos) { +- return doRescale(currentTick, stateSnapshot); +- } +- return stateSnapshot; +- } ++ private static final class RescalingConsumer implements BiConsumer { ++ private final double scalingFactor; ++ private final ConcurrentSkipListMap values; ++ private int count; + +- private State doRescale(long currentTick, State stateSnapshot) { +- State newState = stateSnapshot.rescale(currentTick); +- if (stateUpdater.compareAndSet(this, stateSnapshot, newState)) { +- // newState successfully installed +- return newState; +- } +- // Otherwise another thread has won the race and we can return the result of a volatile read. +- // It's possible this has taken so long that another update is required, however that's unlikely +- // and no worse than the standard race between a rescale and update. +- return this.state; ++ RescalingConsumer(double scalingFactor, ConcurrentSkipListMap values) { ++ this.scalingFactor = scalingFactor; ++ this.values = values; + } + + @Override +- public Snapshot getSnapshot() { +- State stateSnapshot = rescaleIfNeeded(clock.getTick()); +- return new WeightedSnapshot(stateSnapshot.values.values()); ++ public void accept(Double priority, WeightedSample sample) { ++ double newWeight = sample.weight * scalingFactor; ++ if (Double.compare(newWeight, 0) == 0) { ++ return; ++ } ++ WeightedSample newSample = new WeightedSample(sample.value, newWeight); ++ if (values.put(priority * scalingFactor, newSample) == null) { ++ count++; ++ } + } ++ } ++ ++ private LockFreeExponentiallyDecayingReservoir( ++ int size, double alpha, Duration rescaleThreshold, Clock clock) { ++ // Scale alpha to nanoseconds ++ double alphaNanos = alpha * SECONDS_PER_NANO; ++ this.size = size; ++ this.clock = clock; ++ this.rescaleThresholdNanos = rescaleThreshold.toNanos(); ++ this.state = new State(alphaNanos, size, clock.getTick(), 0, new ConcurrentSkipListMap<>()); ++ } ++ ++ @Override ++ public int size() { ++ return Math.min(size, state.count); ++ } ++ ++ @Override ++ public void update(long value) { ++ long now = clock.getTick(); ++ rescaleIfNeeded(now).update(value, now); ++ } ++ ++ private State rescaleIfNeeded(long currentTick) { ++ // This method is optimized for size so the check may be quickly inlined. ++ // Rescaling occurs substantially less frequently than the check itself. ++ State stateSnapshot = this.state; ++ if (currentTick - stateSnapshot.startTick >= rescaleThresholdNanos) { ++ return doRescale(currentTick, stateSnapshot); ++ } ++ return stateSnapshot; ++ } ++ ++ private State doRescale(long currentTick, State stateSnapshot) { ++ State newState = stateSnapshot.rescale(currentTick); ++ if (STATE_UPDATER.compareAndSet(this, stateSnapshot, newState)) { ++ // newState successfully installed ++ return newState; ++ } ++ // Otherwise another thread has won the race and we can return the result of a volatile read. ++ // It's possible this has taken so long that another update is required, however that's unlikely ++ // and no worse than the standard race between a rescale and update. ++ return this.state; ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ State stateSnapshot = rescaleIfNeeded(clock.getTick()); ++ return new WeightedSnapshot(stateSnapshot.values.values()); ++ } ++ ++ public static Builder builder() { ++ return new Builder(); ++ } ++ ++ /** ++ * By default this uses a size of 1028 elements, which offers a 99.9% confidence level with a 5% ++ * margin of error assuming a normal distribution, and an alpha factor of 0.015, which heavily ++ * biases the reservoir to the past 5 minutes of measurements. ++ */ ++ public static final class Builder { ++ private static final int DEFAULT_SIZE = 1028; ++ private static final double DEFAULT_ALPHA = 0.015D; ++ private static final Duration DEFAULT_RESCALE_THRESHOLD = Duration.ofHours(1); ++ ++ private int size = DEFAULT_SIZE; ++ private double alpha = DEFAULT_ALPHA; ++ private Duration rescaleThreshold = DEFAULT_RESCALE_THRESHOLD; ++ private Clock clock = Clock.defaultClock(); ++ ++ private Builder() {} + +- public static Builder builder() { +- return new Builder(); ++ /** ++ * Maximum number of samples to keep in the reservoir. Once this number is reached older samples ++ * are replaced (based on weight, with some amount of random jitter). ++ */ ++ public Builder size(int value) { ++ checkArgument( ++ value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: %s", value); ++ this.size = value; ++ return this; + } + + /** +- * By default this uses a size of 1028 elements, which offers a 99.9% +- * confidence level with a 5% margin of error assuming a normal distribution, and an alpha +- * factor of 0.015, which heavily biases the reservoir to the past 5 minutes of measurements. ++ * Alpha is the exponential decay factor. Higher values bias results more heavily toward newer ++ * values. + */ +- public static final class Builder { +- private static final int DEFAULT_SIZE = 1028; +- private static final double DEFAULT_ALPHA = 0.015D; +- private static final Duration DEFAULT_RESCALE_THRESHOLD = Duration.ofHours(1); +- +- private int size = DEFAULT_SIZE; +- private double alpha = DEFAULT_ALPHA; +- private Duration rescaleThreshold = DEFAULT_RESCALE_THRESHOLD; +- private Clock clock = Clock.defaultClock(); +- +- private Builder() { +- } +- +- /** +- * Maximum number of samples to keep in the reservoir. Once this number is reached older samples are +- * replaced (based on weight, with some amount of random jitter). +- */ +- public Builder size(int value) { +- if (value <= 0) { +- throw new IllegalArgumentException( +- "LockFreeExponentiallyDecayingReservoir size must be positive: " + value); +- } +- this.size = value; +- return this; +- } +- +- /** +- * Alpha is the exponential decay factor. Higher values bias results more heavily toward newer values. +- */ +- public Builder alpha(double value) { +- this.alpha = value; +- return this; +- } +- +- /** +- * Interval at which this reservoir is rescaled. +- */ +- public Builder rescaleThreshold(Duration value) { +- this.rescaleThreshold = Objects.requireNonNull(value, "rescaleThreshold is required"); +- return this; +- } +- +- /** +- * Clock instance used for decay. +- */ +- public Builder clock(Clock value) { +- this.clock = Objects.requireNonNull(value, "clock is required"); +- return this; +- } +- +- public Reservoir build() { +- return new LockFreeExponentiallyDecayingReservoir(size, alpha, rescaleThreshold, clock); +- } ++ public Builder alpha(double value) { ++ this.alpha = value; ++ return this; ++ } ++ ++ /** Interval at which this reservoir is rescaled. */ ++ public Builder rescaleThreshold(Duration value) { ++ this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required"); ++ return this; ++ } ++ ++ /** Clock instance used for decay. */ ++ public Builder clock(Clock value) { ++ this.clock = requireNonNull(value, "clock is required"); ++ return this; ++ } ++ ++ public Reservoir build() { ++ return new LockFreeExponentiallyDecayingReservoir(size, alpha, rescaleThreshold, clock); + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Meter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Meter.java +@@ -4,108 +4,104 @@ import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.LongAdder; + + /** +- * A meter metric which measures mean throughput and one-, five-, and fifteen-minute +- * moving average throughputs. ++ * A meter metric which measures mean throughput and one-, five-, and fifteen-minute moving average ++ * throughputs. + * + * @see MovingAverages + */ + public class Meter implements Metered { + +- private final MovingAverages movingAverages; +- private final LongAdder count = new LongAdder(); +- private final long startTime; +- private final Clock clock; ++ private final MovingAverages movingAverages; ++ private final LongAdder count = new LongAdder(); ++ private final long startTime; ++ private final Clock clock; + +- /** +- * Creates a new {@link Meter}. +- * +- * @param movingAverages the {@link MovingAverages} implementation to use +- */ +- public Meter(MovingAverages movingAverages) { +- this(movingAverages, Clock.defaultClock()); +- } ++ /** ++ * Creates a new {@link Meter}. ++ * ++ * @param movingAverages the {@link MovingAverages} implementation to use ++ */ ++ public Meter(MovingAverages movingAverages) { ++ this(movingAverages, Clock.defaultClock()); ++ } + +- /** +- * Creates a new {@link Meter}. +- */ +- public Meter() { +- this(Clock.defaultClock()); +- } ++ /** Creates a new {@link Meter}. */ ++ public Meter() { ++ this(Clock.defaultClock()); ++ } + +- /** +- * Creates a new {@link Meter}. +- * +- * @param clock the clock to use for the meter ticks +- */ +- public Meter(Clock clock) { +- this(new ExponentialMovingAverages(clock), clock); +- } ++ /** ++ * Creates a new {@link Meter}. ++ * ++ * @param clock the clock to use for the meter ticks ++ */ ++ public Meter(Clock clock) { ++ this(new ExponentialMovingAverages(clock), clock); ++ } + +- /** +- * Creates a new {@link Meter}. +- * +- * @param movingAverages the {@link MovingAverages} implementation to use +- * @param clock the clock to use for the meter ticks +- */ +- public Meter(MovingAverages movingAverages, Clock clock) { +- this.movingAverages = movingAverages; +- this.clock = clock; +- this.startTime = this.clock.getTick(); +- } ++ /** ++ * Creates a new {@link Meter}. ++ * ++ * @param movingAverages the {@link MovingAverages} implementation to use ++ * @param clock the clock to use for the meter ticks ++ */ ++ public Meter(MovingAverages movingAverages, Clock clock) { ++ this.movingAverages = movingAverages; ++ this.clock = clock; ++ this.startTime = this.clock.getTick(); ++ } + +- /** +- * Mark the occurrence of an event. +- */ +- public void mark() { +- mark(1); +- } ++ /** Mark the occurrence of an event. */ ++ public void mark() { ++ mark(1); ++ } + +- /** +- * Mark the occurrence of a given number of events. +- * +- * @param n the number of events +- */ +- public void mark(long n) { +- movingAverages.tickIfNecessary(); +- count.add(n); +- movingAverages.update(n); +- } ++ /** ++ * Mark the occurrence of a given number of events. ++ * ++ * @param n the number of events ++ */ ++ public void mark(long n) { ++ movingAverages.tickIfNecessary(); ++ count.add(n); ++ movingAverages.update(n); ++ } + +- @Override +- public long getCount() { +- return count.sum(); +- } ++ @Override ++ public long getCount() { ++ return count.sum(); ++ } + +- @Override +- public long getSum() { +- return movingAverages.getSum(); +- } ++ @Override ++ public long getSum() { ++ return movingAverages.getSum(); ++ } + +- @Override +- public double getFifteenMinuteRate() { +- movingAverages.tickIfNecessary(); +- return movingAverages.getM15Rate(); +- } ++ @Override ++ public double getFifteenMinuteRate() { ++ movingAverages.tickIfNecessary(); ++ return movingAverages.getM15Rate(); ++ } + +- @Override +- public double getFiveMinuteRate() { +- movingAverages.tickIfNecessary(); +- return movingAverages.getM5Rate(); +- } ++ @Override ++ public double getFiveMinuteRate() { ++ movingAverages.tickIfNecessary(); ++ return movingAverages.getM5Rate(); ++ } + +- @Override +- public double getMeanRate() { +- if (getCount() == 0) { +- return 0.0; +- } else { +- final double elapsed = clock.getTick() - startTime; +- return getCount() / elapsed * TimeUnit.SECONDS.toNanos(1); +- } ++ @Override ++ public double getMeanRate() { ++ if (getCount() == 0) { ++ return 0.0; ++ } else { ++ final double elapsed = clock.getTick() - startTime; ++ return getCount() / elapsed * TimeUnit.SECONDS.toNanos(1); + } ++ } + +- @Override +- public double getOneMinuteRate() { +- movingAverages.tickIfNecessary(); +- return movingAverages.getM1Rate(); +- } ++ @Override ++ public double getOneMinuteRate() { ++ movingAverages.tickIfNecessary(); ++ return movingAverages.getM1Rate(); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Metered.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Metered.java +@@ -1,56 +1,54 @@ + package io.dropwizard.metrics5; + +-/** +- * An object which maintains mean and moving average rates. +- */ ++/** An object which maintains mean and moving average rates. */ + public interface Metered extends Metric, Counting, Summing { +- /** +- * Returns the number of events which have been marked. +- * +- * @return the number of events which have been marked +- */ +- @Override +- long getCount(); ++ /** ++ * Returns the number of events which have been marked. ++ * ++ * @return the number of events which have been marked ++ */ ++ @Override ++ long getCount(); + +- /** +- * Returns the sum of events which have been marked. +- * +- * @return the sum of events which have been marked +- */ +- @Override +- long getSum(); ++ /** ++ * Returns the sum of events which have been marked. ++ * ++ * @return the sum of events which have been marked ++ */ ++ @Override ++ long getSum(); + +- /** +- * Returns the fifteen-minute moving average rate at which events have +- * occurred since the meter was created. +- * +- * @return the fifteen-minute moving average rate at which events have +- * occurred since the meter was created +- */ +- double getFifteenMinuteRate(); ++ /** ++ * Returns the fifteen-minute moving average rate at which events have occurred since the meter ++ * was created. ++ * ++ * @return the fifteen-minute moving average rate at which events have occurred since the meter ++ * was created ++ */ ++ double getFifteenMinuteRate(); + +- /** +- * Returns the five-minute moving average rate at which events have +- * occurred since the meter was created. +- * +- * @return the five-minute moving average rate at which events have +- * occurred since the meter was created +- */ +- double getFiveMinuteRate(); ++ /** ++ * Returns the five-minute moving average rate at which events have occurred since the meter was ++ * created. ++ * ++ * @return the five-minute moving average rate at which events have occurred since the meter was ++ * created ++ */ ++ double getFiveMinuteRate(); + +- /** +- * Returns the mean rate at which events have occurred since the meter was created. +- * +- * @return the mean rate at which events have occurred since the meter was created +- */ +- double getMeanRate(); ++ /** ++ * Returns the mean rate at which events have occurred since the meter was created. ++ * ++ * @return the mean rate at which events have occurred since the meter was created ++ */ ++ double getMeanRate(); + +- /** +- * Returns the one-minute moving average rate at which events have +- * occurred since the meter was created. +- * +- * @return the one-minute moving average rate at which events have +- * occurred since the meter was created +- */ +- double getOneMinuteRate(); ++ /** ++ * Returns the one-minute moving average rate at which events have occurred since the meter was ++ * created. ++ * ++ * @return the one-minute moving average rate at which events have occurred since the meter was ++ * created ++ */ ++ double getOneMinuteRate(); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Metric.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Metric.java +@@ -1,8 +1,4 @@ + package io.dropwizard.metrics5; + +-/** +- * A tag interface to indicate that a class is a metric. +- */ +-public interface Metric { +- +-} ++/** A tag interface to indicate that a class is a metric. */ ++public interface Metric {} +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricAttribute.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricAttribute.java +@@ -1,34 +1,31 @@ + package io.dropwizard.metrics5; + +-/** +- * Represents attributes of metrics which can be reported. +- */ ++/** Represents attributes of metrics which can be reported. */ + public enum MetricAttribute { ++ MAX("max"), ++ MEAN("mean"), ++ MIN("min"), ++ STDDEV("stddev"), ++ P50("p50"), ++ P75("p75"), ++ P95("p95"), ++ P98("p98"), ++ P99("p99"), ++ P999("p999"), ++ COUNT("count"), ++ SUM("sum"), ++ M1_RATE("m1_rate"), ++ M5_RATE("m5_rate"), ++ M15_RATE("m15_rate"), ++ MEAN_RATE("mean_rate"); + +- MAX("max"), +- MEAN("mean"), +- MIN("min"), +- STDDEV("stddev"), +- P50("p50"), +- P75("p75"), +- P95("p95"), +- P98("p98"), +- P99("p99"), +- P999("p999"), +- COUNT("count"), +- SUM("sum"), +- M1_RATE("m1_rate"), +- M5_RATE("m5_rate"), +- M15_RATE("m15_rate"), +- MEAN_RATE("mean_rate"); ++ private final String code; + +- private final String code; ++ MetricAttribute(String code) { ++ this.code = code; ++ } + +- MetricAttribute(String code) { +- this.code = code; +- } +- +- public String getCode() { +- return code; +- } ++ public String getCode() { ++ return code; ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricFilter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricFilter.java +@@ -1,32 +1,28 @@ + package io.dropwizard.metrics5; + +-/** +- * A filter used to determine whether or not a metric should be reported, among other things. +- */ ++/** A filter used to determine whether or not a metric should be reported, among other things. */ + public interface MetricFilter { +- /** +- * Matches all metrics, regardless of type or name. +- */ +- MetricFilter ALL = (name, metric) -> true; ++ /** Matches all metrics, regardless of type or name. */ ++ MetricFilter ALL = (name, metric) -> true; + +- static MetricFilter startsWith(String prefix) { +- return (name, metric) -> name.getKey().startsWith(prefix); +- } ++ static MetricFilter startsWith(String prefix) { ++ return (name, metric) -> name.getKey().startsWith(prefix); ++ } + +- static MetricFilter endsWith(String suffix) { +- return (name, metric) -> name.getKey().endsWith(suffix); +- } ++ static MetricFilter endsWith(String suffix) { ++ return (name, metric) -> name.getKey().endsWith(suffix); ++ } + +- static MetricFilter contains(String substring) { +- return (name, metric) -> name.getKey().contains(substring); +- } ++ static MetricFilter contains(String substring) { ++ return (name, metric) -> name.getKey().contains(substring); ++ } + +- /** +- * Returns {@code true} if the metric matches the filter; {@code false} otherwise. +- * +- * @param name the metric's name +- * @param metric the metric +- * @return {@code true} if the metric matches the filter +- */ +- boolean matches(MetricName name, Metric metric); ++ /** ++ * Returns {@code true} if the metric matches the filter; {@code false} otherwise. ++ * ++ * @param name the metric's name ++ * @param metric the metric ++ * @return {@code true} if the metric matches the filter ++ */ ++ boolean matches(MetricName name, Metric metric); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java +@@ -1,213 +1,212 @@ + package io.dropwizard.metrics5; + +-import java.util.Collections; +-import java.util.Comparator; ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Collections.unmodifiableMap; ++import static java.util.Map.Entry.comparingByKey; ++import static java.util.Objects.requireNonNull; ++import static java.util.stream.Collectors.joining; ++ ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableMap; ++import java.util.Arrays; + import java.util.HashMap; + import java.util.Iterator; + import java.util.LinkedHashMap; + import java.util.Map; + import java.util.Objects; +-import java.util.stream.Collectors; + import java.util.stream.Stream; + + /** +- * A metric name with the ability to include semantic tags. +- * This replaces the previous style where metric names where strictly dot-separated strings. ++ * A metric name with the ability to include semantic tags. This replaces the previous style where ++ * metric names where strictly dot-separated strings. + */ + public class MetricName implements Comparable { + +- private static final String SEPARATOR = "."; +- private static final Map EMPTY_TAGS = Collections.emptyMap(); +- static final MetricName EMPTY = new MetricName("", EMPTY_TAGS); +- +- /** +- * Returns an empty metric name. +- * +- * @return an empty metric name. +- */ +- public static MetricName empty() { +- return EMPTY; ++ private static final String SEPARATOR = "."; ++ private static final Map EMPTY_TAGS = ImmutableMap.of(); ++ static final MetricName EMPTY = new MetricName("", EMPTY_TAGS); ++ ++ /** ++ * Returns an empty metric name. ++ * ++ * @return an empty metric name. ++ */ ++ public static MetricName empty() { ++ return EMPTY; ++ } ++ ++ private final String key; ++ private final Map tags; ++ ++ public MetricName(String key, Map tags) { ++ this.key = requireNonNull(key); ++ this.tags = tags.isEmpty() ? EMPTY_TAGS : unmodifiableSortedCopy(tags); ++ } ++ ++ public String getKey() { ++ return key; ++ } ++ ++ /** ++ * Returns the tags, sorted by key. ++ * ++ * @return the tags (immutable), sorted by key. ++ */ ++ public Map getTags() { ++ return tags; ++ } ++ ++ /** ++ * Build the MetricName that is this with another path appended to it. The new MetricName inherits ++ * the tags of this one. ++ * ++ * @param parts The extra path elements to add to the new metric. ++ * @return A new metric name relative to the original by the path specified in parts. ++ */ ++ public MetricName resolve(String... parts) { ++ if (parts == null || parts.length == 0) { ++ return this; + } + +- private final String key; +- private final Map tags; +- +- public MetricName(String key, Map tags) { +- this.key = Objects.requireNonNull(key); +- this.tags = tags.isEmpty() ? EMPTY_TAGS : unmodifiableSortedCopy(tags); +- } +- +- public String getKey() { +- return key; +- } +- +- /** +- * Returns the tags, sorted by key. +- * +- * @return the tags (immutable), sorted by key. +- */ +- public Map getTags() { +- return tags; ++ String newKey = ++ Stream.concat(Stream.of(key), Arrays.stream(parts)) ++ .filter(s -> !Strings.isNullOrEmpty(s)) ++ .collect(joining(SEPARATOR)); ++ return new MetricName(newKey, tags); ++ } ++ ++ /** ++ * Add tags to a metric name and return the newly created MetricName. ++ * ++ * @param add Tags to add. ++ * @return A newly created metric name with the specified tags associated with it. ++ */ ++ public MetricName tagged(Map add) { ++ final Map newTags = new HashMap<>(); ++ newTags.putAll(tags); ++ newTags.putAll(add); ++ return new MetricName(key, newTags); ++ } ++ ++ /** ++ * Same as {@link #tagged(Map)}, but takes a variadic list of arguments. ++ * ++ * @param pairs An even list of strings acting as key-value pairs. ++ * @return A newly created metric name with the specified tags associated with it. ++ * @see #tagged(Map) ++ */ ++ public MetricName tagged(String... pairs) { ++ if (pairs == null || pairs.length == 0) { ++ return this; + } + +- /** +- * Build the MetricName that is this with another path appended to it. +- * The new MetricName inherits the tags of this one. +- * +- * @param parts The extra path elements to add to the new metric. +- * @return A new metric name relative to the original by the path specified +- * in parts. +- */ +- public MetricName resolve(String... parts) { +- if (parts == null || parts.length == 0) { +- return this; +- } +- +- String newKey = Stream.concat(Stream.of(key), Stream.of(parts)) +- .filter(s -> s != null && !s.isEmpty()) +- .collect(Collectors.joining(SEPARATOR)); +- return new MetricName(newKey, tags); +- } ++ checkArgument(pairs.length % 2 == 0, "Argument count must be even"); + +- /** +- * Add tags to a metric name and return the newly created MetricName. +- * +- * @param add Tags to add. +- * @return A newly created metric name with the specified tags associated with it. +- */ +- public MetricName tagged(Map add) { +- final Map newTags = new HashMap<>(); +- newTags.putAll(tags); +- newTags.putAll(add); +- return new MetricName(key, newTags); ++ final Map add = new HashMap<>(); ++ for (int i = 0; i < pairs.length; i += 2) { ++ add.put(pairs[i], pairs[i + 1]); + } + +- /** +- * Same as {@link #tagged(Map)}, but takes a variadic list of arguments. +- * +- * @param pairs An even list of strings acting as key-value pairs. +- * @return A newly created metric name with the specified tags associated with it. +- * @see #tagged(Map) +- */ +- public MetricName tagged(String... pairs) { +- if (pairs == null || pairs.length == 0) { +- return this; +- } +- +- if (pairs.length % 2 != 0) { +- throw new IllegalArgumentException("Argument count must be even"); +- } +- +- final Map add = new HashMap<>(); +- for (int i = 0; i < pairs.length; i += 2) { +- add.put(pairs[i], pairs[i + 1]); +- } +- +- return tagged(add); ++ return tagged(add); ++ } ++ ++ /** ++ * Build the MetricName that is this with another path and tags appended to it. ++ * ++ *

Semantically equivalent to:
++ * this.resolve(append.getKey()).tagged(append.getTags()); ++ * ++ * @param append The extra name element to add to the new metric. ++ * @return A new metric name with path appended to the original, and tags included from both ++ * names. ++ */ ++ public MetricName append(MetricName append) { ++ return resolve(append.key).tagged(append.tags); ++ } ++ ++ /** ++ * Build a new metric name using the specific path components. ++ * ++ *

Equivalent to:
++ * MetricName.empty().resolve(parts); ++ * ++ * @param parts Path of the new metric name. ++ * @return A newly created metric name with the specified path. ++ */ ++ public static MetricName build(String... parts) { ++ return EMPTY.resolve(parts); ++ } ++ ++ @Override ++ public String toString() { ++ return tags.isEmpty() ? key : key + tags; ++ } ++ ++ @Override ++ public boolean equals(Object o) { ++ if (this == o) { ++ return true; + } +- +- /** +- * Build the MetricName that is this with another path and tags appended to it. +- * +- *

+- * Semantically equivalent to:
+- * this.resolve(append.getKey()).tagged(append.getTags()); +- * +- * @param append The extra name element to add to the new metric. +- * @return A new metric name with path appended to the original, +- * and tags included from both names. +- */ +- public MetricName append(MetricName append) { +- return resolve(append.key).tagged(append.tags); ++ if (!(o instanceof MetricName)) { ++ return false; + } +- +- /** +- * Build a new metric name using the specific path components. +- * +- *

+- * Equivalent to:
+- * MetricName.empty().resolve(parts); +- * +- * @param parts Path of the new metric name. +- * @return A newly created metric name with the specified path. +- **/ +- public static MetricName build(String... parts) { +- return EMPTY.resolve(parts); ++ MetricName that = (MetricName) o; ++ return Objects.equals(key, that.key) && Objects.equals(tags, that.tags); ++ } ++ ++ @Override ++ public int hashCode() { ++ return Objects.hash(key, tags); ++ } ++ ++ @Override ++ public int compareTo(MetricName o) { ++ int c = key.compareTo(o.getKey()); ++ if (c != 0) { ++ return c; + } + +- @Override +- public String toString() { +- return tags.isEmpty() ? key : key + tags; ++ return compareTags(tags, o.getTags()); ++ } ++ ++ private int compareTags(Map left, Map right) { ++ Iterator> lit = left.entrySet().iterator(); ++ Iterator> rit = right.entrySet().iterator(); ++ ++ while (lit.hasNext() && rit.hasNext()) { ++ Map.Entry l = lit.next(); ++ Map.Entry r = rit.next(); ++ int c = l.getKey().compareTo(r.getKey()); ++ if (c != 0) { ++ return c; ++ } ++ if (l.getValue() == null && r.getValue() == null) { ++ return 0; ++ } else if (l.getValue() == null) { ++ return -1; ++ } else if (r.getValue() == null) { ++ return 1; ++ } else { ++ c = l.getValue().compareTo(r.getValue()); ++ } ++ if (c != 0) { ++ return c; ++ } + } +- +- @Override +- public boolean equals(Object o) { +- if (this == o) { +- return true; +- } +- if (!(o instanceof MetricName)) { +- return false; +- } +- MetricName that = (MetricName) o; +- return Objects.equals(key, that.key) && +- Objects.equals(tags, that.tags); ++ if (lit.hasNext()) { ++ return 1; ++ } else if (rit.hasNext()) { ++ return -1; ++ } else { ++ return 0; + } +- +- @Override +- public int hashCode() { +- return Objects.hash(key, tags); +- } +- +- @Override +- public int compareTo(MetricName o) { +- int c = key.compareTo(o.getKey()); +- if (c != 0) { +- return c; +- } +- +- return compareTags(tags, o.getTags()); +- } +- +- private int compareTags(Map left, Map right) { +- Iterator> lit = left.entrySet().iterator(); +- Iterator> rit = right.entrySet().iterator(); +- +- while (lit.hasNext() && rit.hasNext()) { +- Map.Entry l = lit.next(); +- Map.Entry r = rit.next(); +- int c = l.getKey().compareTo(r.getKey()); +- if (c != 0) { +- return c; +- } +- if (l.getValue() == null && r.getValue() == null) { +- return 0; +- } else if (l.getValue() == null) { +- return -1; +- } else if (r.getValue() == null) { +- return 1; +- } else { +- c = l.getValue().compareTo(r.getValue()); +- } +- if (c != 0) { +- return c; +- } +- } +- if (lit.hasNext()) { +- return 1; +- } else if (rit.hasNext()) { +- return -1; +- } else { +- return 0; +- } +- } +- +- private static , V> Map unmodifiableSortedCopy(Map map) { +- LinkedHashMap sorted = new LinkedHashMap<>(); +- map.entrySet() +- .stream() +- .sorted(Comparator.comparing(Map.Entry::getKey)) +- .forEach(e -> sorted.put(e.getKey(), e.getValue())); +- return Collections.unmodifiableMap(sorted); +- } +- ++ } ++ ++ private static , V> Map unmodifiableSortedCopy(Map map) { ++ LinkedHashMap sorted = new LinkedHashMap<>(); ++ map.entrySet().stream() ++ .sorted(comparingByKey()) ++ .forEach(e -> sorted.put(e.getKey(), e.getValue())); ++ return unmodifiableMap(sorted); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java +@@ -1,6 +1,10 @@ + package io.dropwizard.metrics5; + +-import java.util.Collections; ++import static java.util.Collections.unmodifiableMap; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; ++import static java.util.Objects.requireNonNull; ++ + import java.util.List; + import java.util.Map; + import java.util.SortedMap; +@@ -11,701 +15,698 @@ import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; + import java.util.concurrent.CopyOnWriteArrayList; + +-/** +- * A registry of metric instances. +- */ ++/** A registry of metric instances. */ + public class MetricRegistry implements MetricSet { + +- /** +- * Concatenates elements to form a dotted name, eliding any null values or empty strings. +- * +- * @param name the first element of the name +- * @param names the remaining elements of the name +- * @return {@code name} and {@code names} concatenated by periods +- */ +- public static MetricName name(String name, String... names) { +- if (names == null) { +- return MetricName.build(name); +- } +- +- final String[] parts = new String[names.length + 1]; +- parts[0] = name; +- System.arraycopy(names, 0, parts, 1, names.length); +- return MetricName.build(parts); +- } +- +- /** +- * Concatenates a class name and elements to form a dotted name, eliding any null values or +- * empty strings. +- * +- * @param klass the first element of the name +- * @param names the remaining elements of the name +- * @return {@code klass} and {@code names} concatenated by periods +- */ +- public static MetricName name(Class klass, String... names) { +- return name(klass.getName(), names); +- } +- +- private final ConcurrentMap metrics; +- private final List listeners; +- +- /** +- * Creates a new {@link MetricRegistry}. +- */ +- public MetricRegistry() { +- this.metrics = buildMap(); +- this.listeners = new CopyOnWriteArrayList<>(); +- } +- +- /** +- * Creates a new {@link ConcurrentMap} implementation for use inside the registry. Override this +- * to create a {@link MetricRegistry} with space- or time-bounded metric lifecycles, for +- * example. +- * +- * @return a new {@link ConcurrentMap} +- */ +- protected ConcurrentMap buildMap() { +- return new ConcurrentHashMap<>(); +- } +- +- /** +- * See {@link #registerGauge(MetricName, Gauge)} +- */ +- public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { +- return register(MetricName.build(name), metric); +- } +- +- /** +- * Given a {@link Gauge}, registers it under the given name and returns it +- * +- * @param name the name of the gauge +- * @param the type of the gauge's value +- * @return the registered {@link Gauge} +- * @since 4.2.10 +- */ +- public Gauge registerGauge(MetricName name, Gauge metric) throws IllegalArgumentException { +- return register(name, metric); +- } +- +- /** +- * Given a {@link Metric}, registers it under the given name. +- * +- * @param name the name of the metric +- * @param metric the metric +- * @param the type of the metric +- * @return {@code metric} +- * @throws IllegalArgumentException if the name is already registered or metric variable is null +- */ +- public T register(MetricName name, T metric) throws IllegalArgumentException { +- if (metric == null) { +- throw new NullPointerException("metric == null"); +- } +- +- if (metric instanceof MetricRegistry) { +- final MetricRegistry childRegistry = (MetricRegistry) metric; +- final MetricName childName = name; +- childRegistry.addListener(new MetricRegistryListener() { +- @Override +- public void onGaugeAdded(MetricName name, Gauge gauge) { +- register(childName.append(name), gauge); +- } +- +- @Override +- public void onGaugeRemoved(MetricName name) { +- remove(childName.append(name)); +- } +- +- @Override +- public void onCounterAdded(MetricName name, Counter counter) { +- register(childName.append(name), counter); +- } +- +- @Override +- public void onCounterRemoved(MetricName name) { +- remove(childName.append(name)); +- } +- +- @Override +- public void onHistogramAdded(MetricName name, Histogram histogram) { +- register(childName.append(name), histogram); +- } +- +- @Override +- public void onHistogramRemoved(MetricName name) { +- remove(childName.append(name)); +- } +- +- @Override +- public void onMeterAdded(MetricName name, Meter meter) { +- register(childName.append(name), meter); +- } +- +- @Override +- public void onMeterRemoved(MetricName name) { +- remove(childName.append(name)); +- } +- +- @Override +- public void onTimerAdded(MetricName name, Timer timer) { +- register(childName.append(name), timer); +- } +- +- @Override +- public void onTimerRemoved(MetricName name) { +- remove(childName.append(name)); +- } +- }); +- } else if (metric instanceof MetricSet) { +- registerAll(name, (MetricSet) metric); +- } else { +- final Metric existing = metrics.putIfAbsent(name, metric); +- if (existing == null) { +- onMetricAdded(name, metric); +- } else { +- throw new IllegalArgumentException("A metric named " + name + " already exists"); +- } +- } +- return metric; +- } +- +- /** +- * Given a metric set, registers them. +- * +- * @param metrics a set of metrics +- * @throws IllegalArgumentException if any of the names are already registered +- */ +- public void registerAll(MetricSet metrics) throws IllegalArgumentException { +- registerAll(null, metrics); +- } +- +- /** +- * See {@link #counter(MetricName)} +- */ +- public Counter counter(String name) { +- return getOrAdd(MetricName.build(name), MetricBuilder.COUNTERS); +- } +- +- /** +- * Return the {@link Counter} registered under this name; or create and register +- * a new {@link Counter} if none is registered. +- * +- * @param name the name of the metric +- * @return a new or pre-existing {@link Counter} +- */ +- public Counter counter(MetricName name) { +- return getOrAdd(name, MetricBuilder.COUNTERS); +- } +- +- /** +- * See {@link #histogram(MetricName)} +- */ +- public Histogram histogram(String name) { +- return getOrAdd(MetricName.build(name), MetricBuilder.HISTOGRAMS); +- } +- +- /** +- * Return the {@link Counter} registered under this name; or create and register +- * a new {@link Counter} using the provided MetricSupplier if none is registered. +- * +- * @param name the name of the metric +- * @param supplier a MetricSupplier that can be used to manufacture a counter. +- * @return a new or pre-existing {@link Counter} +- */ +- public T counter(MetricName name, final MetricSupplier supplier) { +- return getOrAdd(name, new MetricBuilder() { ++ /** ++ * Concatenates elements to form a dotted name, eliding any null values or empty strings. ++ * ++ * @param name the first element of the name ++ * @param names the remaining elements of the name ++ * @return {@code name} and {@code names} concatenated by periods ++ */ ++ public static MetricName name(String name, String... names) { ++ if (names == null) { ++ return MetricName.build(name); ++ } ++ ++ final String[] parts = new String[names.length + 1]; ++ parts[0] = name; ++ System.arraycopy(names, 0, parts, 1, names.length); ++ return MetricName.build(parts); ++ } ++ ++ /** ++ * Concatenates a class name and elements to form a dotted name, eliding any null values or empty ++ * strings. ++ * ++ * @param klass the first element of the name ++ * @param names the remaining elements of the name ++ * @return {@code klass} and {@code names} concatenated by periods ++ */ ++ public static MetricName name(Class klass, String... names) { ++ return name(klass.getName(), names); ++ } ++ ++ private final ConcurrentMap metrics; ++ private final List listeners; ++ ++ /** Creates a new {@link MetricRegistry}. */ ++ public MetricRegistry() { ++ this.metrics = buildMap(); ++ this.listeners = new CopyOnWriteArrayList<>(); ++ } ++ ++ /** ++ * Creates a new {@link ConcurrentMap} implementation for use inside the registry. Override this ++ * to create a {@link MetricRegistry} with space- or time-bounded metric lifecycles, for example. ++ * ++ * @return a new {@link ConcurrentMap} ++ */ ++ protected ConcurrentMap buildMap() { ++ return new ConcurrentHashMap<>(); ++ } ++ ++ /** See {@link #registerGauge(MetricName, Gauge)} */ ++ public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { ++ return register(MetricName.build(name), metric); ++ } ++ ++ /** ++ * Given a {@link Gauge}, registers it under the given name and returns it ++ * ++ * @param name the name of the gauge ++ * @param the type of the gauge's value ++ * @return the registered {@link Gauge} ++ * @since 4.2.10 ++ */ ++ public Gauge registerGauge(MetricName name, Gauge metric) ++ throws IllegalArgumentException { ++ return register(name, metric); ++ } ++ ++ /** ++ * Given a {@link Metric}, registers it under the given name. ++ * ++ * @param name the name of the metric ++ * @param metric the metric ++ * @param the type of the metric ++ * @return {@code metric} ++ * @throws IllegalArgumentException if the name is already registered or metric variable is null ++ */ ++ public T register(MetricName name, T metric) throws IllegalArgumentException { ++ requireNonNull(metric, "metric == null"); ++ ++ if (metric instanceof MetricRegistry) { ++ final MetricRegistry childRegistry = (MetricRegistry) metric; ++ final MetricName childName = name; ++ childRegistry.addListener( ++ new MetricRegistryListener() { + @Override +- public T newMetric() { +- return supplier.newMetric(); ++ public void onGaugeAdded(MetricName name, Gauge gauge) { ++ register(childName.append(name), gauge); + } + + @Override +- public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); ++ public void onGaugeRemoved(MetricName name) { ++ remove(childName.append(name)); + } +- }); +- } +- +- /** +- * Return the {@link Histogram} registered under this name; or create and register +- * a new {@link Histogram} if none is registered. +- * +- * @param name the name of the metric +- * @return a new or pre-existing {@link Histogram} +- */ +- public Histogram histogram(MetricName name) { +- return getOrAdd(name, MetricBuilder.HISTOGRAMS); +- } + +- /** +- * See {@link #meter(MetricName)} +- */ +- public Meter meter(String name) { +- return getOrAdd(MetricName.build(name), MetricBuilder.METERS); +- } +- +- /** +- * Return the {@link Histogram} registered under this name; or create and register +- * a new {@link Histogram} using the provided MetricSupplier if none is registered. +- * +- * @param name the name of the metric +- * @param supplier a MetricSupplier that can be used to manufacture a histogram +- * @return a new or pre-existing {@link Histogram} +- */ +- public Histogram histogram(MetricName name, final MetricSupplier supplier) { +- return getOrAdd(name, new MetricBuilder() { + @Override +- public Histogram newMetric() { +- return supplier.newMetric(); ++ public void onCounterAdded(MetricName name, Counter counter) { ++ register(childName.append(name), counter); + } + + @Override +- public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); ++ public void onCounterRemoved(MetricName name) { ++ remove(childName.append(name)); + } +- }); +- } + +- /** +- * Return the {@link Meter} registered under this name; or create and register +- * a new {@link Meter} if none is registered. +- * +- * @param name the name of the metric +- * @return a new or pre-existing {@link Meter} +- */ +- public Meter meter(MetricName name) { +- return getOrAdd(name, MetricBuilder.METERS); +- } +- +- /** +- * See {@link #timer(MetricName)} +- */ +- public Timer timer(String name) { +- return getOrAdd(MetricName.build(name), MetricBuilder.TIMERS); +- } +- +- /** +- * Return the {@link Meter} registered under this name; or create and register +- * a new {@link Meter} using the provided MetricSupplier if none is registered. +- * +- * @param name the name of the metric +- * @param supplier a MetricSupplier that can be used to manufacture a Meter +- * @return a new or pre-existing {@link Meter} +- */ +- public Meter meter(MetricName name, final MetricSupplier supplier) { +- return getOrAdd(name, new MetricBuilder() { + @Override +- public Meter newMetric() { +- return supplier.newMetric(); ++ public void onHistogramAdded(MetricName name, Histogram histogram) { ++ register(childName.append(name), histogram); + } + + @Override +- public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); ++ public void onHistogramRemoved(MetricName name) { ++ remove(childName.append(name)); + } +- }); +- } +- +- /** +- * Return the {@link Timer} registered under this name; or create and register +- * a new {@link Timer} if none is registered. +- * +- * @param name the name of the metric +- * @return a new or pre-existing {@link Timer} +- */ +- public Timer timer(MetricName name) { +- return getOrAdd(name, MetricBuilder.TIMERS); +- } + +- /** +- * Return the {@link Timer} registered under this name; or create and register +- * a new {@link Timer} using the provided MetricSupplier if none is registered. +- * +- * @param name the name of the metric +- * @param supplier a MetricSupplier that can be used to manufacture a Timer +- * @return a new or pre-existing {@link Timer} +- */ +- public Timer timer(MetricName name, final MetricSupplier supplier) { +- return getOrAdd(name, new MetricBuilder() { + @Override +- public Timer newMetric() { +- return supplier.newMetric(); ++ public void onMeterAdded(MetricName name, Meter meter) { ++ register(childName.append(name), meter); + } + + @Override +- public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); ++ public void onMeterRemoved(MetricName name) { ++ remove(childName.append(name)); + } +- }); +- } + +- /** +- * Return the {@link Gauge} registered under this name; or create and register +- * a new {@link SettableGauge} if none is registered. +- * +- * @param name the name of the metric +- * @return a pre-existing {@link Gauge} or a new {@link SettableGauge} +- * @since 4.2 +- */ +- @SuppressWarnings({"rawtypes", "unchecked"}) +- public T gauge(MetricName name) { +- return (T) getOrAdd(name, MetricBuilder.GAUGES); +- } +- +- /** +- * Return the {@link Gauge} registered under this name; or create and register +- * a new {@link Gauge} using the provided MetricSupplier if none is registered. +- * +- * @param name the name of the metric +- * @param supplier a MetricSupplier that can be used to manufacture a Gauge +- * @return a new or pre-existing {@link Gauge} +- */ +- @SuppressWarnings("rawtypes") +- public T gauge(MetricName name, final MetricSupplier supplier) { +- return getOrAdd(name, new MetricBuilder() { + @Override +- public T newMetric() { +- return supplier.newMetric(); ++ public void onTimerAdded(MetricName name, Timer timer) { ++ register(childName.append(name), timer); + } + + @Override +- public boolean isInstance(Metric metric) { +- return Gauge.class.isInstance(metric); ++ public void onTimerRemoved(MetricName name) { ++ remove(childName.append(name)); + } ++ }); ++ } else if (metric instanceof MetricSet) { ++ registerAll(name, (MetricSet) metric); ++ } else { ++ final Metric existing = metrics.putIfAbsent(name, metric); ++ if (existing == null) { ++ onMetricAdded(name, metric); ++ } else { ++ throw new IllegalArgumentException("A metric named " + name + " already exists"); ++ } ++ } ++ return metric; ++ } ++ ++ /** ++ * Given a metric set, registers them. ++ * ++ * @param metrics a set of metrics ++ * @throws IllegalArgumentException if any of the names are already registered ++ */ ++ public void registerAll(MetricSet metrics) throws IllegalArgumentException { ++ registerAll(null, metrics); ++ } ++ ++ /** See {@link #counter(MetricName)} */ ++ public Counter counter(String name) { ++ return getOrAdd(MetricName.build(name), MetricBuilder.COUNTERS); ++ } ++ ++ /** ++ * Return the {@link Counter} registered under this name; or create and register a new {@link ++ * Counter} if none is registered. ++ * ++ * @param name the name of the metric ++ * @return a new or pre-existing {@link Counter} ++ */ ++ public Counter counter(MetricName name) { ++ return getOrAdd(name, MetricBuilder.COUNTERS); ++ } ++ ++ /** See {@link #histogram(MetricName)} */ ++ public Histogram histogram(String name) { ++ return getOrAdd(MetricName.build(name), MetricBuilder.HISTOGRAMS); ++ } ++ ++ /** ++ * Return the {@link Counter} registered under this name; or create and register a new {@link ++ * Counter} using the provided MetricSupplier if none is registered. ++ * ++ * @param name the name of the metric ++ * @param supplier a MetricSupplier that can be used to manufacture a counter. ++ * @return a new or pre-existing {@link Counter} ++ */ ++ public T counter(MetricName name, final MetricSupplier supplier) { ++ return getOrAdd( ++ name, ++ new MetricBuilder() { ++ @Override ++ public T newMetric() { ++ return supplier.newMetric(); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Counter; ++ } + }); +- } +- +- +- /** +- * Removes the metric with the given name. +- * +- * @param name the name of the metric +- * @return whether or not the metric was removed +- */ +- public boolean remove(MetricName name) { +- final Metric metric = metrics.remove(name); +- if (metric != null) { +- onMetricRemoved(name, metric); +- return true; +- } +- return false; +- } +- +- /** +- * Removes all metrics which match the given filter. +- * +- * @param filter a filter +- */ +- public void removeMatching(MetricFilter filter) { +- for (Map.Entry entry : metrics.entrySet()) { +- if (filter.matches(entry.getKey(), entry.getValue())) { +- remove(entry.getKey()); +- } +- } +- } +- +- /** +- * Adds a {@link MetricRegistryListener} to a collection of listeners that will be notified on +- * metric creation. Listeners will be notified in the order in which they are added. +- *

+- * N.B.: The listener will be notified of all existing metrics when it first registers. +- * +- * @param listener the listener that will be notified +- */ +- public void addListener(MetricRegistryListener listener) { +- listeners.add(listener); +- +- for (Map.Entry entry : metrics.entrySet()) { +- notifyListenerOfAddedMetric(listener, entry.getValue(), entry.getKey()); +- } +- } +- +- /** +- * Removes a {@link MetricRegistryListener} from this registry's collection of listeners. +- * +- * @param listener the listener that will be removed +- */ +- public void removeListener(MetricRegistryListener listener) { +- listeners.remove(listener); +- } +- +- /** +- * Returns a set of the names of all the metrics in the registry. +- * +- * @return the names of all the metrics +- */ +- public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); +- } +- +- /** +- * Returns a map of all the gauges in the registry and their names. +- * +- * @return all the gauges in the registry +- */ +- public SortedMap> getGauges() { +- return getGauges(MetricFilter.ALL); +- } +- +- /** +- * Returns a map of all the gauges in the registry and their names which match the given filter. +- * +- * @param filter the metric filter to match +- * @return all the gauges in the registry +- */ +- public SortedMap> getGauges(MetricFilter filter) { +- final SortedMap> timers = new TreeMap<>(); +- for (Map.Entry entry : metrics.entrySet()) { +- if (entry.getValue() instanceof Gauge && filter.matches(entry.getKey(), +- entry.getValue())) { +- timers.put(entry.getKey(), (Gauge) entry.getValue()); +- } +- } +- return Collections.unmodifiableSortedMap(timers); +- } +- +- /** +- * Returns a map of all the counters in the registry and their names. +- * +- * @return all the counters in the registry +- */ +- public SortedMap getCounters() { +- return getCounters(MetricFilter.ALL); +- } +- +- /** +- * Returns a map of all the counters in the registry and their names which match the given +- * filter. +- * +- * @param filter the metric filter to match +- * @return all the counters in the registry +- */ +- public SortedMap getCounters(MetricFilter filter) { +- return getMetrics(Counter.class, filter); +- } +- +- /** +- * Returns a map of all the histograms in the registry and their names. +- * +- * @return all the histograms in the registry +- */ +- public SortedMap getHistograms() { +- return getHistograms(MetricFilter.ALL); +- } +- +- /** +- * Returns a map of all the histograms in the registry and their names which match the given +- * filter. +- * +- * @param filter the metric filter to match +- * @return all the histograms in the registry +- */ +- public SortedMap getHistograms(MetricFilter filter) { +- return getMetrics(Histogram.class, filter); +- } +- +- /** +- * Returns a map of all the meters in the registry and their names. +- * +- * @return all the meters in the registry +- */ +- public SortedMap getMeters() { +- return getMeters(MetricFilter.ALL); +- } +- +- /** +- * Returns a map of all the meters in the registry and their names which match the given filter. +- * +- * @param filter the metric filter to match +- * @return all the meters in the registry +- */ +- public SortedMap getMeters(MetricFilter filter) { +- return getMetrics(Meter.class, filter); +- } +- +- /** +- * Returns a map of all the timers in the registry and their names. +- * +- * @return all the timers in the registry +- */ +- public SortedMap getTimers() { +- return getTimers(MetricFilter.ALL); +- } +- +- /** +- * Returns a map of all the timers in the registry and their names which match the given filter. +- * +- * @param filter the metric filter to match +- * @return all the timers in the registry +- */ +- public SortedMap getTimers(MetricFilter filter) { +- return getMetrics(Timer.class, filter); +- } +- +- @SuppressWarnings("unchecked") +- private T getOrAdd(MetricName name, MetricBuilder builder) { +- final Metric metric = metrics.get(name); +- if (builder.isInstance(metric)) { +- return (T) metric; +- } else if (metric == null) { +- try { +- return register(name, builder.newMetric()); +- } catch (IllegalArgumentException e) { +- final Metric added = metrics.get(name); +- if (builder.isInstance(added)) { +- return (T) added; +- } +- } +- } +- throw new IllegalArgumentException(name + " is already used for a different type of metric"); +- } +- +- @SuppressWarnings("unchecked") +- private SortedMap getMetrics(Class klass, MetricFilter filter) { +- final SortedMap timers = new TreeMap<>(); +- for (Map.Entry entry : metrics.entrySet()) { +- if (klass.isInstance(entry.getValue()) && filter.matches(entry.getKey(), +- entry.getValue())) { +- timers.put(entry.getKey(), (T) entry.getValue()); +- } +- } +- return Collections.unmodifiableSortedMap(timers); +- } +- +- private void onMetricAdded(MetricName name, Metric metric) { +- for (MetricRegistryListener listener : listeners) { +- notifyListenerOfAddedMetric(listener, metric, name); +- } +- } +- +- private void notifyListenerOfAddedMetric(MetricRegistryListener listener, Metric metric, MetricName name) { +- if (metric instanceof Gauge) { +- listener.onGaugeAdded(name, (Gauge) metric); +- } else if (metric instanceof Counter) { +- listener.onCounterAdded(name, (Counter) metric); +- } else if (metric instanceof Histogram) { +- listener.onHistogramAdded(name, (Histogram) metric); +- } else if (metric instanceof Meter) { +- listener.onMeterAdded(name, (Meter) metric); +- } else if (metric instanceof Timer) { +- listener.onTimerAdded(name, (Timer) metric); +- } else { +- throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); +- } +- } +- +- private void onMetricRemoved(MetricName name, Metric metric) { +- for (MetricRegistryListener listener : listeners) { +- notifyListenerOfRemovedMetric(name, metric, listener); +- } +- } +- +- private void notifyListenerOfRemovedMetric(MetricName name, Metric metric, MetricRegistryListener listener) { +- if (metric instanceof Gauge) { +- listener.onGaugeRemoved(name); +- } else if (metric instanceof Counter) { +- listener.onCounterRemoved(name); +- } else if (metric instanceof Histogram) { +- listener.onHistogramRemoved(name); +- } else if (metric instanceof Meter) { +- listener.onMeterRemoved(name); +- } else if (metric instanceof Timer) { +- listener.onTimerRemoved(name); +- } else { +- throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); +- } +- } +- +- public void registerAll(MetricName prefix, MetricSet metrics) throws IllegalArgumentException { +- if (prefix == null) { +- prefix = MetricName.EMPTY; +- } +- +- for (Map.Entry entry : metrics.getMetrics().entrySet()) { +- if (entry.getValue() instanceof MetricSet) { +- registerAll(prefix.append(entry.getKey()), (MetricSet) entry.getValue()); +- } else { +- register(prefix.append(entry.getKey()), entry.getValue()); +- } ++ } ++ ++ /** ++ * Return the {@link Histogram} registered under this name; or create and register a new {@link ++ * Histogram} if none is registered. ++ * ++ * @param name the name of the metric ++ * @return a new or pre-existing {@link Histogram} ++ */ ++ public Histogram histogram(MetricName name) { ++ return getOrAdd(name, MetricBuilder.HISTOGRAMS); ++ } ++ ++ /** See {@link #meter(MetricName)} */ ++ public Meter meter(String name) { ++ return getOrAdd(MetricName.build(name), MetricBuilder.METERS); ++ } ++ ++ /** ++ * Return the {@link Histogram} registered under this name; or create and register a new {@link ++ * Histogram} using the provided MetricSupplier if none is registered. ++ * ++ * @param name the name of the metric ++ * @param supplier a MetricSupplier that can be used to manufacture a histogram ++ * @return a new or pre-existing {@link Histogram} ++ */ ++ public Histogram histogram(MetricName name, final MetricSupplier supplier) { ++ return getOrAdd( ++ name, ++ new MetricBuilder() { ++ @Override ++ public Histogram newMetric() { ++ return supplier.newMetric(); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Histogram; ++ } ++ }); ++ } ++ ++ /** ++ * Return the {@link Meter} registered under this name; or create and register a new {@link Meter} ++ * if none is registered. ++ * ++ * @param name the name of the metric ++ * @return a new or pre-existing {@link Meter} ++ */ ++ public Meter meter(MetricName name) { ++ return getOrAdd(name, MetricBuilder.METERS); ++ } ++ ++ /** See {@link #timer(MetricName)} */ ++ public Timer timer(String name) { ++ return getOrAdd(MetricName.build(name), MetricBuilder.TIMERS); ++ } ++ ++ /** ++ * Return the {@link Meter} registered under this name; or create and register a new {@link Meter} ++ * using the provided MetricSupplier if none is registered. ++ * ++ * @param name the name of the metric ++ * @param supplier a MetricSupplier that can be used to manufacture a Meter ++ * @return a new or pre-existing {@link Meter} ++ */ ++ public Meter meter(MetricName name, final MetricSupplier supplier) { ++ return getOrAdd( ++ name, ++ new MetricBuilder() { ++ @Override ++ public Meter newMetric() { ++ return supplier.newMetric(); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Meter; ++ } ++ }); ++ } ++ ++ /** ++ * Return the {@link Timer} registered under this name; or create and register a new {@link Timer} ++ * if none is registered. ++ * ++ * @param name the name of the metric ++ * @return a new or pre-existing {@link Timer} ++ */ ++ public Timer timer(MetricName name) { ++ return getOrAdd(name, MetricBuilder.TIMERS); ++ } ++ ++ /** ++ * Return the {@link Timer} registered under this name; or create and register a new {@link Timer} ++ * using the provided MetricSupplier if none is registered. ++ * ++ * @param name the name of the metric ++ * @param supplier a MetricSupplier that can be used to manufacture a Timer ++ * @return a new or pre-existing {@link Timer} ++ */ ++ public Timer timer(MetricName name, final MetricSupplier supplier) { ++ return getOrAdd( ++ name, ++ new MetricBuilder() { ++ @Override ++ public Timer newMetric() { ++ return supplier.newMetric(); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Timer; ++ } ++ }); ++ } ++ ++ /** ++ * Return the {@link Gauge} registered under this name; or create and register a new {@link ++ * SettableGauge} if none is registered. ++ * ++ * @param name the name of the metric ++ * @return a pre-existing {@link Gauge} or a new {@link SettableGauge} ++ * @since 4.2 ++ */ ++ @SuppressWarnings({"rawtypes", "unchecked"}) ++ public T gauge(MetricName name) { ++ return (T) getOrAdd(name, MetricBuilder.GAUGES); ++ } ++ ++ /** ++ * Return the {@link Gauge} registered under this name; or create and register a new {@link Gauge} ++ * using the provided MetricSupplier if none is registered. ++ * ++ * @param name the name of the metric ++ * @param supplier a MetricSupplier that can be used to manufacture a Gauge ++ * @return a new or pre-existing {@link Gauge} ++ */ ++ @SuppressWarnings("rawtypes") ++ public T gauge(MetricName name, final MetricSupplier supplier) { ++ return getOrAdd( ++ name, ++ new MetricBuilder() { ++ @Override ++ public T newMetric() { ++ return supplier.newMetric(); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Gauge; ++ } ++ }); ++ } ++ ++ /** ++ * Removes the metric with the given name. ++ * ++ * @param name the name of the metric ++ * @return whether or not the metric was removed ++ */ ++ public boolean remove(MetricName name) { ++ final Metric metric = metrics.remove(name); ++ if (metric != null) { ++ onMetricRemoved(name, metric); ++ return true; ++ } ++ return false; ++ } ++ ++ /** ++ * Removes all metrics which match the given filter. ++ * ++ * @param filter a filter ++ */ ++ public void removeMatching(MetricFilter filter) { ++ for (Map.Entry entry : metrics.entrySet()) { ++ if (filter.matches(entry.getKey(), entry.getValue())) { ++ remove(entry.getKey()); ++ } ++ } ++ } ++ ++ /** ++ * Adds a {@link MetricRegistryListener} to a collection of listeners that will be notified on ++ * metric creation. Listeners will be notified in the order in which they are added. ++ * ++ *

N.B.: The listener will be notified of all existing metrics when it first registers. ++ * ++ * @param listener the listener that will be notified ++ */ ++ public void addListener(MetricRegistryListener listener) { ++ listeners.add(listener); ++ ++ for (Map.Entry entry : metrics.entrySet()) { ++ notifyListenerOfAddedMetric(listener, entry.getValue(), entry.getKey()); ++ } ++ } ++ ++ /** ++ * Removes a {@link MetricRegistryListener} from this registry's collection of listeners. ++ * ++ * @param listener the listener that will be removed ++ */ ++ public void removeListener(MetricRegistryListener listener) { ++ listeners.remove(listener); ++ } ++ ++ /** ++ * Returns a set of the names of all the metrics in the registry. ++ * ++ * @return the names of all the metrics ++ */ ++ public SortedSet getNames() { ++ return unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); ++ } ++ ++ /** ++ * Returns a map of all the gauges in the registry and their names. ++ * ++ * @return all the gauges in the registry ++ */ ++ public SortedMap> getGauges() { ++ return getGauges(MetricFilter.ALL); ++ } ++ ++ /** ++ * Returns a map of all the gauges in the registry and their names which match the given filter. ++ * ++ * @param filter the metric filter to match ++ * @return all the gauges in the registry ++ */ ++ public SortedMap> getGauges(MetricFilter filter) { ++ final SortedMap> timers = new TreeMap<>(); ++ for (Map.Entry entry : metrics.entrySet()) { ++ if (entry.getValue() instanceof Gauge && filter.matches(entry.getKey(), entry.getValue())) { ++ timers.put(entry.getKey(), (Gauge) entry.getValue()); ++ } ++ } ++ return unmodifiableSortedMap(timers); ++ } ++ ++ /** ++ * Returns a map of all the counters in the registry and their names. ++ * ++ * @return all the counters in the registry ++ */ ++ public SortedMap getCounters() { ++ return getCounters(MetricFilter.ALL); ++ } ++ ++ /** ++ * Returns a map of all the counters in the registry and their names which match the given filter. ++ * ++ * @param filter the metric filter to match ++ * @return all the counters in the registry ++ */ ++ public SortedMap getCounters(MetricFilter filter) { ++ return getMetrics(Counter.class, filter); ++ } ++ ++ /** ++ * Returns a map of all the histograms in the registry and their names. ++ * ++ * @return all the histograms in the registry ++ */ ++ public SortedMap getHistograms() { ++ return getHistograms(MetricFilter.ALL); ++ } ++ ++ /** ++ * Returns a map of all the histograms in the registry and their names which match the given ++ * filter. ++ * ++ * @param filter the metric filter to match ++ * @return all the histograms in the registry ++ */ ++ public SortedMap getHistograms(MetricFilter filter) { ++ return getMetrics(Histogram.class, filter); ++ } ++ ++ /** ++ * Returns a map of all the meters in the registry and their names. ++ * ++ * @return all the meters in the registry ++ */ ++ public SortedMap getMeters() { ++ return getMeters(MetricFilter.ALL); ++ } ++ ++ /** ++ * Returns a map of all the meters in the registry and their names which match the given filter. ++ * ++ * @param filter the metric filter to match ++ * @return all the meters in the registry ++ */ ++ public SortedMap getMeters(MetricFilter filter) { ++ return getMetrics(Meter.class, filter); ++ } ++ ++ /** ++ * Returns a map of all the timers in the registry and their names. ++ * ++ * @return all the timers in the registry ++ */ ++ public SortedMap getTimers() { ++ return getTimers(MetricFilter.ALL); ++ } ++ ++ /** ++ * Returns a map of all the timers in the registry and their names which match the given filter. ++ * ++ * @param filter the metric filter to match ++ * @return all the timers in the registry ++ */ ++ public SortedMap getTimers(MetricFilter filter) { ++ return getMetrics(Timer.class, filter); ++ } ++ ++ @SuppressWarnings("unchecked") ++ private T getOrAdd(MetricName name, MetricBuilder builder) { ++ final Metric metric = metrics.get(name); ++ if (builder.isInstance(metric)) { ++ return (T) metric; ++ } else if (metric == null) { ++ try { ++ return register(name, builder.newMetric()); ++ } catch (IllegalArgumentException e) { ++ final Metric added = metrics.get(name); ++ if (builder.isInstance(added)) { ++ return (T) added; + } +- } +- +- @Override +- public Map getMetrics() { +- return Collections.unmodifiableMap(metrics); +- } +- +- @FunctionalInterface +- public interface MetricSupplier { +- T newMetric(); +- } +- +- /** +- * A quick and easy way of capturing the notion of default metrics. +- */ +- private interface MetricBuilder { +- MetricBuilder COUNTERS = new MetricBuilder() { +- @Override +- public Counter newMetric() { +- return new Counter(); +- } +- +- @Override +- public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); +- } ++ } ++ } ++ throw new IllegalArgumentException(name + " is already used for a different type of metric"); ++ } ++ ++ @SuppressWarnings("unchecked") ++ private SortedMap getMetrics( ++ Class klass, MetricFilter filter) { ++ final SortedMap timers = new TreeMap<>(); ++ for (Map.Entry entry : metrics.entrySet()) { ++ if (klass.isInstance(entry.getValue()) && filter.matches(entry.getKey(), entry.getValue())) { ++ timers.put(entry.getKey(), (T) entry.getValue()); ++ } ++ } ++ return unmodifiableSortedMap(timers); ++ } ++ ++ private void onMetricAdded(MetricName name, Metric metric) { ++ for (MetricRegistryListener listener : listeners) { ++ notifyListenerOfAddedMetric(listener, metric, name); ++ } ++ } ++ ++ private void notifyListenerOfAddedMetric( ++ MetricRegistryListener listener, Metric metric, MetricName name) { ++ if (metric instanceof Gauge) { ++ listener.onGaugeAdded(name, (Gauge) metric); ++ } else if (metric instanceof Counter) { ++ listener.onCounterAdded(name, (Counter) metric); ++ } else if (metric instanceof Histogram) { ++ listener.onHistogramAdded(name, (Histogram) metric); ++ } else if (metric instanceof Meter) { ++ listener.onMeterAdded(name, (Meter) metric); ++ } else if (metric instanceof Timer) { ++ listener.onTimerAdded(name, (Timer) metric); ++ } else { ++ throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); ++ } ++ } ++ ++ private void onMetricRemoved(MetricName name, Metric metric) { ++ for (MetricRegistryListener listener : listeners) { ++ notifyListenerOfRemovedMetric(name, metric, listener); ++ } ++ } ++ ++ private void notifyListenerOfRemovedMetric( ++ MetricName name, Metric metric, MetricRegistryListener listener) { ++ if (metric instanceof Gauge) { ++ listener.onGaugeRemoved(name); ++ } else if (metric instanceof Counter) { ++ listener.onCounterRemoved(name); ++ } else if (metric instanceof Histogram) { ++ listener.onHistogramRemoved(name); ++ } else if (metric instanceof Meter) { ++ listener.onMeterRemoved(name); ++ } else if (metric instanceof Timer) { ++ listener.onTimerRemoved(name); ++ } else { ++ throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); ++ } ++ } ++ ++ public void registerAll(MetricName prefix, MetricSet metrics) throws IllegalArgumentException { ++ if (prefix == null) { ++ prefix = MetricName.EMPTY; ++ } ++ ++ for (Map.Entry entry : metrics.getMetrics().entrySet()) { ++ if (entry.getValue() instanceof MetricSet) { ++ registerAll(prefix.append(entry.getKey()), (MetricSet) entry.getValue()); ++ } else { ++ register(prefix.append(entry.getKey()), entry.getValue()); ++ } ++ } ++ } ++ ++ @Override ++ public Map getMetrics() { ++ return unmodifiableMap(metrics); ++ } ++ ++ @FunctionalInterface ++ public interface MetricSupplier { ++ T newMetric(); ++ } ++ ++ /** A quick and easy way of capturing the notion of default metrics. */ ++ private interface MetricBuilder { ++ MetricBuilder COUNTERS = ++ new MetricBuilder() { ++ @Override ++ public Counter newMetric() { ++ return new Counter(); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Counter; ++ } + }; + +- MetricBuilder HISTOGRAMS = new MetricBuilder() { +- @Override +- public Histogram newMetric() { +- return new Histogram(new ExponentiallyDecayingReservoir()); +- } +- +- @Override +- public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); +- } ++ MetricBuilder HISTOGRAMS = ++ new MetricBuilder() { ++ @Override ++ public Histogram newMetric() { ++ return new Histogram(new ExponentiallyDecayingReservoir()); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Histogram; ++ } + }; + +- MetricBuilder METERS = new MetricBuilder() { +- @Override +- public Meter newMetric() { +- return new Meter(); +- } +- +- @Override +- public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); +- } ++ MetricBuilder METERS = ++ new MetricBuilder() { ++ @Override ++ public Meter newMetric() { ++ return new Meter(); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Meter; ++ } + }; + +- MetricBuilder TIMERS = new MetricBuilder() { +- @Override +- public Timer newMetric() { +- return new Timer(); +- } +- +- @Override +- public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); +- } ++ MetricBuilder TIMERS = ++ new MetricBuilder() { ++ @Override ++ public Timer newMetric() { ++ return new Timer(); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Timer; ++ } + }; + +- @SuppressWarnings("rawtypes") +- MetricBuilder GAUGES = new MetricBuilder() { +- @Override +- public Gauge newMetric() { +- return new DefaultSettableGauge<>(); +- } +- +- @Override +- public boolean isInstance(Metric metric) { +- return Gauge.class.isInstance(metric); +- } ++ @SuppressWarnings("rawtypes") ++ MetricBuilder GAUGES = ++ new MetricBuilder() { ++ @Override ++ public Gauge newMetric() { ++ return new DefaultSettableGauge<>(); ++ } ++ ++ @Override ++ public boolean isInstance(Metric metric) { ++ return metric instanceof Gauge; ++ } + }; + +- T newMetric(); ++ T newMetric(); + +- boolean isInstance(Metric metric); +- } ++ boolean isInstance(Metric metric); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistryListener.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistryListener.java +@@ -2,127 +2,113 @@ package io.dropwizard.metrics5; + + import java.util.EventListener; + +-/** +- * Listeners for events from the registry. Listeners must be thread-safe. +- */ ++/** Listeners for events from the registry. Listeners must be thread-safe. */ + public interface MetricRegistryListener extends EventListener { +- /** +- * A no-op implementation of {@link MetricRegistryListener}. +- */ +- abstract class Base implements MetricRegistryListener { +- @Override +- public void onGaugeAdded(MetricName name, Gauge gauge) { +- } +- +- @Override +- public void onGaugeRemoved(MetricName name) { +- } +- +- @Override +- public void onCounterAdded(MetricName name, Counter counter) { +- } +- +- @Override +- public void onCounterRemoved(MetricName name) { +- } +- +- @Override +- public void onHistogramAdded(MetricName name, Histogram histogram) { +- } +- +- @Override +- public void onHistogramRemoved(MetricName name) { +- } +- +- @Override +- public void onMeterAdded(MetricName name, Meter meter) { +- } +- +- @Override +- public void onMeterRemoved(MetricName name) { +- } +- +- @Override +- public void onTimerAdded(MetricName name, Timer timer) { +- } +- +- @Override +- public void onTimerRemoved(MetricName name) { +- } +- } +- +- /** +- * Called when a {@link Gauge} is added to the registry. +- * +- * @param name the gauge's name +- * @param gauge the gauge +- */ +- void onGaugeAdded(MetricName name, Gauge gauge); +- +- /** +- * Called when a {@link Gauge} is removed from the registry. +- * +- * @param name the gauge's name +- */ +- void onGaugeRemoved(MetricName name); +- +- /** +- * Called when a {@link Counter} is added to the registry. +- * +- * @param name the counter's name +- * @param counter the counter +- */ +- void onCounterAdded(MetricName name, Counter counter); +- +- /** +- * Called when a {@link Counter} is removed from the registry. +- * +- * @param name the counter's name +- */ +- void onCounterRemoved(MetricName name); +- +- /** +- * Called when a {@link Histogram} is added to the registry. +- * +- * @param name the histogram's name +- * @param histogram the histogram +- */ +- void onHistogramAdded(MetricName name, Histogram histogram); +- +- /** +- * Called when a {@link Histogram} is removed from the registry. +- * +- * @param name the histogram's name +- */ +- void onHistogramRemoved(MetricName name); +- +- /** +- * Called when a {@link Meter} is added to the registry. +- * +- * @param name the meter's name +- * @param meter the meter +- */ +- void onMeterAdded(MetricName name, Meter meter); +- +- /** +- * Called when a {@link Meter} is removed from the registry. +- * +- * @param name the meter's name +- */ +- void onMeterRemoved(MetricName name); +- +- /** +- * Called when a {@link Timer} is added to the registry. +- * +- * @param name the timer's name +- * @param timer the timer +- */ +- void onTimerAdded(MetricName name, Timer timer); +- +- /** +- * Called when a {@link Timer} is removed from the registry. +- * +- * @param name the timer's name +- */ +- void onTimerRemoved(MetricName name); ++ /** A no-op implementation of {@link MetricRegistryListener}. */ ++ abstract class Base implements MetricRegistryListener { ++ @Override ++ public void onGaugeAdded(MetricName name, Gauge gauge) {} ++ ++ @Override ++ public void onGaugeRemoved(MetricName name) {} ++ ++ @Override ++ public void onCounterAdded(MetricName name, Counter counter) {} ++ ++ @Override ++ public void onCounterRemoved(MetricName name) {} ++ ++ @Override ++ public void onHistogramAdded(MetricName name, Histogram histogram) {} ++ ++ @Override ++ public void onHistogramRemoved(MetricName name) {} ++ ++ @Override ++ public void onMeterAdded(MetricName name, Meter meter) {} ++ ++ @Override ++ public void onMeterRemoved(MetricName name) {} ++ ++ @Override ++ public void onTimerAdded(MetricName name, Timer timer) {} ++ ++ @Override ++ public void onTimerRemoved(MetricName name) {} ++ } ++ ++ /** ++ * Called when a {@link Gauge} is added to the registry. ++ * ++ * @param name the gauge's name ++ * @param gauge the gauge ++ */ ++ void onGaugeAdded(MetricName name, Gauge gauge); ++ ++ /** ++ * Called when a {@link Gauge} is removed from the registry. ++ * ++ * @param name the gauge's name ++ */ ++ void onGaugeRemoved(MetricName name); ++ ++ /** ++ * Called when a {@link Counter} is added to the registry. ++ * ++ * @param name the counter's name ++ * @param counter the counter ++ */ ++ void onCounterAdded(MetricName name, Counter counter); ++ ++ /** ++ * Called when a {@link Counter} is removed from the registry. ++ * ++ * @param name the counter's name ++ */ ++ void onCounterRemoved(MetricName name); ++ ++ /** ++ * Called when a {@link Histogram} is added to the registry. ++ * ++ * @param name the histogram's name ++ * @param histogram the histogram ++ */ ++ void onHistogramAdded(MetricName name, Histogram histogram); ++ ++ /** ++ * Called when a {@link Histogram} is removed from the registry. ++ * ++ * @param name the histogram's name ++ */ ++ void onHistogramRemoved(MetricName name); ++ ++ /** ++ * Called when a {@link Meter} is added to the registry. ++ * ++ * @param name the meter's name ++ * @param meter the meter ++ */ ++ void onMeterAdded(MetricName name, Meter meter); ++ ++ /** ++ * Called when a {@link Meter} is removed from the registry. ++ * ++ * @param name the meter's name ++ */ ++ void onMeterRemoved(MetricName name); ++ ++ /** ++ * Called when a {@link Timer} is added to the registry. ++ * ++ * @param name the timer's name ++ * @param timer the timer ++ */ ++ void onTimerAdded(MetricName name, Timer timer); ++ ++ /** ++ * Called when a {@link Timer} is removed from the registry. ++ * ++ * @param name the timer's name ++ */ ++ void onTimerRemoved(MetricName name); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricSet.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricSet.java +@@ -8,10 +8,10 @@ import java.util.Map; + * @see MetricRegistry#registerAll(MetricSet) + */ + public interface MetricSet extends Metric { +- /** +- * A map of metric names to metrics. +- * +- * @return the metrics +- */ +- Map getMetrics(); ++ /** ++ * A map of metric names to metrics. ++ * ++ * @return the metrics ++ */ ++ Map getMetrics(); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MovingAverages.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MovingAverages.java +@@ -1,50 +1,52 @@ + package io.dropwizard.metrics5; + + /** +- * A triple of moving averages (one-, five-, and fifteen-minute +- * moving average) as needed by {@link Meter}. +- *

+- * Included implementations are: ++ * A triple of moving averages (one-, five-, and fifteen-minute moving average) as needed by {@link ++ * Meter}. ++ * ++ *

Included implementations are: ++ * + *

    +- *
  • {@link ExponentialMovingAverages} exponential decaying average similar to the {@code top} Unix command. +- *
  • {@link SlidingTimeWindowMovingAverages} simple (unweighted) moving average ++ *
  • {@link ExponentialMovingAverages} exponential decaying average similar to the {@code top} ++ * Unix command. ++ *
  • {@link SlidingTimeWindowMovingAverages} simple (unweighted) moving average + *
+ */ + public interface MovingAverages { + +- /** +- * Tick the internal clock of the MovingAverages implementation if needed +- * (according to the internal ticking interval) +- */ +- void tickIfNecessary(); ++ /** ++ * Tick the internal clock of the MovingAverages implementation if needed (according to the ++ * internal ticking interval) ++ */ ++ void tickIfNecessary(); + +- /** +- * Update all three moving averages with n events having occurred since the last update. +- * +- * @param n +- */ +- void update(long n); ++ /** ++ * Update all three moving averages with n events having occurred since the last update. ++ * ++ * @param n ++ */ ++ void update(long n); + +- /** +- * Returns the one-minute moving average rate +- * +- * @return the one-minute moving average rate +- */ +- double getM1Rate(); ++ /** ++ * Returns the one-minute moving average rate ++ * ++ * @return the one-minute moving average rate ++ */ ++ double getM1Rate(); + +- /** +- * Returns the five-minute moving average rate +- * +- * @return the five-minute moving average rate +- */ +- double getM5Rate(); ++ /** ++ * Returns the five-minute moving average rate ++ * ++ * @return the five-minute moving average rate ++ */ ++ double getM5Rate(); + +- /** +- * Returns the fifteen-minute moving average rate +- * +- * @return the fifteen-minute moving average rate +- */ +- double getM15Rate(); ++ /** ++ * Returns the fifteen-minute moving average rate ++ * ++ * @return the fifteen-minute moving average rate ++ */ ++ double getM15Rate(); + +- long getSum(); ++ long getSum(); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java +@@ -1,9 +1,14 @@ + package io.dropwizard.metrics5; + ++import static java.util.Collections.emptySortedMap; ++import static java.util.Collections.emptySortedSet; ++import static java.util.Objects.requireNonNull; ++ ++import com.google.common.collect.ImmutableMap; ++import com.google.common.collect.ImmutableSet; + import java.io.OutputStream; + import java.time.Duration; + import java.util.Collection; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -13,817 +18,634 @@ import java.util.concurrent.ConcurrentMap; + import java.util.concurrent.TimeUnit; + import java.util.function.Supplier; + +-import static java.util.Objects.requireNonNull; +- + /** +- * A registry of metric instances which never creates or registers any metrics and returns no-op implementations of any metric type. ++ * A registry of metric instances which never creates or registers any metrics and returns no-op ++ * implementations of any metric type. + * + * @since 4.1.17 + */ + public final class NoopMetricRegistry extends MetricRegistry { +- private static final EmptyConcurrentMap EMPTY_CONCURRENT_MAP = new EmptyConcurrentMap<>(); ++ private static final EmptyConcurrentMap EMPTY_CONCURRENT_MAP = ++ new EmptyConcurrentMap<>(); ++ ++ /** ++ * {@inheritDoc} ++ * ++ * @return ++ */ ++ @Override ++ protected ConcurrentMap buildMap() { ++ return EMPTY_CONCURRENT_MAP; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void registerAll(MetricSet metrics) throws IllegalArgumentException { ++ // NOP ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Counter counter(String name) { ++ return NoopCounter.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Counter counter(MetricName name) { ++ return NoopCounter.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ @SuppressWarnings("unchecked") ++ public T counter(MetricName name, final MetricSupplier supplier) { ++ return (T) NoopCounter.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Histogram histogram(String name) { ++ return NoopHistogram.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Histogram histogram(MetricName name) { ++ return NoopHistogram.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Histogram histogram(MetricName name, MetricSupplier supplier) { ++ return NoopHistogram.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Meter meter(String name) { ++ return NoopMeter.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Meter meter(MetricName name) { ++ return NoopMeter.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Meter meter(MetricName name, MetricSupplier supplier) { ++ return NoopMeter.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Timer timer(String name) { ++ return NoopTimer.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Timer timer(MetricName name) { ++ return NoopTimer.INSTANCE; ++ } ++ ++ /** ++ * {@inheritDoc} ++ * ++ * @since 4.2 ++ */ ++ @Override ++ @SuppressWarnings({"rawtypes", "unchecked"}) ++ public T gauge(MetricName name) { ++ return (T) NoopGauge.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Timer timer(MetricName name, MetricSupplier supplier) { ++ return NoopTimer.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @SuppressWarnings({"rawtypes", "unchecked"}) ++ public T gauge(MetricName name, final MetricSupplier supplier) { ++ return (T) NoopGauge.INSTANCE; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public boolean remove(MetricName name) { ++ return false; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void removeMatching(MetricFilter filter) { ++ // NOP ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void addListener(MetricRegistryListener listener) { ++ // NOP ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void removeListener(MetricRegistryListener listener) { ++ // NOP ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedSet getNames() { ++ return emptySortedSet(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap> getGauges() { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap> getGauges(MetricFilter filter) { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap getCounters() { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap getCounters(MetricFilter filter) { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap getHistograms() { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap getHistograms(MetricFilter filter) { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap getMeters() { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap getMeters(MetricFilter filter) { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap getTimers() { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public SortedMap getTimers(MetricFilter filter) { ++ return emptySortedMap(); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void registerAll(MetricName prefix, MetricSet metrics) throws IllegalArgumentException { ++ // NOP ++ } + +- /** +- * {@inheritDoc} +- * @return +- */ ++ /** {@inheritDoc} */ ++ @Override ++ public T register(MetricName name, T metric) throws IllegalArgumentException { ++ return requireNonNull(metric, "metric == null"); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Map getMetrics() { ++ return ImmutableMap.of(); ++ } ++ ++ static final class NoopMetric implements Metric { ++ private static final NoopMetric INSTANCE = new NoopMetric(); ++ } ++ ++ static final class NoopGauge implements Gauge { ++ private static final NoopGauge INSTANCE = new NoopGauge<>(); ++ ++ /** {@inheritDoc} */ + @Override +- protected ConcurrentMap buildMap() { +- return EMPTY_CONCURRENT_MAP; ++ public T getValue() { ++ return null; + } ++ } + +- /** +- * {@inheritDoc} +- */ ++ private static final class EmptySnapshot extends Snapshot { ++ private static final EmptySnapshot INSTANCE = new EmptySnapshot(); ++ private static final long[] EMPTY_LONG_ARRAY = new long[0]; ++ ++ /** {@inheritDoc} */ + @Override +- public void registerAll(MetricSet metrics) throws IllegalArgumentException { +- // NOP ++ public double getValue(double quantile) { ++ return 0D; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Counter counter(String name) { +- return NoopCounter.INSTANCE; ++ public long[] getValues() { ++ return EMPTY_LONG_ARRAY; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Counter counter(MetricName name) { +- return NoopCounter.INSTANCE; ++ public int size() { ++ return 0; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- @SuppressWarnings("unchecked") +- public T counter(MetricName name, final MetricSupplier supplier) { +- return (T) NoopCounter.INSTANCE; ++ public long getMax() { ++ return 0L; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Histogram histogram(String name) { +- return NoopHistogram.INSTANCE; ++ public double getMean() { ++ return 0D; + } + +- +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Histogram histogram(MetricName name) { +- return NoopHistogram.INSTANCE; ++ public long getMin() { ++ return 0L; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Histogram histogram(MetricName name, MetricSupplier supplier) { +- return NoopHistogram.INSTANCE; ++ public double getStdDev() { ++ return 0D; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Meter meter(String name) { +- return NoopMeter.INSTANCE; ++ public void dump(OutputStream output) { ++ // NOP + } ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public Meter meter(MetricName name) { +- return NoopMeter.INSTANCE; ++ static final class NoopTimer extends Timer { ++ private static final NoopTimer INSTANCE = new NoopTimer(); ++ private static final Timer.Context CONTEXT = new NoopTimer.Context(); ++ ++ private static class Context extends Timer.Context { ++ private static final Clock CLOCK = ++ new Clock() { ++ /** {@inheritDoc} */ ++ @Override ++ public long getTick() { ++ return 0L; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public long getTime() { ++ return 0L; ++ } ++ }; ++ ++ private Context() { ++ super(INSTANCE, CLOCK); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public long stop() { ++ return 0L; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void close() { ++ // NOP ++ } + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Meter meter(MetricName name, MetricSupplier supplier) { +- return NoopMeter.INSTANCE; ++ public void update(long duration, TimeUnit unit) { ++ // NOP + } + +- +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Timer timer(String name) { +- return NoopTimer.INSTANCE; ++ public void update(Duration duration) { ++ // NOP + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Timer timer(MetricName name) { +- return NoopTimer.INSTANCE; ++ public T time(Callable event) throws Exception { ++ return event.call(); + } + +- /** +- * {@inheritDoc} +- * +- * @since 4.2 +- */ ++ /** {@inheritDoc} */ + @Override +- @SuppressWarnings({"rawtypes", "unchecked"}) +- public T gauge(MetricName name) { +- return (T) NoopGauge.INSTANCE; ++ public T timeSupplier(Supplier event) { ++ return event.get(); + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Timer timer(MetricName name, MetricSupplier supplier) { +- return NoopTimer.INSTANCE; ++ public void time(Runnable event) { ++ // NOP + } + +- /** +- * {@inheritDoc} +- */ +- @SuppressWarnings({"rawtypes", "unchecked"}) +- public T gauge(MetricName name, final MetricSupplier supplier) { +- return (T) NoopGauge.INSTANCE; ++ /** {@inheritDoc} */ ++ @Override ++ public Timer.Context time() { ++ return CONTEXT; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public boolean remove(MetricName name) { +- return false; ++ public long getCount() { ++ return 0L; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public void removeMatching(MetricFilter filter) { +- // NOP ++ public double getFifteenMinuteRate() { ++ return 0D; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public void addListener(MetricRegistryListener listener) { +- // NOP ++ public double getFiveMinuteRate() { ++ return 0D; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public void removeListener(MetricRegistryListener listener) { +- // NOP ++ public double getMeanRate() { ++ return 0D; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedSet getNames() { +- return Collections.emptySortedSet(); ++ public double getOneMinuteRate() { ++ return 0D; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedMap> getGauges() { +- return Collections.emptySortedMap(); ++ public Snapshot getSnapshot() { ++ return EmptySnapshot.INSTANCE; + } ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public SortedMap> getGauges(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ static final class NoopHistogram extends Histogram { ++ private static final NoopHistogram INSTANCE = new NoopHistogram(); ++ private static final Reservoir EMPTY_RESERVOIR = ++ new Reservoir() { ++ /** {@inheritDoc} */ ++ @Override ++ public int size() { ++ return 0; ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void update(long value) { ++ // NOP ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public Snapshot getSnapshot() { ++ return EmptySnapshot.INSTANCE; ++ } ++ }; ++ ++ private NoopHistogram() { ++ super(EMPTY_RESERVOIR); + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedMap getCounters() { +- return Collections.emptySortedMap(); ++ public void update(int value) { ++ // NOP + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedMap getCounters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ public void update(long value) { ++ // NOP + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedMap getHistograms() { +- return Collections.emptySortedMap(); ++ public long getCount() { ++ return 0L; + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedMap getHistograms(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ public Snapshot getSnapshot() { ++ return EmptySnapshot.INSTANCE; + } ++ } ++ ++ static final class NoopCounter extends Counter { ++ private static final NoopCounter INSTANCE = new NoopCounter(); + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedMap getMeters() { +- return Collections.emptySortedMap(); ++ public void inc() { ++ // NOP + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedMap getMeters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ public void inc(long n) { ++ // NOP + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedMap getTimers() { +- return Collections.emptySortedMap(); ++ public void dec() { ++ // NOP + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public SortedMap getTimers(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ public void dec(long n) { ++ // NOP + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public void registerAll(MetricName prefix, MetricSet metrics) throws IllegalArgumentException { +- // NOP ++ public long getCount() { ++ return 0L; + } ++ } ++ ++ static final class NoopMeter extends Meter { ++ private static final NoopMeter INSTANCE = new NoopMeter(); + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public T register(MetricName name, T metric) throws IllegalArgumentException { +- return requireNonNull(metric, "metric == null"); ++ public void mark() { ++ // NOP + } + +- /** +- * {@inheritDoc} +- */ ++ /** {@inheritDoc} */ + @Override +- public Map getMetrics() { +- return Collections.emptyMap(); ++ public void mark(long n) { ++ // NOP + } + +- static final class NoopMetric implements Metric { +- private static final NoopMetric INSTANCE = new NoopMetric(); ++ /** {@inheritDoc} */ ++ @Override ++ public long getCount() { ++ return 0L; + } + +- static final class NoopGauge implements Gauge { +- private static final NoopGauge INSTANCE = new NoopGauge<>(); +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public T getValue() { +- return null; +- } ++ /** {@inheritDoc} */ ++ @Override ++ public double getFifteenMinuteRate() { ++ return 0D; + } + +- private static final class EmptySnapshot extends Snapshot { +- private static final EmptySnapshot INSTANCE = new EmptySnapshot(); +- private static final long[] EMPTY_LONG_ARRAY = new long[0]; +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getValue(double quantile) { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public long[] getValues() { +- return EMPTY_LONG_ARRAY; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public int size() { +- return 0; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public long getMax() { +- return 0L; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getMean() { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public long getMin() { +- return 0L; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getStdDev() { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public void dump(OutputStream output) { +- // NOP +- } +- } +- +- static final class NoopTimer extends Timer { +- private static final NoopTimer INSTANCE = new NoopTimer(); +- private static final Timer.Context CONTEXT = new NoopTimer.Context(); +- +- private static class Context extends Timer.Context { +- private static final Clock CLOCK = new Clock() { +- /** +- * {@inheritDoc} +- */ +- @Override +- public long getTick() { +- return 0L; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public long getTime() { +- return 0L; +- } +- }; +- +- private Context() { +- super(INSTANCE, CLOCK); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public long stop() { +- return 0L; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public void close() { +- // NOP +- } +- } ++ /** {@inheritDoc} */ ++ @Override ++ public double getFiveMinuteRate() { ++ return 0D; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void update(long duration, TimeUnit unit) { +- // NOP +- } ++ /** {@inheritDoc} */ ++ @Override ++ public double getMeanRate() { ++ return 0D; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void update(Duration duration) { +- // NOP +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public T time(Callable event) throws Exception { +- return event.call(); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public T timeSupplier(Supplier event) { +- return event.get(); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public void time(Runnable event) { +- // NOP +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public Timer.Context time() { +- return CONTEXT; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public long getCount() { +- return 0L; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getFifteenMinuteRate() { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getFiveMinuteRate() { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getMeanRate() { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getOneMinuteRate() { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public Snapshot getSnapshot() { +- return EmptySnapshot.INSTANCE; +- } ++ /** {@inheritDoc} */ ++ @Override ++ public double getOneMinuteRate() { ++ return 0D; + } ++ } + +- static final class NoopHistogram extends Histogram { +- private static final NoopHistogram INSTANCE = new NoopHistogram(); +- private static final Reservoir EMPTY_RESERVOIR = new Reservoir() { +- /** +- * {@inheritDoc} +- */ +- @Override +- public int size() { +- return 0; +- } ++ private static final class EmptyConcurrentMap implements ConcurrentMap { ++ /** {@inheritDoc} */ ++ @Override ++ public V putIfAbsent(K key, V value) { ++ return null; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void update(long value) { +- // NOP +- } ++ /** {@inheritDoc} */ ++ @Override ++ public boolean remove(Object key, Object value) { ++ return false; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public Snapshot getSnapshot() { +- return EmptySnapshot.INSTANCE; +- } +- }; ++ /** {@inheritDoc} */ ++ @Override ++ public boolean replace(K key, V oldValue, V newValue) { ++ return false; ++ } + +- private NoopHistogram() { +- super(EMPTY_RESERVOIR); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public V replace(K key, V value) { ++ return null; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void update(int value) { +- // NOP +- } ++ /** {@inheritDoc} */ ++ @Override ++ public int size() { ++ return 0; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void update(long value) { +- // NOP +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public long getCount() { +- return 0L; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public Snapshot getSnapshot() { +- return EmptySnapshot.INSTANCE; +- } ++ /** {@inheritDoc} */ ++ @Override ++ public boolean isEmpty() { ++ return true; + } + +- static final class NoopCounter extends Counter { +- private static final NoopCounter INSTANCE = new NoopCounter(); ++ /** {@inheritDoc} */ ++ @Override ++ public boolean containsKey(Object key) { ++ return false; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void inc() { +- // NOP +- } ++ /** {@inheritDoc} */ ++ @Override ++ public boolean containsValue(Object value) { ++ return false; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void inc(long n) { +- // NOP +- } ++ /** {@inheritDoc} */ ++ @Override ++ public V get(Object key) { ++ return null; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void dec() { +- // NOP +- } ++ /** {@inheritDoc} */ ++ @Override ++ public V put(K key, V value) { ++ return null; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void dec(long n) { +- // NOP +- } ++ /** {@inheritDoc} */ ++ @Override ++ public V remove(Object key) { ++ return null; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public long getCount() { +- return 0L; +- } ++ /** {@inheritDoc} */ ++ @Override ++ public void putAll(Map m) { ++ // NOP + } + +- static final class NoopMeter extends Meter { +- private static final NoopMeter INSTANCE = new NoopMeter(); ++ /** {@inheritDoc} */ ++ @Override ++ public void clear() { ++ // NOP ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void mark() { +- // NOP +- } ++ /** {@inheritDoc} */ ++ @Override ++ public Set keySet() { ++ return ImmutableSet.of(); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void mark(long n) { +- // NOP +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public long getCount() { +- return 0L; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getFifteenMinuteRate() { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getFiveMinuteRate() { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getMeanRate() { +- return 0D; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public double getOneMinuteRate() { +- return 0D; +- } +- } +- +- private static final class EmptyConcurrentMap implements ConcurrentMap { +- /** +- * {@inheritDoc} +- */ +- @Override +- public V putIfAbsent(K key, V value) { +- return null; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public boolean remove(Object key, Object value) { +- return false; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public boolean replace(K key, V oldValue, V newValue) { +- return false; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public V replace(K key, V value) { +- return null; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public int size() { +- return 0; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public boolean isEmpty() { +- return true; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public boolean containsKey(Object key) { +- return false; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public boolean containsValue(Object value) { +- return false; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public V get(Object key) { +- return null; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public V put(K key, V value) { +- return null; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public V remove(Object key) { +- return null; +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public void putAll(Map m) { +- // NOP +- } ++ /** {@inheritDoc} */ ++ @Override ++ public Collection values() { ++ return ImmutableSet.of(); ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void clear() { +- // NOP +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public Set keySet() { +- return Collections.emptySet(); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public Collection values() { +- return Collections.emptySet(); +- } +- +- /** +- * {@inheritDoc} +- */ +- @Override +- public Set> entrySet() { +- return Collections.emptySet(); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public Set> entrySet() { ++ return ImmutableSet.of(); + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/RatioGauge.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/RatioGauge.java +@@ -5,62 +5,60 @@ import static java.lang.Double.isNaN; + + /** + * A gauge which measures the ratio of one value to another. +- *

+- * If the denominator is zero, not a number, or infinite, the resulting ratio is not a number. ++ * ++ *

If the denominator is zero, not a number, or infinite, the resulting ratio is not a number. + */ + public abstract class RatioGauge implements Gauge { ++ /** A ratio of one quantity to another. */ ++ public static class Ratio { + /** +- * A ratio of one quantity to another. ++ * Creates a new ratio with the given numerator and denominator. ++ * ++ * @param numerator the numerator of the ratio ++ * @param denominator the denominator of the ratio ++ * @return {@code numerator:denominator} + */ +- public static class Ratio { +- /** +- * Creates a new ratio with the given numerator and denominator. +- * +- * @param numerator the numerator of the ratio +- * @param denominator the denominator of the ratio +- * @return {@code numerator:denominator} +- */ +- public static Ratio of(double numerator, double denominator) { +- return new Ratio(numerator, denominator); +- } +- +- private final double numerator; +- private final double denominator; +- +- private Ratio(double numerator, double denominator) { +- this.numerator = numerator; +- this.denominator = denominator; +- } ++ public static Ratio of(double numerator, double denominator) { ++ return new Ratio(numerator, denominator); ++ } + +- /** +- * Returns the ratio, which is either a {@code double} between 0 and 1 (inclusive) or +- * {@code NaN}. +- * +- * @return the ratio +- */ +- public double getValue() { +- final double d = denominator; +- if (isNaN(d) || isInfinite(d) || d == 0) { +- return Double.NaN; +- } +- return numerator / d; +- } ++ private final double numerator; ++ private final double denominator; + +- @Override +- public String toString() { +- return numerator + ":" + denominator; +- } ++ private Ratio(double numerator, double denominator) { ++ this.numerator = numerator; ++ this.denominator = denominator; + } + + /** +- * Returns the {@link Ratio} which is the gauge's current value. ++ * Returns the ratio, which is either a {@code double} between 0 and 1 (inclusive) or {@code ++ * NaN}. + * +- * @return the {@link Ratio} which is the gauge's current value ++ * @return the ratio + */ +- protected abstract Ratio getRatio(); ++ public double getValue() { ++ final double d = denominator; ++ if (isNaN(d) || isInfinite(d) || d == 0) { ++ return Double.NaN; ++ } ++ return numerator / d; ++ } + + @Override +- public Double getValue() { +- return getRatio().getValue(); ++ public String toString() { ++ return numerator + ":" + denominator; + } ++ } ++ ++ /** ++ * Returns the {@link Ratio} which is the gauge's current value. ++ * ++ * @return the {@link Ratio} which is the gauge's current value ++ */ ++ protected abstract Ratio getRatio(); ++ ++ @Override ++ public Double getValue() { ++ return getRatio().getValue(); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Reporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Reporter.java +@@ -5,6 +5,4 @@ import java.io.Closeable; + /* + * A tag interface to indicate that a class is a Reporter. + */ +-public interface Reporter extends Closeable { +- +-} ++public interface Reporter extends Closeable {} +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Reservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Reservoir.java +@@ -1,27 +1,25 @@ + package io.dropwizard.metrics5; + +-/** +- * A statistically representative reservoir of a data stream. +- */ ++/** A statistically representative reservoir of a data stream. */ + public interface Reservoir { +- /** +- * Returns the number of values recorded. +- * +- * @return the number of values recorded +- */ +- int size(); ++ /** ++ * Returns the number of values recorded. ++ * ++ * @return the number of values recorded ++ */ ++ int size(); + +- /** +- * Adds a new recorded value to the reservoir. +- * +- * @param value a new recorded value +- */ +- void update(long value); ++ /** ++ * Adds a new recorded value to the reservoir. ++ * ++ * @param value a new recorded value ++ */ ++ void update(long value); + +- /** +- * Returns a snapshot of the reservoir's values. +- * +- * @return a snapshot of the reservoir's values +- */ +- Snapshot getSnapshot(); ++ /** ++ * Returns a snapshot of the reservoir's values. ++ * ++ * @return a snapshot of the reservoir's values ++ */ ++ Snapshot getSnapshot(); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Sampling.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Sampling.java +@@ -1,13 +1,11 @@ + package io.dropwizard.metrics5; + +-/** +- * An object which samples values. +- */ ++/** An object which samples values. */ + public interface Sampling { +- /** +- * Returns a snapshot of the values. +- * +- * @return a snapshot of the values +- */ +- Snapshot getSnapshot(); ++ /** ++ * Returns a snapshot of the values. ++ * ++ * @return a snapshot of the values ++ */ ++ Snapshot getSnapshot(); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java +@@ -1,20 +1,21 @@ + package io.dropwizard.metrics5; + +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Objects.requireNonNull; + ++import com.google.common.collect.ImmutableSet; + import java.io.Closeable; +-import java.util.Collections; + import java.util.Locale; + import java.util.Set; + import java.util.SortedMap; +-import java.util.concurrent.Executor; + import java.util.concurrent.Executors; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.ScheduledFuture; + import java.util.concurrent.ThreadFactory; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicInteger; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + + /** + * The abstract base class for all scheduled reporters (i.e., reporters which process a registry's +@@ -26,312 +27,333 @@ import java.util.concurrent.atomic.AtomicInteger; + */ + public abstract class ScheduledReporter implements Closeable, Reporter { + +- private static final Logger LOG = LoggerFactory.getLogger(ScheduledReporter.class); +- +- /** +- * A simple named thread factory. +- */ +- @SuppressWarnings("NullableProblems") +- private static class NamedThreadFactory implements ThreadFactory { +- private final ThreadGroup group; +- private final AtomicInteger threadNumber = new AtomicInteger(1); +- private final String namePrefix; +- +- private NamedThreadFactory(String name) { +- final SecurityManager s = System.getSecurityManager(); +- this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); +- this.namePrefix = "metrics-" + name + "-thread-"; +- } +- +- @Override +- public Thread newThread(Runnable r) { +- final Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); +- t.setDaemon(true); +- if (t.getPriority() != Thread.NORM_PRIORITY) { +- t.setPriority(Thread.NORM_PRIORITY); +- } +- return t; +- } +- } +- +- private static final AtomicInteger FACTORY_ID = new AtomicInteger(); +- +- private final MetricRegistry registry; +- private final ScheduledExecutorService executor; +- private final boolean shutdownExecutorOnStop; +- private final Set disabledMetricAttributes; +- private ScheduledFuture scheduledFuture; +- private final MetricFilter filter; +- private final long durationFactor; +- private final String durationUnit; +- private final long rateFactor; +- private final String rateUnit; +- +- /** +- * Creates a new {@link ScheduledReporter} instance. +- * +- * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this +- * reporter will report +- * @param name the reporter's name +- * @param filter the filter for which metrics to report +- * @param rateUnit a unit of time +- * @param durationUnit a unit of time +- */ +- protected ScheduledReporter(MetricRegistry registry, +- String name, +- MetricFilter filter, +- TimeUnit rateUnit, +- TimeUnit durationUnit) { +- this(registry, name, filter, rateUnit, durationUnit, createDefaultExecutor(name)); +- } +- +- /** +- * Creates a new {@link ScheduledReporter} instance. +- * +- * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this +- * reporter will report +- * @param name the reporter's name +- * @param filter the filter for which metrics to report +- * @param executor the executor to use while scheduling reporting of metrics. +- */ +- protected ScheduledReporter(MetricRegistry registry, +- String name, +- MetricFilter filter, +- TimeUnit rateUnit, +- TimeUnit durationUnit, +- ScheduledExecutorService executor) { +- this(registry, name, filter, rateUnit, durationUnit, executor, true); +- } +- +- /** +- * Creates a new {@link ScheduledReporter} instance. +- * +- * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this +- * reporter will report +- * @param name the reporter's name +- * @param filter the filter for which metrics to report +- * @param executor the executor to use while scheduling reporting of metrics. +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- */ +- protected ScheduledReporter(MetricRegistry registry, +- String name, +- MetricFilter filter, +- TimeUnit rateUnit, +- TimeUnit durationUnit, +- ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop) { +- this(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, Collections.emptySet()); +- } +- +- protected ScheduledReporter(MetricRegistry registry, +- String name, +- MetricFilter filter, +- TimeUnit rateUnit, +- TimeUnit durationUnit, +- ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop, +- Set disabledMetricAttributes) { +- +- if (registry == null) { +- throw new NullPointerException("registry == null"); +- } ++ private static final Logger LOG = LoggerFactory.getLogger(ScheduledReporter.class); + +- this.registry = registry; +- this.filter = filter; +- this.executor = executor == null ? createDefaultExecutor(name) : executor; +- this.shutdownExecutorOnStop = shutdownExecutorOnStop; +- this.rateFactor = rateUnit.toSeconds(1); +- this.rateUnit = calculateRateUnit(rateUnit); +- this.durationFactor = durationUnit.toNanos(1); +- this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); +- this.disabledMetricAttributes = disabledMetricAttributes != null ? disabledMetricAttributes : +- Collections.emptySet(); +- } ++ /** A simple named thread factory. */ ++ @SuppressWarnings("NullableProblems") ++ private static class NamedThreadFactory implements ThreadFactory { ++ private final ThreadGroup group; ++ private final AtomicInteger threadNumber = new AtomicInteger(1); ++ private final String namePrefix; + +- /** +- * Starts the reporter polling at the given period. +- * +- * @param period the amount of time between polls +- * @param unit the unit for {@code period} +- */ +- public void start(long period, TimeUnit unit) { +- start(period, period, unit); ++ private NamedThreadFactory(String name) { ++ final SecurityManager s = System.getSecurityManager(); ++ this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); ++ this.namePrefix = "metrics-" + name + "-thread-"; + } + +- /** +- * Starts the reporter polling at the given period with the specific runnable action. +- * Visible only for testing. +- */ +- synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) { +- if (this.scheduledFuture != null) { +- throw new IllegalArgumentException("Reporter already started"); +- } +- +- this.scheduledFuture = getScheduledFuture(initialDelay, period, unit, runnable); +- } +- +- +- /** +- * Schedule the task, and return a future. +- * +- * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, ScheduledExecutorService)} instead. +- */ +- @SuppressWarnings("DeprecatedIsStillUsed") +- @Deprecated +- protected ScheduledFuture getScheduledFuture(long initialDelay, long period, TimeUnit unit, Runnable runnable) { +- return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); +- } +- +- /** +- * Schedule the task, and return a future. +- * The current implementation uses scheduleWithFixedDelay, replacing scheduleWithFixedRate. This avoids queueing issues, but may +- * cause some reporters to skip metrics, as scheduleWithFixedDelay introduces a growing delta from the original start point. +- * +- * Overriding this in a subclass to revert to the old behavior is permitted. +- */ +- protected ScheduledFuture getScheduledFuture(long initialDelay, long period, TimeUnit unit, Runnable runnable, ScheduledExecutorService executor) { +- return executor.scheduleWithFixedDelay(runnable, initialDelay, period, unit); ++ @Override ++ public Thread newThread(Runnable r) { ++ final Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); ++ t.setDaemon(true); ++ if (t.getPriority() != Thread.NORM_PRIORITY) { ++ t.setPriority(Thread.NORM_PRIORITY); ++ } ++ return t; + } +- +- /** +- * Starts the reporter polling at the given period. +- * +- * @param initialDelay the time to delay the first execution +- * @param period the amount of time between polls +- * @param unit the unit for {@code period} and {@code initialDelay} +- */ +- synchronized public void start(long initialDelay, long period, TimeUnit unit) { +- start(initialDelay, period, unit, () -> { +- try { +- report(); +- } catch (Throwable ex) { +- LOG.error("Exception thrown from {}#report. Exception was suppressed.", ScheduledReporter.this.getClass().getSimpleName(), ex); +- } ++ } ++ ++ private static final AtomicInteger FACTORY_ID = new AtomicInteger(); ++ ++ private final MetricRegistry registry; ++ private final ScheduledExecutorService executor; ++ private final boolean shutdownExecutorOnStop; ++ private final Set disabledMetricAttributes; ++ private ScheduledFuture scheduledFuture; ++ private final MetricFilter filter; ++ private final long durationFactor; ++ private final String durationUnit; ++ private final long rateFactor; ++ private final String rateUnit; ++ ++ /** ++ * Creates a new {@link ScheduledReporter} instance. ++ * ++ * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this ++ * reporter will report ++ * @param name the reporter's name ++ * @param filter the filter for which metrics to report ++ * @param rateUnit a unit of time ++ * @param durationUnit a unit of time ++ */ ++ protected ScheduledReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit) { ++ this(registry, name, filter, rateUnit, durationUnit, createDefaultExecutor(name)); ++ } ++ ++ /** ++ * Creates a new {@link ScheduledReporter} instance. ++ * ++ * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this ++ * reporter will report ++ * @param name the reporter's name ++ * @param filter the filter for which metrics to report ++ * @param executor the executor to use while scheduling reporting of metrics. ++ */ ++ protected ScheduledReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor) { ++ this(registry, name, filter, rateUnit, durationUnit, executor, true); ++ } ++ ++ /** ++ * Creates a new {@link ScheduledReporter} instance. ++ * ++ * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this ++ * reporter will report ++ * @param name the reporter's name ++ * @param filter the filter for which metrics to report ++ * @param executor the executor to use while scheduling reporting of metrics. ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ */ ++ protected ScheduledReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop) { ++ this( ++ registry, ++ name, ++ filter, ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop, ++ ImmutableSet.of()); ++ } ++ ++ protected ScheduledReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes) { ++ ++ requireNonNull(registry, "registry == null"); ++ ++ this.registry = registry; ++ this.filter = filter; ++ this.executor = executor == null ? createDefaultExecutor(name) : executor; ++ this.shutdownExecutorOnStop = shutdownExecutorOnStop; ++ this.rateFactor = rateUnit.toSeconds(1); ++ this.rateUnit = calculateRateUnit(rateUnit); ++ this.durationFactor = durationUnit.toNanos(1); ++ this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); ++ this.disabledMetricAttributes = ++ disabledMetricAttributes != null ? disabledMetricAttributes : ImmutableSet.of(); ++ } ++ ++ /** ++ * Starts the reporter polling at the given period. ++ * ++ * @param period the amount of time between polls ++ * @param unit the unit for {@code period} ++ */ ++ public void start(long period, TimeUnit unit) { ++ start(period, period, unit); ++ } ++ ++ /** ++ * Starts the reporter polling at the given period with the specific runnable action. Visible only ++ * for testing. ++ */ ++ synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) { ++ checkArgument(this.scheduledFuture == null, "Reporter already started"); ++ ++ this.scheduledFuture = getScheduledFuture(initialDelay, period, unit, runnable); ++ } ++ ++ /** ++ * Schedule the task, and return a future. ++ * ++ * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, ++ * ScheduledExecutorService)} instead. ++ */ ++ @Deprecated ++ @SuppressWarnings("DeprecatedIsStillUsed") ++ protected ScheduledFuture getScheduledFuture( ++ long initialDelay, long period, TimeUnit unit, Runnable runnable) { ++ return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); ++ } ++ ++ /** ++ * Schedule the task, and return a future. The current implementation uses scheduleWithFixedDelay, ++ * replacing scheduleWithFixedRate. This avoids queueing issues, but may cause some reporters to ++ * skip metrics, as scheduleWithFixedDelay introduces a growing delta from the original start ++ * point. ++ * ++ *

Overriding this in a subclass to revert to the old behavior is permitted. ++ */ ++ protected ScheduledFuture getScheduledFuture( ++ long initialDelay, ++ long period, ++ TimeUnit unit, ++ Runnable runnable, ++ ScheduledExecutorService executor) { ++ return executor.scheduleWithFixedDelay(runnable, initialDelay, period, unit); ++ } ++ ++ /** ++ * Starts the reporter polling at the given period. ++ * ++ * @param initialDelay the time to delay the first execution ++ * @param period the amount of time between polls ++ * @param unit the unit for {@code period} and {@code initialDelay} ++ */ ++ public synchronized void start(long initialDelay, long period, TimeUnit unit) { ++ start( ++ initialDelay, ++ period, ++ unit, ++ () -> { ++ try { ++ report(); ++ } catch (Throwable ex) { ++ LOG.error( ++ "Exception thrown from {}#report. Exception was suppressed.", ++ ScheduledReporter.this.getClass().getSimpleName(), ++ ex); ++ } + }); ++ } ++ ++ /** ++ * Stops the reporter and if shutdownExecutorOnStop is true then shuts down its thread of ++ * execution. ++ * ++ *

Uses the shutdown pattern from ++ * http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html ++ */ ++ public void stop() { ++ if (shutdownExecutorOnStop) { ++ executor.shutdown(); // Disable new tasks from being submitted + } + +- /** +- * Stops the reporter and if shutdownExecutorOnStop is true then shuts down its thread of execution. +- *

+- * Uses the shutdown pattern from http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html +- */ +- public void stop() { +- if (shutdownExecutorOnStop) { +- executor.shutdown(); // Disable new tasks from being submitted +- } +- +- if (this.scheduledFuture != null) { +- // Reporter started, try to report metrics one last time +- try { +- report(); +- } catch (Exception e) { +- LOG.warn("Final reporting of metrics failed.", e); +- } +- } +- +- if (shutdownExecutorOnStop) { +- try { +- // Wait a while for existing tasks to terminate +- if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { +- executor.shutdownNow(); // Cancel currently executing tasks +- // Wait a while for tasks to respond to being cancelled +- if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { +- LOG.warn("ScheduledExecutorService did not terminate."); +- } +- } +- } catch (InterruptedException ie) { +- // (Re-)Cancel if current thread also interrupted +- executor.shutdownNow(); +- // Preserve interrupt status +- Thread.currentThread().interrupt(); +- } +- } else { +- // The external manager (like JEE container) responsible for lifecycle of executor +- cancelScheduledFuture(); +- } ++ if (this.scheduledFuture != null) { ++ // Reporter started, try to report metrics one last time ++ try { ++ report(); ++ } catch (Exception e) { ++ LOG.warn("Final reporting of metrics failed.", e); ++ } + } + +- private synchronized void cancelScheduledFuture() { +- if (this.scheduledFuture == null) { +- // was never started +- return; +- } +- if (this.scheduledFuture.isCancelled()) { +- // already cancelled +- return; ++ if (shutdownExecutorOnStop) { ++ try { ++ // Wait a while for existing tasks to terminate ++ if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { ++ executor.shutdownNow(); // Cancel currently executing tasks ++ // Wait a while for tasks to respond to being cancelled ++ if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { ++ LOG.warn("ScheduledExecutorService did not terminate."); ++ } + } +- // just cancel the scheduledFuture and exit +- this.scheduledFuture.cancel(false); ++ } catch (InterruptedException ie) { ++ // (Re-)Cancel if current thread also interrupted ++ executor.shutdownNow(); ++ // Preserve interrupt status ++ Thread.currentThread().interrupt(); ++ } ++ } else { ++ // The external manager (like JEE container) responsible for lifecycle of executor ++ cancelScheduledFuture(); + } ++ } + +- /** +- * Stops the reporter and shuts down its thread of execution. +- */ +- @Override +- public void close() { +- stop(); ++ private synchronized void cancelScheduledFuture() { ++ if (this.scheduledFuture == null) { ++ // was never started ++ return; + } +- +- /** +- * Report the current values of all metrics in the registry. +- */ +- public void report() { +- synchronized (this) { +- report(registry.getGauges(filter), +- registry.getCounters(filter), +- registry.getHistograms(filter), +- registry.getMeters(filter), +- registry.getTimers(filter)); +- } +- } +- +- /** +- * Called periodically by the polling thread. Subclasses should report all the given metrics. +- * +- * @param gauges all of the gauges in the registry +- * @param counters all of the counters in the registry +- * @param histograms all of the histograms in the registry +- * @param meters all of the meters in the registry +- * @param timers all of the timers in the registry +- */ +- @SuppressWarnings("rawtypes") +- public abstract void report(SortedMap> gauges, +- SortedMap counters, +- SortedMap histograms, +- SortedMap meters, +- SortedMap timers); +- +- public String getRateUnit() { +- return rateUnit; ++ if (this.scheduledFuture.isCancelled()) { ++ // already cancelled ++ return; + } +- +- public String getDurationUnit() { +- return durationUnit; ++ // just cancel the scheduledFuture and exit ++ this.scheduledFuture.cancel(false); ++ } ++ ++ /** Stops the reporter and shuts down its thread of execution. */ ++ @Override ++ public void close() { ++ stop(); ++ } ++ ++ /** Report the current values of all metrics in the registry. */ ++ public void report() { ++ synchronized (this) { ++ report( ++ registry.getGauges(filter), ++ registry.getCounters(filter), ++ registry.getHistograms(filter), ++ registry.getMeters(filter), ++ registry.getTimers(filter)); + } +- +- public double convertDuration(double duration) { +- return duration / durationFactor; +- } +- +- public double convertRate(double rate) { +- return rate * rateFactor; +- } +- +- public boolean isShutdownExecutorOnStop() { +- return shutdownExecutorOnStop; +- } +- +- public Set getDisabledMetricAttributes() { +- return disabledMetricAttributes; +- } +- +- private String calculateRateUnit(TimeUnit unit) { +- final String s = unit.toString().toLowerCase(Locale.US); +- return s.substring(0, s.length() - 1); +- } +- +- private static ScheduledExecutorService createDefaultExecutor(String name) { +- return Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet())); +- } +- ++ } ++ ++ /** ++ * Called periodically by the polling thread. Subclasses should report all the given metrics. ++ * ++ * @param gauges all of the gauges in the registry ++ * @param counters all of the counters in the registry ++ * @param histograms all of the histograms in the registry ++ * @param meters all of the meters in the registry ++ * @param timers all of the timers in the registry ++ */ ++ @SuppressWarnings("rawtypes") ++ public abstract void report( ++ SortedMap> gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers); ++ ++ public String getRateUnit() { ++ return rateUnit; ++ } ++ ++ public String getDurationUnit() { ++ return durationUnit; ++ } ++ ++ public double convertDuration(double duration) { ++ return duration / durationFactor; ++ } ++ ++ public double convertRate(double rate) { ++ return rate * rateFactor; ++ } ++ ++ public boolean isShutdownExecutorOnStop() { ++ return shutdownExecutorOnStop; ++ } ++ ++ public Set getDisabledMetricAttributes() { ++ return disabledMetricAttributes; ++ } ++ ++ private String calculateRateUnit(TimeUnit unit) { ++ final String s = unit.toString().toLowerCase(Locale.US); ++ return s.substring(0, s.length() - 1); ++ } ++ ++ private static ScheduledExecutorService createDefaultExecutor(String name) { ++ return Executors.newSingleThreadScheduledExecutor( ++ new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet())); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SettableGauge.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SettableGauge.java +@@ -1,14 +1,10 @@ + package io.dropwizard.metrics5; + + /** +- *

+ * Similar to {@link Gauge}, but metric value is updated via calling {@link #setValue(T)} instead. + * See {@link DefaultSettableGauge}. +- *

+ */ + public interface SettableGauge extends Gauge { +- /** +- * Set the metric to a new value. +- */ +- void setValue(T value); ++ /** Set the metric to a new value. */ ++ void setValue(T value); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java +@@ -1,107 +1,106 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkState; ++ + import java.util.Set; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; + import java.util.concurrent.atomic.AtomicReference; + +-/** +- * A map of shared, named metric registries. +- */ ++/** A map of shared, named metric registries. */ + public class SharedMetricRegistries { +- private static final ConcurrentMap REGISTRIES = +- new ConcurrentHashMap<>(); ++ private static final ConcurrentMap REGISTRIES = new ConcurrentHashMap<>(); + +- private static AtomicReference defaultRegistryName = new AtomicReference<>(); ++ private static AtomicReference defaultRegistryName = new AtomicReference<>(); + +- /* Visible for testing */ +- static void setDefaultRegistryName(AtomicReference defaultRegistryName) { +- SharedMetricRegistries.defaultRegistryName = defaultRegistryName; +- } ++ /* Visible for testing */ ++ static void setDefaultRegistryName(AtomicReference defaultRegistryName) { ++ SharedMetricRegistries.defaultRegistryName = defaultRegistryName; ++ } + +- private SharedMetricRegistries() { /* singleton */ } ++ private SharedMetricRegistries() { ++ /* singleton */ ++ } + +- public static void clear() { +- REGISTRIES.clear(); +- } ++ public static void clear() { ++ REGISTRIES.clear(); ++ } + +- public static Set names() { +- return REGISTRIES.keySet(); +- } ++ public static Set names() { ++ return REGISTRIES.keySet(); ++ } + +- public static void remove(String key) { +- REGISTRIES.remove(key); +- } ++ public static void remove(String key) { ++ REGISTRIES.remove(key); ++ } + +- public static MetricRegistry add(String name, MetricRegistry registry) { +- return REGISTRIES.putIfAbsent(name, registry); +- } ++ public static MetricRegistry add(String name, MetricRegistry registry) { ++ return REGISTRIES.putIfAbsent(name, registry); ++ } + +- public static MetricRegistry getOrCreate(String name) { +- final MetricRegistry existing = REGISTRIES.get(name); +- if (existing == null) { +- final MetricRegistry created = new MetricRegistry(); +- final MetricRegistry raced = add(name, created); +- if (raced == null) { +- return created; +- } +- return raced; +- } +- return existing; ++ public static MetricRegistry getOrCreate(String name) { ++ final MetricRegistry existing = REGISTRIES.get(name); ++ if (existing == null) { ++ final MetricRegistry created = new MetricRegistry(); ++ final MetricRegistry raced = add(name, created); ++ if (raced == null) { ++ return created; ++ } ++ return raced; + } ++ return existing; ++ } + +- /** +- * Creates a new registry and sets it as the default one under the provided name. +- * +- * @param name the registry name +- * @return the default registry +- * @throws IllegalStateException if the name has already been set +- */ +- public synchronized static MetricRegistry setDefault(String name) { +- final MetricRegistry registry = getOrCreate(name); +- return setDefault(name, registry); +- } ++ /** ++ * Creates a new registry and sets it as the default one under the provided name. ++ * ++ * @param name the registry name ++ * @return the default registry ++ * @throws IllegalStateException if the name has already been set ++ */ ++ public static synchronized MetricRegistry setDefault(String name) { ++ final MetricRegistry registry = getOrCreate(name); ++ return setDefault(name, registry); ++ } + +- /** +- * Sets the provided registry as the default one under the provided name +- * +- * @param name the default registry name +- * @param metricRegistry the default registry +- * @throws IllegalStateException if the default registry has already been set +- */ +- public static MetricRegistry setDefault(String name, MetricRegistry metricRegistry) { +- if (defaultRegistryName.compareAndSet(null, name)) { +- add(name, metricRegistry); +- return metricRegistry; +- } +- throw new IllegalStateException("Default metric registry name is already set."); ++ /** ++ * Sets the provided registry as the default one under the provided name ++ * ++ * @param name the default registry name ++ * @param metricRegistry the default registry ++ * @throws IllegalStateException if the default registry has already been set ++ */ ++ public static MetricRegistry setDefault(String name, MetricRegistry metricRegistry) { ++ if (defaultRegistryName.compareAndSet(null, name)) { ++ add(name, metricRegistry); ++ return metricRegistry; + } ++ throw new IllegalStateException("Default metric registry name is already set."); ++ } + +- /** +- * Gets the name of the default registry, if it has been set +- * +- * @return the default registry +- * @throws IllegalStateException if the default has not been set +- */ +- public static MetricRegistry getDefault() { +- MetricRegistry metricRegistry = tryGetDefault(); +- if (metricRegistry == null) { +- throw new IllegalStateException("Default registry name has not been set."); +- } +- return metricRegistry; +- } ++ /** ++ * Gets the name of the default registry, if it has been set ++ * ++ * @return the default registry ++ * @throws IllegalStateException if the default has not been set ++ */ ++ public static MetricRegistry getDefault() { ++ MetricRegistry metricRegistry = tryGetDefault(); ++ checkState(metricRegistry != null, "Default registry name has not been set."); ++ return metricRegistry; ++ } + +- /** +- * Same as {@link #getDefault()} except returns null when the default registry has not been set. +- * +- * @return the default registry or null +- */ +- public static MetricRegistry tryGetDefault() { +- final String name = defaultRegistryName.get(); +- if (name != null) { +- return getOrCreate(name); +- } else { +- return null; +- } ++ /** ++ * Same as {@link #getDefault()} except returns null when the default registry has not been set. ++ * ++ * @return the default registry or null ++ */ ++ public static MetricRegistry tryGetDefault() { ++ final String name = defaultRegistryName.get(); ++ if (name != null) { ++ return getOrCreate(name); ++ } else { ++ return null; + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java +@@ -1,25 +1,11 @@ + package io.dropwizard.metrics5; + +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; +-import org.slf4j.Marker; +- +-import java.util.Collections; +-import java.util.Map.Entry; +-import java.util.Set; +-import java.util.SortedMap; +-import java.util.concurrent.ScheduledExecutorService; +-import java.util.concurrent.TimeUnit; +-import java.util.function.Supplier; +- + import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MAX; + import static io.dropwizard.metrics5.MetricAttribute.MEAN; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P75; + import static io.dropwizard.metrics5.MetricAttribute.P95; +@@ -28,6 +14,17 @@ import static io.dropwizard.metrics5.MetricAttribute.P99; + import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; + ++import com.google.common.collect.ImmutableSet; ++import java.util.Map.Entry; ++import java.util.Set; ++import java.util.SortedMap; ++import java.util.concurrent.ScheduledExecutorService; ++import java.util.concurrent.TimeUnit; ++import java.util.function.Supplier; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; ++import org.slf4j.Marker; ++ + /** + * A reporter class for logging metrics values to a SLF4J {@link Logger} periodically, similar to + * {@link ConsoleReporter} or {@link CsvReporter}, but using the SLF4J framework instead. It also +@@ -35,482 +32,507 @@ import static io.dropwizard.metrics5.MetricAttribute.STDDEV; + * for the bound logging toolkit to further process metrics reports. + */ + public class Slf4jReporter extends ScheduledReporter { ++ /** ++ * Returns a new {@link Builder} for {@link Slf4jReporter}. ++ * ++ * @param registry the registry to report ++ * @return a {@link Builder} instance for a {@link Slf4jReporter} ++ */ ++ public static Builder forRegistry(MetricRegistry registry) { ++ return new Builder(registry); ++ } ++ ++ public enum LoggingLevel { ++ TRACE, ++ DEBUG, ++ INFO, ++ WARN, ++ ERROR ++ } ++ ++ /** ++ * A builder for {@link Slf4jReporter} instances. Defaults to logging to {@code metrics}, not ++ * using a marker, converting rates to events/second, converting durations to milliseconds, and ++ * not filtering metrics. ++ */ ++ public static class Builder { ++ private final MetricRegistry registry; ++ private Logger logger; ++ private LoggingLevel loggingLevel; ++ private Marker marker; ++ private String prefix; ++ private TimeUnit rateUnit; ++ private TimeUnit durationUnit; ++ private MetricFilter filter; ++ private ScheduledExecutorService executor; ++ private boolean shutdownExecutorOnStop; ++ private Set disabledMetricAttributes; ++ ++ private Builder(MetricRegistry registry) { ++ this.registry = registry; ++ this.logger = LoggerFactory.getLogger("metrics"); ++ this.marker = null; ++ this.prefix = ""; ++ this.rateUnit = TimeUnit.SECONDS; ++ this.durationUnit = TimeUnit.MILLISECONDS; ++ this.filter = MetricFilter.ALL; ++ this.loggingLevel = LoggingLevel.INFO; ++ this.executor = null; ++ this.shutdownExecutorOnStop = true; ++ this.disabledMetricAttributes = ImmutableSet.of(); ++ } ++ + /** +- * Returns a new {@link Builder} for {@link Slf4jReporter}. ++ * Specifies whether or not, the executor (used for reporting) will be stopped with same time ++ * with reporter. Default value is true. Setting this parameter to false, has the sense in ++ * combining with providing external managed executor via {@link ++ * #scheduleOn(ScheduledExecutorService)}. + * +- * @param registry the registry to report +- * @return a {@link Builder} instance for a {@link Slf4jReporter} ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ * @return {@code this} + */ +- public static Builder forRegistry(MetricRegistry registry) { +- return new Builder(registry); ++ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { ++ this.shutdownExecutorOnStop = shutdownExecutorOnStop; ++ return this; + } + +- public enum LoggingLevel { TRACE, DEBUG, INFO, WARN, ERROR } ++ /** ++ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. ++ * Null value leads to executor will be auto created on start. ++ * ++ * @param executor the executor to use while scheduling reporting of metrics. ++ * @return {@code this} ++ */ ++ public Builder scheduleOn(ScheduledExecutorService executor) { ++ this.executor = executor; ++ return this; ++ } + + /** +- * A builder for {@link Slf4jReporter} instances. Defaults to logging to {@code metrics}, not +- * using a marker, converting rates to events/second, converting durations to milliseconds, and +- * not filtering metrics. ++ * Log metrics to the given logger. ++ * ++ * @param logger an SLF4J {@link Logger} ++ * @return {@code this} + */ +- public static class Builder { +- private final MetricRegistry registry; +- private Logger logger; +- private LoggingLevel loggingLevel; +- private Marker marker; +- private String prefix; +- private TimeUnit rateUnit; +- private TimeUnit durationUnit; +- private MetricFilter filter; +- private ScheduledExecutorService executor; +- private boolean shutdownExecutorOnStop; +- private Set disabledMetricAttributes; +- +- private Builder(MetricRegistry registry) { +- this.registry = registry; +- this.logger = LoggerFactory.getLogger("metrics"); +- this.marker = null; +- this.prefix = ""; +- this.rateUnit = TimeUnit.SECONDS; +- this.durationUnit = TimeUnit.MILLISECONDS; +- this.filter = MetricFilter.ALL; +- this.loggingLevel = LoggingLevel.INFO; +- this.executor = null; +- this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); +- } +- +- /** +- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. +- * Default value is true. +- * Setting this parameter to false, has the sense in combining with providing external managed executor via {@link #scheduleOn(ScheduledExecutorService)}. +- * +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- * @return {@code this} +- */ +- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { +- this.shutdownExecutorOnStop = shutdownExecutorOnStop; +- return this; +- } +- +- /** +- * Specifies the executor to use while scheduling reporting of metrics. +- * Default value is null. +- * Null value leads to executor will be auto created on start. +- * +- * @param executor the executor to use while scheduling reporting of metrics. +- * @return {@code this} +- */ +- public Builder scheduleOn(ScheduledExecutorService executor) { +- this.executor = executor; +- return this; +- } +- +- /** +- * Log metrics to the given logger. +- * +- * @param logger an SLF4J {@link Logger} +- * @return {@code this} +- */ +- public Builder outputTo(Logger logger) { +- this.logger = logger; +- return this; +- } +- +- /** +- * Mark all logged metrics with the given marker. +- * +- * @param marker an SLF4J {@link Marker} +- * @return {@code this} +- */ +- public Builder markWith(Marker marker) { +- this.marker = marker; +- return this; +- } +- +- /** +- * Prefix all metric names with the given string. +- * +- * @param prefix the prefix for all metric names +- * @return {@code this} +- */ +- public Builder prefixedWith(String prefix) { +- this.prefix = prefix; +- return this; +- } +- +- /** +- * Convert rates to the given time unit. +- * +- * @param rateUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertRatesTo(TimeUnit rateUnit) { +- this.rateUnit = rateUnit; +- return this; +- } +- +- /** +- * Convert durations to the given time unit. +- * +- * @param durationUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertDurationsTo(TimeUnit durationUnit) { +- this.durationUnit = durationUnit; +- return this; +- } +- +- /** +- * Only report metrics which match the given filter. +- * +- * @param filter a {@link MetricFilter} +- * @return {@code this} +- */ +- public Builder filter(MetricFilter filter) { +- this.filter = filter; +- return this; +- } +- +- /** +- * Use Logging Level when reporting. +- * +- * @param loggingLevel a (@link Slf4jReporter.LoggingLevel} +- * @return {@code this} +- */ +- public Builder withLoggingLevel(LoggingLevel loggingLevel) { +- this.loggingLevel = loggingLevel; +- return this; +- } +- +- /** +- * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). +- * See {@link MetricAttribute}. +- * +- * @param disabledMetricAttributes a set of {@link MetricAttribute} +- * @return {@code this} +- */ +- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { +- this.disabledMetricAttributes = disabledMetricAttributes; +- return this; +- } +- +- /** +- * Builds a {@link Slf4jReporter} with the given properties. +- * +- * @return a {@link Slf4jReporter} +- */ +- public Slf4jReporter build() { +- LoggerProxy loggerProxy; +- switch (loggingLevel) { +- case TRACE: +- loggerProxy = new TraceLoggerProxy(logger); +- break; +- case INFO: +- loggerProxy = new InfoLoggerProxy(logger); +- break; +- case WARN: +- loggerProxy = new WarnLoggerProxy(logger); +- break; +- case ERROR: +- loggerProxy = new ErrorLoggerProxy(logger); +- break; +- default: +- case DEBUG: +- loggerProxy = new DebugLoggerProxy(logger); +- break; +- } +- return new Slf4jReporter(registry, loggerProxy, marker, prefix, rateUnit, durationUnit, filter, executor, +- shutdownExecutorOnStop, disabledMetricAttributes); +- } +- } +- +- private final LoggerProxy loggerProxy; +- private final Marker marker; +- private final MetricName prefix; +- +- private Slf4jReporter(MetricRegistry registry, +- LoggerProxy loggerProxy, +- Marker marker, +- String prefix, +- TimeUnit rateUnit, +- TimeUnit durationUnit, +- MetricFilter filter, +- ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop, +- Set disabledMetricAttributes) { +- super(registry, "logger-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, +- disabledMetricAttributes); +- this.loggerProxy = loggerProxy; +- this.marker = marker; +- this.prefix = MetricName.build(prefix); ++ public Builder outputTo(Logger logger) { ++ this.logger = logger; ++ return this; + } + +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap> gauges, +- SortedMap counters, +- SortedMap histograms, +- SortedMap meters, +- SortedMap timers) { +- if (loggerProxy.isEnabled(marker)) { +- StringBuilder b = new StringBuilder(); +- for (Entry> entry : gauges.entrySet()) { +- logGauge(b, entry.getKey(), entry.getValue()); +- } +- +- for (Entry entry : counters.entrySet()) { +- logCounter(b, entry.getKey(), entry.getValue()); +- } +- +- for (Entry entry : histograms.entrySet()) { +- logHistogram(b, entry.getKey(), entry.getValue()); +- } +- +- for (Entry entry : meters.entrySet()) { +- logMeter(b, entry.getKey(), entry.getValue()); +- } +- +- for (Entry entry : timers.entrySet()) { +- logTimer(b, entry.getKey(), entry.getValue()); +- } +- } +- } +- +- private void logTimer(StringBuilder b, MetricName name, Timer timer) { +- final Snapshot snapshot = timer.getSnapshot(); +- b.setLength(0); +- b.append("type=TIMER"); +- append(b, "name", prefix(name)); +- appendCountIfEnabled(b, timer); +- appendLongDurationIfEnabled(b, MIN, snapshot::getMin); +- appendLongDurationIfEnabled(b, MAX, snapshot::getMax); +- appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); +- appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); +- appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); +- appendDoubleDurationIfEnabled(b, P75, snapshot::get75thPercentile); +- appendDoubleDurationIfEnabled(b, P95, snapshot::get95thPercentile); +- appendDoubleDurationIfEnabled(b, P98, snapshot::get98thPercentile); +- appendDoubleDurationIfEnabled(b, P99, snapshot::get99thPercentile); +- appendDoubleDurationIfEnabled(b, P999, snapshot::get999thPercentile); +- appendMetered(b, timer); +- append(b, "rate_unit", getRateUnit()); +- append(b, "duration_unit", getDurationUnit()); +- loggerProxy.log(marker, b.toString()); +- } +- +- private void logMeter(StringBuilder b, MetricName name, Meter meter) { +- b.setLength(0); +- b.append("type=METER"); +- append(b, "name", prefix(name)); +- appendCountIfEnabled(b, meter); +- appendMetered(b, meter); +- append(b, "rate_unit", getRateUnit()); +- loggerProxy.log(marker, b.toString()); +- } +- +- private void logHistogram(StringBuilder b, MetricName name, Histogram histogram) { +- final Snapshot snapshot = histogram.getSnapshot(); +- b.setLength(0); +- b.append("type=HISTOGRAM"); +- append(b, "name", prefix(name)); +- appendCountIfEnabled(b, histogram); +- appendLongIfEnabled(b, MIN, snapshot::getMin); +- appendLongIfEnabled(b, MAX, snapshot::getMax); +- appendDoubleIfEnabled(b, MEAN, snapshot::getMean); +- appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); +- appendDoubleIfEnabled(b, P50, snapshot::getMedian); +- appendDoubleIfEnabled(b, P75, snapshot::get75thPercentile); +- appendDoubleIfEnabled(b, P95, snapshot::get95thPercentile); +- appendDoubleIfEnabled(b, P98, snapshot::get98thPercentile); +- appendDoubleIfEnabled(b, P99, snapshot::get99thPercentile); +- appendDoubleIfEnabled(b, P999, snapshot::get999thPercentile); +- loggerProxy.log(marker, b.toString()); +- } +- +- private void logCounter(StringBuilder b, MetricName name, Counter counter) { +- b.setLength(0); +- b.append("type=COUNTER"); +- append(b, "name", prefix(name)); +- append(b, COUNT.getCode(), counter.getCount()); +- loggerProxy.log(marker, b.toString()); +- } +- +- private void logGauge(StringBuilder b, MetricName name, Gauge gauge) { +- b.setLength(0); +- b.append("type=GAUGE"); +- append(b, "name", prefix(name)); +- append(b, "value", gauge.getValue()); +- loggerProxy.log(marker, b.toString()); +- } +- +- private void appendLongDurationIfEnabled(StringBuilder b, MetricAttribute metricAttribute, +- Supplier durationSupplier) { +- if (!getDisabledMetricAttributes().contains(metricAttribute)) { +- append(b, metricAttribute.getCode(), convertDuration(durationSupplier.get())); +- } +- } +- +- private void appendDoubleDurationIfEnabled(StringBuilder b, MetricAttribute metricAttribute, +- Supplier durationSupplier) { +- if (!getDisabledMetricAttributes().contains(metricAttribute)) { +- append(b, metricAttribute.getCode(), convertDuration(durationSupplier.get())); +- } ++ /** ++ * Mark all logged metrics with the given marker. ++ * ++ * @param marker an SLF4J {@link Marker} ++ * @return {@code this} ++ */ ++ public Builder markWith(Marker marker) { ++ this.marker = marker; ++ return this; + } + +- private void appendLongIfEnabled(StringBuilder b, MetricAttribute metricAttribute, +- Supplier valueSupplier) { +- if (!getDisabledMetricAttributes().contains(metricAttribute)) { +- append(b, metricAttribute.getCode(), valueSupplier.get()); +- } ++ /** ++ * Prefix all metric names with the given string. ++ * ++ * @param prefix the prefix for all metric names ++ * @return {@code this} ++ */ ++ public Builder prefixedWith(String prefix) { ++ this.prefix = prefix; ++ return this; + } + +- private void appendDoubleIfEnabled(StringBuilder b, MetricAttribute metricAttribute, +- Supplier valueSupplier) { +- if (!getDisabledMetricAttributes().contains(metricAttribute)) { +- append(b, metricAttribute.getCode(), valueSupplier.get()); +- } ++ /** ++ * Convert rates to the given time unit. ++ * ++ * @param rateUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertRatesTo(TimeUnit rateUnit) { ++ this.rateUnit = rateUnit; ++ return this; + } + +- private void appendCountIfEnabled(StringBuilder b, Counting counting) { +- if (!getDisabledMetricAttributes().contains(COUNT)) { +- append(b, COUNT.getCode(), counting.getCount()); +- } ++ /** ++ * Convert durations to the given time unit. ++ * ++ * @param durationUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertDurationsTo(TimeUnit durationUnit) { ++ this.durationUnit = durationUnit; ++ return this; + } + +- private void appendMetered(StringBuilder b, Metered meter) { +- appendRateIfEnabled(b, M1_RATE, meter::getOneMinuteRate); +- appendRateIfEnabled(b, M5_RATE, meter::getFiveMinuteRate); +- appendRateIfEnabled(b, M15_RATE, meter::getFifteenMinuteRate); +- appendRateIfEnabled(b, MEAN_RATE, meter::getMeanRate); ++ /** ++ * Only report metrics which match the given filter. ++ * ++ * @param filter a {@link MetricFilter} ++ * @return {@code this} ++ */ ++ public Builder filter(MetricFilter filter) { ++ this.filter = filter; ++ return this; + } + +- private void appendRateIfEnabled(StringBuilder b, MetricAttribute metricAttribute, Supplier rateSupplier) { +- if (!getDisabledMetricAttributes().contains(metricAttribute)) { +- append(b, metricAttribute.getCode(), convertRate(rateSupplier.get())); +- } ++ /** ++ * Use Logging Level when reporting. ++ * ++ * @param loggingLevel a (@link Slf4jReporter.LoggingLevel} ++ * @return {@code this} ++ */ ++ public Builder withLoggingLevel(LoggingLevel loggingLevel) { ++ this.loggingLevel = loggingLevel; ++ return this; + } + +- private void append(StringBuilder b, String key, long value) { +- b.append(", ").append(key).append('=').append(value); ++ /** ++ * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). ++ * See {@link MetricAttribute}. ++ * ++ * @param disabledMetricAttributes a set of {@link MetricAttribute} ++ * @return {@code this} ++ */ ++ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { ++ this.disabledMetricAttributes = disabledMetricAttributes; ++ return this; + } + +- private void append(StringBuilder b, String key, double value) { +- b.append(", ").append(key).append('=').append(value); ++ /** ++ * Builds a {@link Slf4jReporter} with the given properties. ++ * ++ * @return a {@link Slf4jReporter} ++ */ ++ public Slf4jReporter build() { ++ LoggerProxy loggerProxy; ++ switch (loggingLevel) { ++ case TRACE: ++ loggerProxy = new TraceLoggerProxy(logger); ++ break; ++ case INFO: ++ loggerProxy = new InfoLoggerProxy(logger); ++ break; ++ case WARN: ++ loggerProxy = new WarnLoggerProxy(logger); ++ break; ++ case ERROR: ++ loggerProxy = new ErrorLoggerProxy(logger); ++ break; ++ default: ++ case DEBUG: ++ loggerProxy = new DebugLoggerProxy(logger); ++ break; ++ } ++ return new Slf4jReporter( ++ registry, ++ loggerProxy, ++ marker, ++ prefix, ++ rateUnit, ++ durationUnit, ++ filter, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes); ++ } ++ } ++ ++ private final LoggerProxy loggerProxy; ++ private final Marker marker; ++ private final MetricName prefix; ++ ++ private Slf4jReporter( ++ MetricRegistry registry, ++ LoggerProxy loggerProxy, ++ Marker marker, ++ String prefix, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ MetricFilter filter, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes) { ++ super( ++ registry, ++ "logger-reporter", ++ filter, ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes); ++ this.loggerProxy = loggerProxy; ++ this.marker = marker; ++ this.prefix = MetricName.build(prefix); ++ } ++ ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap> gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ if (loggerProxy.isEnabled(marker)) { ++ StringBuilder b = new StringBuilder(); ++ for (Entry> entry : gauges.entrySet()) { ++ logGauge(b, entry.getKey(), entry.getValue()); ++ } ++ ++ for (Entry entry : counters.entrySet()) { ++ logCounter(b, entry.getKey(), entry.getValue()); ++ } ++ ++ for (Entry entry : histograms.entrySet()) { ++ logHistogram(b, entry.getKey(), entry.getValue()); ++ } ++ ++ for (Entry entry : meters.entrySet()) { ++ logMeter(b, entry.getKey(), entry.getValue()); ++ } ++ ++ for (Entry entry : timers.entrySet()) { ++ logTimer(b, entry.getKey(), entry.getValue()); ++ } ++ } ++ } ++ ++ private void logTimer(StringBuilder b, MetricName name, Timer timer) { ++ final Snapshot snapshot = timer.getSnapshot(); ++ b.setLength(0); ++ b.append("type=TIMER"); ++ append(b, "name", prefix(name)); ++ appendCountIfEnabled(b, timer); ++ appendLongDurationIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongDurationIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); ++ appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); ++ appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); ++ appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); ++ appendDoubleDurationIfEnabled(b, P75, snapshot::get75thPercentile); ++ appendDoubleDurationIfEnabled(b, P95, snapshot::get95thPercentile); ++ appendDoubleDurationIfEnabled(b, P98, snapshot::get98thPercentile); ++ appendDoubleDurationIfEnabled(b, P99, snapshot::get99thPercentile); ++ appendDoubleDurationIfEnabled(b, P999, snapshot::get999thPercentile); ++ appendMetered(b, timer); ++ append(b, "rate_unit", getRateUnit()); ++ append(b, "duration_unit", getDurationUnit()); ++ loggerProxy.log(marker, b.toString()); ++ } ++ ++ private void logMeter(StringBuilder b, MetricName name, Meter meter) { ++ b.setLength(0); ++ b.append("type=METER"); ++ append(b, "name", prefix(name)); ++ appendCountIfEnabled(b, meter); ++ appendMetered(b, meter); ++ append(b, "rate_unit", getRateUnit()); ++ loggerProxy.log(marker, b.toString()); ++ } ++ ++ private void logHistogram(StringBuilder b, MetricName name, Histogram histogram) { ++ final Snapshot snapshot = histogram.getSnapshot(); ++ b.setLength(0); ++ b.append("type=HISTOGRAM"); ++ append(b, "name", prefix(name)); ++ appendCountIfEnabled(b, histogram); ++ appendLongIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); ++ appendDoubleIfEnabled(b, MEAN, snapshot::getMean); ++ appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); ++ appendDoubleIfEnabled(b, P50, snapshot::getMedian); ++ appendDoubleIfEnabled(b, P75, snapshot::get75thPercentile); ++ appendDoubleIfEnabled(b, P95, snapshot::get95thPercentile); ++ appendDoubleIfEnabled(b, P98, snapshot::get98thPercentile); ++ appendDoubleIfEnabled(b, P99, snapshot::get99thPercentile); ++ appendDoubleIfEnabled(b, P999, snapshot::get999thPercentile); ++ loggerProxy.log(marker, b.toString()); ++ } ++ ++ private void logCounter(StringBuilder b, MetricName name, Counter counter) { ++ b.setLength(0); ++ b.append("type=COUNTER"); ++ append(b, "name", prefix(name)); ++ append(b, COUNT.getCode(), counter.getCount()); ++ loggerProxy.log(marker, b.toString()); ++ } ++ ++ private void logGauge(StringBuilder b, MetricName name, Gauge gauge) { ++ b.setLength(0); ++ b.append("type=GAUGE"); ++ append(b, "name", prefix(name)); ++ append(b, "value", gauge.getValue()); ++ loggerProxy.log(marker, b.toString()); ++ } ++ ++ private void appendLongDurationIfEnabled( ++ StringBuilder b, MetricAttribute metricAttribute, Supplier durationSupplier) { ++ if (!getDisabledMetricAttributes().contains(metricAttribute)) { ++ append(b, metricAttribute.getCode(), convertDuration(durationSupplier.get())); + } ++ } + +- private void append(StringBuilder b, String key, String value) { +- b.append(", ").append(key).append('=').append(value); ++ private void appendDoubleDurationIfEnabled( ++ StringBuilder b, MetricAttribute metricAttribute, Supplier durationSupplier) { ++ if (!getDisabledMetricAttributes().contains(metricAttribute)) { ++ append(b, metricAttribute.getCode(), convertDuration(durationSupplier.get())); + } ++ } + +- private void append(StringBuilder b, String key, Object value) { +- b.append(", ").append(key).append('=').append(value); ++ private void appendLongIfEnabled( ++ StringBuilder b, MetricAttribute metricAttribute, Supplier valueSupplier) { ++ if (!getDisabledMetricAttributes().contains(metricAttribute)) { ++ append(b, metricAttribute.getCode(), valueSupplier.get()); + } ++ } + +- @Override +- public String getRateUnit() { +- return "events/" + super.getRateUnit(); ++ private void appendDoubleIfEnabled( ++ StringBuilder b, MetricAttribute metricAttribute, Supplier valueSupplier) { ++ if (!getDisabledMetricAttributes().contains(metricAttribute)) { ++ append(b, metricAttribute.getCode(), valueSupplier.get()); + } ++ } + +- private String prefix(MetricName metricName) { +- return prefix.append(metricName).toString(); ++ private void appendCountIfEnabled(StringBuilder b, Counting counting) { ++ if (!getDisabledMetricAttributes().contains(COUNT)) { ++ append(b, COUNT.getCode(), counting.getCount()); ++ } ++ } ++ ++ private void appendMetered(StringBuilder b, Metered meter) { ++ appendRateIfEnabled(b, M1_RATE, meter::getOneMinuteRate); ++ appendRateIfEnabled(b, M5_RATE, meter::getFiveMinuteRate); ++ appendRateIfEnabled(b, M15_RATE, meter::getFifteenMinuteRate); ++ appendRateIfEnabled(b, MEAN_RATE, meter::getMeanRate); ++ } ++ ++ private void appendRateIfEnabled( ++ StringBuilder b, MetricAttribute metricAttribute, Supplier rateSupplier) { ++ if (!getDisabledMetricAttributes().contains(metricAttribute)) { ++ append(b, metricAttribute.getCode(), convertRate(rateSupplier.get())); + } ++ } + +- /* private class to allow logger configuration */ +- static abstract class LoggerProxy { +- protected final Logger logger; ++ private void append(StringBuilder b, String key, long value) { ++ b.append(", ").append(key).append('=').append(value); ++ } + +- public LoggerProxy(Logger logger) { +- this.logger = logger; +- } ++ private void append(StringBuilder b, String key, double value) { ++ b.append(", ").append(key).append('=').append(value); ++ } + +- abstract void log(Marker marker, String format); ++ private void append(StringBuilder b, String key, String value) { ++ b.append(", ").append(key).append('=').append(value); ++ } + +- abstract boolean isEnabled(Marker marker); ++ private void append(StringBuilder b, String key, Object value) { ++ b.append(", ").append(key).append('=').append(value); ++ } ++ ++ @Override ++ public String getRateUnit() { ++ return "events/" + super.getRateUnit(); ++ } ++ ++ private String prefix(MetricName metricName) { ++ return prefix.append(metricName).toString(); ++ } ++ ++ /* private class to allow logger configuration */ ++ abstract static class LoggerProxy { ++ protected final Logger logger; ++ ++ public LoggerProxy(Logger logger) { ++ this.logger = logger; + } + +- /* private class to allow logger configuration */ +- private static class DebugLoggerProxy extends LoggerProxy { +- public DebugLoggerProxy(Logger logger) { +- super(logger); +- } ++ abstract void log(Marker marker, String format); + +- @Override +- public void log(Marker marker, String format) { +- logger.debug(marker, format); +- } ++ abstract boolean isEnabled(Marker marker); ++ } + +- @Override +- public boolean isEnabled(Marker marker) { +- return logger.isDebugEnabled(marker); +- } ++ /* private class to allow logger configuration */ ++ private static class DebugLoggerProxy extends LoggerProxy { ++ public DebugLoggerProxy(Logger logger) { ++ super(logger); + } + +- /* private class to allow logger configuration */ +- private static class TraceLoggerProxy extends LoggerProxy { +- public TraceLoggerProxy(Logger logger) { +- super(logger); +- } ++ @Override ++ public void log(Marker marker, String format) { ++ logger.debug(marker, format); ++ } + +- @Override +- public void log(Marker marker, String format) { +- logger.trace(marker, format); +- } ++ @Override ++ public boolean isEnabled(Marker marker) { ++ return logger.isDebugEnabled(marker); ++ } ++ } ++ ++ /* private class to allow logger configuration */ ++ private static class TraceLoggerProxy extends LoggerProxy { ++ public TraceLoggerProxy(Logger logger) { ++ super(logger); ++ } + +- @Override +- public boolean isEnabled(Marker marker) { +- return logger.isTraceEnabled(marker); +- } ++ @Override ++ public void log(Marker marker, String format) { ++ logger.trace(marker, format); + } + +- /* private class to allow logger configuration */ +- private static class InfoLoggerProxy extends LoggerProxy { +- public InfoLoggerProxy(Logger logger) { +- super(logger); +- } ++ @Override ++ public boolean isEnabled(Marker marker) { ++ return logger.isTraceEnabled(marker); ++ } ++ } + +- @Override +- public void log(Marker marker, String format) { +- logger.info(marker, format); +- } ++ /* private class to allow logger configuration */ ++ private static class InfoLoggerProxy extends LoggerProxy { ++ public InfoLoggerProxy(Logger logger) { ++ super(logger); ++ } + +- @Override +- public boolean isEnabled(Marker marker) { +- return logger.isInfoEnabled(marker); +- } ++ @Override ++ public void log(Marker marker, String format) { ++ logger.info(marker, format); + } + +- /* private class to allow logger configuration */ +- private static class WarnLoggerProxy extends LoggerProxy { +- public WarnLoggerProxy(Logger logger) { +- super(logger); +- } ++ @Override ++ public boolean isEnabled(Marker marker) { ++ return logger.isInfoEnabled(marker); ++ } ++ } + +- @Override +- public void log(Marker marker, String format) { +- logger.warn(marker, format); +- } ++ /* private class to allow logger configuration */ ++ private static class WarnLoggerProxy extends LoggerProxy { ++ public WarnLoggerProxy(Logger logger) { ++ super(logger); ++ } + +- @Override +- public boolean isEnabled(Marker marker) { +- return logger.isWarnEnabled(marker); +- } ++ @Override ++ public void log(Marker marker, String format) { ++ logger.warn(marker, format); + } + +- /* private class to allow logger configuration */ +- private static class ErrorLoggerProxy extends LoggerProxy { +- public ErrorLoggerProxy(Logger logger) { +- super(logger); +- } ++ @Override ++ public boolean isEnabled(Marker marker) { ++ return logger.isWarnEnabled(marker); ++ } ++ } + +- @Override +- public void log(Marker marker, String format) { +- logger.error(marker, format); +- } ++ /* private class to allow logger configuration */ ++ private static class ErrorLoggerProxy extends LoggerProxy { ++ public ErrorLoggerProxy(Logger logger) { ++ super(logger); ++ } + +- @Override +- public boolean isEnabled(Marker marker) { +- return logger.isErrorEnabled(marker); +- } ++ @Override ++ public void log(Marker marker, String format) { ++ logger.error(marker, format); + } + ++ @Override ++ public boolean isEnabled(Marker marker) { ++ return logger.isErrorEnabled(marker); ++ } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoir.java +@@ -4,98 +4,98 @@ import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicLong; + + /** +- * A {@link Reservoir} implementation backed by a sliding window that stores only the measurements made +- * in the last {@code N} seconds (or other time unit). ++ * A {@link Reservoir} implementation backed by a sliding window that stores only the measurements ++ * made in the last {@code N} seconds (or other time unit). + */ + public class SlidingTimeWindowArrayReservoir implements Reservoir { +- // allow for this many duplicate ticks before overwriting measurements +- private static final long COLLISION_BUFFER = 256L; +- // only trim on updating once every N +- private static final long TRIM_THRESHOLD = 256L; +- private static final long CLEAR_BUFFER = TimeUnit.HOURS.toNanos(1) * COLLISION_BUFFER; ++ // allow for this many duplicate ticks before overwriting measurements ++ private static final long COLLISION_BUFFER = 256L; ++ // only trim on updating once every N ++ private static final long TRIM_THRESHOLD = 256L; ++ private static final long CLEAR_BUFFER = TimeUnit.HOURS.toNanos(1) * COLLISION_BUFFER; + +- private final Clock clock; +- private final ChunkedAssociativeLongArray measurements; +- private final long window; +- private final AtomicLong lastTick; +- private final AtomicLong count; +- private final long startTick; ++ private final Clock clock; ++ private final ChunkedAssociativeLongArray measurements; ++ private final long window; ++ private final AtomicLong lastTick; ++ private final AtomicLong count; ++ private final long startTick; + +- /** +- * Creates a new {@link SlidingTimeWindowArrayReservoir} with the given window of time. +- * +- * @param window the window of time +- * @param windowUnit the unit of {@code window} +- */ +- public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit) { +- this(window, windowUnit, Clock.defaultClock()); +- } +- +- /** +- * Creates a new {@link SlidingTimeWindowArrayReservoir} with the given clock and window of time. +- * +- * @param window the window of time +- * @param windowUnit the unit of {@code window} +- * @param clock the {@link Clock} to use +- */ +- public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit, Clock clock) { +- this.startTick = clock.getTick(); +- this.clock = clock; +- this.measurements = new ChunkedAssociativeLongArray(); +- this.window = windowUnit.toNanos(window) * COLLISION_BUFFER; +- this.lastTick = new AtomicLong((clock.getTick() - startTick) * COLLISION_BUFFER); +- this.count = new AtomicLong(); +- } ++ /** ++ * Creates a new {@link SlidingTimeWindowArrayReservoir} with the given window of time. ++ * ++ * @param window the window of time ++ * @param windowUnit the unit of {@code window} ++ */ ++ public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit) { ++ this(window, windowUnit, Clock.defaultClock()); ++ } + +- @Override +- public int size() { +- trim(); +- return measurements.size(); +- } ++ /** ++ * Creates a new {@link SlidingTimeWindowArrayReservoir} with the given clock and window of time. ++ * ++ * @param window the window of time ++ * @param windowUnit the unit of {@code window} ++ * @param clock the {@link Clock} to use ++ */ ++ public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit, Clock clock) { ++ this.startTick = clock.getTick(); ++ this.clock = clock; ++ this.measurements = new ChunkedAssociativeLongArray(); ++ this.window = windowUnit.toNanos(window) * COLLISION_BUFFER; ++ this.lastTick = new AtomicLong((clock.getTick() - startTick) * COLLISION_BUFFER); ++ this.count = new AtomicLong(); ++ } + +- @Override +- public void update(long value) { +- long newTick; +- do { +- if (count.incrementAndGet() % TRIM_THRESHOLD == 0L) { +- trim(); +- } +- long lastTick = this.lastTick.get(); +- newTick = getTick(); +- boolean longOverflow = newTick < lastTick; +- if (longOverflow) { +- measurements.clear(); +- } +- } while (!measurements.put(newTick, value)); +- } ++ @Override ++ public int size() { ++ trim(); ++ return measurements.size(); ++ } + +- @Override +- public Snapshot getSnapshot() { ++ @Override ++ public void update(long value) { ++ long newTick; ++ do { ++ if (count.incrementAndGet() % TRIM_THRESHOLD == 0L) { + trim(); +- return new UniformSnapshot(measurements.values()); +- } ++ } ++ long lastTick = this.lastTick.get(); ++ newTick = getTick(); ++ boolean longOverflow = newTick < lastTick; ++ if (longOverflow) { ++ measurements.clear(); ++ } ++ } while (!measurements.put(newTick, value)); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ trim(); ++ return new UniformSnapshot(measurements.values()); ++ } + +- private long getTick() { +- for ( ;; ) { +- final long oldTick = lastTick.get(); +- final long tick = (clock.getTick() - startTick) * COLLISION_BUFFER; +- // ensure the tick is strictly incrementing even if there are duplicate ticks +- final long newTick = tick - oldTick > 0L ? tick : oldTick + 1L; +- if (lastTick.compareAndSet(oldTick, newTick)) { +- return newTick; +- } +- } ++ private long getTick() { ++ for (; ; ) { ++ final long oldTick = lastTick.get(); ++ final long tick = (clock.getTick() - startTick) * COLLISION_BUFFER; ++ // ensure the tick is strictly incrementing even if there are duplicate ticks ++ final long newTick = tick - oldTick > 0L ? tick : oldTick + 1L; ++ if (lastTick.compareAndSet(oldTick, newTick)) { ++ return newTick; ++ } + } ++ } + +- void trim() { +- final long now = getTick(); +- final long windowStart = now - window; +- final long windowEnd = now + CLEAR_BUFFER; +- if (windowStart < windowEnd) { +- measurements.trim(windowStart, windowEnd); +- } else { +- // long overflow handling that can happen only after 1 year after class loading +- measurements.clear(); +- } ++ void trim() { ++ final long now = getTick(); ++ final long windowStart = now - window; ++ final long windowEnd = now + CLEAR_BUFFER; ++ if (windowStart < windowEnd) { ++ measurements.trim(windowStart, windowEnd); ++ } else { ++ // long overflow handling that can happen only after 1 year after class loading ++ measurements.clear(); + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java +@@ -8,197 +8,189 @@ import java.util.concurrent.atomic.AtomicLong; + import java.util.concurrent.atomic.LongAdder; + + /** +- * A triple of simple moving average rates (one, five and fifteen minutes rates) as needed by {@link Meter}. +- *

+- * The averages are unweighted, i.e. they include strictly only the events in the +- * sliding time window, every event having the same weight. Unlike the +- * the more widely used {@link ExponentialMovingAverages} implementation, +- * with this class the moving average rate drops immediately to zero if the last +- * marked event is older than the time window. +- *

+- * A {@link Meter} with {@link SlidingTimeWindowMovingAverages} works similarly to +- * a {@link Histogram} with an {@link SlidingTimeWindowArrayReservoir}, but as a Meter +- * needs to keep track only of the count of events (not the events itself), the memory +- * overhead is much smaller. SlidingTimeWindowMovingAverages uses buckets with just one +- * counter to accumulate the number of events (one bucket per seconds, giving 900 buckets +- * for the 15 minutes time window). ++ * A triple of simple moving average rates (one, five and fifteen minutes rates) as needed by {@link ++ * Meter}. ++ * ++ *

The averages are unweighted, i.e. they include strictly only the events in the sliding time ++ * window, every event having the same weight. Unlike the the more widely used {@link ++ * ExponentialMovingAverages} implementation, with this class the moving average rate drops ++ * immediately to zero if the last marked event is older than the time window. ++ * ++ *

A {@link Meter} with {@link SlidingTimeWindowMovingAverages} works similarly to a {@link ++ * Histogram} with an {@link SlidingTimeWindowArrayReservoir}, but as a Meter needs to keep track ++ * only of the count of events (not the events itself), the memory overhead is much smaller. ++ * SlidingTimeWindowMovingAverages uses buckets with just one counter to accumulate the number of ++ * events (one bucket per seconds, giving 900 buckets for the 15 minutes time window). + */ + public class SlidingTimeWindowMovingAverages implements MovingAverages { + +- private static final long TIME_WINDOW_DURATION_MINUTES = 15; +- private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(1); +- private static final Duration TIME_WINDOW_DURATION = Duration.ofMinutes(TIME_WINDOW_DURATION_MINUTES); +- +- // package private for the benefit of the unit test +- static final int NUMBER_OF_BUCKETS = (int) (TIME_WINDOW_DURATION.toNanos() / TICK_INTERVAL); +- +- private final AtomicLong lastTick; +- private final Clock clock; +- private final LongAdder sum = new LongAdder(); +- +- /** +- * One counter per time bucket/slot (i.e. per second, see TICK_INTERVAL) for the entire +- * time window (i.e. 15 minutes, see TIME_WINDOW_DURATION_MINUTES) +- */ +- private ArrayList buckets; +- +- /** +- * Index into buckets, pointing at the bucket containing the oldest counts +- */ +- private int oldestBucketIndex; +- +- /** +- * Index into buckets, pointing at the bucket with the count for the current time (tick) +- */ +- private int currentBucketIndex; +- +- /** +- * Instant at creation time of the time window. Used to calculate the currentBucketIndex +- * for the instant of a given tick (instant modulo time window duration) +- */ +- private final Instant bucketBaseTime; +- +- /** +- * Instant of the bucket with index oldestBucketIndex +- */ +- Instant oldestBucketTime; +- +- /** +- * Creates a new {@link SlidingTimeWindowMovingAverages}. +- */ +- public SlidingTimeWindowMovingAverages() { +- this(Clock.defaultClock()); ++ private static final long TIME_WINDOW_DURATION_MINUTES = 15; ++ private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(1); ++ private static final Duration TIME_WINDOW_DURATION = ++ Duration.ofMinutes(TIME_WINDOW_DURATION_MINUTES); ++ ++ // package private for the benefit of the unit test ++ static final int NUMBER_OF_BUCKETS = (int) (TIME_WINDOW_DURATION.toNanos() / TICK_INTERVAL); ++ ++ private final AtomicLong lastTick; ++ private final Clock clock; ++ private final LongAdder sum = new LongAdder(); ++ ++ /** ++ * One counter per time bucket/slot (i.e. per second, see TICK_INTERVAL) for the entire time ++ * window (i.e. 15 minutes, see TIME_WINDOW_DURATION_MINUTES) ++ */ ++ private ArrayList buckets; ++ ++ /** Index into buckets, pointing at the bucket containing the oldest counts */ ++ private int oldestBucketIndex; ++ ++ /** Index into buckets, pointing at the bucket with the count for the current time (tick) */ ++ private int currentBucketIndex; ++ ++ /** ++ * Instant at creation time of the time window. Used to calculate the currentBucketIndex for the ++ * instant of a given tick (instant modulo time window duration) ++ */ ++ private final Instant bucketBaseTime; ++ ++ /** Instant of the bucket with index oldestBucketIndex */ ++ Instant oldestBucketTime; ++ ++ /** Creates a new {@link SlidingTimeWindowMovingAverages}. */ ++ public SlidingTimeWindowMovingAverages() { ++ this(Clock.defaultClock()); ++ } ++ ++ /** ++ * Creates a new {@link SlidingTimeWindowMovingAverages}. ++ * ++ * @param clock the clock to use for the meter ticks ++ */ ++ public SlidingTimeWindowMovingAverages(Clock clock) { ++ this.clock = clock; ++ final long startTime = clock.getTick(); ++ lastTick = new AtomicLong(startTime); ++ ++ buckets = new ArrayList<>(NUMBER_OF_BUCKETS); ++ for (int i = 0; i < NUMBER_OF_BUCKETS; i++) { ++ buckets.add(new LongAdder()); + } +- +- /** +- * Creates a new {@link SlidingTimeWindowMovingAverages}. +- * +- * @param clock the clock to use for the meter ticks +- */ +- public SlidingTimeWindowMovingAverages(Clock clock) { +- this.clock = clock; +- final long startTime = clock.getTick(); +- lastTick = new AtomicLong(startTime); +- +- buckets = new ArrayList<>(NUMBER_OF_BUCKETS); +- for (int i = 0; i < NUMBER_OF_BUCKETS; i++) { +- buckets.add(new LongAdder()); +- } +- bucketBaseTime = Instant.ofEpochSecond(0L, startTime); +- oldestBucketTime = bucketBaseTime; +- oldestBucketIndex = 0; +- currentBucketIndex = 0; +- } +- +- @Override +- public void update(long n) { +- buckets.get(currentBucketIndex).add(n); +- } +- +- @Override +- public void tickIfNecessary() { +- final long oldTick = lastTick.get(); +- final long newTick = clock.getTick(); +- final long age = newTick - oldTick; +- if (age >= TICK_INTERVAL) { +- // - the newTick doesn't fall into the same slot as the oldTick anymore +- // - newLastTick is the lower border time of the new currentBucketIndex slot +- final long newLastTick = newTick - age % TICK_INTERVAL; +- if (lastTick.compareAndSet(oldTick, newLastTick)) { +- sum.add(age); +- Instant currentInstant = Instant.ofEpochSecond(0L, newLastTick); +- currentBucketIndex = normalizeIndex(calculateIndexOfTick(currentInstant)); +- cleanOldBuckets(currentInstant); +- } +- } +- } +- +- @Override +- public double getM15Rate() { +- return getMinuteRate(15); +- } +- +- @Override +- public double getM5Rate() { +- return getMinuteRate(5); +- } +- +- @Override +- public double getM1Rate() { +- return getMinuteRate(1); +- } +- +- private double getMinuteRate(int minutes) { +- Instant now = Instant.ofEpochSecond(0L, lastTick.get()); +- return sumBuckets(now, (int) (TimeUnit.MINUTES.toNanos(minutes) / TICK_INTERVAL)); +- } +- +- int calculateIndexOfTick(Instant tickTime) { +- return (int) (Duration.between(bucketBaseTime, tickTime).toNanos() / TICK_INTERVAL); ++ bucketBaseTime = Instant.ofEpochSecond(0L, startTime); ++ oldestBucketTime = bucketBaseTime; ++ oldestBucketIndex = 0; ++ currentBucketIndex = 0; ++ } ++ ++ @Override ++ public void update(long n) { ++ buckets.get(currentBucketIndex).add(n); ++ } ++ ++ @Override ++ public void tickIfNecessary() { ++ final long oldTick = lastTick.get(); ++ final long newTick = clock.getTick(); ++ final long age = newTick - oldTick; ++ if (age >= TICK_INTERVAL) { ++ // - the newTick doesn't fall into the same slot as the oldTick anymore ++ // - newLastTick is the lower border time of the new currentBucketIndex slot ++ final long newLastTick = newTick - age % TICK_INTERVAL; ++ if (lastTick.compareAndSet(oldTick, newLastTick)) { ++ sum.add(age); ++ Instant currentInstant = Instant.ofEpochSecond(0L, newLastTick); ++ currentBucketIndex = normalizeIndex(calculateIndexOfTick(currentInstant)); ++ cleanOldBuckets(currentInstant); ++ } + } +- +- int normalizeIndex(int index) { +- int mod = index % NUMBER_OF_BUCKETS; +- return mod >= 0 ? mod : mod + NUMBER_OF_BUCKETS; ++ } ++ ++ @Override ++ public double getM15Rate() { ++ return getMinuteRate(15); ++ } ++ ++ @Override ++ public double getM5Rate() { ++ return getMinuteRate(5); ++ } ++ ++ @Override ++ public double getM1Rate() { ++ return getMinuteRate(1); ++ } ++ ++ private double getMinuteRate(int minutes) { ++ Instant now = Instant.ofEpochSecond(0L, lastTick.get()); ++ return sumBuckets(now, (int) (TimeUnit.MINUTES.toNanos(minutes) / TICK_INTERVAL)); ++ } ++ ++ int calculateIndexOfTick(Instant tickTime) { ++ return (int) (Duration.between(bucketBaseTime, tickTime).toNanos() / TICK_INTERVAL); ++ } ++ ++ int normalizeIndex(int index) { ++ int mod = index % NUMBER_OF_BUCKETS; ++ return mod >= 0 ? mod : mod + NUMBER_OF_BUCKETS; ++ } ++ ++ private void cleanOldBuckets(Instant currentTick) { ++ int newOldestIndex; ++ Instant oldestStillNeededTime = ++ currentTick.minus(TIME_WINDOW_DURATION).plusNanos(TICK_INTERVAL); ++ Instant youngestNotInWindow = oldestBucketTime.plus(TIME_WINDOW_DURATION); ++ if (oldestStillNeededTime.isAfter(youngestNotInWindow)) { ++ // there was no update() call for more than two whole TIME_WINDOW_DURATION ++ newOldestIndex = oldestBucketIndex; ++ oldestBucketTime = currentTick; ++ } else if (oldestStillNeededTime.isAfter(oldestBucketTime)) { ++ newOldestIndex = normalizeIndex(calculateIndexOfTick(oldestStillNeededTime)); ++ oldestBucketTime = oldestStillNeededTime; ++ } else { ++ return; + } + +- private void cleanOldBuckets(Instant currentTick) { +- int newOldestIndex; +- Instant oldestStillNeededTime = currentTick.minus(TIME_WINDOW_DURATION).plusNanos(TICK_INTERVAL); +- Instant youngestNotInWindow = oldestBucketTime.plus(TIME_WINDOW_DURATION); +- if (oldestStillNeededTime.isAfter(youngestNotInWindow)) { +- // there was no update() call for more than two whole TIME_WINDOW_DURATION +- newOldestIndex = oldestBucketIndex; +- oldestBucketTime = currentTick; +- } else if (oldestStillNeededTime.isAfter(oldestBucketTime)) { +- newOldestIndex = normalizeIndex(calculateIndexOfTick(oldestStillNeededTime)); +- oldestBucketTime = oldestStillNeededTime; +- } else { +- return; +- } +- +- cleanBucketRange(oldestBucketIndex, newOldestIndex); +- oldestBucketIndex = newOldestIndex; ++ cleanBucketRange(oldestBucketIndex, newOldestIndex); ++ oldestBucketIndex = newOldestIndex; ++ } ++ ++ private void cleanBucketRange(int fromIndex, int toIndex) { ++ if (fromIndex < toIndex) { ++ for (int i = fromIndex; i < toIndex; i++) { ++ buckets.get(i).reset(); ++ } ++ } else { ++ for (int i = fromIndex; i < NUMBER_OF_BUCKETS; i++) { ++ buckets.get(i).reset(); ++ } ++ for (int i = 0; i < toIndex; i++) { ++ buckets.get(i).reset(); ++ } + } +- +- private void cleanBucketRange(int fromIndex, int toIndex) { +- if (fromIndex < toIndex) { +- for (int i = fromIndex; i < toIndex; i++) { +- buckets.get(i).reset(); +- } +- } else { +- for (int i = fromIndex; i < NUMBER_OF_BUCKETS; i++) { +- buckets.get(i).reset(); +- } +- for (int i = 0; i < toIndex; i++) { +- buckets.get(i).reset(); +- } +- } ++ } ++ ++ private long sumBuckets(Instant toTime, int numberOfBuckets) { ++ ++ // increment toIndex to include the current bucket into the sum ++ int toIndex = normalizeIndex(calculateIndexOfTick(toTime) + 1); ++ int fromIndex = normalizeIndex(toIndex - numberOfBuckets); ++ LongAdder adder = new LongAdder(); ++ ++ if (fromIndex < toIndex) { ++ buckets.stream() ++ .skip(fromIndex) ++ .limit(toIndex - fromIndex) ++ .mapToLong(LongAdder::longValue) ++ .forEach(adder::add); ++ } else { ++ buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); ++ buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); + } ++ return adder.longValue(); ++ } + +- private long sumBuckets(Instant toTime, int numberOfBuckets) { +- +- // increment toIndex to include the current bucket into the sum +- int toIndex = normalizeIndex(calculateIndexOfTick(toTime) + 1); +- int fromIndex = normalizeIndex(toIndex - numberOfBuckets); +- LongAdder adder = new LongAdder(); +- +- if (fromIndex < toIndex) { +- buckets.stream() +- .skip(fromIndex) +- .limit(toIndex - fromIndex) +- .mapToLong(LongAdder::longValue) +- .forEach(adder::add); +- } else { +- buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); +- buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); +- } +- long retval = adder.longValue(); +- return retval; +- } +- +- @Override +- public long getSum() { +- return sum.sum(); +- } ++ @Override ++ public long getSum() { ++ return sum.sum(); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowReservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowReservoir.java +@@ -5,91 +5,91 @@ import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicLong; + + /** +- * A {@link Reservoir} implementation backed by a sliding window that stores only the measurements made +- * in the last {@code N} seconds (or other time unit). ++ * A {@link Reservoir} implementation backed by a sliding window that stores only the measurements ++ * made in the last {@code N} seconds (or other time unit). + */ + public class SlidingTimeWindowReservoir implements Reservoir { +- // allow for this many duplicate ticks before overwriting measurements +- private static final int COLLISION_BUFFER = 256; +- // only trim on updating once every N +- private static final int TRIM_THRESHOLD = 256; +- // offsets the front of the time window for the purposes of clearing the buffer in trim +- private static final long CLEAR_BUFFER = TimeUnit.HOURS.toNanos(1) * COLLISION_BUFFER; ++ // allow for this many duplicate ticks before overwriting measurements ++ private static final int COLLISION_BUFFER = 256; ++ // only trim on updating once every N ++ private static final int TRIM_THRESHOLD = 256; ++ // offsets the front of the time window for the purposes of clearing the buffer in trim ++ private static final long CLEAR_BUFFER = TimeUnit.HOURS.toNanos(1) * COLLISION_BUFFER; + +- private final Clock clock; +- private final ConcurrentSkipListMap measurements; +- private final long window; +- private final AtomicLong lastTick; +- private final AtomicLong count; +- private final long startTick; ++ private final Clock clock; ++ private final ConcurrentSkipListMap measurements; ++ private final long window; ++ private final AtomicLong lastTick; ++ private final AtomicLong count; ++ private final long startTick; + +- /** +- * Creates a new {@link SlidingTimeWindowReservoir} with the given window of time. +- * +- * @param window the window of time +- * @param windowUnit the unit of {@code window} +- */ +- public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit) { +- this(window, windowUnit, Clock.defaultClock()); +- } ++ /** ++ * Creates a new {@link SlidingTimeWindowReservoir} with the given window of time. ++ * ++ * @param window the window of time ++ * @param windowUnit the unit of {@code window} ++ */ ++ public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit) { ++ this(window, windowUnit, Clock.defaultClock()); ++ } + +- /** +- * Creates a new {@link SlidingTimeWindowReservoir} with the given clock and window of time. +- * +- * @param window the window of time +- * @param windowUnit the unit of {@code window} +- * @param clock the {@link Clock} to use +- */ +- public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) { +- this.startTick = clock.getTick(); +- this.clock = clock; +- this.measurements = new ConcurrentSkipListMap<>(); +- this.window = windowUnit.toNanos(window) * COLLISION_BUFFER; +- this.lastTick = new AtomicLong((clock.getTick() - startTick) * COLLISION_BUFFER); +- this.count = new AtomicLong(); +- } ++ /** ++ * Creates a new {@link SlidingTimeWindowReservoir} with the given clock and window of time. ++ * ++ * @param window the window of time ++ * @param windowUnit the unit of {@code window} ++ * @param clock the {@link Clock} to use ++ */ ++ public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) { ++ this.startTick = clock.getTick(); ++ this.clock = clock; ++ this.measurements = new ConcurrentSkipListMap<>(); ++ this.window = windowUnit.toNanos(window) * COLLISION_BUFFER; ++ this.lastTick = new AtomicLong((clock.getTick() - startTick) * COLLISION_BUFFER); ++ this.count = new AtomicLong(); ++ } + +- @Override +- public int size() { +- trim(); +- return measurements.size(); +- } ++ @Override ++ public int size() { ++ trim(); ++ return measurements.size(); ++ } + +- @Override +- public void update(long value) { +- if (count.incrementAndGet() % TRIM_THRESHOLD == 0) { +- trim(); +- } +- measurements.put(getTick(), value); ++ @Override ++ public void update(long value) { ++ if (count.incrementAndGet() % TRIM_THRESHOLD == 0) { ++ trim(); + } ++ measurements.put(getTick(), value); ++ } + +- @Override +- public Snapshot getSnapshot() { +- trim(); +- return new UniformSnapshot(measurements.values()); +- } ++ @Override ++ public Snapshot getSnapshot() { ++ trim(); ++ return new UniformSnapshot(measurements.values()); ++ } + +- private long getTick() { +- for ( ;; ) { +- final long oldTick = lastTick.get(); +- final long tick = (clock.getTick() - startTick) * COLLISION_BUFFER; +- // ensure the tick is strictly incrementing even if there are duplicate ticks +- final long newTick = tick - oldTick > 0 ? tick : oldTick + 1; +- if (lastTick.compareAndSet(oldTick, newTick)) { +- return newTick; +- } +- } ++ private long getTick() { ++ for (; ; ) { ++ final long oldTick = lastTick.get(); ++ final long tick = (clock.getTick() - startTick) * COLLISION_BUFFER; ++ // ensure the tick is strictly incrementing even if there are duplicate ticks ++ final long newTick = tick - oldTick > 0 ? tick : oldTick + 1; ++ if (lastTick.compareAndSet(oldTick, newTick)) { ++ return newTick; ++ } + } ++ } + +- private void trim() { +- final long now = getTick(); +- final long windowStart = now - window; +- final long windowEnd = now + CLEAR_BUFFER; +- if (windowStart < windowEnd) { +- measurements.headMap(windowStart).clear(); +- measurements.tailMap(windowEnd).clear(); +- } else { +- measurements.subMap(windowEnd, windowStart).clear(); +- } ++ private void trim() { ++ final long now = getTick(); ++ final long windowStart = now - window; ++ final long windowEnd = now + CLEAR_BUFFER; ++ if (windowStart < windowEnd) { ++ measurements.headMap(windowStart).clear(); ++ measurements.tailMap(windowEnd).clear(); ++ } else { ++ measurements.subMap(windowEnd, windowStart).clear(); + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingWindowReservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingWindowReservoir.java +@@ -7,37 +7,37 @@ import static java.lang.Math.min; + * measurements. + */ + public class SlidingWindowReservoir implements Reservoir { +- private final long[] measurements; +- private long count; ++ private final long[] measurements; ++ private long count; + +- /** +- * Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements. +- * +- * @param size the number of measurements to store +- */ +- public SlidingWindowReservoir(int size) { +- this.measurements = new long[size]; +- this.count = 0; +- } ++ /** ++ * Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements. ++ * ++ * @param size the number of measurements to store ++ */ ++ public SlidingWindowReservoir(int size) { ++ this.measurements = new long[size]; ++ this.count = 0; ++ } + +- @Override +- public synchronized int size() { +- return (int) min(count, measurements.length); +- } ++ @Override ++ public synchronized int size() { ++ return (int) min(count, measurements.length); ++ } + +- @Override +- public synchronized void update(long value) { +- measurements[(int) (count++ % measurements.length)] = value; +- } ++ @Override ++ public synchronized void update(long value) { ++ measurements[(int) (count++ % measurements.length)] = value; ++ } + +- @Override +- public Snapshot getSnapshot() { +- final long[] values = new long[size()]; +- for (int i = 0; i < values.length; i++) { +- synchronized (this) { +- values[i] = measurements[i]; +- } +- } +- return new UniformSnapshot(values); ++ @Override ++ public Snapshot getSnapshot() { ++ final long[] values = new long[size()]; ++ for (int i = 0; i < values.length; i++) { ++ synchronized (this) { ++ values[i] = measurements[i]; ++ } + } ++ return new UniformSnapshot(values); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Snapshot.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Snapshot.java +@@ -2,120 +2,117 @@ package io.dropwizard.metrics5; + + import java.io.OutputStream; + +-/** +- * A statistical snapshot of a {@link Snapshot}. +- */ ++/** A statistical snapshot of a {@link Snapshot}. */ + public abstract class Snapshot { + +- /** +- * Returns the value at the given quantile. +- * +- * @param quantile a given quantile, in {@code [0..1]} +- * @return the value in the distribution at {@code quantile} +- */ +- public abstract double getValue(double quantile); +- +- /** +- * Returns the entire set of values in the snapshot. +- * +- * @return the entire set of values +- */ +- public abstract long[] getValues(); +- +- /** +- * Returns the number of values in the snapshot. +- * +- * @return the number of values +- */ +- public abstract int size(); +- +- /** +- * Returns the median value in the distribution. +- * +- * @return the median value +- */ +- public double getMedian() { +- return getValue(0.5); +- } +- +- /** +- * Returns the value at the 75th percentile in the distribution. +- * +- * @return the value at the 75th percentile +- */ +- public double get75thPercentile() { +- return getValue(0.75); +- } +- +- /** +- * Returns the value at the 95th percentile in the distribution. +- * +- * @return the value at the 95th percentile +- */ +- public double get95thPercentile() { +- return getValue(0.95); +- } +- +- /** +- * Returns the value at the 98th percentile in the distribution. +- * +- * @return the value at the 98th percentile +- */ +- public double get98thPercentile() { +- return getValue(0.98); +- } +- +- /** +- * Returns the value at the 99th percentile in the distribution. +- * +- * @return the value at the 99th percentile +- */ +- public double get99thPercentile() { +- return getValue(0.99); +- } +- +- /** +- * Returns the value at the 99.9th percentile in the distribution. +- * +- * @return the value at the 99.9th percentile +- */ +- public double get999thPercentile() { +- return getValue(0.999); +- } +- +- /** +- * Returns the highest value in the snapshot. +- * +- * @return the highest value +- */ +- public abstract long getMax(); +- +- /** +- * Returns the arithmetic mean of the values in the snapshot. +- * +- * @return the arithmetic mean +- */ +- public abstract double getMean(); +- +- /** +- * Returns the lowest value in the snapshot. +- * +- * @return the lowest value +- */ +- public abstract long getMin(); +- +- /** +- * Returns the standard deviation of the values in the snapshot. +- * +- * @return the standard value +- */ +- public abstract double getStdDev(); +- +- /** +- * Writes the values of the snapshot to the given stream. +- * +- * @param output an output stream +- */ +- public abstract void dump(OutputStream output); +- ++ /** ++ * Returns the value at the given quantile. ++ * ++ * @param quantile a given quantile, in {@code [0..1]} ++ * @return the value in the distribution at {@code quantile} ++ */ ++ public abstract double getValue(double quantile); ++ ++ /** ++ * Returns the entire set of values in the snapshot. ++ * ++ * @return the entire set of values ++ */ ++ public abstract long[] getValues(); ++ ++ /** ++ * Returns the number of values in the snapshot. ++ * ++ * @return the number of values ++ */ ++ public abstract int size(); ++ ++ /** ++ * Returns the median value in the distribution. ++ * ++ * @return the median value ++ */ ++ public double getMedian() { ++ return getValue(0.5); ++ } ++ ++ /** ++ * Returns the value at the 75th percentile in the distribution. ++ * ++ * @return the value at the 75th percentile ++ */ ++ public double get75thPercentile() { ++ return getValue(0.75); ++ } ++ ++ /** ++ * Returns the value at the 95th percentile in the distribution. ++ * ++ * @return the value at the 95th percentile ++ */ ++ public double get95thPercentile() { ++ return getValue(0.95); ++ } ++ ++ /** ++ * Returns the value at the 98th percentile in the distribution. ++ * ++ * @return the value at the 98th percentile ++ */ ++ public double get98thPercentile() { ++ return getValue(0.98); ++ } ++ ++ /** ++ * Returns the value at the 99th percentile in the distribution. ++ * ++ * @return the value at the 99th percentile ++ */ ++ public double get99thPercentile() { ++ return getValue(0.99); ++ } ++ ++ /** ++ * Returns the value at the 99.9th percentile in the distribution. ++ * ++ * @return the value at the 99.9th percentile ++ */ ++ public double get999thPercentile() { ++ return getValue(0.999); ++ } ++ ++ /** ++ * Returns the highest value in the snapshot. ++ * ++ * @return the highest value ++ */ ++ public abstract long getMax(); ++ ++ /** ++ * Returns the arithmetic mean of the values in the snapshot. ++ * ++ * @return the arithmetic mean ++ */ ++ public abstract double getMean(); ++ ++ /** ++ * Returns the lowest value in the snapshot. ++ * ++ * @return the lowest value ++ */ ++ public abstract long getMin(); ++ ++ /** ++ * Returns the standard deviation of the values in the snapshot. ++ * ++ * @return the standard value ++ */ ++ public abstract double getStdDev(); ++ ++ /** ++ * Writes the values of the snapshot to the given stream. ++ * ++ * @param output an output stream ++ */ ++ public abstract void dump(OutputStream output); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Summing.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Summing.java +@@ -1,14 +1,12 @@ + package io.dropwizard.metrics5; + +-/** +- * An interface for metric types which aggregate a sum +- */ ++/** An interface for metric types which aggregate a sum */ + public interface Summing { + +- /** +- * Return the current sum. +- * +- * @return the current sum +- */ +- long getSum(); ++ /** ++ * Return the current sum. ++ * ++ * @return the current sum ++ */ ++ long getSum(); + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Timer.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Timer.java +@@ -10,199 +10,197 @@ import java.util.function.Supplier; + * throughput statistics via {@link Meter}. + */ + public class Timer implements Metered, Sampling { +- /** +- * A timing context. +- * +- * @see Timer#time() +- */ +- public static class Context implements AutoCloseable { +- private final Timer timer; +- private final Clock clock; +- private final long startTime; +- +- Context(Timer timer, Clock clock) { +- this.timer = timer; +- this.clock = clock; +- this.startTime = clock.getTick(); +- } +- +- /** +- * Updates the timer with the difference between current and start time. Call to this method will +- * not reset the start time. Multiple calls result in multiple updates. +- * +- * @return the elapsed time in nanoseconds +- */ +- public long stop() { +- final long elapsed = clock.getTick() - startTime; +- timer.update(elapsed, TimeUnit.NANOSECONDS); +- return elapsed; +- } +- +- /** +- * Equivalent to calling {@link #stop()}. +- */ +- @Override +- public void close() { +- stop(); +- } +- } +- +- private final Meter meter; +- private final Histogram histogram; ++ /** ++ * A timing context. ++ * ++ * @see Timer#time() ++ */ ++ public static class Context implements AutoCloseable { ++ private final Timer timer; + private final Clock clock; ++ private final long startTime; + +- /** +- * Creates a new {@link Timer} using an {@link ExponentiallyDecayingReservoir} and the default +- * {@link Clock}. +- */ +- public Timer() { +- this(new ExponentiallyDecayingReservoir()); ++ Context(Timer timer, Clock clock) { ++ this.timer = timer; ++ this.clock = clock; ++ this.startTime = clock.getTick(); + } + + /** +- * Creates a new {@link Timer} that uses the given {@link Reservoir}. ++ * Updates the timer with the difference between current and start time. Call to this method ++ * will not reset the start time. Multiple calls result in multiple updates. + * +- * @param reservoir the {@link Reservoir} implementation the timer should use ++ * @return the elapsed time in nanoseconds + */ +- public Timer(Reservoir reservoir) { +- this(reservoir, Clock.defaultClock()); +- } +- +- /** +- * Creates a new {@link Timer} that uses the given {@link Reservoir} and {@link Clock}. +- * +- * @param reservoir the {@link Reservoir} implementation the timer should use +- * @param clock the {@link Clock} implementation the timer should use +- */ +- public Timer(Reservoir reservoir, Clock clock) { +- this(new Meter(clock), new Histogram(reservoir), clock); +- } +- +- public Timer(Meter meter, Histogram histogram, Clock clock) { +- this.meter = meter; +- this.histogram = histogram; +- this.clock = clock; +- } +- +- /** +- * Adds a recorded duration. +- * +- * @param duration the length of the duration +- * @param unit the scale unit of {@code duration} +- */ +- public void update(long duration, TimeUnit unit) { +- update(unit.toNanos(duration)); +- } +- +- /** +- * Adds a recorded duration. +- * +- * @param duration the {@link Duration} to add to the timer. Negative or zero value are ignored. +- */ +- public void update(Duration duration) { +- update(duration.toNanos()); +- } +- +- /** +- * Times and records the duration of event. +- * +- * @param event a {@link Callable} whose {@link Callable#call()} method implements a process +- * whose duration should be timed +- * @param the type of the value returned by {@code event} +- * @return the value returned by {@code event} +- * @throws Exception if {@code event} throws an {@link Exception} +- */ +- public T time(Callable event) throws Exception { +- final long startTime = clock.getTick(); +- try { +- return event.call(); +- } finally { +- update(clock.getTick() - startTime); +- } +- } +- +- /** +- * Times and records the duration of event. Should not throw exceptions, for that use the +- * {@link #time(Callable)} method. +- * +- * @param event a {@link Supplier} whose {@link Supplier#get()} method implements a process +- * whose duration should be timed +- * @param the type of the value returned by {@code event} +- * @return the value returned by {@code event} +- */ +- public T timeSupplier(Supplier event) { +- final long startTime = clock.getTick(); +- try { +- return event.get(); +- } finally { +- update(clock.getTick() - startTime); +- } +- } +- +- /** +- * Times and records the duration of event. +- * +- * @param event a {@link Runnable} whose {@link Runnable#run()} method implements a process +- * whose duration should be timed +- */ +- public void time(Runnable event) { +- final long startTime = clock.getTick(); +- try { +- event.run(); +- } finally { +- update(clock.getTick() - startTime); +- } +- } +- +- /** +- * Returns a new {@link Context}. +- * +- * @return a new {@link Context} +- * @see Context +- */ +- public Context time() { +- return new Context(this, clock); +- } +- +- @Override +- public long getCount() { +- return histogram.getCount(); +- } +- +- @Override +- public long getSum() { +- return histogram.getSum(); +- } +- +- @Override +- public double getFifteenMinuteRate() { +- return meter.getFifteenMinuteRate(); +- } +- +- @Override +- public double getFiveMinuteRate() { +- return meter.getFiveMinuteRate(); +- } +- +- @Override +- public double getMeanRate() { +- return meter.getMeanRate(); +- } +- +- @Override +- public double getOneMinuteRate() { +- return meter.getOneMinuteRate(); ++ public long stop() { ++ final long elapsed = clock.getTick() - startTime; ++ timer.update(elapsed, TimeUnit.NANOSECONDS); ++ return elapsed; + } + ++ /** Equivalent to calling {@link #stop()}. */ + @Override +- public Snapshot getSnapshot() { +- return histogram.getSnapshot(); +- } +- +- private void update(long duration) { +- if (duration >= 0) { +- histogram.update(duration); +- meter.mark(); +- } +- } ++ public void close() { ++ stop(); ++ } ++ } ++ ++ private final Meter meter; ++ private final Histogram histogram; ++ private final Clock clock; ++ ++ /** ++ * Creates a new {@link Timer} using an {@link ExponentiallyDecayingReservoir} and the default ++ * {@link Clock}. ++ */ ++ public Timer() { ++ this(new ExponentiallyDecayingReservoir()); ++ } ++ ++ /** ++ * Creates a new {@link Timer} that uses the given {@link Reservoir}. ++ * ++ * @param reservoir the {@link Reservoir} implementation the timer should use ++ */ ++ public Timer(Reservoir reservoir) { ++ this(reservoir, Clock.defaultClock()); ++ } ++ ++ /** ++ * Creates a new {@link Timer} that uses the given {@link Reservoir} and {@link Clock}. ++ * ++ * @param reservoir the {@link Reservoir} implementation the timer should use ++ * @param clock the {@link Clock} implementation the timer should use ++ */ ++ public Timer(Reservoir reservoir, Clock clock) { ++ this(new Meter(clock), new Histogram(reservoir), clock); ++ } ++ ++ public Timer(Meter meter, Histogram histogram, Clock clock) { ++ this.meter = meter; ++ this.histogram = histogram; ++ this.clock = clock; ++ } ++ ++ /** ++ * Adds a recorded duration. ++ * ++ * @param duration the length of the duration ++ * @param unit the scale unit of {@code duration} ++ */ ++ public void update(long duration, TimeUnit unit) { ++ update(unit.toNanos(duration)); ++ } ++ ++ /** ++ * Adds a recorded duration. ++ * ++ * @param duration the {@link Duration} to add to the timer. Negative or zero value are ignored. ++ */ ++ public void update(Duration duration) { ++ update(duration.toNanos()); ++ } ++ ++ /** ++ * Times and records the duration of event. ++ * ++ * @param event a {@link Callable} whose {@link Callable#call()} method implements a process whose ++ * duration should be timed ++ * @param the type of the value returned by {@code event} ++ * @return the value returned by {@code event} ++ * @throws Exception if {@code event} throws an {@link Exception} ++ */ ++ public T time(Callable event) throws Exception { ++ final long startTime = clock.getTick(); ++ try { ++ return event.call(); ++ } finally { ++ update(clock.getTick() - startTime); ++ } ++ } ++ ++ /** ++ * Times and records the duration of event. Should not throw exceptions, for that use the {@link ++ * #time(Callable)} method. ++ * ++ * @param event a {@link Supplier} whose {@link Supplier#get()} method implements a process whose ++ * duration should be timed ++ * @param the type of the value returned by {@code event} ++ * @return the value returned by {@code event} ++ */ ++ public T timeSupplier(Supplier event) { ++ final long startTime = clock.getTick(); ++ try { ++ return event.get(); ++ } finally { ++ update(clock.getTick() - startTime); ++ } ++ } ++ ++ /** ++ * Times and records the duration of event. ++ * ++ * @param event a {@link Runnable} whose {@link Runnable#run()} method implements a process whose ++ * duration should be timed ++ */ ++ public void time(Runnable event) { ++ final long startTime = clock.getTick(); ++ try { ++ event.run(); ++ } finally { ++ update(clock.getTick() - startTime); ++ } ++ } ++ ++ /** ++ * Returns a new {@link Context}. ++ * ++ * @return a new {@link Context} ++ * @see Context ++ */ ++ public Context time() { ++ return new Context(this, clock); ++ } ++ ++ @Override ++ public long getCount() { ++ return histogram.getCount(); ++ } ++ ++ @Override ++ public long getSum() { ++ return histogram.getSum(); ++ } ++ ++ @Override ++ public double getFifteenMinuteRate() { ++ return meter.getFifteenMinuteRate(); ++ } ++ ++ @Override ++ public double getFiveMinuteRate() { ++ return meter.getFiveMinuteRate(); ++ } ++ ++ @Override ++ public double getMeanRate() { ++ return meter.getMeanRate(); ++ } ++ ++ @Override ++ public double getOneMinuteRate() { ++ return meter.getOneMinuteRate(); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ return histogram.getSnapshot(); ++ } ++ ++ private void update(long duration) { ++ if (duration >= 0) { ++ histogram.update(duration); ++ meter.mark(); ++ } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformReservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformReservoir.java +@@ -11,60 +11,60 @@ import java.util.concurrent.atomic.AtomicLongArray; + * @see Random Sampling with a Reservoir + */ + public class UniformReservoir implements Reservoir { +- private static final int DEFAULT_SIZE = 1028; +- private final AtomicLong count = new AtomicLong(); +- private final AtomicLongArray values; ++ private static final int DEFAULT_SIZE = 1028; ++ private final AtomicLong count = new AtomicLong(); ++ private final AtomicLongArray values; + +- /** +- * Creates a new {@link UniformReservoir} of 1028 elements, which offers a 99.9% confidence level +- * with a 5% margin of error assuming a normal distribution. +- */ +- public UniformReservoir() { +- this(DEFAULT_SIZE); +- } ++ /** ++ * Creates a new {@link UniformReservoir} of 1028 elements, which offers a 99.9% confidence level ++ * with a 5% margin of error assuming a normal distribution. ++ */ ++ public UniformReservoir() { ++ this(DEFAULT_SIZE); ++ } + +- /** +- * Creates a new {@link UniformReservoir}. +- * +- * @param size the number of samples to keep in the sampling reservoir +- */ +- public UniformReservoir(int size) { +- this.values = new AtomicLongArray(size); +- for (int i = 0; i < values.length(); i++) { +- values.set(i, 0); +- } +- count.set(0); ++ /** ++ * Creates a new {@link UniformReservoir}. ++ * ++ * @param size the number of samples to keep in the sampling reservoir ++ */ ++ public UniformReservoir(int size) { ++ this.values = new AtomicLongArray(size); ++ for (int i = 0; i < values.length(); i++) { ++ values.set(i, 0); + } ++ count.set(0); ++ } + +- @Override +- public int size() { +- final long c = count.get(); +- if (c > values.length()) { +- return values.length(); +- } +- return (int) c; ++ @Override ++ public int size() { ++ final long c = count.get(); ++ if (c > values.length()) { ++ return values.length(); + } ++ return (int) c; ++ } + +- @Override +- public void update(long value) { +- final long c = count.incrementAndGet(); +- if (c <= values.length()) { +- values.set((int) c - 1, value); +- } else { +- final long r = ThreadLocalRandom.current().nextLong(c); +- if (r < values.length()) { +- values.set((int) r, value); +- } +- } ++ @Override ++ public void update(long value) { ++ final long c = count.incrementAndGet(); ++ if (c <= values.length()) { ++ values.set((int) c - 1, value); ++ } else { ++ final long r = ThreadLocalRandom.current().nextLong(c); ++ if (r < values.length()) { ++ values.set((int) r, value); ++ } + } ++ } + +- @Override +- public Snapshot getSnapshot() { +- final int s = size(); +- long[] copy = new long[s]; +- for (int i = 0; i < s; i++) { +- copy[i] = values.get(i); +- } +- return new UniformSnapshot(copy); ++ @Override ++ public Snapshot getSnapshot() { ++ final int s = size(); ++ long[] copy = new long[s]; ++ for (int i = 0; i < s; i++) { ++ copy[i] = values.get(i); + } ++ return new UniformSnapshot(copy); ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java +@@ -1,177 +1,178 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.lang.Math.floor; ++import static java.nio.charset.StandardCharsets.UTF_8; ++ + import java.io.OutputStream; + import java.io.OutputStreamWriter; + import java.io.PrintWriter; + import java.util.Arrays; + import java.util.Collection; + +-import static java.lang.Math.floor; +-import static java.nio.charset.StandardCharsets.UTF_8; +- +-/** +- * A statistical snapshot of a {@link UniformSnapshot}. +- */ ++/** A statistical snapshot of a {@link UniformSnapshot}. */ + public class UniformSnapshot extends Snapshot { + +- private final long[] values; +- +- /** +- * Create a new {@link Snapshot} with the given values. +- * +- * @param values an unordered set of values in the reservoir +- */ +- public UniformSnapshot(Collection values) { +- final Object[] copy = values.toArray(); +- this.values = new long[copy.length]; +- for (int i = 0; i < copy.length; i++) { +- this.values[i] = (Long) copy[i]; +- } +- Arrays.sort(this.values); ++ private final long[] values; ++ ++ /** ++ * Create a new {@link Snapshot} with the given values. ++ * ++ * @param values an unordered set of values in the reservoir ++ */ ++ public UniformSnapshot(Collection values) { ++ final Object[] copy = values.toArray(); ++ this.values = new long[copy.length]; ++ for (int i = 0; i < copy.length; i++) { ++ this.values[i] = (Long) copy[i]; + } +- +- /** +- * Create a new {@link Snapshot} with the given values. +- * +- * @param values an unordered set of values in the reservoir that can be used by this class directly +- */ +- public UniformSnapshot(long[] values) { +- this.values = Arrays.copyOf(values, values.length); +- Arrays.sort(this.values); ++ Arrays.sort(this.values); ++ } ++ ++ /** ++ * Create a new {@link Snapshot} with the given values. ++ * ++ * @param values an unordered set of values in the reservoir that can be used by this class ++ * directly ++ */ ++ public UniformSnapshot(long[] values) { ++ this.values = Arrays.copyOf(values, values.length); ++ Arrays.sort(this.values); ++ } ++ ++ /** ++ * Returns the value at the given quantile. ++ * ++ * @param quantile a given quantile, in {@code [0..1]} ++ * @return the value in the distribution at {@code quantile} ++ */ ++ @Override ++ public double getValue(double quantile) { ++ checkArgument( ++ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), ++ "%s is not in [0..1]", ++ quantile); ++ ++ if (values.length == 0) { ++ return 0.0; + } + +- /** +- * Returns the value at the given quantile. +- * +- * @param quantile a given quantile, in {@code [0..1]} +- * @return the value in the distribution at {@code quantile} +- */ +- @Override +- public double getValue(double quantile) { +- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { +- throw new IllegalArgumentException(quantile + " is not in [0..1]"); +- } +- +- if (values.length == 0) { +- return 0.0; +- } +- +- final double pos = quantile * (values.length + 1); +- final int index = (int) pos; +- +- if (index < 1) { +- return values[0]; +- } +- +- if (index >= values.length) { +- return values[values.length - 1]; +- } +- +- final double lower = values[index - 1]; +- final double upper = values[index]; +- return lower + (pos - floor(pos)) * (upper - lower); +- } ++ final double pos = quantile * (values.length + 1); ++ final int index = (int) pos; + +- /** +- * Returns the number of values in the snapshot. +- * +- * @return the number of values +- */ +- @Override +- public int size() { +- return values.length; ++ if (index < 1) { ++ return values[0]; + } + +- /** +- * Returns the entire set of values in the snapshot. +- * +- * @return the entire set of values +- */ +- @Override +- public long[] getValues() { +- return Arrays.copyOf(values, values.length); ++ if (index >= values.length) { ++ return values[values.length - 1]; + } + +- /** +- * Returns the highest value in the snapshot. +- * +- * @return the highest value +- */ +- @Override +- public long getMax() { +- if (values.length == 0) { +- return 0; +- } +- return values[values.length - 1]; ++ final double lower = values[index - 1]; ++ final double upper = values[index]; ++ return lower + (pos - floor(pos)) * (upper - lower); ++ } ++ ++ /** ++ * Returns the number of values in the snapshot. ++ * ++ * @return the number of values ++ */ ++ @Override ++ public int size() { ++ return values.length; ++ } ++ ++ /** ++ * Returns the entire set of values in the snapshot. ++ * ++ * @return the entire set of values ++ */ ++ @Override ++ public long[] getValues() { ++ return Arrays.copyOf(values, values.length); ++ } ++ ++ /** ++ * Returns the highest value in the snapshot. ++ * ++ * @return the highest value ++ */ ++ @Override ++ public long getMax() { ++ if (values.length == 0) { ++ return 0; + } +- +- /** +- * Returns the lowest value in the snapshot. +- * +- * @return the lowest value +- */ +- @Override +- public long getMin() { +- if (values.length == 0) { +- return 0; +- } +- return values[0]; ++ return values[values.length - 1]; ++ } ++ ++ /** ++ * Returns the lowest value in the snapshot. ++ * ++ * @return the lowest value ++ */ ++ @Override ++ public long getMin() { ++ if (values.length == 0) { ++ return 0; ++ } ++ return values[0]; ++ } ++ ++ /** ++ * Returns the arithmetic mean of the values in the snapshot. ++ * ++ * @return the arithmetic mean ++ */ ++ @Override ++ public double getMean() { ++ if (values.length == 0) { ++ return 0; + } + +- /** +- * Returns the arithmetic mean of the values in the snapshot. +- * +- * @return the arithmetic mean +- */ +- @Override +- public double getMean() { +- if (values.length == 0) { +- return 0; +- } +- +- double sum = 0; +- for (long value : values) { +- sum += value; +- } +- return sum / values.length; ++ double sum = 0; ++ for (long value : values) { ++ sum += value; ++ } ++ return sum / values.length; ++ } ++ ++ /** ++ * Returns the standard deviation of the values in the snapshot. ++ * ++ * @return the standard deviation value ++ */ ++ @Override ++ public double getStdDev() { ++ // two-pass algorithm for variance, avoids numeric overflow ++ ++ if (values.length <= 1) { ++ return 0; + } + +- /** +- * Returns the standard deviation of the values in the snapshot. +- * +- * @return the standard deviation value +- */ +- @Override +- public double getStdDev() { +- // two-pass algorithm for variance, avoids numeric overflow +- +- if (values.length <= 1) { +- return 0; +- } +- +- final double mean = getMean(); +- double sum = 0; +- +- for (long value : values) { +- final double diff = value - mean; +- sum += diff * diff; +- } +- +- final double variance = sum / (values.length - 1); +- return Math.sqrt(variance); ++ final double mean = getMean(); ++ double sum = 0; ++ ++ for (long value : values) { ++ final double diff = value - mean; ++ sum += diff * diff; + } + +- /** +- * Writes the values of the snapshot to the given stream. +- * +- * @param output an output stream +- */ +- @Override +- public void dump(OutputStream output) { +- try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { +- for (long value : values) { +- out.printf("%d%n", value); +- } +- } ++ final double variance = sum / (values.length - 1); ++ return Math.sqrt(variance); ++ } ++ ++ /** ++ * Writes the values of the snapshot to the given stream. ++ * ++ * @param output an output stream ++ */ ++ @Override ++ public void dump(OutputStream output) { ++ try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { ++ for (long value : values) { ++ out.printf("%d%n", value); ++ } + } ++ } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java +@@ -1,195 +1,192 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.nio.charset.StandardCharsets.UTF_8; ++import static java.util.Comparator.comparingLong; ++ + import java.io.OutputStream; + import java.io.OutputStreamWriter; + import java.io.PrintWriter; + import java.util.Arrays; + import java.util.Collection; +-import java.util.Comparator; + +-import static java.nio.charset.StandardCharsets.UTF_8; +- +-/** +- * A statistical snapshot of a {@link WeightedSnapshot}. +- */ ++/** A statistical snapshot of a {@link WeightedSnapshot}. */ + public class WeightedSnapshot extends Snapshot { + +- /** +- * A single sample item with value and its weights for {@link WeightedSnapshot}. +- */ +- public static class WeightedSample { +- public final long value; +- public final double weight; +- +- public WeightedSample(long value, double weight) { +- this.value = value; +- this.weight = weight; +- } +- } ++ /** A single sample item with value and its weights for {@link WeightedSnapshot}. */ ++ public static class WeightedSample { ++ public final long value; ++ public final double weight; + +- private final long[] values; +- private final double[] normWeights; +- private final double[] quantiles; +- +- /** +- * Create a new {@link Snapshot} with the given values. +- * +- * @param values an unordered set of values in the reservoir +- */ +- public WeightedSnapshot(Collection values) { +- final WeightedSample[] copy = values.toArray(new WeightedSample[]{}); +- +- Arrays.sort(copy, Comparator.comparingLong(w -> w.value)); +- +- this.values = new long[copy.length]; +- this.normWeights = new double[copy.length]; +- this.quantiles = new double[copy.length]; +- +- double sumWeight = 0; +- for (WeightedSample sample : copy) { +- sumWeight += sample.weight; +- } +- +- for (int i = 0; i < copy.length; i++) { +- this.values[i] = copy[i].value; +- this.normWeights[i] = sumWeight != 0 ? copy[i].weight / sumWeight : 0; +- } +- +- for (int i = 1; i < copy.length; i++) { +- this.quantiles[i] = this.quantiles[i - 1] + this.normWeights[i - 1]; +- } ++ public WeightedSample(long value, double weight) { ++ this.value = value; ++ this.weight = weight; + } ++ } + +- /** +- * Returns the value at the given quantile. +- * +- * @param quantile a given quantile, in {@code [0..1]} +- * @return the value in the distribution at {@code quantile} +- */ +- @Override +- public double getValue(double quantile) { +- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { +- throw new IllegalArgumentException(quantile + " is not in [0..1]"); +- } +- +- if (values.length == 0) { +- return 0.0; +- } +- +- int posx = Arrays.binarySearch(quantiles, quantile); +- if (posx < 0) +- posx = ((-posx) - 1) - 1; +- +- if (posx < 1) { +- return values[0]; +- } +- +- if (posx >= values.length) { +- return values[values.length - 1]; +- } +- +- return values[posx]; +- } ++ private final long[] values; ++ private final double[] normWeights; ++ private final double[] quantiles; + +- /** +- * Returns the number of values in the snapshot. +- * +- * @return the number of values +- */ +- @Override +- public int size() { +- return values.length; +- } ++ /** ++ * Create a new {@link Snapshot} with the given values. ++ * ++ * @param values an unordered set of values in the reservoir ++ */ ++ public WeightedSnapshot(Collection values) { ++ final WeightedSample[] copy = values.toArray(new WeightedSample[] {}); ++ ++ Arrays.sort(copy, comparingLong(w -> w.value)); ++ ++ this.values = new long[copy.length]; ++ this.normWeights = new double[copy.length]; ++ this.quantiles = new double[copy.length]; + +- /** +- * Returns the entire set of values in the snapshot. +- * +- * @return the entire set of values +- */ +- @Override +- public long[] getValues() { +- return Arrays.copyOf(values, values.length); ++ double sumWeight = 0; ++ for (WeightedSample sample : copy) { ++ sumWeight += sample.weight; + } + +- /** +- * Returns the highest value in the snapshot. +- * +- * @return the highest value +- */ +- @Override +- public long getMax() { +- if (values.length == 0) { +- return 0; +- } +- return values[values.length - 1]; ++ for (int i = 0; i < copy.length; i++) { ++ this.values[i] = copy[i].value; ++ this.normWeights[i] = sumWeight != 0 ? copy[i].weight / sumWeight : 0; + } + +- /** +- * Returns the lowest value in the snapshot. +- * +- * @return the lowest value +- */ +- @Override +- public long getMin() { +- if (values.length == 0) { +- return 0; +- } +- return values[0]; ++ for (int i = 1; i < copy.length; i++) { ++ this.quantiles[i] = this.quantiles[i - 1] + this.normWeights[i - 1]; + } ++ } ++ ++ /** ++ * Returns the value at the given quantile. ++ * ++ * @param quantile a given quantile, in {@code [0..1]} ++ * @return the value in the distribution at {@code quantile} ++ */ ++ @Override ++ public double getValue(double quantile) { ++ checkArgument( ++ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), ++ "%s is not in [0..1]", ++ quantile); ++ ++ if (values.length == 0) { ++ return 0.0; ++ } ++ ++ int posx = Arrays.binarySearch(quantiles, quantile); ++ if (posx < 0) posx = ((-posx) - 1) - 1; + +- /** +- * Returns the weighted arithmetic mean of the values in the snapshot. +- * +- * @return the weighted arithmetic mean +- */ +- @Override +- public double getMean() { +- if (values.length == 0) { +- return 0; +- } +- +- double sum = 0; +- for (int i = 0; i < values.length; i++) { +- sum += values[i] * normWeights[i]; +- } +- return sum; ++ if (posx < 1) { ++ return values[0]; + } + +- /** +- * Returns the weighted standard deviation of the values in the snapshot. +- * +- * @return the weighted standard deviation value +- */ +- @Override +- public double getStdDev() { +- // two-pass algorithm for variance, avoids numeric overflow ++ if (posx >= values.length) { ++ return values[values.length - 1]; ++ } + +- if (values.length <= 1) { +- return 0; +- } ++ return values[posx]; ++ } ++ ++ /** ++ * Returns the number of values in the snapshot. ++ * ++ * @return the number of values ++ */ ++ @Override ++ public int size() { ++ return values.length; ++ } ++ ++ /** ++ * Returns the entire set of values in the snapshot. ++ * ++ * @return the entire set of values ++ */ ++ @Override ++ public long[] getValues() { ++ return Arrays.copyOf(values, values.length); ++ } ++ ++ /** ++ * Returns the highest value in the snapshot. ++ * ++ * @return the highest value ++ */ ++ @Override ++ public long getMax() { ++ if (values.length == 0) { ++ return 0; ++ } ++ return values[values.length - 1]; ++ } ++ ++ /** ++ * Returns the lowest value in the snapshot. ++ * ++ * @return the lowest value ++ */ ++ @Override ++ public long getMin() { ++ if (values.length == 0) { ++ return 0; ++ } ++ return values[0]; ++ } ++ ++ /** ++ * Returns the weighted arithmetic mean of the values in the snapshot. ++ * ++ * @return the weighted arithmetic mean ++ */ ++ @Override ++ public double getMean() { ++ if (values.length == 0) { ++ return 0; ++ } + +- final double mean = getMean(); +- double variance = 0; ++ double sum = 0; ++ for (int i = 0; i < values.length; i++) { ++ sum += values[i] * normWeights[i]; ++ } ++ return sum; ++ } ++ ++ /** ++ * Returns the weighted standard deviation of the values in the snapshot. ++ * ++ * @return the weighted standard deviation value ++ */ ++ @Override ++ public double getStdDev() { ++ // two-pass algorithm for variance, avoids numeric overflow ++ ++ if (values.length <= 1) { ++ return 0; ++ } + +- for (int i = 0; i < values.length; i++) { +- final double diff = values[i] - mean; +- variance += normWeights[i] * diff * diff; +- } ++ final double mean = getMean(); ++ double variance = 0; + +- return Math.sqrt(variance); ++ for (int i = 0; i < values.length; i++) { ++ final double diff = values[i] - mean; ++ variance += normWeights[i] * diff * diff; + } + +- /** +- * Writes the values of the snapshot to the given stream. +- * +- * @param output an output stream +- */ +- @Override +- public void dump(OutputStream output) { +- try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { +- for (long value : values) { +- out.printf("%d%n", value); +- } +- } ++ return Math.sqrt(variance); ++ } ++ ++ /** ++ * Writes the values of the snapshot to the given stream. ++ * ++ * @param output an output stream ++ */ ++ @Override ++ public void dump(OutputStream output) { ++ try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { ++ for (long value : values) { ++ out.printf("%d%n", value); ++ } + } ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java +@@ -1,8 +1,6 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.util.ArrayList; + import java.util.List; +@@ -12,120 +10,120 @@ import java.util.concurrent.Future; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicInteger; + import java.util.concurrent.atomic.AtomicLong; ++import org.junit.jupiter.api.Test; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertTrue; +- +-class CachedGaugeTest { +- private static final Logger LOGGER = LoggerFactory.getLogger(CachedGaugeTest.class); +- private static final int THREAD_COUNT = 10; +- private static final long RUNNING_TIME_MILLIS = TimeUnit.SECONDS.toMillis(10); ++final class CachedGaugeTest { ++ private static final Logger LOG = LoggerFactory.getLogger(CachedGaugeTest.class); ++ private static final int THREAD_COUNT = 10; ++ private static final long RUNNING_TIME_MILLIS = TimeUnit.SECONDS.toMillis(10); + +- private final AtomicInteger value = new AtomicInteger(0); +- private final Gauge gauge = new CachedGauge(100, TimeUnit.MILLISECONDS) { ++ private final AtomicInteger value = new AtomicInteger(0); ++ private final Gauge gauge = ++ new CachedGauge(100, TimeUnit.MILLISECONDS) { + @Override + protected Integer loadValue() { +- return value.incrementAndGet(); ++ return value.incrementAndGet(); + } +- }; +- private final Gauge shortTimeoutGauge = new CachedGauge(1, TimeUnit.MILLISECONDS) { ++ }; ++ private final Gauge shortTimeoutGauge = ++ new CachedGauge(1, TimeUnit.MILLISECONDS) { + @Override + protected Integer loadValue() { +- try { +- Thread.sleep(5); +- } catch (InterruptedException e) { +- throw new RuntimeException("Thread was interrupted", e); +- } +- return value.incrementAndGet(); ++ try { ++ Thread.sleep(5); ++ } catch (InterruptedException e) { ++ throw new RuntimeException("Thread was interrupted", e); ++ } ++ return value.incrementAndGet(); + } +- }; +- private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); +- +- @Test +- void cachesTheValueForTheGivenPeriod() { +- assertThat(gauge.getValue()) +- .isEqualTo(1); +- assertThat(gauge.getValue()) +- .isEqualTo(1); +- } +- +- @Test +- void reloadsTheCachedValueAfterTheGivenPeriod() throws Exception { +- assertThat(gauge.getValue()) +- .isEqualTo(1); +- +- Thread.sleep(150); +- +- assertThat(gauge.getValue()) +- .isEqualTo(2); +- +- assertThat(gauge.getValue()) +- .isEqualTo(2); +- } +- +- @Test +- void reloadsCachedValueInNegativeTime() throws Exception { +- AtomicLong time = new AtomicLong(-2L); +- Clock clock = new Clock() { +- @Override +- public long getTick() { +- return time.get(); +- } ++ }; ++ private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); ++ ++ @Test ++ void cachesTheValueForTheGivenPeriod() { ++ assertThat(gauge.getValue()).isEqualTo(1); ++ assertThat(gauge.getValue()).isEqualTo(1); ++ } ++ ++ @Test ++ void reloadsTheCachedValueAfterTheGivenPeriod() throws Exception { ++ assertThat(gauge.getValue()).isEqualTo(1); ++ ++ Thread.sleep(150); ++ ++ assertThat(gauge.getValue()).isEqualTo(2); ++ ++ assertThat(gauge.getValue()).isEqualTo(2); ++ } ++ ++ @Test ++ void reloadsCachedValueInNegativeTime() throws Exception { ++ AtomicLong time = new AtomicLong(-2L); ++ Clock clock = ++ new Clock() { ++ @Override ++ public long getTick() { ++ return time.get(); ++ } + }; +- Gauge clockGauge = new CachedGauge(clock, 1, TimeUnit.NANOSECONDS) { +- @Override +- protected Integer loadValue() { +- return value.incrementAndGet(); +- } ++ Gauge clockGauge = ++ new CachedGauge(clock, 1, TimeUnit.NANOSECONDS) { ++ @Override ++ protected Integer loadValue() { ++ return value.incrementAndGet(); ++ } + }; +- assertThat(clockGauge.getValue()) +- .isEqualTo(1); +- assertThat(clockGauge.getValue()) +- .isEqualTo(1); ++ assertThat(clockGauge.getValue()).isEqualTo(1); ++ assertThat(clockGauge.getValue()).isEqualTo(1); + +- time.set(-1L); ++ time.set(-1L); + +- assertThat(clockGauge.getValue()) +- .isEqualTo(2); +- assertThat(clockGauge.getValue()) +- .isEqualTo(2); +- } ++ assertThat(clockGauge.getValue()).isEqualTo(2); ++ assertThat(clockGauge.getValue()).isEqualTo(2); ++ } + +- @Test +- void multipleThreadAccessReturnsConsistentResults() throws Exception { +- List> futures = new ArrayList<>(THREAD_COUNT); ++ @Test ++ void multipleThreadAccessReturnsConsistentResults() throws Exception { ++ List> futures = new ArrayList<>(THREAD_COUNT); + +- for (int i = 0; i < THREAD_COUNT; i++) { +- Future future = executor.submit(() -> { ++ for (int i = 0; i < THREAD_COUNT; i++) { ++ Future future = ++ executor.submit( ++ () -> { + long startTime = System.currentTimeMillis(); + int lastValue = 0; + + do { +- Integer newValue = shortTimeoutGauge.getValue(); +- +- if (newValue == null) { +- LOGGER.warn("Cached gauge returned null value"); +- return false; +- } +- +- if (newValue < lastValue) { +- LOGGER.error("Cached gauge returned stale value, last: {}, new: {}", lastValue, newValue); +- return false; +- } +- +- lastValue = newValue; ++ Integer newValue = shortTimeoutGauge.getValue(); ++ ++ if (newValue == null) { ++ LOG.warn("Cached gauge returned null value"); ++ return false; ++ } ++ ++ if (newValue < lastValue) { ++ LOG.error( ++ "Cached gauge returned stale value, last: {}, new: {}", ++ lastValue, ++ newValue); ++ return false; ++ } ++ ++ lastValue = newValue; + } while (System.currentTimeMillis() - startTime <= RUNNING_TIME_MILLIS); + + return true; +- }); +- +- futures.add(future); +- } ++ }); + +- for (int i = 0; i < futures.size(); i++) { +- assertTrue(futures.get(i).get(), "Future " + i + " failed"); +- } ++ futures.add(future); ++ } + +- executor.shutdown(); ++ for (int i = 0; i < futures.size(); i++) { ++ assertThat(futures.get(i).get()).withFailMessage("Future %s failed", i).isTrue(); + } ++ ++ executor.shutdown(); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java +@@ -4,37 +4,32 @@ import static org.assertj.core.api.BDDAssertions.then; + + import org.junit.jupiter.api.Test; + +-class ChunkedAssociativeLongArrayTest { +- +- @Test +- void testTrim() { +- ChunkedAssociativeLongArray array = new ChunkedAssociativeLongArray(3); +- array.put(-3, 3); +- array.put(-2, 1); +- array.put(0, 5); +- array.put(3, 0); +- array.put(9, 8); +- array.put(15, 0); +- array.put(19, 5); +- array.put(21, 5); +- array.put(34, -9); +- array.put(109, 5); +- +- then(array.out()) +- .isEqualTo("[(-3: 3) (-2: 1) (0: 5) ]->[(3: 0) (9: 8) (15: 0) ]->[(19: 5) (21: 5) (34: -9) ]->[(109: 5) ]"); +- then(array.values()) +- .isEqualTo(new long[]{3, 1, 5, 0, 8, 0, 5, 5, -9, 5}); +- then(array.size()) +- .isEqualTo(10); +- +- array.trim(-2, 20); +- +- then(array.out()) +- .isEqualTo("[(-2: 1) (0: 5) ]->[(3: 0) (9: 8) (15: 0) ]->[(19: 5) ]"); +- then(array.values()) +- .isEqualTo(new long[]{1, 5, 0, 8, 0, 5}); +- then(array.size()) +- .isEqualTo(6); +- +- } ++final class ChunkedAssociativeLongArrayTest { ++ ++ @Test ++ void trim() { ++ ChunkedAssociativeLongArray array = new ChunkedAssociativeLongArray(3); ++ array.put(-3, 3); ++ array.put(-2, 1); ++ array.put(0, 5); ++ array.put(3, 0); ++ array.put(9, 8); ++ array.put(15, 0); ++ array.put(19, 5); ++ array.put(21, 5); ++ array.put(34, -9); ++ array.put(109, 5); ++ ++ then(array.out()) ++ .isEqualTo( ++ "[(-3: 3) (-2: 1) (0: 5) ]->[(3: 0) (9: 8) (15: 0) ]->[(19: 5) (21: 5) (34: -9) ]->[(109: 5) ]"); ++ then(array.values()).isEqualTo(new long[] {3, 1, 5, 0, 8, 0, 5, 5, -9, 5}); ++ then(array.size()).isEqualTo(10); ++ ++ array.trim(-2, 20); ++ ++ then(array.out()).isEqualTo("[(-2: 1) (0: 5) ]->[(3: 0) (9: 8) (15: 0) ]->[(19: 5) ]"); ++ then(array.values()).isEqualTo(new long[] {1, 5, 0, 8, 0, 5}); ++ then(array.size()).isEqualTo(6); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java +@@ -1,13 +1,13 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-public class ClassMetadataTest { +- @Test +- public void testParameterMetadataIsAvailable() throws NoSuchMethodException { +- assertThat(DefaultSettableGauge.class.getConstructor(Object.class).getParameters()) +- .allSatisfy(parameter -> assertThat(parameter.isNamePresent()).isTrue()); +- } +-} +\ No newline at end of file ++import org.junit.jupiter.api.Test; ++ ++final class ClassMetadataTest { ++ @Test ++ void parameterMetadataIsAvailable() throws NoSuchMethodException { ++ assertThat(DefaultSettableGauge.class.getConstructor(Object.class).getParameters()) ++ .allSatisfy(parameter -> assertThat(parameter.isNamePresent()).isTrue()); ++ } ++} +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java +@@ -1,28 +1,23 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.offset; + +-class ClockTest { ++import org.junit.jupiter.api.Test; ++ ++final class ClockTest { + +- @Test +- void userTimeClock() { +- final Clock.UserTimeClock clock = new Clock.UserTimeClock(); ++ @Test ++ void userTimeClock() { ++ final Clock.UserTimeClock clock = new Clock.UserTimeClock(); + +- assertThat((double) clock.getTime()) +- .isEqualTo(System.currentTimeMillis(), +- offset(100.0)); ++ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0)); + +- assertThat((double) clock.getTick()) +- .isEqualTo(System.nanoTime(), +- offset(1000000.0)); +- } ++ assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0)); ++ } + +- @Test +- void defaultsToUserTime() { +- assertThat(Clock.defaultClock()) +- .isInstanceOf(Clock.UserTimeClock.class); +- } ++ @Test ++ void defaultsToUserTime() { ++ assertThat(Clock.defaultClock()).isInstanceOf(Clock.UserTimeClock.class); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java +@@ -1,9 +1,8 @@ + package io.dropwizard.metrics5; + +-import org.apache.commons.lang3.JavaVersion; +-import org.apache.commons.lang3.SystemUtils; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; + + import java.io.ByteArrayOutputStream; + import java.io.PrintStream; +@@ -15,20 +14,221 @@ import java.util.SortedMap; + import java.util.TimeZone; + import java.util.TreeMap; + import java.util.concurrent.TimeUnit; ++import org.apache.commons.lang3.JavaVersion; ++import org.apache.commons.lang3.SystemUtils; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-class ConsoleReporterTest { +- private final Locale locale = Locale.US; +- private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); +- +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); +- private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); +- private final PrintStream output = new PrintStream(bytes); +- private final ConsoleReporter reporter = ConsoleReporter.forRegistry(registry) ++final class ConsoleReporterTest { ++ private final Locale locale = Locale.US; ++ private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); ++ ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); ++ private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ++ private final PrintStream output = new PrintStream(bytes); ++ private final ConsoleReporter reporter = ++ ConsoleReporter.forRegistry(registry) ++ .outputTo(output) ++ .formattedFor(locale) ++ .withClock(clock) ++ .formattedFor(timeZone) ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .build(); ++ private String dateHeader; ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ when(clock.getTime()).thenReturn(1363568676000L); ++ // JDK9 has changed the java.text.DateFormat API implementation according to Unicode. ++ // See http://mail.openjdk.java.net/pipermail/jdk9-dev/2017-April/005732.html ++ dateHeader = ++ SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8) ++ ? "3/17/13 6:04:36 PM =============================================================" ++ : ++ // https://bugs.openjdk.org/browse/JDK-8304925 ++ SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_20) ++ ? "3/17/13, 6:04:36\u202FPM ============================================================" ++ : "3/17/13, 6:04:36 PM ============================================================"; ++ } ++ ++ @Test ++ void reportsGaugeValues() throws Exception { ++ final Gauge gauge = () -> 1; ++ ++ reporter.report(map(MetricName.build("gauge"), gauge), map(), map(), map(), map()); ++ ++ assertThat(consoleOutput()) ++ .isEqualTo( ++ lines( ++ dateHeader, ++ "", ++ "-- Gauges ----------------------------------------------------------------------", ++ "gauge", ++ " value = 1", ++ "", ++ "")); ++ } ++ ++ @Test ++ void reportsCounterValues() throws Exception { ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(100L); ++ ++ reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); ++ ++ assertThat(consoleOutput()) ++ .isEqualTo( ++ lines( ++ dateHeader, ++ "", ++ "-- Counters --------------------------------------------------------------------", ++ "test.counter", ++ " count = 100", ++ "", ++ "")); ++ } ++ ++ @Test ++ void reportsHistogramValues() throws Exception { ++ final Histogram histogram = mock(); ++ when(histogram.getCount()).thenReturn(1L); ++ when(histogram.getSum()).thenReturn(4L); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(2L); ++ when(snapshot.getMean()).thenReturn(3.0); ++ when(snapshot.getMin()).thenReturn(4L); ++ when(snapshot.getStdDev()).thenReturn(5.0); ++ when(snapshot.getMedian()).thenReturn(6.0); ++ when(snapshot.get75thPercentile()).thenReturn(7.0); ++ when(snapshot.get95thPercentile()).thenReturn(8.0); ++ when(snapshot.get98thPercentile()).thenReturn(9.0); ++ when(snapshot.get99thPercentile()).thenReturn(10.0); ++ when(snapshot.get999thPercentile()).thenReturn(11.0); ++ ++ when(histogram.getSnapshot()).thenReturn(snapshot); ++ ++ reporter.report(map(), map(), map(MetricName.build("test.histogram"), histogram), map(), map()); ++ ++ assertThat(consoleOutput()) ++ .isEqualTo( ++ lines( ++ dateHeader, ++ "", ++ "-- Histograms ------------------------------------------------------------------", ++ "test.histogram", ++ " count = 1", ++ " sum = 4", ++ " min = 4", ++ " max = 2", ++ " mean = 3.00", ++ " stddev = 5.00", ++ " median = 6.00", ++ " 75% <= 7.00", ++ " 95% <= 8.00", ++ " 98% <= 9.00", ++ " 99% <= 10.00", ++ " 99.9% <= 11.00", ++ "", ++ "")); ++ } ++ ++ @Test ++ void reportsMeterValues() throws Exception { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(3L); ++ when(meter.getMeanRate()).thenReturn(2.0); ++ when(meter.getOneMinuteRate()).thenReturn(3.0); ++ when(meter.getFiveMinuteRate()).thenReturn(4.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ reporter.report(map(), map(), map(), map(MetricName.build("test.meter"), meter), map()); ++ ++ assertThat(consoleOutput()) ++ .isEqualTo( ++ lines( ++ dateHeader, ++ "", ++ "-- Meters ----------------------------------------------------------------------", ++ "test.meter", ++ " count = 1", ++ " sum = 3", ++ " mean rate = 2.00 events/second", ++ " 1-minute rate = 3.00 events/second", ++ " 5-minute rate = 4.00 events/second", ++ " 15-minute rate = 5.00 events/second", ++ "", ++ "")); ++ } ++ ++ @Test ++ void reportsTimerValues() throws Exception { ++ final Timer timer = mock(); ++ when(timer.getCount()).thenReturn(1L); ++ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(5)); ++ when(timer.getMeanRate()).thenReturn(2.0); ++ when(timer.getOneMinuteRate()).thenReturn(3.0); ++ when(timer.getFiveMinuteRate()).thenReturn(4.0); ++ when(timer.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); ++ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); ++ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ++ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); ++ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); ++ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); ++ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); ++ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); ++ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); ++ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); ++ ++ when(timer.getSnapshot()).thenReturn(snapshot); ++ ++ reporter.report(map(), map(), map(), map(), map(MetricName.build("test.another.timer"), timer)); ++ ++ assertThat(consoleOutput()) ++ .isEqualTo( ++ lines( ++ dateHeader, ++ "", ++ "-- Timers ----------------------------------------------------------------------", ++ "test.another.timer", ++ " count = 1", ++ " sum = 5.00", ++ " mean rate = 2.00 calls/second", ++ " 1-minute rate = 3.00 calls/second", ++ " 5-minute rate = 4.00 calls/second", ++ " 15-minute rate = 5.00 calls/second", ++ " min = 300.00 milliseconds", ++ " max = 100.00 milliseconds", ++ " mean = 200.00 milliseconds", ++ " stddev = 400.00 milliseconds", ++ " median = 500.00 milliseconds", ++ " 75% <= 600.00 milliseconds", ++ " 95% <= 700.00 milliseconds", ++ " 98% <= 800.00 milliseconds", ++ " 99% <= 900.00 milliseconds", ++ " 99.9% <= 1000.00 milliseconds", ++ "", ++ "")); ++ } ++ ++ @Test ++ void reportMeterWithDisabledAttributes() throws Exception { ++ Set disabledMetricAttributes = ++ EnumSet.of( ++ MetricAttribute.M15_RATE, ++ MetricAttribute.M5_RATE, ++ MetricAttribute.COUNT, ++ MetricAttribute.SUM); ++ ++ final ConsoleReporter customReporter = ++ ConsoleReporter.forRegistry(registry) + .outputTo(output) + .formattedFor(locale) + .withClock(clock) +@@ -36,393 +236,178 @@ class ConsoleReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(disabledMetricAttributes) + .build(); +- private String dateHeader; +- +- @BeforeEach +- void setUp() throws Exception { +- when(clock.getTime()).thenReturn(1363568676000L); +- // JDK9 has changed the java.text.DateFormat API implementation according to Unicode. +- // See http://mail.openjdk.java.net/pipermail/jdk9-dev/2017-April/005732.html +- dateHeader = SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8) ? +- "3/17/13 6:04:36 PM =============================================================" : +- // https://bugs.openjdk.org/browse/JDK-8304925 +- SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_20) ? +- "3/17/13, 6:04:36\u202FPM ============================================================" : +- "3/17/13, 6:04:36 PM ============================================================"; +- } +- +- @Test +- void reportsGaugeValues() throws Exception { +- final Gauge gauge = () -> 1; +- +- reporter.report(map(MetricName.build("gauge"), gauge), +- map(), +- map(), +- map(), +- map()); +- +- assertThat(consoleOutput()) +- .isEqualTo(lines( +- dateHeader, +- "", +- "-- Gauges ----------------------------------------------------------------------", +- "gauge", +- " value = 1", +- "", +- "" +- )); +- } +- +- @Test +- void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(100L); +- +- reporter.report(map(), +- map(MetricName.build("test.counter"), counter), +- map(), +- map(), +- map()); +- +- assertThat(consoleOutput()) +- .isEqualTo(lines( +- dateHeader, +- "", +- "-- Counters --------------------------------------------------------------------", +- "test.counter", +- " count = 100", +- "", +- "" +- )); +- } +- +- @Test +- void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); +- when(histogram.getCount()).thenReturn(1L); +- when(histogram.getSum()).thenReturn(4L); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(2L); +- when(snapshot.getMean()).thenReturn(3.0); +- when(snapshot.getMin()).thenReturn(4L); +- when(snapshot.getStdDev()).thenReturn(5.0); +- when(snapshot.getMedian()).thenReturn(6.0); +- when(snapshot.get75thPercentile()).thenReturn(7.0); +- when(snapshot.get95thPercentile()).thenReturn(8.0); +- when(snapshot.get98thPercentile()).thenReturn(9.0); +- when(snapshot.get99thPercentile()).thenReturn(10.0); +- when(snapshot.get999thPercentile()).thenReturn(11.0); +- +- when(histogram.getSnapshot()).thenReturn(snapshot); +- +- reporter.report(map(), +- map(), +- map(MetricName.build("test.histogram"), histogram), +- map(), +- map()); +- +- assertThat(consoleOutput()) +- .isEqualTo(lines( +- dateHeader, +- "", +- "-- Histograms ------------------------------------------------------------------", +- "test.histogram", +- " count = 1", +- " sum = 4", +- " min = 4", +- " max = 2", +- " mean = 3.00", +- " stddev = 5.00", +- " median = 6.00", +- " 75% <= 7.00", +- " 95% <= 8.00", +- " 98% <= 9.00", +- " 99% <= 10.00", +- " 99.9% <= 11.00", +- "", +- "" +- )); +- } +- +- @Test +- void reportsMeterValues() throws Exception { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(3L); +- when(meter.getMeanRate()).thenReturn(2.0); +- when(meter.getOneMinuteRate()).thenReturn(3.0); +- when(meter.getFiveMinuteRate()).thenReturn(4.0); +- when(meter.getFifteenMinuteRate()).thenReturn(5.0); +- +- reporter.report(map(), +- map(), +- map(), +- map(MetricName.build("test.meter"), meter), +- map()); +- +- assertThat(consoleOutput()) +- .isEqualTo(lines( +- dateHeader, +- "", +- "-- Meters ----------------------------------------------------------------------", +- "test.meter", +- " count = 1", +- " sum = 3", +- " mean rate = 2.00 events/second", +- " 1-minute rate = 3.00 events/second", +- " 5-minute rate = 4.00 events/second", +- " 15-minute rate = 5.00 events/second", +- "", +- "" +- )); +- } +- +- @Test +- void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); +- when(timer.getCount()).thenReturn(1L); +- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(5)); +- when(timer.getMeanRate()).thenReturn(2.0); +- when(timer.getOneMinuteRate()).thenReturn(3.0); +- when(timer.getFiveMinuteRate()).thenReturn(4.0); +- when(timer.getFifteenMinuteRate()).thenReturn(5.0); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); +- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); +- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); +- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); +- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); +- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); +- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); +- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); +- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS +- .toNanos(1000)); +- +- when(timer.getSnapshot()).thenReturn(snapshot); +- +- reporter.report(map(), +- map(), +- map(), +- map(), +- map(MetricName.build("test.another.timer"), timer)); +- +- assertThat(consoleOutput()) +- .isEqualTo(lines( +- dateHeader, +- "", +- "-- Timers ----------------------------------------------------------------------", +- "test.another.timer", +- " count = 1", +- " sum = 5.00", +- " mean rate = 2.00 calls/second", +- " 1-minute rate = 3.00 calls/second", +- " 5-minute rate = 4.00 calls/second", +- " 15-minute rate = 5.00 calls/second", +- " min = 300.00 milliseconds", +- " max = 100.00 milliseconds", +- " mean = 200.00 milliseconds", +- " stddev = 400.00 milliseconds", +- " median = 500.00 milliseconds", +- " 75% <= 600.00 milliseconds", +- " 95% <= 700.00 milliseconds", +- " 98% <= 800.00 milliseconds", +- " 99% <= 900.00 milliseconds", +- " 99.9% <= 1000.00 milliseconds", +- "", +- "" +- )); +- } + +- @Test +- void reportMeterWithDisabledAttributes() throws Exception { +- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE, MetricAttribute.COUNT, MetricAttribute.SUM); +- +- final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) +- .outputTo(output) +- .formattedFor(locale) +- .withClock(clock) +- .formattedFor(timeZone) +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(disabledMetricAttributes) +- .build(); +- +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(5L); +- when(meter.getMeanRate()).thenReturn(2.0); +- when(meter.getOneMinuteRate()).thenReturn(3.0); +- when(meter.getFiveMinuteRate()).thenReturn(4.0); +- when(meter.getFifteenMinuteRate()).thenReturn(5.0); +- +- customReporter.report(map(), +- map(), +- map(), +- map(MetricName.build("test.meter"), meter), +- map()); +- +- assertThat(consoleOutput()) +- .isEqualTo(lines( +- dateHeader, +- "", +- "-- Meters ----------------------------------------------------------------------", +- "test.meter", +- " mean rate = 2.00 events/second", +- " 1-minute rate = 3.00 events/second", +- "", +- "" +- )); +- } +- +- @Test +- void reportTimerWithDisabledAttributes() throws Exception { +- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.P50, MetricAttribute.P999, MetricAttribute.M5_RATE, MetricAttribute.MAX); +- +- final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) +- .outputTo(output) +- .formattedFor(locale) +- .withClock(clock) +- .formattedFor(timeZone) +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(disabledMetricAttributes) +- .build(); +- +- final Timer timer = mock(Timer.class); +- when(timer.getCount()).thenReturn(1L); +- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); +- when(timer.getMeanRate()).thenReturn(2.0); +- when(timer.getOneMinuteRate()).thenReturn(3.0); +- when(timer.getFiveMinuteRate()).thenReturn(4.0); +- when(timer.getFifteenMinuteRate()).thenReturn(5.0); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); +- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); +- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); +- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); +- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); +- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); +- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); +- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); +- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS +- .toNanos(1000)); +- +- when(timer.getSnapshot()).thenReturn(snapshot); +- +- customReporter.report(map(), +- map(), +- map(), +- map(), +- map(MetricName.build("test.another.timer"), timer)); +- +- assertThat(consoleOutput()) +- .isEqualTo(lines( +- dateHeader, +- "", +- "-- Timers ----------------------------------------------------------------------", +- "test.another.timer", +- " count = 1", +- " sum = 6.00", +- " mean rate = 2.00 calls/second", +- " 1-minute rate = 3.00 calls/second", +- " 15-minute rate = 5.00 calls/second", +- " min = 300.00 milliseconds", +- " mean = 200.00 milliseconds", +- " stddev = 400.00 milliseconds", +- " 75% <= 600.00 milliseconds", +- " 95% <= 700.00 milliseconds", +- " 98% <= 800.00 milliseconds", +- " 99% <= 900.00 milliseconds", +- "", +- "" +- )); +- } +- +- @Test +- void reportHistogramWithDisabledAttributes() throws Exception { +- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, MetricAttribute.MAX, MetricAttribute.STDDEV, MetricAttribute.P95); +- +- final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) +- .outputTo(output) +- .formattedFor(locale) +- .withClock(clock) +- .formattedFor(timeZone) +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(disabledMetricAttributes) +- .build(); +- +- final Histogram histogram = mock(Histogram.class); +- when(histogram.getCount()).thenReturn(1L); +- when(histogram.getSum()).thenReturn(5L); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(2L); +- when(snapshot.getMean()).thenReturn(3.0); +- when(snapshot.getMin()).thenReturn(4L); +- when(snapshot.getStdDev()).thenReturn(5.0); +- when(snapshot.getMedian()).thenReturn(6.0); +- when(snapshot.get75thPercentile()).thenReturn(7.0); +- when(snapshot.get95thPercentile()).thenReturn(8.0); +- when(snapshot.get98thPercentile()).thenReturn(9.0); +- when(snapshot.get99thPercentile()).thenReturn(10.0); +- when(snapshot.get999thPercentile()).thenReturn(11.0); +- +- when(histogram.getSnapshot()).thenReturn(snapshot); +- +- customReporter.report(map(), +- map(), +- map(MetricName.build("test.histogram"), histogram), +- map(), +- map()); +- +- assertThat(consoleOutput()) +- .isEqualTo(lines( +- dateHeader, +- "", +- "-- Histograms ------------------------------------------------------------------", +- "test.histogram", +- " count = 1", +- " sum = 5", +- " mean = 3.00", +- " median = 6.00", +- " 75% <= 7.00", +- " 98% <= 9.00", +- " 99% <= 10.00", +- " 99.9% <= 11.00", +- "", +- "" +- )); +- } +- +- private String lines(String... lines) { +- final StringBuilder builder = new StringBuilder(); +- for (String line : lines) { +- builder.append(line).append(String.format("%n")); +- } +- return builder.toString(); +- } +- +- private String consoleOutput() throws UnsupportedEncodingException { +- return bytes.toString("UTF-8"); +- } ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(5L); ++ when(meter.getMeanRate()).thenReturn(2.0); ++ when(meter.getOneMinuteRate()).thenReturn(3.0); ++ when(meter.getFiveMinuteRate()).thenReturn(4.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ customReporter.report(map(), map(), map(), map(MetricName.build("test.meter"), meter), map()); ++ ++ assertThat(consoleOutput()) ++ .isEqualTo( ++ lines( ++ dateHeader, ++ "", ++ "-- Meters ----------------------------------------------------------------------", ++ "test.meter", ++ " mean rate = 2.00 events/second", ++ " 1-minute rate = 3.00 events/second", ++ "", ++ "")); ++ } ++ ++ @Test ++ void reportTimerWithDisabledAttributes() throws Exception { ++ Set disabledMetricAttributes = ++ EnumSet.of( ++ MetricAttribute.P50, ++ MetricAttribute.P999, ++ MetricAttribute.M5_RATE, ++ MetricAttribute.MAX); ++ ++ final ConsoleReporter customReporter = ++ ConsoleReporter.forRegistry(registry) ++ .outputTo(output) ++ .formattedFor(locale) ++ .withClock(clock) ++ .formattedFor(timeZone) ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(disabledMetricAttributes) ++ .build(); + +- private SortedMap map() { +- return new TreeMap<>(); +- } ++ final Timer timer = mock(); ++ when(timer.getCount()).thenReturn(1L); ++ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); ++ when(timer.getMeanRate()).thenReturn(2.0); ++ when(timer.getOneMinuteRate()).thenReturn(3.0); ++ when(timer.getFiveMinuteRate()).thenReturn(4.0); ++ when(timer.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); ++ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); ++ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ++ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); ++ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); ++ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); ++ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); ++ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); ++ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); ++ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); ++ ++ when(timer.getSnapshot()).thenReturn(snapshot); ++ ++ customReporter.report( ++ map(), map(), map(), map(), map(MetricName.build("test.another.timer"), timer)); ++ ++ assertThat(consoleOutput()) ++ .isEqualTo( ++ lines( ++ dateHeader, ++ "", ++ "-- Timers ----------------------------------------------------------------------", ++ "test.another.timer", ++ " count = 1", ++ " sum = 6.00", ++ " mean rate = 2.00 calls/second", ++ " 1-minute rate = 3.00 calls/second", ++ " 15-minute rate = 5.00 calls/second", ++ " min = 300.00 milliseconds", ++ " mean = 200.00 milliseconds", ++ " stddev = 400.00 milliseconds", ++ " 75% <= 600.00 milliseconds", ++ " 95% <= 700.00 milliseconds", ++ " 98% <= 800.00 milliseconds", ++ " 99% <= 900.00 milliseconds", ++ "", ++ "")); ++ } ++ ++ @Test ++ void reportHistogramWithDisabledAttributes() throws Exception { ++ Set disabledMetricAttributes = ++ EnumSet.of( ++ MetricAttribute.MIN, MetricAttribute.MAX, MetricAttribute.STDDEV, MetricAttribute.P95); ++ ++ final ConsoleReporter customReporter = ++ ConsoleReporter.forRegistry(registry) ++ .outputTo(output) ++ .formattedFor(locale) ++ .withClock(clock) ++ .formattedFor(timeZone) ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(disabledMetricAttributes) ++ .build(); + +- private SortedMap map(MetricName name, T metric) { +- final TreeMap map = new TreeMap<>(); +- map.put(name, metric); +- return map; ++ final Histogram histogram = mock(); ++ when(histogram.getCount()).thenReturn(1L); ++ when(histogram.getSum()).thenReturn(5L); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(2L); ++ when(snapshot.getMean()).thenReturn(3.0); ++ when(snapshot.getMin()).thenReturn(4L); ++ when(snapshot.getStdDev()).thenReturn(5.0); ++ when(snapshot.getMedian()).thenReturn(6.0); ++ when(snapshot.get75thPercentile()).thenReturn(7.0); ++ when(snapshot.get95thPercentile()).thenReturn(8.0); ++ when(snapshot.get98thPercentile()).thenReturn(9.0); ++ when(snapshot.get99thPercentile()).thenReturn(10.0); ++ when(snapshot.get999thPercentile()).thenReturn(11.0); ++ ++ when(histogram.getSnapshot()).thenReturn(snapshot); ++ ++ customReporter.report( ++ map(), map(), map(MetricName.build("test.histogram"), histogram), map(), map()); ++ ++ assertThat(consoleOutput()) ++ .isEqualTo( ++ lines( ++ dateHeader, ++ "", ++ "-- Histograms ------------------------------------------------------------------", ++ "test.histogram", ++ " count = 1", ++ " sum = 5", ++ " mean = 3.00", ++ " median = 6.00", ++ " 75% <= 7.00", ++ " 98% <= 9.00", ++ " 99% <= 10.00", ++ " 99.9% <= 11.00", ++ "", ++ "")); ++ } ++ ++ private String lines(String... lines) { ++ final StringBuilder builder = new StringBuilder(); ++ for (String line : lines) { ++ builder.append(line).append(String.format("%n")); + } ++ return builder.toString(); ++ } ++ ++ private String consoleOutput() throws UnsupportedEncodingException { ++ return bytes.toString("UTF-8"); ++ } ++ ++ private SortedMap map() { ++ return new TreeMap<>(); ++ } ++ ++ private SortedMap map(MetricName name, T metric) { ++ final TreeMap map = new TreeMap<>(); ++ map.put(name, metric); ++ return map; ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java +@@ -1,63 +1,56 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-class CounterTest { +- private final Counter counter = new Counter(); ++import org.junit.jupiter.api.Test; ++ ++final class CounterTest { ++ private final Counter counter = new Counter(); + +- @Test +- void startsAtZero() { +- assertThat(counter.getCount()) +- .isZero(); +- } ++ @Test ++ void startsAtZero() { ++ assertThat(counter.getCount()).isEqualTo(0); ++ } + +- @Test +- void incrementsByOne() { +- counter.inc(); ++ @Test ++ void incrementsByOne() { ++ counter.inc(); + +- assertThat(counter.getCount()) +- .isEqualTo(1); +- } ++ assertThat(counter.getCount()).isEqualTo(1); ++ } + +- @Test +- void incrementsByAnArbitraryDelta() { +- counter.inc(12); ++ @Test ++ void incrementsByAnArbitraryDelta() { ++ counter.inc(12); + +- assertThat(counter.getCount()) +- .isEqualTo(12); +- } ++ assertThat(counter.getCount()).isEqualTo(12); ++ } + +- @Test +- void decrementsByOne() { +- counter.dec(); ++ @Test ++ void decrementsByOne() { ++ counter.dec(); + +- assertThat(counter.getCount()) +- .isEqualTo(-1); +- } ++ assertThat(counter.getCount()).isEqualTo(-1); ++ } + +- @Test +- void decrementsByAnArbitraryDelta() { +- counter.dec(12); ++ @Test ++ void decrementsByAnArbitraryDelta() { ++ counter.dec(12); + +- assertThat(counter.getCount()) +- .isEqualTo(-12); +- } ++ assertThat(counter.getCount()).isEqualTo(-12); ++ } + +- @Test +- void incrementByNegativeDelta() { +- counter.inc(-12); ++ @Test ++ void incrementByNegativeDelta() { ++ counter.inc(-12); + +- assertThat(counter.getCount()) +- .isEqualTo(-12); +- } ++ assertThat(counter.getCount()).isEqualTo(-12); ++ } + +- @Test +- void decrementByNegativeDelta() { +- counter.dec(-12); ++ @Test ++ void decrementByNegativeDelta() { ++ counter.dec(-12); + +- assertThat(counter.getCount()) +- .isEqualTo(12); +- } ++ assertThat(counter.getCount()).isEqualTo(12); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +@@ -1,257 +1,222 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +-import org.junit.jupiter.api.io.TempDir; ++import static java.nio.charset.StandardCharsets.UTF_8; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; + + import java.io.File; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.nio.file.Files; + import java.util.Locale; + import java.util.SortedMap; + import java.util.TreeMap; + import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; ++import org.junit.jupiter.api.io.TempDir; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- +-public class CsvReporterTest { +- @TempDir +- public File folder; +- +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); +- +- private File dataDirectory; +- private CsvReporter reporter; +- +- @BeforeEach +- void setUp() throws Exception { +- when(clock.getTime()).thenReturn(19910191000L); +- +- this.dataDirectory = newFolder(folder, "junit"); +- +- this.reporter = CsvReporter.forRegistry(registry) +- .formatFor(Locale.US) +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .withClock(clock) +- .filter(MetricFilter.ALL) +- .build(dataDirectory); +- } +- +- @Test +- void reportsGaugeValues() throws Exception { +- final Gauge gauge = () -> 1; +- +- reporter.report(map(MetricName.build("gauge"), gauge), +- map(), +- map(), +- map(), +- map()); +- +- assertThat(fileContents("gauge.csv")) +- .isEqualTo(csv( +- "t,value", +- "19910191,1" +- )); +- } +- +- @Test +- void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(100L); +- +- reporter.report(map(), +- map(MetricName.build("test.counter"), counter), +- map(), +- map(), +- map()); +- +- assertThat(fileContents("test.counter.csv")) +- .isEqualTo(csv( +- "t,count", +- "19910191,100" +- )); +- } +- +- @Test +- void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); +- when(histogram.getCount()).thenReturn(1L); +- when(histogram.getSum()).thenReturn(12L); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(2L); +- when(snapshot.getMean()).thenReturn(3.0); +- when(snapshot.getMin()).thenReturn(4L); +- when(snapshot.getStdDev()).thenReturn(5.0); +- when(snapshot.getMedian()).thenReturn(6.0); +- when(snapshot.get75thPercentile()).thenReturn(7.0); +- when(snapshot.get95thPercentile()).thenReturn(8.0); +- when(snapshot.get98thPercentile()).thenReturn(9.0); +- when(snapshot.get99thPercentile()).thenReturn(10.0); +- when(snapshot.get999thPercentile()).thenReturn(11.0); +- +- when(histogram.getSnapshot()).thenReturn(snapshot); +- +- reporter.report(map(), +- map(), +- map(MetricName.build("test.histogram"), histogram), +- map(), +- map()); +- +- assertThat(fileContents("test.histogram.csv")) +- .isEqualTo(csv( +- "t,count,sum,max,mean,min,stddev,p50,p75,p95,p98,p99,p999", +- "19910191,1,12,2,3.000000,4,5.000000,6.000000,7.000000,8.000000,9.000000,10.000000,11.000000" +- )); +- } +- +- @Test +- void reportsMeterValues() throws Exception { +- final Meter meter = mockMeter(); +- +- reporter.report(map(), +- map(), +- map(), +- map(MetricName.build("test.meter"), meter), +- map()); +- +- assertThat(fileContents("test.meter.csv")) +- .isEqualTo(csv( +- "t,count,sum,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit", +- "19910191,1,6,2.000000,3.000000,4.000000,5.000000,events/second" +- )); +- } +- +- @Test +- void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); +- when(timer.getCount()).thenReturn(1L); +- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); +- when(timer.getMeanRate()).thenReturn(2.0); +- when(timer.getOneMinuteRate()).thenReturn(3.0); +- when(timer.getFiveMinuteRate()).thenReturn(4.0); +- when(timer.getFifteenMinuteRate()).thenReturn(5.0); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); +- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); +- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); +- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); +- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); +- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); +- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); +- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); +- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); +- +- when(timer.getSnapshot()).thenReturn(snapshot); +- +- reporter.report(map(), +- map(), +- map(), +- map(), +- map(MetricName.build("test.another.timer"), timer)); +- +- assertThat(fileContents("test.another.timer.csv")) +- .isEqualTo(csv( +- "t,count,sum,max,mean,min,stddev,p50,p75,p95,p98,p99,p999,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit,duration_unit", +- "19910191,1,6.000000,100.000000,200.000000,300.000000,400.000000,500.000000,600.000000,700.000000,800.000000,900.000000,1000.000000,2.000000,3.000000,4.000000,5.000000,calls/second,milliseconds" +- )); +- } +- +- @Test +- void testCsvFileProviderIsUsed() { +- CsvFileProvider fileProvider = mock(CsvFileProvider.class); +- when(fileProvider.getFile(dataDirectory, "gauge")).thenReturn(new File(dataDirectory, "guage.csv")); +- +- CsvReporter reporter = CsvReporter.forRegistry(registry) +- .withCsvFileProvider(fileProvider) +- .build(dataDirectory); +- +- final Gauge gauge = () -> 1; +- +- reporter.report(map(MetricName.build("gauge"), gauge), +- map(), +- map(), +- map(), +- map()); +- +- verify(fileProvider).getFile(dataDirectory, "gauge"); +- } +- +- @Test +- void itFormatsWithCustomSeparator() throws Exception { +- final Meter meter = mockMeter(); +- +- CsvReporter customSeparatorReporter = CsvReporter.forRegistry(registry) +- .formatFor(Locale.US) +- .withSeparator("|") +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .withClock(clock) +- .filter(MetricFilter.ALL) +- .build(dataDirectory); +- +- customSeparatorReporter.report(map(), +- map(), +- map(), +- map(MetricName.build("test.meter"), meter), +- map()); +- +- assertThat(fileContents("test.meter.csv")) +- .isEqualTo(csv( +- "t|count|sum|mean_rate|m1_rate|m5_rate|m15_rate|rate_unit", +- "19910191|1|6|2.000000|3.000000|4.000000|5.000000|events/second" +- )); +- } +- +- private Meter mockMeter() { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(6L); +- when(meter.getMeanRate()).thenReturn(2.0); +- when(meter.getOneMinuteRate()).thenReturn(3.0); +- when(meter.getFiveMinuteRate()).thenReturn(4.0); +- when(meter.getFifteenMinuteRate()).thenReturn(5.0); +- +- return meter; +- } +- +- private String csv(String... lines) { +- final StringBuilder builder = new StringBuilder(); +- for (String line : lines) { +- builder.append(line).append(String.format("%n")); +- } +- return builder.toString(); +- } +- +- @SuppressWarnings("FilesReadStringWithCharset") +- private String fileContents(String filename) throws IOException { +- return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); +- } +- +- private SortedMap map() { +- return new TreeMap<>(); +- } +- +- private SortedMap map(MetricName name, T metric) { +- final TreeMap map = new TreeMap<>(); +- map.put(name, metric); +- return map; ++final class CsvReporterTest { ++ @TempDir public File folder; ++ ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); ++ ++ private File dataDirectory; ++ private CsvReporter reporter; ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ when(clock.getTime()).thenReturn(19910191000L); ++ ++ this.dataDirectory = newFolder(folder, "junit"); ++ ++ this.reporter = ++ CsvReporter.forRegistry(registry) ++ .formatFor(Locale.US) ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .withClock(clock) ++ .filter(MetricFilter.ALL) ++ .build(dataDirectory); ++ } ++ ++ @Test ++ void reportsGaugeValues() throws Exception { ++ final Gauge gauge = () -> 1; ++ ++ reporter.report(map(MetricName.build("gauge"), gauge), map(), map(), map(), map()); ++ ++ assertThat(fileContents("gauge.csv")).isEqualTo(csv("t,value", "19910191,1")); ++ } ++ ++ @Test ++ void reportsCounterValues() throws Exception { ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(100L); ++ ++ reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); ++ ++ assertThat(fileContents("test.counter.csv")).isEqualTo(csv("t,count", "19910191,100")); ++ } ++ ++ @Test ++ void reportsHistogramValues() throws Exception { ++ final Histogram histogram = mock(); ++ when(histogram.getCount()).thenReturn(1L); ++ when(histogram.getSum()).thenReturn(12L); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(2L); ++ when(snapshot.getMean()).thenReturn(3.0); ++ when(snapshot.getMin()).thenReturn(4L); ++ when(snapshot.getStdDev()).thenReturn(5.0); ++ when(snapshot.getMedian()).thenReturn(6.0); ++ when(snapshot.get75thPercentile()).thenReturn(7.0); ++ when(snapshot.get95thPercentile()).thenReturn(8.0); ++ when(snapshot.get98thPercentile()).thenReturn(9.0); ++ when(snapshot.get99thPercentile()).thenReturn(10.0); ++ when(snapshot.get999thPercentile()).thenReturn(11.0); ++ ++ when(histogram.getSnapshot()).thenReturn(snapshot); ++ ++ reporter.report(map(), map(), map(MetricName.build("test.histogram"), histogram), map(), map()); ++ ++ assertThat(fileContents("test.histogram.csv")) ++ .isEqualTo( ++ csv( ++ "t,count,sum,max,mean,min,stddev,p50,p75,p95,p98,p99,p999", ++ "19910191,1,12,2,3.000000,4,5.000000,6.000000,7.000000,8.000000,9.000000,10.000000,11.000000")); ++ } ++ ++ @Test ++ void reportsMeterValues() throws Exception { ++ final Meter meter = mockMeter(); ++ ++ reporter.report(map(), map(), map(), map(MetricName.build("test.meter"), meter), map()); ++ ++ assertThat(fileContents("test.meter.csv")) ++ .isEqualTo( ++ csv( ++ "t,count,sum,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit", ++ "19910191,1,6,2.000000,3.000000,4.000000,5.000000,events/second")); ++ } ++ ++ @Test ++ void reportsTimerValues() throws Exception { ++ final Timer timer = mock(); ++ when(timer.getCount()).thenReturn(1L); ++ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); ++ when(timer.getMeanRate()).thenReturn(2.0); ++ when(timer.getOneMinuteRate()).thenReturn(3.0); ++ when(timer.getFiveMinuteRate()).thenReturn(4.0); ++ when(timer.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); ++ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); ++ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ++ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); ++ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); ++ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); ++ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); ++ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); ++ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); ++ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); ++ ++ when(timer.getSnapshot()).thenReturn(snapshot); ++ ++ reporter.report(map(), map(), map(), map(), map(MetricName.build("test.another.timer"), timer)); ++ ++ assertThat(fileContents("test.another.timer.csv")) ++ .isEqualTo( ++ csv( ++ "t,count,sum,max,mean,min,stddev,p50,p75,p95,p98,p99,p999,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit,duration_unit", ++ "19910191,1,6.000000,100.000000,200.000000,300.000000,400.000000,500.000000,600.000000,700.000000,800.000000,900.000000,1000.000000,2.000000,3.000000,4.000000,5.000000,calls/second,milliseconds")); ++ } ++ ++ @Test ++ void csvFileProviderIsUsed() { ++ CsvFileProvider fileProvider = mock(); ++ when(fileProvider.getFile(dataDirectory, "gauge")) ++ .thenReturn(new File(dataDirectory, "guage.csv")); ++ ++ CsvReporter reporter = ++ CsvReporter.forRegistry(registry).withCsvFileProvider(fileProvider).build(dataDirectory); ++ ++ final Gauge gauge = () -> 1; ++ ++ reporter.report(map(MetricName.build("gauge"), gauge), map(), map(), map(), map()); ++ ++ verify(fileProvider).getFile(dataDirectory, "gauge"); ++ } ++ ++ @Test ++ void itFormatsWithCustomSeparator() throws Exception { ++ final Meter meter = mockMeter(); ++ ++ CsvReporter customSeparatorReporter = ++ CsvReporter.forRegistry(registry) ++ .formatFor(Locale.US) ++ .withSeparator("|") ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .withClock(clock) ++ .filter(MetricFilter.ALL) ++ .build(dataDirectory); ++ ++ customSeparatorReporter.report( ++ map(), map(), map(), map(MetricName.build("test.meter"), meter), map()); ++ ++ assertThat(fileContents("test.meter.csv")) ++ .isEqualTo( ++ csv( ++ "t|count|sum|mean_rate|m1_rate|m5_rate|m15_rate|rate_unit", ++ "19910191|1|6|2.000000|3.000000|4.000000|5.000000|events/second")); ++ } ++ ++ private Meter mockMeter() { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(6L); ++ when(meter.getMeanRate()).thenReturn(2.0); ++ when(meter.getOneMinuteRate()).thenReturn(3.0); ++ when(meter.getFiveMinuteRate()).thenReturn(4.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ return meter; ++ } ++ ++ private String csv(String... lines) { ++ final StringBuilder builder = new StringBuilder(); ++ for (String line : lines) { ++ builder.append(line).append(String.format("%n")); + } +- +- private static File newFolder(File root, String... subDirs) throws IOException { +- String subFolder = String.join("/", subDirs); +- File result = new File(root, subFolder); +- if (!result.mkdirs()) { +- throw new IOException("Couldn't create folders " + root); +- } +- return result; ++ return builder.toString(); ++ } ++ ++ @SuppressWarnings("FilesReadStringWithCharset") ++ private String fileContents(String filename) throws IOException { ++ return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), UTF_8); ++ } ++ ++ private SortedMap map() { ++ return new TreeMap<>(); ++ } ++ ++ private SortedMap map(MetricName name, T metric) { ++ final TreeMap map = new TreeMap<>(); ++ map.put(name, metric); ++ return map; ++ } ++ ++ private static File newFolder(File root, String... subDirs) throws IOException { ++ String subFolder = String.join("/", subDirs); ++ File result = new File(root, subFolder); ++ if (!result.mkdirs()) { ++ throw new IOException("Couldn't create folders " + root); + } ++ return result; ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java +@@ -1,26 +1,26 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-class DefaultSettableGaugeTest { +- @Test +- void newSettableGaugeWithoutDefaultReturnsNull() { +- DefaultSettableGauge gauge = new DefaultSettableGauge<>(); +- assertThat(gauge.getValue()).isNull(); +- } ++import org.junit.jupiter.api.Test; ++ ++final class DefaultSettableGaugeTest { ++ @Test ++ void newSettableGaugeWithoutDefaultReturnsNull() { ++ DefaultSettableGauge gauge = new DefaultSettableGauge<>(); ++ assertThat(gauge.getValue()).isNull(); ++ } + +- @Test +- void newSettableGaugeWithDefaultReturnsDefault() { +- DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); +- assertThat(gauge.getValue()).isEqualTo("default"); +- } ++ @Test ++ void newSettableGaugeWithDefaultReturnsDefault() { ++ DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); ++ assertThat(gauge.getValue()).isEqualTo("default"); ++ } + +- @Test +- void setValueOverwritesExistingValue() { +- DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); +- gauge.setValue("test"); +- assertThat(gauge.getValue()).isEqualTo("test"); +- } ++ @Test ++ void setValueOverwritesExistingValue() { ++ DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); ++ gauge.setValue("test"); ++ assertThat(gauge.getValue()).isEqualTo("test"); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java +@@ -1,21 +1,21 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-class DerivativeGaugeTest { +- private final Gauge gauge1 = () -> "woo"; +- private final Gauge gauge2 = new DerivativeGauge(gauge1) { ++import org.junit.jupiter.api.Test; ++ ++final class DerivativeGaugeTest { ++ private final Gauge gauge1 = () -> "woo"; ++ private final Gauge gauge2 = ++ new DerivativeGauge(gauge1) { + @Override + protected Integer transform(String value) { +- return value.length(); ++ return value.length(); + } +- }; ++ }; + +- @Test +- void returnsATransformedValue() { +- assertThat(gauge2.getValue()) +- .isEqualTo(3); +- } ++ @Test ++ void returnsATransformedValue() { ++ assertThat(gauge2.getValue()).isEqualTo(3); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java +@@ -1,224 +1,222 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- +-import java.util.concurrent.TimeUnit; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.offset; + +-class EWMATest { +- @Test +- void aOneMinuteEWMAWithAValueOfThree() { +- final EWMA ewma = EWMA.oneMinuteEWMA(); +- ewma.update(3); +- ewma.tick(); ++import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.Test; + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++final class EWMATest { ++ @Test ++ void aOneMinuteEWMAWithAValueOfThree() { ++ final EWMA ewma = EWMA.oneMinuteEWMA(); ++ ewma.update(3); ++ ewma.tick(); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.01098938, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00404277, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00148725, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00054713, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00020128, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00007405, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00002724, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00001002, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000369, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000136, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000050, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000018, offset(0.000001)); +- } ++ elapseMinute(ewma); + +- @Test +- void aFiveMinuteEWMAWithAValueOfThree() { +- final EWMA ewma = EWMA.fiveMinuteEWMA(); +- ewma.update(3); +- ewma.tick(); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001)); ++ } + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ @Test ++ void aFiveMinuteEWMAWithAValueOfThree() { ++ final EWMA ewma = EWMA.fiveMinuteEWMA(); ++ ewma.update(3); ++ ewma.tick(); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.18071653, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.14795818, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.12113791, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.09917933, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.06648190, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.05443077, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.04456415, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.03648604, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); +- } ++ elapseMinute(ewma); + +- @Test +- void aFifteenMinuteEWMAWithAValueOfThree() { +- final EWMA ewma = EWMA.fifteenMinuteEWMA(); +- ewma.update(3); +- ewma.tick(); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); ++ } + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ @Test ++ void aFifteenMinuteEWMAWithAValueOfThree() { ++ final EWMA ewma = EWMA.fifteenMinuteEWMA(); ++ ewma.update(3); ++ ewma.tick(); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.56130419, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.52510399, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.45955700, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.42991879, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.37625345, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.35198773, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.30805027, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.28818318, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.25221023, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.23594443, offset(0.000001)); ++ elapseMinute(ewma); + +- elapseMinute(ewma); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001)); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); +- } ++ elapseMinute(ewma); + ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); ++ } + +- private void elapseMinute(EWMA ewma) { +- for (int i = 1; i <= 12; i++) { +- ewma.tick(); +- } ++ private void elapseMinute(EWMA ewma) { ++ for (int i = 1; i <= 12; i++) { ++ ewma.tick(); + } ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java +@@ -1,24 +1,23 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- +-import java.util.concurrent.TimeUnit; +- + import static org.junit.jupiter.api.Assertions.assertEquals; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + +-public class ExponentialMovingAveragesTest { +- @Test +- public void testMaxTicks() { +- final Clock clock = mock(Clock.class); +- when(clock.getTick()).thenReturn(0L, Long.MAX_VALUE); +- final ExponentialMovingAverages ema = new ExponentialMovingAverages(clock); +- ema.update(Long.MAX_VALUE); +- ema.tickIfNecessary(); +- final long secondNanos = TimeUnit.SECONDS.toNanos(1); +- assertEquals(ema.getM1Rate(), Double.MIN_NORMAL * secondNanos, 0.0); +- assertEquals(ema.getM5Rate(), Double.MIN_NORMAL * secondNanos, 0.0); +- assertEquals(ema.getM15Rate(), Double.MIN_NORMAL * secondNanos, 0.0); +- } ++import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.Test; ++ ++final class ExponentialMovingAveragesTest { ++ @Test ++ void maxTicks() { ++ final Clock clock = mock(); ++ when(clock.getTick()).thenReturn(0L, Long.MAX_VALUE); ++ final ExponentialMovingAverages ema = new ExponentialMovingAverages(clock); ++ ema.update(Long.MAX_VALUE); ++ ema.tickIfNecessary(); ++ final long secondNanos = TimeUnit.SECONDS.toNanos(1); ++ assertEquals(ema.getM1Rate(), Double.MIN_NORMAL * secondNanos, 0.0); ++ assertEquals(ema.getM5Rate(), Double.MIN_NORMAL * secondNanos, 0.0); ++ assertEquals(ema.getM15Rate(), Double.MIN_NORMAL * secondNanos, 0.0); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java +@@ -1,437 +1,405 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.params.ParameterizedTest; +-import org.junit.jupiter.params.provider.MethodSource; ++import static com.google.common.collect.ImmutableList.toImmutableList; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.util.Arrays; + import java.util.Collection; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicBoolean; + import java.util.concurrent.atomic.AtomicInteger; +-import java.util.stream.Collectors; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.params.ParameterizedTest; ++import org.junit.jupiter.params.provider.MethodSource; + +-public class ExponentiallyDecayingReservoirTest { ++final class ExponentiallyDecayingReservoirTest { + +- public enum ReservoirFactory { +- EXPONENTIALLY_DECAYING() { +- @Override +- Reservoir create(int size, double alpha, Clock clock) { +- return new ExponentiallyDecayingReservoir(size, alpha, clock); +- } ++ public enum ReservoirFactory { ++ EXPONENTIALLY_DECAYING() { ++ @Override ++ Reservoir create(int size, double alpha, Clock clock) { ++ return new ExponentiallyDecayingReservoir(size, alpha, clock); ++ } + }, + +- LOCK_FREE_EXPONENTIALLY_DECAYING() { +- @Override +- Reservoir create(int size, double alpha, Clock clock) { +- return LockFreeExponentiallyDecayingReservoir.builder() +- .size(size) +- .alpha(alpha) +- .clock(clock) +- .build(); +- } +- }; +- +- abstract Reservoir create(int size, double alpha, Clock clock); +- +- Reservoir create(int size, double alpha) { +- return create(size, alpha, Clock.defaultClock()); +- } ++ LOCK_FREE_EXPONENTIALLY_DECAYING() { ++ @Override ++ Reservoir create(int size, double alpha, Clock clock) { ++ return LockFreeExponentiallyDecayingReservoir.builder() ++ .size(size) ++ .alpha(alpha) ++ .clock(clock) ++ .build(); ++ } ++ }; ++ ++ abstract Reservoir create(int size, double alpha, Clock clock); ++ ++ Reservoir create(int size, double alpha) { ++ return create(size, alpha, Clock.defaultClock()); + } +- +- public static Collection reservoirs() { +- return Arrays.stream(ReservoirFactory.values()) +- .map(value -> new Object[]{value}) +- .collect(Collectors.toList()); ++ } ++ ++ public static Collection reservoirs() { ++ return Arrays.stream(ReservoirFactory.values()) ++ .map(value -> new Object[] {value}) ++ .collect(toImmutableList()); ++ } ++ ++ private ReservoirFactory reservoirFactory; ++ ++ public void initExponentiallyDecayingReservoirTest(ReservoirFactory reservoirFactory) { ++ this.reservoirFactory = reservoirFactory; ++ } ++ ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void aReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final Reservoir reservoir = reservoirFactory.create(100, 0.99); ++ for (int i = 0; i < 1000; i++) { ++ reservoir.update(i); + } + +- private ReservoirFactory reservoirFactory; +- +- public void initExponentiallyDecayingReservoirTest(ReservoirFactory reservoirFactory) { +- this.reservoirFactory = reservoirFactory; +- } +- +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void aReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final Reservoir reservoir = reservoirFactory.create(100, 0.99); +- for (int i = 0; i < 1000; i++) { +- reservoir.update(i); +- } ++ assertThat(reservoir.size()).isEqualTo(100); + +- assertThat(reservoir.size()) +- .isEqualTo(100); ++ final Snapshot snapshot = reservoir.getSnapshot(); + +- final Snapshot snapshot = reservoir.getSnapshot(); ++ assertThat(snapshot.size()).isEqualTo(100); + +- assertThat(snapshot.size()) +- .isEqualTo(100); ++ assertAllValuesBetween(reservoir, 0, 1000); ++ } + +- assertAllValuesBetween(reservoir, 0, 1000); ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void aReservoirOf100OutOf10Elements(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final Reservoir reservoir = reservoirFactory.create(100, 0.99); ++ for (int i = 0; i < 10; i++) { ++ reservoir.update(i); + } + +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void aReservoirOf100OutOf10Elements(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final Reservoir reservoir = reservoirFactory.create(100, 0.99); +- for (int i = 0; i < 10; i++) { +- reservoir.update(i); +- } ++ final Snapshot snapshot = reservoir.getSnapshot(); + +- final Snapshot snapshot = reservoir.getSnapshot(); ++ assertThat(snapshot.size()).isEqualTo(10); + +- assertThat(snapshot.size()) +- .isEqualTo(10); ++ assertThat(snapshot.size()).isEqualTo(10); + +- assertThat(snapshot.size()) +- .isEqualTo(10); ++ assertAllValuesBetween(reservoir, 0, 10); ++ } + +- assertAllValuesBetween(reservoir, 0, 10); ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void aHeavilyBiasedReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final Reservoir reservoir = reservoirFactory.create(1000, 0.01); ++ for (int i = 0; i < 100; i++) { ++ reservoir.update(i); + } + +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void aHeavilyBiasedReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final Reservoir reservoir = reservoirFactory.create(1000, 0.01); +- for (int i = 0; i < 100; i++) { +- reservoir.update(i); +- } ++ assertThat(reservoir.size()).isEqualTo(100); + ++ final Snapshot snapshot = reservoir.getSnapshot(); + +- assertThat(reservoir.size()) +- .isEqualTo(100); ++ assertThat(snapshot.size()).isEqualTo(100); + +- final Snapshot snapshot = reservoir.getSnapshot(); ++ assertAllValuesBetween(reservoir, 0, 100); ++ } + +- assertThat(snapshot.size()) +- .isEqualTo(100); ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void longPeriodsOfInactivityShouldNotCorruptSamplingState(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final ManualClock clock = new ManualClock(); ++ final Reservoir reservoir = reservoirFactory.create(10, 0.15, clock); + +- assertAllValuesBetween(reservoir, 0, 100); ++ // add 1000 values at a rate of 10 values/second ++ for (int i = 0; i < 1000; i++) { ++ reservoir.update(1000 + i); ++ clock.addMillis(100); + } +- +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void longPeriodsOfInactivityShouldNotCorruptSamplingState(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final ManualClock clock = new ManualClock(); +- final Reservoir reservoir = reservoirFactory.create(10, 0.15, clock); +- +- // add 1000 values at a rate of 10 values/second +- for (int i = 0; i < 1000; i++) { +- reservoir.update(1000 + i); +- clock.addMillis(100); +- } +- assertThat(reservoir.getSnapshot().size()) +- .isEqualTo(10); +- assertAllValuesBetween(reservoir, 1000, 2000); +- +- // wait for 15 hours and add another value. +- // this should trigger a rescale. Note that the number of samples will be reduced to 1 +- // because scaling factor equal to zero will remove all existing entries after rescale. +- clock.addHours(15); +- reservoir.update(2000); +- assertThat(reservoir.getSnapshot().size()) +- .isEqualTo(1); +- assertAllValuesBetween(reservoir, 1000, 2001); +- +- +- // add 1000 values at a rate of 10 values/second +- for (int i = 0; i < 1000; i++) { +- reservoir.update(3000 + i); +- clock.addMillis(100); +- } +- assertThat(reservoir.getSnapshot().size()) +- .isEqualTo(10); +- assertAllValuesBetween(reservoir, 3000, 4000); +- } +- +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void longPeriodsOfInactivity_fetchShouldResample(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final ManualClock clock = new ManualClock(); +- final Reservoir reservoir = reservoirFactory.create(10, +- 0.015, +- clock); +- +- // add 1000 values at a rate of 10 values/second +- for (int i = 0; i < 1000; i++) { +- reservoir.update(1000 + i); +- clock.addMillis(100); +- } +- assertThat(reservoir.getSnapshot().size()) +- .isEqualTo(10); +- assertAllValuesBetween(reservoir, 1000, 2000); +- +- // wait for 20 hours and take snapshot. +- // this should trigger a rescale. Note that the number of samples will be reduced to 0 +- // because scaling factor equal to zero will remove all existing entries after rescale. +- clock.addHours(20); +- Snapshot snapshot = reservoir.getSnapshot(); +- assertThat(snapshot.getMax()).isEqualTo(0); +- assertThat(snapshot.getMean()).isEqualTo(0); +- assertThat(snapshot.getMedian()).isEqualTo(0); +- assertThat(snapshot.size()).isEqualTo(0); ++ assertThat(reservoir.getSnapshot().size()).isEqualTo(10); ++ assertAllValuesBetween(reservoir, 1000, 2000); ++ ++ // wait for 15 hours and add another value. ++ // this should trigger a rescale. Note that the number of samples will be reduced to 1 ++ // because scaling factor equal to zero will remove all existing entries after rescale. ++ clock.addHours(15); ++ reservoir.update(2000); ++ assertThat(reservoir.getSnapshot().size()).isEqualTo(1); ++ assertAllValuesBetween(reservoir, 1000, 2001); ++ ++ // add 1000 values at a rate of 10 values/second ++ for (int i = 0; i < 1000; i++) { ++ reservoir.update(3000 + i); ++ clock.addMillis(100); + } +- +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void emptyReservoirSnapshot_shouldReturnZeroForAllValues(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final Reservoir reservoir = reservoirFactory.create(100, 0.015, +- new ManualClock()); +- +- Snapshot snapshot = reservoir.getSnapshot(); +- assertThat(snapshot.getMax()).isEqualTo(0); +- assertThat(snapshot.getMean()).isEqualTo(0); +- assertThat(snapshot.getMedian()).isEqualTo(0); +- assertThat(snapshot.size()).isEqualTo(0); ++ assertThat(reservoir.getSnapshot().size()).isEqualTo(10); ++ assertAllValuesBetween(reservoir, 3000, 4000); ++ } ++ ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void longPeriodsOfInactivity_fetchShouldResample(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final ManualClock clock = new ManualClock(); ++ final Reservoir reservoir = reservoirFactory.create(10, 0.015, clock); ++ ++ // add 1000 values at a rate of 10 values/second ++ for (int i = 0; i < 1000; i++) { ++ reservoir.update(1000 + i); ++ clock.addMillis(100); + } +- +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void removeZeroWeightsInSamplesToPreventNaNInMeanValues(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final ManualClock clock = new ManualClock(); +- final Reservoir reservoir = reservoirFactory.create(1028, 0.015, clock); +- Timer timer = new Timer(reservoir, clock); +- +- Timer.Context context = timer.time(); +- clock.addMillis(100); +- context.stop(); +- +- for (int i = 1; i < 48; i++) { +- clock.addHours(1); +- assertThat(reservoir.getSnapshot().getMean()).isBetween(0.0, Double.MAX_VALUE); +- } ++ assertThat(reservoir.getSnapshot().size()).isEqualTo(10); ++ assertAllValuesBetween(reservoir, 1000, 2000); ++ ++ // wait for 20 hours and take snapshot. ++ // this should trigger a rescale. Note that the number of samples will be reduced to 0 ++ // because scaling factor equal to zero will remove all existing entries after rescale. ++ clock.addHours(20); ++ Snapshot snapshot = reservoir.getSnapshot(); ++ assertThat(snapshot.getMax()).isEqualTo(0); ++ assertThat(snapshot.getMean()).isEqualTo(0); ++ assertThat(snapshot.getMedian()).isEqualTo(0); ++ assertThat(snapshot.size()).isEqualTo(0); ++ } ++ ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void emptyReservoirSnapshot_shouldReturnZeroForAllValues(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final Reservoir reservoir = reservoirFactory.create(100, 0.015, new ManualClock()); ++ ++ Snapshot snapshot = reservoir.getSnapshot(); ++ assertThat(snapshot.getMax()).isEqualTo(0); ++ assertThat(snapshot.getMean()).isEqualTo(0); ++ assertThat(snapshot.getMedian()).isEqualTo(0); ++ assertThat(snapshot.size()).isEqualTo(0); ++ } ++ ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void removeZeroWeightsInSamplesToPreventNaNInMeanValues(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final ManualClock clock = new ManualClock(); ++ final Reservoir reservoir = reservoirFactory.create(1028, 0.015, clock); ++ Timer timer = new Timer(reservoir, clock); ++ ++ Timer.Context context = timer.time(); ++ clock.addMillis(100); ++ context.stop(); ++ ++ for (int i = 1; i < 48; i++) { ++ clock.addHours(1); ++ assertThat(reservoir.getSnapshot().getMean()).isBetween(0.0, Double.MAX_VALUE); + } +- +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void multipleUpdatesAfterlongPeriodsOfInactivityShouldNotCorruptSamplingState(ReservoirFactory reservoirFactory) throws Exception { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- // This test illustrates the potential race condition in rescale that +- // can lead to a corrupt state. Note that while this test uses updates +- // exclusively to trigger the race condition, two concurrent updates +- // may be made much more likely to trigger this behavior if executed +- // while another thread is constructing a snapshot of the reservoir; +- // that thread then holds the read lock when the two competing updates +- // are executed and the race condition's window is substantially +- // expanded. +- +- // Run the test several times. +- for (int attempt = 0; attempt < 10; attempt++) { +- final ManualClock clock = new ManualClock(); +- final Reservoir reservoir = reservoirFactory.create(10, +- 0.015, +- clock); +- +- // Various atomics used to communicate between this thread and the +- // thread created below. +- final AtomicBoolean running = new AtomicBoolean(true); +- final AtomicInteger threadUpdates = new AtomicInteger(0); +- final AtomicInteger testUpdates = new AtomicInteger(0); +- +- final Thread thread = new Thread(() -> { ++ } ++ ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void multipleUpdatesAfterlongPeriodsOfInactivityShouldNotCorruptSamplingState( ++ ReservoirFactory reservoirFactory) throws Exception { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ // This test illustrates the potential race condition in rescale that ++ // can lead to a corrupt state. Note that while this test uses updates ++ // exclusively to trigger the race condition, two concurrent updates ++ // may be made much more likely to trigger this behavior if executed ++ // while another thread is constructing a snapshot of the reservoir; ++ // that thread then holds the read lock when the two competing updates ++ // are executed and the race condition's window is substantially ++ // expanded. ++ ++ // Run the test several times. ++ for (int attempt = 0; attempt < 10; attempt++) { ++ final ManualClock clock = new ManualClock(); ++ final Reservoir reservoir = reservoirFactory.create(10, 0.015, clock); ++ ++ // Various atomics used to communicate between this thread and the ++ // thread created below. ++ final AtomicBoolean running = new AtomicBoolean(true); ++ final AtomicInteger threadUpdates = new AtomicInteger(0); ++ final AtomicInteger testUpdates = new AtomicInteger(0); ++ ++ final Thread thread = ++ new Thread( ++ () -> { + int previous = 0; + while (running.get()) { +- // Wait for the test thread to update it's counter +- // before updaing the reservoir. +- while (true) { +- int next = testUpdates.get(); +- if (previous < next) { +- previous = next; +- break; +- } ++ // Wait for the test thread to update it's counter ++ // before updaing the reservoir. ++ while (true) { ++ int next = testUpdates.get(); ++ if (previous < next) { ++ previous = next; ++ break; + } ++ } + +- // Update the reservoir. This needs to occur at the +- // same time as the test thread's update. +- reservoir.update(1000); ++ // Update the reservoir. This needs to occur at the ++ // same time as the test thread's update. ++ reservoir.update(1000); + +- // Signal the main thread; allows the next update +- // attempt to begin. +- threadUpdates.incrementAndGet(); +- } +- }); +- +- thread.start(); +- +- int sum = 0; +- int previous = -1; +- for (int i = 0; i < 100; i++) { +- // Wait for 15 hours before attempting the next concurrent +- // update. The delay here needs to be sufficiently long to +- // overflow if an update attempt is allowed to add a value to +- // the reservoir without rescaling. Note that: +- // e(alpha*(15*60*60)) =~ 10^351 >> Double.MAX_VALUE =~ 1.8*10^308. +- clock.addHours(15); +- +- // Signal the other thread; asynchronously updates the reservoir. +- testUpdates.incrementAndGet(); +- +- // Delay a variable length of time. Without a delay here this +- // thread is heavily favored and the race condition is almost +- // never observed. +- for (int j = 0; j < i; j++) +- sum += j; +- +- // Competing reservoir update. +- reservoir.update(1000); +- +- // Wait for the other thread to finish it's update. +- while (true) { +- int next = threadUpdates.get(); +- if (previous < next) { +- previous = next; +- break; +- } ++ // Signal the main thread; allows the next update ++ // attempt to begin. ++ threadUpdates.incrementAndGet(); + } +- } ++ }); ++ ++ thread.start(); ++ ++ int sum = 0; ++ int previous = -1; ++ for (int i = 0; i < 100; i++) { ++ // Wait for 15 hours before attempting the next concurrent ++ // update. The delay here needs to be sufficiently long to ++ // overflow if an update attempt is allowed to add a value to ++ // the reservoir without rescaling. Note that: ++ // e(alpha*(15*60*60)) =~ 10^351 >> Double.MAX_VALUE =~ 1.8*10^308. ++ clock.addHours(15); + +- // Terminate the thread. +- running.set(false); +- testUpdates.incrementAndGet(); +- thread.join(); ++ // Signal the other thread; asynchronously updates the reservoir. ++ testUpdates.incrementAndGet(); + +- // Test failures will result in normWeights that are not finite; +- // checking the mean value here is sufficient. +- assertThat(reservoir.getSnapshot().getMean()).isBetween(0.0, Double.MAX_VALUE); ++ // Delay a variable length of time. Without a delay here this ++ // thread is heavily favored and the race condition is almost ++ // never observed. ++ for (int j = 0; j < i; j++) sum += j; + +- // Check the value of sum; should prevent the JVM from optimizing +- // out the delay loop entirely. +- assertThat(sum).isEqualTo(161700); +- } +- } ++ // Competing reservoir update. ++ reservoir.update(1000); + +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void spotLift(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final ManualClock clock = new ManualClock(); +- final Reservoir reservoir = reservoirFactory.create(1000, +- 0.015, +- clock); +- +- final int valuesRatePerMinute = 10; +- final int valuesIntervalMillis = (int) (TimeUnit.MINUTES.toMillis(1) / valuesRatePerMinute); +- // mode 1: steady regime for 120 minutes +- for (int i = 0; i < 120 * valuesRatePerMinute; i++) { +- reservoir.update(177); +- clock.addMillis(valuesIntervalMillis); ++ // Wait for the other thread to finish it's update. ++ while (true) { ++ int next = threadUpdates.get(); ++ if (previous < next) { ++ previous = next; ++ break; ++ } + } ++ } + +- // switching to mode 2: 10 minutes more with the same rate, but larger value +- for (int i = 0; i < 10 * valuesRatePerMinute; i++) { +- reservoir.update(9999); +- clock.addMillis(valuesIntervalMillis); +- } ++ // Terminate the thread. ++ running.set(false); ++ testUpdates.incrementAndGet(); ++ thread.join(); + +- // expect that quantiles should be more about mode 2 after 10 minutes +- assertThat(reservoir.getSnapshot().getMedian()) +- .isEqualTo(9999); +- } ++ // Test failures will result in normWeights that are not finite; ++ // checking the mean value here is sufficient. ++ assertThat(reservoir.getSnapshot().getMean()).isBetween(0.0, Double.MAX_VALUE); + +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void spotFall(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final ManualClock clock = new ManualClock(); +- final Reservoir reservoir = reservoirFactory.create(1000, +- 0.015, +- clock); +- +- final int valuesRatePerMinute = 10; +- final int valuesIntervalMillis = (int) (TimeUnit.MINUTES.toMillis(1) / valuesRatePerMinute); +- // mode 1: steady regime for 120 minutes +- for (int i = 0; i < 120 * valuesRatePerMinute; i++) { +- reservoir.update(9998); +- clock.addMillis(valuesIntervalMillis); +- } +- +- // switching to mode 2: 10 minutes more with the same rate, but smaller value +- for (int i = 0; i < 10 * valuesRatePerMinute; i++) { +- reservoir.update(178); +- clock.addMillis(valuesIntervalMillis); +- } +- +- // expect that quantiles should be more about mode 2 after 10 minutes +- assertThat(reservoir.getSnapshot().get95thPercentile()) +- .isEqualTo(178); ++ // Check the value of sum; should prevent the JVM from optimizing ++ // out the delay loop entirely. ++ assertThat(sum).isEqualTo(161700); ++ } ++ } ++ ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void spotLift(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final ManualClock clock = new ManualClock(); ++ final Reservoir reservoir = reservoirFactory.create(1000, 0.015, clock); ++ ++ final int valuesRatePerMinute = 10; ++ final int valuesIntervalMillis = (int) (TimeUnit.MINUTES.toMillis(1) / valuesRatePerMinute); ++ // mode 1: steady regime for 120 minutes ++ for (int i = 0; i < 120 * valuesRatePerMinute; i++) { ++ reservoir.update(177); ++ clock.addMillis(valuesIntervalMillis); + } + +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void quantiliesShouldBeBasedOnWeights(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- final ManualClock clock = new ManualClock(); +- final Reservoir reservoir = reservoirFactory.create(1000, +- 0.015, +- clock); +- for (int i = 0; i < 40; i++) { +- reservoir.update(177); +- } +- +- clock.addSeconds(120); +- +- for (int i = 0; i < 10; i++) { +- reservoir.update(9999); +- } ++ // switching to mode 2: 10 minutes more with the same rate, but larger value ++ for (int i = 0; i < 10 * valuesRatePerMinute; i++) { ++ reservoir.update(9999); ++ clock.addMillis(valuesIntervalMillis); ++ } + +- assertThat(reservoir.getSnapshot().size()) +- .isEqualTo(50); ++ // expect that quantiles should be more about mode 2 after 10 minutes ++ assertThat(reservoir.getSnapshot().getMedian()).isEqualTo(9999); ++ } ++ ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void spotFall(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final ManualClock clock = new ManualClock(); ++ final Reservoir reservoir = reservoirFactory.create(1000, 0.015, clock); ++ ++ final int valuesRatePerMinute = 10; ++ final int valuesIntervalMillis = (int) (TimeUnit.MINUTES.toMillis(1) / valuesRatePerMinute); ++ // mode 1: steady regime for 120 minutes ++ for (int i = 0; i < 120 * valuesRatePerMinute; i++) { ++ reservoir.update(9998); ++ clock.addMillis(valuesIntervalMillis); ++ } + +- // the first added 40 items (177) have weights 1 +- // the next added 10 items (9999) have weights ~6 +- // so, it's 40 vs 60 distribution, not 40 vs 10 +- assertThat(reservoir.getSnapshot().getMedian()) +- .isEqualTo(9999); +- assertThat(reservoir.getSnapshot().get75thPercentile()) +- .isEqualTo(9999); ++ // switching to mode 2: 10 minutes more with the same rate, but smaller value ++ for (int i = 0; i < 10 * valuesRatePerMinute; i++) { ++ reservoir.update(178); ++ clock.addMillis(valuesIntervalMillis); + } + +- @MethodSource("reservoirs") +- @ParameterizedTest(name = "{index}: {0}") +- void clockWrapShouldNotRescale(ReservoirFactory reservoirFactory) { +- initExponentiallyDecayingReservoirTest(reservoirFactory); +- // First verify the test works as expected given low values +- testShortPeriodShouldNotRescale(0); +- // Now revalidate using an edge case nanoTime value just prior to wrapping +- testShortPeriodShouldNotRescale(Long.MAX_VALUE - TimeUnit.MINUTES.toNanos(30)); ++ // expect that quantiles should be more about mode 2 after 10 minutes ++ assertThat(reservoir.getSnapshot().get95thPercentile()).isEqualTo(178); ++ } ++ ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void quantiliesShouldBeBasedOnWeights(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ final ManualClock clock = new ManualClock(); ++ final Reservoir reservoir = reservoirFactory.create(1000, 0.015, clock); ++ for (int i = 0; i < 40; i++) { ++ reservoir.update(177); + } + +- private void testShortPeriodShouldNotRescale(long startTimeNanos) { +- final ManualClock clock = new ManualClock(startTimeNanos); +- final Reservoir reservoir = reservoirFactory.create(10, 1, clock); ++ clock.addSeconds(120); + +- reservoir.update(1000); +- assertThat(reservoir.getSnapshot().size()).isEqualTo(1); +- +- assertAllValuesBetween(reservoir, 1000, 1001); +- +- // wait for 10 millis and take snapshot. +- // this should not trigger a rescale. Note that the number of samples will be reduced to 0 +- // because scaling factor equal to zero will remove all existing entries after rescale. +- clock.addSeconds(20 * 60); +- Snapshot snapshot = reservoir.getSnapshot(); +- assertThat(snapshot.getMax()).isEqualTo(1000); +- assertThat(snapshot.getMean()).isEqualTo(1000); +- assertThat(snapshot.getMedian()).isEqualTo(1000); +- assertThat(snapshot.size()).isEqualTo(1); ++ for (int i = 0; i < 10; i++) { ++ reservoir.update(9999); + } + +- private static void assertAllValuesBetween(Reservoir reservoir, +- double min, +- double max) { +- for (double i : reservoir.getSnapshot().getValues()) { +- assertThat(i) +- .isLessThan(max) +- .isGreaterThanOrEqualTo(min); +- } ++ assertThat(reservoir.getSnapshot().size()).isEqualTo(50); ++ ++ // the first added 40 items (177) have weights 1 ++ // the next added 10 items (9999) have weights ~6 ++ // so, it's 40 vs 60 distribution, not 40 vs 10 ++ assertThat(reservoir.getSnapshot().getMedian()).isEqualTo(9999); ++ assertThat(reservoir.getSnapshot().get75thPercentile()).isEqualTo(9999); ++ } ++ ++ @MethodSource("reservoirs") ++ @ParameterizedTest(name = "{index}: {0}") ++ void clockWrapShouldNotRescale(ReservoirFactory reservoirFactory) { ++ initExponentiallyDecayingReservoirTest(reservoirFactory); ++ // First verify the test works as expected given low values ++ testShortPeriodShouldNotRescale(0); ++ // Now revalidate using an edge case nanoTime value just prior to wrapping ++ testShortPeriodShouldNotRescale(Long.MAX_VALUE - TimeUnit.MINUTES.toNanos(30)); ++ } ++ ++ private void testShortPeriodShouldNotRescale(long startTimeNanos) { ++ final ManualClock clock = new ManualClock(startTimeNanos); ++ final Reservoir reservoir = reservoirFactory.create(10, 1, clock); ++ ++ reservoir.update(1000); ++ assertThat(reservoir.getSnapshot().size()).isEqualTo(1); ++ ++ assertAllValuesBetween(reservoir, 1000, 1001); ++ ++ // wait for 10 millis and take snapshot. ++ // this should not trigger a rescale. Note that the number of samples will be reduced to 0 ++ // because scaling factor equal to zero will remove all existing entries after rescale. ++ clock.addSeconds(20 * 60); ++ Snapshot snapshot = reservoir.getSnapshot(); ++ assertThat(snapshot.getMax()).isEqualTo(1000); ++ assertThat(snapshot.getMean()).isEqualTo(1000); ++ assertThat(snapshot.getMedian()).isEqualTo(1000); ++ assertThat(snapshot.size()).isEqualTo(1); ++ } ++ ++ private static void assertAllValuesBetween(Reservoir reservoir, double min, double max) { ++ for (double i : reservoir.getSnapshot().getValues()) { ++ assertThat(i).isLessThan(max).isGreaterThanOrEqualTo(min); + } +- ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java +@@ -1,47 +1,45 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +-import org.junit.jupiter.api.io.TempDir; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.io.File; + import java.io.IOException; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; ++import org.junit.jupiter.api.io.TempDir; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-public class FixedNameCsvFileProviderTest { +- @TempDir +- public File folder; +- +- private File dataDirectory; +- +- @BeforeEach +- void setUp() throws Exception { +- this.dataDirectory = newFolder(folder, "junit"); +- } +- +- @Test +- void testGetFile() { +- FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); +- File file = provider.getFile(dataDirectory, "test"); +- assertThat(file.getParentFile()).isEqualTo(dataDirectory); +- assertThat(file.getName()).isEqualTo("test.csv"); +- } +- +- @Test +- void testGetFileSanitize() { +- FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); +- File file = provider.getFile(dataDirectory, "/myfake/uri"); +- assertThat(file.getParentFile()).isEqualTo(dataDirectory); +- assertThat(file.getName()).isEqualTo("myfake.uri.csv"); +- } +- +- private static File newFolder(File root, String... subDirs) throws IOException { +- String subFolder = String.join("/", subDirs); +- File result = new File(root, subFolder); +- if (!result.mkdirs()) { +- throw new IOException("Couldn't create folders " + root); +- } +- return result; ++final class FixedNameCsvFileProviderTest { ++ @TempDir public File folder; ++ ++ private File dataDirectory; ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ this.dataDirectory = newFolder(folder, "junit"); ++ } ++ ++ @Test ++ void getFile() { ++ FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); ++ File file = provider.getFile(dataDirectory, "test"); ++ assertThat(file.getParentFile()).isEqualTo(dataDirectory); ++ assertThat(file.getName()).isEqualTo("test.csv"); ++ } ++ ++ @Test ++ void getFileSanitize() { ++ FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); ++ File file = provider.getFile(dataDirectory, "/myfake/uri"); ++ assertThat(file.getParentFile()).isEqualTo(dataDirectory); ++ assertThat(file.getName()).isEqualTo("myfake.uri.csv"); ++ } ++ ++ private static File newFolder(File root, String... subDirs) throws IOException { ++ String subFolder = String.join("/", subDirs); ++ File result = new File(root, subFolder); ++ if (!result.mkdirs()) { ++ throw new IOException("Couldn't create folders " + root); + } +-} +\ No newline at end of file ++ return result; ++ } ++} +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java +@@ -1,45 +1,40 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +-class HistogramTest { +- private final Reservoir reservoir = mock(Reservoir.class); +- private final Histogram histogram = new Histogram(reservoir); +- +- @Test +- void updatesTheCountAndSumOnUpdates() { +- assertThat(histogram.getCount()) +- .isZero(); +- assertThat(histogram.getSum()) +- .isZero(); +- +- histogram.update(1); +- histogram.update(5); +- +- assertThat(histogram.getCount()) +- .isEqualTo(2); +- assertThat(histogram.getSum()) +- .isEqualTo(6); +- } +- +- @Test +- void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); +- when(reservoir.getSnapshot()).thenReturn(snapshot); +- +- assertThat(histogram.getSnapshot()) +- .isEqualTo(snapshot); +- } +- +- @Test +- void updatesTheReservoir() throws Exception { +- histogram.update(1); +- +- verify(reservoir).update(1); +- } ++import org.junit.jupiter.api.Test; ++ ++final class HistogramTest { ++ private final Reservoir reservoir = mock(); ++ private final Histogram histogram = new Histogram(reservoir); ++ ++ @Test ++ void updatesTheCountAndSumOnUpdates() { ++ assertThat(histogram.getCount()).isEqualTo(0); ++ assertThat(histogram.getSum()).isEqualTo(0); ++ ++ histogram.update(1); ++ histogram.update(5); ++ ++ assertThat(histogram.getCount()).isEqualTo(2); ++ assertThat(histogram.getSum()).isEqualTo(6); ++ } ++ ++ @Test ++ void returnsTheSnapshotFromTheReservoir() { ++ final Snapshot snapshot = mock(); ++ when(reservoir.getSnapshot()).thenReturn(snapshot); ++ ++ assertThat(histogram.getSnapshot()).isEqualTo(snapshot); ++ } ++ ++ @Test ++ void updatesTheReservoir() throws Exception { ++ histogram.update(1); ++ ++ verify(reservoir).update(1); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java +@@ -1,10 +1,7 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + + import java.time.Duration; + import java.util.concurrent.Callable; +@@ -16,283 +13,301 @@ import java.util.concurrent.LinkedBlockingQueue; + import java.util.concurrent.RejectedExecutionException; + import java.util.concurrent.ThreadPoolExecutor; + import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatThrownBy; +- +-class InstrumentedExecutorServiceTest { +- +- private static final Logger LOGGER = LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); +- private ExecutorService executor; +- private MetricRegistry registry; +- private InstrumentedExecutorService instrumentedExecutorService; +- private Meter submitted; +- private Counter running; +- private Meter completed; +- private Timer duration; +- private Timer idle; +- +- @BeforeEach +- void setup() { +- executor = Executors.newCachedThreadPool(); +- registry = new MetricRegistry(); +- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "xs"); +- submitted = registry.meter("xs.submitted"); +- running = registry.counter("xs.running"); +- completed = registry.meter("xs.completed"); +- duration = registry.timer("xs.duration"); +- idle = registry.timer("xs.idle"); +- } +- +- @AfterEach +- void tearDown() throws Exception { +- instrumentedExecutorService.shutdown(); +- if (!instrumentedExecutorService.awaitTermination(2, TimeUnit.SECONDS)) { +- LOGGER.error("InstrumentedExecutorService did not terminate."); +- } ++final class InstrumentedExecutorServiceTest { ++ ++ private static final Logger LOG = LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); ++ private ExecutorService executor; ++ private MetricRegistry registry; ++ private InstrumentedExecutorService instrumentedExecutorService; ++ private Meter submitted; ++ private Counter running; ++ private Meter completed; ++ private Timer duration; ++ private Timer idle; ++ ++ @BeforeEach ++ void setup() { ++ executor = Executors.newCachedThreadPool(); ++ registry = new MetricRegistry(); ++ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "xs"); ++ submitted = registry.meter("xs.submitted"); ++ running = registry.counter("xs.running"); ++ completed = registry.meter("xs.completed"); ++ duration = registry.timer("xs.duration"); ++ idle = registry.timer("xs.idle"); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ instrumentedExecutorService.shutdown(); ++ if (!instrumentedExecutorService.awaitTermination(2, TimeUnit.SECONDS)) { ++ LOG.error("InstrumentedExecutorService did not terminate."); + } +- +- @Test +- void reportsTasksInformationForRunnable() throws Exception { +- +- assertThat(submitted.getCount()).isEqualTo(0); +- assertThat(running.getCount()).isEqualTo(0); +- assertThat(completed.getCount()).isEqualTo(0); +- assertThat(duration.getCount()).isEqualTo(0); +- assertThat(idle.getCount()).isEqualTo(0); +- +- Runnable runnable = () -> { +- assertThat(submitted.getCount()).isEqualTo(1); +- assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isEqualTo(0); +- assertThat(duration.getCount()).isEqualTo(0); +- assertThat(idle.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void reportsTasksInformationForRunnable() throws Exception { ++ ++ assertThat(submitted.getCount()).isEqualTo(0); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ assertThat(idle.getCount()).isEqualTo(0); ++ ++ Runnable runnable = ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(1); ++ assertThat(running.getCount()).isEqualTo(1); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ assertThat(idle.getCount()).isEqualTo(1); + }; + +- Future theFuture = instrumentedExecutorService.submit(runnable); +- +- theFuture.get(); +- +- assertThat(submitted.getCount()).isEqualTo(1); +- assertThat(running.getCount()).isEqualTo(0); +- assertThat(completed.getCount()).isEqualTo(1); +- assertThat(duration.getCount()).isEqualTo(1); +- assertThat(duration.getSnapshot().size()).isEqualTo(1); +- assertThat(idle.getCount()).isEqualTo(1); +- assertThat(idle.getSnapshot().size()).isEqualTo(1); +- } +- +- @Test +- void reportsTasksInformationForCallable() throws Exception { +- +- assertThat(submitted.getCount()).isEqualTo(0); +- assertThat(running.getCount()).isEqualTo(0); +- assertThat(completed.getCount()).isEqualTo(0); +- assertThat(duration.getCount()).isEqualTo(0); +- assertThat(idle.getCount()).isEqualTo(0); +- +- Callable callable = () -> { +- assertThat(submitted.getCount()).isEqualTo(1); +- assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isEqualTo(0); +- assertThat(duration.getCount()).isEqualTo(0); +- assertThat(idle.getCount()).isEqualTo(1); +- return null; ++ Future theFuture = instrumentedExecutorService.submit(runnable); ++ ++ theFuture.get(); ++ ++ assertThat(submitted.getCount()).isEqualTo(1); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(1); ++ assertThat(duration.getCount()).isEqualTo(1); ++ assertThat(duration.getSnapshot().size()).isEqualTo(1); ++ assertThat(idle.getCount()).isEqualTo(1); ++ assertThat(idle.getSnapshot().size()).isEqualTo(1); ++ } ++ ++ @Test ++ void reportsTasksInformationForCallable() throws Exception { ++ ++ assertThat(submitted.getCount()).isEqualTo(0); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ assertThat(idle.getCount()).isEqualTo(0); ++ ++ Callable callable = ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(1); ++ assertThat(running.getCount()).isEqualTo(1); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ assertThat(idle.getCount()).isEqualTo(1); ++ return null; + }; + +- Future theFuture = instrumentedExecutorService.submit(callable); +- +- theFuture.get(); +- +- assertThat(submitted.getCount()).isEqualTo(1); +- assertThat(running.getCount()).isEqualTo(0); +- assertThat(completed.getCount()).isEqualTo(1); +- assertThat(duration.getCount()).isEqualTo(1); +- assertThat(duration.getSnapshot().size()).isEqualTo(1); +- assertThat(idle.getCount()).isEqualTo(1); +- assertThat(idle.getSnapshot().size()).isEqualTo(1); +- } +- +- @Test +- @SuppressWarnings("unchecked") +- void reportsTasksInformationForThreadPoolExecutor() throws Exception { +- executor = new ThreadPoolExecutor(4, 16, +- 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); +- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); +- submitted = registry.meter("tp.submitted"); +- running = registry.counter("tp.running"); +- completed = registry.meter("tp.completed"); +- duration = registry.timer("tp.duration"); +- idle = registry.timer("tp.idle"); +- final Gauge poolSize = (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "size")); +- final Gauge poolCoreSize = (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "core")); +- final Gauge poolMaxSize = (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "max")); +- final Gauge tasksActive = (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "active")); +- final Gauge tasksCompleted = (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "completed")); +- final Gauge tasksQueued = (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "queued")); +- final Gauge tasksCapacityRemaining = (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "capacity")); +- +- assertThat(submitted.getCount()).isEqualTo(0); +- assertThat(running.getCount()).isEqualTo(0); +- assertThat(completed.getCount()).isEqualTo(0); +- assertThat(duration.getCount()).isEqualTo(0); +- assertThat(idle.getCount()).isEqualTo(0); +- assertThat(poolSize.getValue()).isEqualTo(0); +- assertThat(poolCoreSize.getValue()).isEqualTo(4); +- assertThat(poolMaxSize.getValue()).isEqualTo(16); +- assertThat(tasksActive.getValue()).isEqualTo(0); +- assertThat(tasksCompleted.getValue()).isEqualTo(0L); +- assertThat(tasksQueued.getValue()).isEqualTo(0); +- assertThat(tasksCapacityRemaining.getValue()).isEqualTo(32); +- +- Runnable runnable = () -> { +- assertThat(submitted.getCount()).isEqualTo(1); +- assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isEqualTo(0); +- assertThat(duration.getCount()).isEqualTo(0); +- assertThat(idle.getCount()).isEqualTo(1); +- assertThat(tasksActive.getValue()).isEqualTo(1); +- assertThat(tasksQueued.getValue()).isEqualTo(0); ++ Future theFuture = instrumentedExecutorService.submit(callable); ++ ++ theFuture.get(); ++ ++ assertThat(submitted.getCount()).isEqualTo(1); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(1); ++ assertThat(duration.getCount()).isEqualTo(1); ++ assertThat(duration.getSnapshot().size()).isEqualTo(1); ++ assertThat(idle.getCount()).isEqualTo(1); ++ assertThat(idle.getSnapshot().size()).isEqualTo(1); ++ } ++ ++ @SuppressWarnings("unchecked") ++ @Test ++ void reportsTasksInformationForThreadPoolExecutor() throws Exception { ++ executor = ++ new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); ++ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); ++ submitted = registry.meter("tp.submitted"); ++ running = registry.counter("tp.running"); ++ completed = registry.meter("tp.completed"); ++ duration = registry.timer("tp.duration"); ++ idle = registry.timer("tp.idle"); ++ final Gauge poolSize = ++ (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "size")); ++ final Gauge poolCoreSize = ++ (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "core")); ++ final Gauge poolMaxSize = ++ (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "max")); ++ final Gauge tasksActive = ++ (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "active")); ++ final Gauge tasksCompleted = ++ (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "completed")); ++ final Gauge tasksQueued = ++ (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "queued")); ++ final Gauge tasksCapacityRemaining = ++ (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "capacity")); ++ ++ assertThat(submitted.getCount()).isEqualTo(0); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ assertThat(idle.getCount()).isEqualTo(0); ++ assertThat(poolSize.getValue()).isEqualTo(0); ++ assertThat(poolCoreSize.getValue()).isEqualTo(4); ++ assertThat(poolMaxSize.getValue()).isEqualTo(16); ++ assertThat(tasksActive.getValue()).isEqualTo(0); ++ assertThat(tasksCompleted.getValue()).isEqualTo(0L); ++ assertThat(tasksQueued.getValue()).isEqualTo(0); ++ assertThat(tasksCapacityRemaining.getValue()).isEqualTo(32); ++ ++ Runnable runnable = ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(1); ++ assertThat(running.getCount()).isEqualTo(1); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ assertThat(idle.getCount()).isEqualTo(1); ++ assertThat(tasksActive.getValue()).isEqualTo(1); ++ assertThat(tasksQueued.getValue()).isEqualTo(0); + }; + +- Future theFuture = instrumentedExecutorService.submit(runnable); +- +- assertThat(theFuture).succeedsWithin(Duration.ofSeconds(5L)); +- +- assertThat(submitted.getCount()).isEqualTo(1); +- assertThat(running.getCount()).isEqualTo(0); +- assertThat(completed.getCount()).isEqualTo(1); +- assertThat(duration.getCount()).isEqualTo(1); +- assertThat(duration.getSnapshot().size()).isEqualTo(1); +- assertThat(idle.getCount()).isEqualTo(1); +- assertThat(idle.getSnapshot().size()).isEqualTo(1); +- assertThat(poolSize.getValue()).isEqualTo(1); +- } +- +- @Test +- public void reportsRejectedTasksForThreadPoolExecutor() throws Exception { +- executor = new ThreadPoolExecutor(1, 1, +- 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1)); +- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); +- final Counter rejected = registry.counter("tp.rejected"); +- assertThat(rejected.getCount()).isEqualTo(0); +- +- final CountDownLatch latch = new CountDownLatch(1); +- +- Runnable runnable = () -> { +- try { +- latch.await(); +- } catch (InterruptedException e) { +- throw new RuntimeException(e); +- } ++ Future theFuture = instrumentedExecutorService.submit(runnable); ++ ++ assertThat(theFuture).succeedsWithin(Duration.ofSeconds(5L)); ++ ++ assertThat(submitted.getCount()).isEqualTo(1); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(1); ++ assertThat(duration.getCount()).isEqualTo(1); ++ assertThat(duration.getSnapshot().size()).isEqualTo(1); ++ assertThat(idle.getCount()).isEqualTo(1); ++ assertThat(idle.getSnapshot().size()).isEqualTo(1); ++ assertThat(poolSize.getValue()).isEqualTo(1); ++ } ++ ++ @Test ++ void reportsRejectedTasksForThreadPoolExecutor() throws Exception { ++ executor = ++ new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1)); ++ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); ++ final Counter rejected = registry.counter("tp.rejected"); ++ assertThat(rejected.getCount()).isEqualTo(0); ++ ++ final CountDownLatch latch = new CountDownLatch(1); ++ ++ Runnable runnable = ++ () -> { ++ try { ++ latch.await(); ++ } catch (InterruptedException e) { ++ throw new RuntimeException(e); ++ } + }; + +- Future executingFuture = instrumentedExecutorService.submit(runnable); +- Future queuedFuture = instrumentedExecutorService.submit(runnable); +- assertThatThrownBy(() -> instrumentedExecutorService.submit(runnable)) +- .isInstanceOf(RejectedExecutionException.class); +- latch.countDown(); +- assertThat(rejected.getCount()).isEqualTo(1); +- } +- +- @Test +- public void removesMetricsAfterShutdownForThreadPoolExecutor() { +- executor = new ThreadPoolExecutor(4, 16, +- 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); +- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "stp"); +- +- MetricName prefix = MetricName.build("stp"); +- assertThat(registry.getMetrics()).containsKeys( +- MetricRegistry.name("stp", "pool.size"), +- MetricRegistry.name("stp", "pool.core"), +- MetricRegistry.name("stp", "pool.max"), +- MetricRegistry.name("stp", "tasks.active"), +- MetricRegistry.name("stp", "tasks.completed"), +- MetricRegistry.name("stp", "tasks.queued"), +- MetricRegistry.name("stp", "tasks.capacity") +- ); +- +- instrumentedExecutorService.shutdown(); +- +- assertThat(registry.getMetrics()).doesNotContainKeys( +- MetricRegistry.name("stp", "pool.size"), +- MetricRegistry.name("stp", "pool.core"), +- MetricRegistry.name("stp", "pool.max"), +- MetricRegistry.name("stp", "tasks.active"), +- MetricRegistry.name("stp", "tasks.completed"), +- MetricRegistry.name("stp", "tasks.queued"), +- MetricRegistry.name("stp", "tasks.capacity") +- ); +- } +- +- @Test +- @SuppressWarnings("unchecked") +- void reportsTasksInformationForForkJoinPool() throws Exception { +- executor = Executors.newWorkStealingPool(4); +- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); +- submitted = registry.meter("fjp.submitted"); +- running = registry.counter("fjp.running"); +- completed = registry.meter("fjp.completed"); +- duration = registry.timer("fjp.duration"); +- idle = registry.timer("fjp.idle"); +- final Gauge tasksStolen = (Gauge) registry.getGauges().get(MetricName.build("fjp", "tasks", "stolen")); +- final Gauge tasksQueued = (Gauge) registry.getGauges().get(MetricName.build("fjp", "tasks", "queued")); +- final Gauge threadsActive = (Gauge) registry.getGauges().get(MetricName.build("fjp", "threads", "active")); +- final Gauge threadsRunning = (Gauge) registry.getGauges().get(MetricName.build("fjp", "threads", "running")); +- +- assertThat(submitted.getCount()).isEqualTo(0); +- assertThat(running.getCount()).isEqualTo(0); +- assertThat(completed.getCount()).isEqualTo(0); +- assertThat(duration.getCount()).isEqualTo(0); +- assertThat(idle.getCount()).isEqualTo(0); +- assertThat(tasksStolen.getValue()).isEqualTo(0L); +- assertThat(tasksQueued.getValue()).isEqualTo(0L); +- assertThat(threadsActive.getValue()).isEqualTo(0); +- assertThat(threadsRunning.getValue()).isEqualTo(0); +- +- Runnable runnable = () -> { +- assertThat(submitted.getCount()).isEqualTo(1); +- assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isEqualTo(0); +- assertThat(duration.getCount()).isEqualTo(0); +- assertThat(idle.getCount()).isEqualTo(1); +- assertThat(tasksQueued.getValue()).isEqualTo(0L); +- assertThat(threadsActive.getValue()).isEqualTo(1); +- assertThat(threadsRunning.getValue()).isEqualTo(1); ++ Future executingFuture = instrumentedExecutorService.submit(runnable); ++ Future queuedFuture = instrumentedExecutorService.submit(runnable); ++ assertThatThrownBy(() -> instrumentedExecutorService.submit(runnable)) ++ .isInstanceOf(RejectedExecutionException.class); ++ latch.countDown(); ++ assertThat(rejected.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void removesMetricsAfterShutdownForThreadPoolExecutor() { ++ executor = ++ new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); ++ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "stp"); ++ ++ MetricName prefix = MetricName.build("stp"); ++ assertThat(registry.getMetrics()) ++ .containsKeys( ++ MetricRegistry.name("stp", "pool.size"), ++ MetricRegistry.name("stp", "pool.core"), ++ MetricRegistry.name("stp", "pool.max"), ++ MetricRegistry.name("stp", "tasks.active"), ++ MetricRegistry.name("stp", "tasks.completed"), ++ MetricRegistry.name("stp", "tasks.queued"), ++ MetricRegistry.name("stp", "tasks.capacity")); ++ ++ instrumentedExecutorService.shutdown(); ++ ++ assertThat(registry.getMetrics()) ++ .doesNotContainKeys( ++ MetricRegistry.name("stp", "pool.size"), ++ MetricRegistry.name("stp", "pool.core"), ++ MetricRegistry.name("stp", "pool.max"), ++ MetricRegistry.name("stp", "tasks.active"), ++ MetricRegistry.name("stp", "tasks.completed"), ++ MetricRegistry.name("stp", "tasks.queued"), ++ MetricRegistry.name("stp", "tasks.capacity")); ++ } ++ ++ @SuppressWarnings("unchecked") ++ @Test ++ void reportsTasksInformationForForkJoinPool() throws Exception { ++ executor = Executors.newWorkStealingPool(4); ++ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); ++ submitted = registry.meter("fjp.submitted"); ++ running = registry.counter("fjp.running"); ++ completed = registry.meter("fjp.completed"); ++ duration = registry.timer("fjp.duration"); ++ idle = registry.timer("fjp.idle"); ++ final Gauge tasksStolen = ++ (Gauge) registry.getGauges().get(MetricName.build("fjp", "tasks", "stolen")); ++ final Gauge tasksQueued = ++ (Gauge) registry.getGauges().get(MetricName.build("fjp", "tasks", "queued")); ++ final Gauge threadsActive = ++ (Gauge) registry.getGauges().get(MetricName.build("fjp", "threads", "active")); ++ final Gauge threadsRunning = ++ (Gauge) registry.getGauges().get(MetricName.build("fjp", "threads", "running")); ++ ++ assertThat(submitted.getCount()).isEqualTo(0); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ assertThat(idle.getCount()).isEqualTo(0); ++ assertThat(tasksStolen.getValue()).isEqualTo(0L); ++ assertThat(tasksQueued.getValue()).isEqualTo(0L); ++ assertThat(threadsActive.getValue()).isEqualTo(0); ++ assertThat(threadsRunning.getValue()).isEqualTo(0); ++ ++ Runnable runnable = ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(1); ++ assertThat(running.getCount()).isEqualTo(1); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ assertThat(idle.getCount()).isEqualTo(1); ++ assertThat(tasksQueued.getValue()).isEqualTo(0L); ++ assertThat(threadsActive.getValue()).isEqualTo(1); ++ assertThat(threadsRunning.getValue()).isEqualTo(1); + }; + +- Future theFuture = instrumentedExecutorService.submit(runnable); +- +- assertThat(theFuture).succeedsWithin(Duration.ofSeconds(5L)); +- +- assertThat(submitted.getCount()).isEqualTo(1); +- assertThat(running.getCount()).isEqualTo(0); +- assertThat(completed.getCount()).isEqualTo(1); +- assertThat(duration.getCount()).isEqualTo(1); +- assertThat(duration.getSnapshot().size()).isEqualTo(1); +- assertThat(idle.getCount()).isEqualTo(1); +- assertThat(idle.getSnapshot().size()).isEqualTo(1); +- } +- +- @Test +- public void removesMetricsAfterShutdownForForkJoinPool() { +- executor = Executors.newWorkStealingPool(4); +- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "sfjp"); +- +- assertThat(registry.getMetrics()).containsKeys( +- MetricRegistry.name("sfjp", "tasks.stolen"), +- MetricRegistry.name("sfjp", "tasks.queued"), +- MetricRegistry.name("sfjp", "threads.active"), +- MetricRegistry.name("sfjp", "threads.running") +- ); +- +- instrumentedExecutorService.shutdown(); +- +- assertThat(registry.getMetrics()).doesNotContainKeys( +- MetricRegistry.name("sfjp", "tasks.stolen"), +- MetricRegistry.name("sfjp", "tasks.queued"), +- MetricRegistry.name("sfjp", "threads.active"), +- MetricRegistry.name("sfjp", "threads.running") +- ); +- } ++ Future theFuture = instrumentedExecutorService.submit(runnable); ++ ++ assertThat(theFuture).succeedsWithin(Duration.ofSeconds(5L)); ++ ++ assertThat(submitted.getCount()).isEqualTo(1); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(1); ++ assertThat(duration.getCount()).isEqualTo(1); ++ assertThat(duration.getSnapshot().size()).isEqualTo(1); ++ assertThat(idle.getCount()).isEqualTo(1); ++ assertThat(idle.getSnapshot().size()).isEqualTo(1); ++ } ++ ++ @Test ++ void removesMetricsAfterShutdownForForkJoinPool() { ++ executor = Executors.newWorkStealingPool(4); ++ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "sfjp"); ++ ++ assertThat(registry.getMetrics()) ++ .containsKeys( ++ MetricRegistry.name("sfjp", "tasks.stolen"), ++ MetricRegistry.name("sfjp", "tasks.queued"), ++ MetricRegistry.name("sfjp", "threads.active"), ++ MetricRegistry.name("sfjp", "threads.running")); ++ ++ instrumentedExecutorService.shutdown(); ++ ++ assertThat(registry.getMetrics()) ++ .doesNotContainKeys( ++ MetricRegistry.name("sfjp", "tasks.stolen"), ++ MetricRegistry.name("sfjp", "tasks.queued"), ++ MetricRegistry.name("sfjp", "threads.active"), ++ MetricRegistry.name("sfjp", "threads.running")); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java +@@ -1,9 +1,6 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.Test; +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.Executors; +@@ -11,295 +8,321 @@ import java.util.concurrent.Future; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.ScheduledFuture; + import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.Test; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class InstrumentedScheduledExecutorServiceTest { +- private static final Logger LOGGER = LoggerFactory.getLogger(InstrumentedScheduledExecutorServiceTest.class); +- +- private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); +- private final MetricRegistry registry = new MetricRegistry(); +- private final InstrumentedScheduledExecutorService instrumentedScheduledExecutor = new InstrumentedScheduledExecutorService(scheduledExecutor, registry, "xs"); +- +- private final Meter submitted = registry.meter("xs.submitted"); +- +- private final Counter running = registry.counter("xs.running"); +- private final Meter completed = registry.meter("xs.completed"); +- private final Timer duration = registry.timer("xs.duration"); +- +- private final Meter scheduledOnce = registry.meter("xs.scheduled.once"); +- private final Meter scheduledRepetitively = registry.meter("xs.scheduled.repetitively"); +- private final Counter scheduledOverrun = registry.counter("xs.scheduled.overrun"); +- private final Histogram percentOfPeriod = registry.histogram("xs.scheduled.percent-of-period"); +- +- @Test +- void testSubmitRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- +- Future theFuture = instrumentedScheduledExecutor.submit(() -> { +- assertThat(submitted.getCount()).isEqualTo(1); +- +- assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- }); +- +- theFuture.get(); +- +- assertThat(submitted.getCount()).isEqualTo(1); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isEqualTo(1); +- assertThat(duration.getCount()).isEqualTo(1); +- assertThat(duration.getSnapshot().size()).isEqualTo(1); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- } +- +- @Test +- void testScheduleRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- +- ScheduledFuture theFuture = instrumentedScheduledExecutor.schedule(() -> { +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); +- +- assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- }, 10L, TimeUnit.MILLISECONDS); +- +- theFuture.get(); +- +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isEqualTo(1); +- assertThat(duration.getCount()).isEqualTo(1); +- assertThat(duration.getSnapshot().size()).isEqualTo(1); +- +- assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- } +- +- @Test +- void testSubmitCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- +- final Object obj = new Object(); +- +- Future theFuture = instrumentedScheduledExecutor.submit(() -> { +- assertThat(submitted.getCount()).isEqualTo(1); +- +- assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- +- return obj; +- }); +- +- assertThat(theFuture.get()).isEqualTo(obj); +- +- assertThat(submitted.getCount()).isEqualTo(1); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isEqualTo(1); +- assertThat(duration.getCount()).isEqualTo(1); +- assertThat(duration.getSnapshot().size()).isEqualTo(1); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- } +- +- @Test +- void testScheduleCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- +- final Object obj = new Object(); ++final class InstrumentedScheduledExecutorServiceTest { ++ private static final Logger LOG = ++ LoggerFactory.getLogger(InstrumentedScheduledExecutorServiceTest.class); ++ ++ private final ScheduledExecutorService scheduledExecutor = ++ Executors.newSingleThreadScheduledExecutor(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final InstrumentedScheduledExecutorService instrumentedScheduledExecutor = ++ new InstrumentedScheduledExecutorService(scheduledExecutor, registry, "xs"); ++ ++ private final Meter submitted = registry.meter("xs.submitted"); ++ ++ private final Counter running = registry.counter("xs.running"); ++ private final Meter completed = registry.meter("xs.completed"); ++ private final Timer duration = registry.timer("xs.duration"); ++ ++ private final Meter scheduledOnce = registry.meter("xs.scheduled.once"); ++ private final Meter scheduledRepetitively = registry.meter("xs.scheduled.repetitively"); ++ private final Counter scheduledOverrun = registry.counter("xs.scheduled.overrun"); ++ private final Histogram percentOfPeriod = registry.histogram("xs.scheduled.percent-of-period"); ++ ++ @Test ++ void submitRunnable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ ++ Future theFuture = ++ instrumentedScheduledExecutor.submit( ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(1); ++ ++ assertThat(running.getCount()).isEqualTo(1); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ }); ++ ++ theFuture.get(); ++ ++ assertThat(submitted.getCount()).isEqualTo(1); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(1); ++ assertThat(duration.getCount()).isEqualTo(1); ++ assertThat(duration.getSnapshot().size()).isEqualTo(1); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void scheduleRunnable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ ++ ScheduledFuture theFuture = ++ instrumentedScheduledExecutor.schedule( ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(1); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(1); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ }, ++ 10L, ++ TimeUnit.MILLISECONDS); + +- ScheduledFuture theFuture = instrumentedScheduledExecutor.schedule(() -> { +- assertThat(submitted.getCount()).isZero(); ++ theFuture.get(); ++ ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(1); ++ assertThat(duration.getCount()).isEqualTo(1); ++ assertThat(duration.getSnapshot().size()).isEqualTo(1); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(1); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void submitCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ ++ final Object obj = new Object(); ++ ++ Future theFuture = ++ instrumentedScheduledExecutor.submit( ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(1); ++ ++ assertThat(running.getCount()).isEqualTo(1); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ ++ return obj; ++ }); ++ ++ assertThat(theFuture.get()).isEqualTo(obj); ++ ++ assertThat(submitted.getCount()).isEqualTo(1); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(1); ++ assertThat(duration.getCount()).isEqualTo(1); ++ assertThat(duration.getSnapshot().size()).isEqualTo(1); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void scheduleCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ ++ final Object obj = new Object(); ++ ++ ScheduledFuture theFuture = ++ instrumentedScheduledExecutor.schedule( ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(1); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- return obj; +- }, 10L, TimeUnit.MILLISECONDS); ++ assertThat(scheduledOnce.getCount()).isEqualTo(1); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + +- assertThat(theFuture.get()).isEqualTo(obj); ++ return obj; ++ }, ++ 10L, ++ TimeUnit.MILLISECONDS); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(theFuture.get()).isEqualTo(obj); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isEqualTo(1); +- assertThat(duration.getCount()).isEqualTo(1); +- assertThat(duration.getSnapshot().size()).isEqualTo(1); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- } ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(1); ++ assertThat(duration.getCount()).isEqualTo(1); ++ assertThat(duration.getSnapshot().size()).isEqualTo(1); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(1); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ } + +- @Test +- void testScheduleFixedRateCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ @Test ++ void scheduleFixedRateCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + +- CountDownLatch countDownLatch = new CountDownLatch(1); +- ScheduledFuture theFuture = instrumentedScheduledExecutor.scheduleAtFixedRate(() -> { +- assertThat(submitted.getCount()).isZero(); ++ CountDownLatch countDownLatch = new CountDownLatch(1); ++ ScheduledFuture theFuture = ++ instrumentedScheduledExecutor.scheduleAtFixedRate( ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isEqualTo(1); ++ assertThat(running.getCount()).isEqualTo(1); + +- assertThat(scheduledOnce.getCount()).isEqualTo(0); +- assertThat(scheduledRepetitively.getCount()).isEqualTo(1); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(1); + +- try { ++ try { + TimeUnit.MILLISECONDS.sleep(50); +- } catch (InterruptedException ex) { ++ } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); +- } +- countDownLatch.countDown(); +- }, 10L, 10L, TimeUnit.MILLISECONDS); +- TimeUnit.MILLISECONDS.sleep(100); // Give some time for the task to be run +- countDownLatch.await(5, TimeUnit.SECONDS); // Don't cancel until it didn't complete once +- theFuture.cancel(true); +- TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled +- +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isNotEqualTo(0); +- assertThat(duration.getCount()).isNotEqualTo(0); +- assertThat(duration.getSnapshot().size()).isNotEqualTo(0); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isEqualTo(1); +- assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); +- assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); +- } +- +- @Test +- void testScheduleFixedDelayCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); +- +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); +- +- CountDownLatch countDownLatch = new CountDownLatch(1); +- ScheduledFuture theFuture = instrumentedScheduledExecutor.scheduleWithFixedDelay(() -> { +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isEqualTo(1); +- +- assertThat(scheduledOnce.getCount()).isEqualTo(0); +- assertThat(scheduledRepetitively.getCount()).isEqualTo(1); +- +- try { ++ } ++ countDownLatch.countDown(); ++ }, ++ 10L, ++ 10L, ++ TimeUnit.MILLISECONDS); ++ TimeUnit.MILLISECONDS.sleep(100); // Give some time for the task to be run ++ countDownLatch.await(5, TimeUnit.SECONDS); // Don't cancel until it didn't complete once ++ theFuture.cancel(true); ++ TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled ++ ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isNotEqualTo(0); ++ assertThat(duration.getCount()).isNotEqualTo(0); ++ assertThat(duration.getSnapshot().size()).isNotEqualTo(0); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(1); ++ assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); ++ } ++ ++ @Test ++ void scheduleFixedDelayCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); ++ ++ CountDownLatch countDownLatch = new CountDownLatch(1); ++ ScheduledFuture theFuture = ++ instrumentedScheduledExecutor.scheduleWithFixedDelay( ++ () -> { ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(1); ++ ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(1); ++ ++ try { + TimeUnit.MILLISECONDS.sleep(50); +- } catch (InterruptedException ex) { ++ } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); +- } +- countDownLatch.countDown(); +- }, 10L, 10L, TimeUnit.MILLISECONDS); +- +- TimeUnit.MILLISECONDS.sleep(100); +- countDownLatch.await(5, TimeUnit.SECONDS); +- theFuture.cancel(true); +- TimeUnit.MILLISECONDS.sleep(200); +- +- assertThat(submitted.getCount()).isZero(); +- +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isNotEqualTo(0); +- assertThat(duration.getCount()).isNotEqualTo(0); +- assertThat(duration.getSnapshot().size()).isNotEqualTo(0); +- } +- +- @AfterEach +- void tearDown() throws Exception { +- instrumentedScheduledExecutor.shutdown(); +- if (!instrumentedScheduledExecutor.awaitTermination(2, TimeUnit.SECONDS)) { +- LOGGER.error("InstrumentedScheduledExecutorService did not terminate."); +- } ++ } ++ countDownLatch.countDown(); ++ }, ++ 10L, ++ 10L, ++ TimeUnit.MILLISECONDS); ++ ++ TimeUnit.MILLISECONDS.sleep(100); ++ countDownLatch.await(5, TimeUnit.SECONDS); ++ theFuture.cancel(true); ++ TimeUnit.MILLISECONDS.sleep(200); ++ ++ assertThat(submitted.getCount()).isEqualTo(0); ++ ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isNotEqualTo(0); ++ assertThat(duration.getCount()).isNotEqualTo(0); ++ assertThat(duration.getSnapshot().size()).isNotEqualTo(0); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ instrumentedScheduledExecutor.shutdown(); ++ if (!instrumentedScheduledExecutor.awaitTermination(2, TimeUnit.SECONDS)) { ++ LOG.error("InstrumentedScheduledExecutorService did not terminate."); + } +- ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java +@@ -9,69 +9,71 @@ import java.util.concurrent.Future; + import java.util.concurrent.ThreadFactory; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicInteger; +- + import org.junit.jupiter.api.Test; + +-class InstrumentedThreadFactoryTest { +- private static final int THREAD_COUNT = 10; ++final class InstrumentedThreadFactoryTest { ++ private static final int THREAD_COUNT = 10; + +- private final ThreadFactory factory = Executors.defaultThreadFactory(); +- private final MetricRegistry registry = new MetricRegistry(); +- private final InstrumentedThreadFactory instrumentedFactory = new InstrumentedThreadFactory(factory, registry, "factory"); +- private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT, instrumentedFactory); ++ private final ThreadFactory factory = Executors.defaultThreadFactory(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final InstrumentedThreadFactory instrumentedFactory = ++ new InstrumentedThreadFactory(factory, registry, "factory"); ++ private final ExecutorService executor = ++ Executors.newFixedThreadPool(THREAD_COUNT, instrumentedFactory); + +- /** +- * Tests all parts of the InstrumentedThreadFactory except for termination since that +- * is currently difficult to do without race conditions. +- * TODO: Try not using real threads in a unit test? +- */ +- @Test +- void reportsThreadInformation() throws Exception { +- final CountDownLatch allTasksAreCreated = new CountDownLatch(THREAD_COUNT); +- final CountDownLatch allTasksAreCounted = new CountDownLatch(1); +- final AtomicInteger interrupted = new AtomicInteger(); ++ /** ++ * Tests all parts of the InstrumentedThreadFactory except for termination since that is currently ++ * difficult to do without race conditions. TODO: Try not using real threads in a unit test? ++ */ ++ @Test ++ void reportsThreadInformation() throws Exception { ++ final CountDownLatch allTasksAreCreated = new CountDownLatch(THREAD_COUNT); ++ final CountDownLatch allTasksAreCounted = new CountDownLatch(1); ++ final AtomicInteger interrupted = new AtomicInteger(); + +- Meter created = registry.meter("factory.created"); +- Meter terminated = registry.meter("factory.terminated"); ++ Meter created = registry.meter("factory.created"); ++ Meter terminated = registry.meter("factory.terminated"); + +- assertThat(created.getCount()).isEqualTo(0); +- assertThat(terminated.getCount()).isEqualTo(0); ++ assertThat(created.getCount()).isEqualTo(0); ++ assertThat(terminated.getCount()).isEqualTo(0); + +- // generate demand so the executor service creates the threads through our factory. +- for (int i = 0; i < THREAD_COUNT + 1; i++) { +- Future t = executor.submit(() -> { ++ // generate demand so the executor service creates the threads through our factory. ++ for (int i = 0; i < THREAD_COUNT + 1; i++) { ++ Future t = ++ executor.submit( ++ () -> { + allTasksAreCreated.countDown(); + + // This asserts that all threads have wait wail the testing thread notifies all. + // We have to do this to guarantee that the thread pool has 10 LIVE threads + // before we check the 'created' Meter. + try { +- allTasksAreCounted.await(); ++ allTasksAreCounted.await(); + } catch (InterruptedException e) { +- interrupted.incrementAndGet(); +- Thread.currentThread().interrupt(); ++ interrupted.incrementAndGet(); ++ Thread.currentThread().interrupt(); + } +- }); +- assertThat(t).isNotNull(); +- } ++ }); ++ assertThat(t).isNotNull(); ++ } + +- allTasksAreCreated.await(1, TimeUnit.SECONDS); +- allTasksAreCounted.countDown(); ++ allTasksAreCreated.await(1, TimeUnit.SECONDS); ++ allTasksAreCounted.countDown(); + +- assertThat(created.getCount()).isEqualTo(10); +- assertThat(terminated.getCount()).isEqualTo(0); ++ assertThat(created.getCount()).isEqualTo(10); ++ assertThat(terminated.getCount()).isEqualTo(0); + +- // terminate all threads in the executor service. +- executor.shutdown(); +- executor.awaitTermination(1, TimeUnit.SECONDS); ++ // terminate all threads in the executor service. ++ executor.shutdown(); ++ executor.awaitTermination(1, TimeUnit.SECONDS); + +- // assert that all threads from the factory have been terminated. +- // TODO: Remove this? +- // There is no guarantee that all threads have entered the block where they are +- // counted as terminated by this time. +- // assertThat(terminated.getCount()).isEqualTo(10); ++ // assert that all threads from the factory have been terminated. ++ // TODO: Remove this? ++ // There is no guarantee that all threads have entered the block where they are ++ // counted as terminated by this time. ++ // assertThat(terminated.getCount()).isEqualTo(10); + +- // Check that none of the threads were interrupted. +- assertThat(interrupted.get()).isEqualTo(0); +- } ++ // Check that none of the threads were interrupted. ++ assertThat(interrupted.get()).isEqualTo(0); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ManualClock.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ManualClock.java +@@ -3,42 +3,41 @@ package io.dropwizard.metrics5; + import java.util.concurrent.TimeUnit; + + public class ManualClock extends Clock { +- private final long initialTicksInNanos; +- long ticksInNanos; +- +- public ManualClock(long initialTicksInNanos) { +- this.initialTicksInNanos = initialTicksInNanos; +- this.ticksInNanos = initialTicksInNanos; +- } +- +- public ManualClock() { +- this(0L); +- } +- +- public synchronized void addNanos(long nanos) { +- ticksInNanos += nanos; +- } +- +- public synchronized void addSeconds(long seconds) { +- ticksInNanos += TimeUnit.SECONDS.toNanos(seconds); +- } +- +- public synchronized void addMillis(long millis) { +- ticksInNanos += TimeUnit.MILLISECONDS.toNanos(millis); +- } +- +- public synchronized void addHours(long hours) { +- ticksInNanos += TimeUnit.HOURS.toNanos(hours); +- } +- +- @Override +- public synchronized long getTick() { +- return ticksInNanos; +- } +- +- @Override +- public synchronized long getTime() { +- return TimeUnit.NANOSECONDS.toMillis(ticksInNanos - initialTicksInNanos); +- } +- ++ private final long initialTicksInNanos; ++ long ticksInNanos; ++ ++ public ManualClock(long initialTicksInNanos) { ++ this.initialTicksInNanos = initialTicksInNanos; ++ this.ticksInNanos = initialTicksInNanos; ++ } ++ ++ public ManualClock() { ++ this(0L); ++ } ++ ++ public synchronized void addNanos(long nanos) { ++ ticksInNanos += nanos; ++ } ++ ++ public synchronized void addSeconds(long seconds) { ++ ticksInNanos += TimeUnit.SECONDS.toNanos(seconds); ++ } ++ ++ public synchronized void addMillis(long millis) { ++ ticksInNanos += TimeUnit.MILLISECONDS.toNanos(millis); ++ } ++ ++ public synchronized void addHours(long hours) { ++ ticksInNanos += TimeUnit.HOURS.toNanos(hours); ++ } ++ ++ @Override ++ public synchronized long getTick() { ++ return ticksInNanos; ++ } ++ ++ @Override ++ public synchronized long getTime() { ++ return TimeUnit.NANOSECONDS.toMillis(ticksInNanos - initialTicksInNanos); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java +@@ -1,84 +1,82 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.params.ParameterizedTest; +-import org.junit.jupiter.params.provider.MethodSource; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.offset; + + import java.util.Arrays; + import java.util.Collection; + import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.params.ParameterizedTest; ++import org.junit.jupiter.params.provider.MethodSource; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.offset; +- +-public class MeterApproximationTest { +- +- public static Collection ratesPerMinute() { +- Object[][] data = new Object[][]{ +- {15}, {60}, {600}, {6000} +- }; +- return Arrays.asList(data); +- } +- +- private long ratePerMinute; +- +- public void initMeterApproximationTest(long ratePerMinute) { +- this.ratePerMinute = ratePerMinute; +- } +- +- @MethodSource("ratesPerMinute") +- @ParameterizedTest +- void controlMeter1MinuteMeanApproximation(long ratePerMinute) { +- initMeterApproximationTest(ratePerMinute); +- final Meter meter = simulateMetronome( +- 62934, TimeUnit.MILLISECONDS, +- 3, TimeUnit.MINUTES); +- +- assertThat(meter.getOneMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); +- } +- +- @MethodSource("ratesPerMinute") +- @ParameterizedTest +- void controlMeter5MinuteMeanApproximation(long ratePerMinute) { +- initMeterApproximationTest(ratePerMinute); +- final Meter meter = simulateMetronome( +- 62934, TimeUnit.MILLISECONDS, +- 13, TimeUnit.MINUTES); +- +- assertThat(meter.getFiveMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); +- } +- +- @MethodSource("ratesPerMinute") +- @ParameterizedTest +- void controlMeter15MinuteMeanApproximation(long ratePerMinute) { +- initMeterApproximationTest(ratePerMinute); +- final Meter meter = simulateMetronome( +- 62934, TimeUnit.MILLISECONDS, +- 38, TimeUnit.MINUTES); +- +- assertThat(meter.getFifteenMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); +- } +- +- private Meter simulateMetronome( +- long introDelay, TimeUnit introDelayUnit, +- long duration, TimeUnit durationUnit) { +- +- final ManualClock clock = new ManualClock(); +- final Meter meter = new Meter(clock); +- +- clock.addNanos(introDelayUnit.toNanos(introDelay)); +- +- final long endTick = clock.getTick() + durationUnit.toNanos(duration); +- final long marksIntervalInNanos = TimeUnit.MINUTES.toNanos(1) / ratePerMinute; +- +- while (clock.getTick() <= endTick) { +- clock.addNanos(marksIntervalInNanos); +- meter.mark(); +- } +- +- return meter; ++final class MeterApproximationTest { ++ ++ public static Collection ratesPerMinute() { ++ Object[][] data = new Object[][] {{15}, {60}, {600}, {6000}}; ++ return Arrays.asList(data); ++ } ++ ++ private long ratePerMinute; ++ ++ public void initMeterApproximationTest(long ratePerMinute) { ++ this.ratePerMinute = ratePerMinute; ++ } ++ ++ @MethodSource("ratesPerMinute") ++ @ParameterizedTest ++ void controlMeter1MinuteMeanApproximation(long ratePerMinute) { ++ initMeterApproximationTest(ratePerMinute); ++ final Meter meter = ++ simulateMetronome( ++ 62934, TimeUnit.MILLISECONDS, ++ 3, TimeUnit.MINUTES); ++ ++ assertThat(meter.getOneMinuteRate() * 60.0) ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ } ++ ++ @MethodSource("ratesPerMinute") ++ @ParameterizedTest ++ void controlMeter5MinuteMeanApproximation(long ratePerMinute) { ++ initMeterApproximationTest(ratePerMinute); ++ final Meter meter = ++ simulateMetronome( ++ 62934, TimeUnit.MILLISECONDS, ++ 13, TimeUnit.MINUTES); ++ ++ assertThat(meter.getFiveMinuteRate() * 60.0) ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ } ++ ++ @MethodSource("ratesPerMinute") ++ @ParameterizedTest ++ void controlMeter15MinuteMeanApproximation(long ratePerMinute) { ++ initMeterApproximationTest(ratePerMinute); ++ final Meter meter = ++ simulateMetronome( ++ 62934, TimeUnit.MILLISECONDS, ++ 38, TimeUnit.MINUTES); ++ ++ assertThat(meter.getFifteenMinuteRate() * 60.0) ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ } ++ ++ private Meter simulateMetronome( ++ long introDelay, TimeUnit introDelayUnit, long duration, TimeUnit durationUnit) { ++ ++ final ManualClock clock = new ManualClock(); ++ final Meter meter = new Meter(clock); ++ ++ clock.addNanos(introDelayUnit.toNanos(introDelay)); ++ ++ final long endTick = clock.getTick() + durationUnit.toNanos(duration); ++ final long marksIntervalInNanos = TimeUnit.MINUTES.toNanos(1) / ratePerMinute; ++ ++ while (clock.getTick() <= endTick) { ++ clock.addNanos(marksIntervalInNanos); ++ meter.mark(); + } + ++ return meter; ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java +@@ -1,67 +1,53 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import java.util.concurrent.TimeUnit; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.offset; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + +-class MeterTest { +- private final Clock clock = mock(Clock.class); +- private final Meter meter = new Meter(clock); ++import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +- @BeforeEach +- void setUp() throws Exception { +- when(clock.getTick()).thenReturn(0L, TimeUnit.SECONDS.toNanos(10)); ++final class MeterTest { ++ private final Clock clock = mock(); ++ private final Meter meter = new Meter(clock); + +- } ++ @BeforeEach ++ void setUp() throws Exception { ++ when(clock.getTick()).thenReturn(0L, TimeUnit.SECONDS.toNanos(10)); ++ } + +- @Test +- void startsOutWithNoRatesOrCount() { +- assertThat(meter.getCount()) +- .isZero(); ++ @Test ++ void startsOutWithNoRatesOrCount() { ++ assertThat(meter.getCount()).isEqualTo(0); + +- assertThat(meter.getSum()) +- .isZero(); ++ assertThat(meter.getSum()).isEqualTo(0); + +- assertThat(meter.getMeanRate()) +- .isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getOneMinuteRate()) +- .isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getFiveMinuteRate()) +- .isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getFifteenMinuteRate()) +- .isEqualTo(0.0, offset(0.001)); +- } ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); ++ } + +- @Test +- void marksEventsAndUpdatesRatesAndCount() { +- meter.mark(); +- meter.mark(2); ++ @Test ++ void marksEventsAndUpdatesRatesAndCount() { ++ meter.mark(); ++ meter.mark(2); + +- assertThat(meter.getCount()) +- .isEqualTo(3); ++ assertThat(meter.getCount()).isEqualTo(3); + +- assertThat(meter.getSum()) +- .isEqualTo(10000000000L); ++ assertThat(meter.getSum()).isEqualTo(10000000000L); + +- assertThat(meter.getMeanRate()) +- .isEqualTo(0.3, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001)); + +- assertThat(meter.getOneMinuteRate()) +- .isEqualTo(0.1840, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001)); + +- assertThat(meter.getFiveMinuteRate()) +- .isEqualTo(0.1966, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001)); + +- assertThat(meter.getFifteenMinuteRate()) +- .isEqualTo(0.1988, offset(0.001)); +- } ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001)); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java +@@ -1,38 +1,44 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + +-class MetricFilterTest { +- @Test +- void theAllFilterMatchesAllMetrics() { +- assertThat(MetricFilter.ALL.matches(MetricName.build(""), mock(Metric.class))) +- .isTrue(); +- } ++import org.junit.jupiter.api.Test; ++ ++final class MetricFilterTest { ++ @Test ++ void theAllFilterMatchesAllMetrics() { ++ assertThat(MetricFilter.ALL.matches(MetricName.build(""), mock(Metric.class))).isTrue(); ++ } + +- @Test +- void theStartsWithFilterMatches() { +- assertThat(MetricFilter.startsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) +- .isTrue(); +- assertThat(MetricFilter.startsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) +- .isFalse(); +- } ++ @Test ++ void theStartsWithFilterMatches() { ++ assertThat( ++ MetricFilter.startsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) ++ .isTrue(); ++ assertThat( ++ MetricFilter.startsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) ++ .isFalse(); ++ } + +- @Test +- void theEndsWithFilterMatches() { +- assertThat(MetricFilter.endsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) +- .isFalse(); +- assertThat(MetricFilter.endsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) +- .isTrue(); +- } ++ @Test ++ void theEndsWithFilterMatches() { ++ assertThat( ++ MetricFilter.endsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) ++ .isFalse(); ++ assertThat( ++ MetricFilter.endsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) ++ .isTrue(); ++ } + +- @Test +- void theContainsFilterMatches() { +- assertThat(MetricFilter.contains("foo").matches(MetricName.build("bar.foo.bar"), mock(Metric.class))) +- .isTrue(); +- assertThat(MetricFilter.contains("foo").matches(MetricName.build("bar.bar"), mock(Metric.class))) +- .isFalse(); +- } ++ @Test ++ void theContainsFilterMatches() { ++ assertThat( ++ MetricFilter.contains("foo") ++ .matches(MetricName.build("bar.foo.bar"), mock(Metric.class))) ++ .isTrue(); ++ assertThat( ++ MetricFilter.contains("foo").matches(MetricName.build("bar.bar"), mock(Metric.class))) ++ .isFalse(); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java +@@ -1,102 +1,106 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + + import java.util.HashMap; + import java.util.Map; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; +- +-class MetricNameTest { +- @Test +- void testEmpty() { +- assertThat(MetricName.EMPTY.getTags()).isEmpty(); +- assertThat(MetricName.EMPTY.getKey()).isEqualTo(""); +- +- assertThat(MetricName.build()).isEqualTo(MetricName.EMPTY); +- assertThat(MetricName.EMPTY.resolve((String) null)).isEqualTo(MetricName.EMPTY); +- } +- +- @Test +- void testEmptyResolve() { +- final MetricName name = MetricName.build(); +- assertThat(name.resolve("foo")).isEqualTo(MetricName.build("foo")); +- } +- +- @Test +- void testResolveToEmpty() { +- final MetricName name = MetricName.build("foo"); +- assertThat(name.resolve((String) null)).isEqualTo(MetricName.build("foo")); +- } +- +- @Test +- void testResolve() { +- final MetricName name = MetricName.build("foo"); +- assertThat(name.resolve("bar")).isEqualTo(MetricName.build("foo.bar")); +- } +- +- @Test +- void testResolveBothEmpty() { +- final MetricName name = MetricName.build(); +- assertThat(name.resolve((String) null)).isEqualTo(MetricName.EMPTY); +- } +- +- @Test +- void testAddTagsVarious() { +- final Map refTags = new HashMap(); +- refTags.put("foo", "bar"); +- final MetricName test = MetricName.EMPTY.tagged("foo", "bar"); +- final MetricName test2 = MetricName.EMPTY.tagged(refTags); +- +- assertThat(test).isEqualTo(new MetricName("", refTags)); +- assertThat(test.getTags()).isEqualTo(refTags); +- +- assertThat(test2).isEqualTo(new MetricName("", refTags)); +- assertThat(test2.getTags()).isEqualTo(refTags); +- } +- +- @Test +- void testTaggedMoreArguments() { +- final Map refTags = new HashMap(); +- refTags.put("foo", "bar"); +- refTags.put("baz", "biz"); +- assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()).isEqualTo(refTags); +- } +- +- @Test +- void testTaggedNotPairs() { +- assertThrows(IllegalArgumentException.class, () -> { +- MetricName.EMPTY.tagged("foo"); +- }); +- } +- +- @Test +- void testTaggedNotPairs2() { +- assertThrows(IllegalArgumentException.class, () -> { +- MetricName.EMPTY.tagged("foo", "bar", "baz"); +- }); +- } +- +- @Test +- void testCompareTo() { +- final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); +- final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); +- +- assertThat(a.compareTo(b)).isLessThan(0); +- assertThat(b.compareTo(a)).isGreaterThan(0); +- assertThat(b.resolve("key").compareTo(b)).isGreaterThan(0); +- assertThat(b.compareTo(b.resolve("key"))).isLessThan(0); +- } +- +- @Test +- void testCompareTo2() { +- final MetricName a = MetricName.EMPTY.tagged("a", "x"); +- final MetricName b = MetricName.EMPTY.tagged("b", "x"); +- +- assertThat(MetricName.EMPTY.compareTo(a)).isLessThan(0); +- assertThat(MetricName.EMPTY.compareTo(b)).isLessThan(0); +- assertThat(a.compareTo(b)).isLessThan(0); +- assertThat(b.compareTo(a)).isGreaterThan(0); +- } ++final class MetricNameTest { ++ @Test ++ void empty() { ++ assertThat(MetricName.EMPTY.getTags()).isEmpty(); ++ assertThat(MetricName.EMPTY.getKey()).isEmpty(); ++ ++ assertThat(MetricName.build()).isEqualTo(MetricName.EMPTY); ++ assertThat(MetricName.EMPTY.resolve((String) null)).isEqualTo(MetricName.EMPTY); ++ } ++ ++ @Test ++ void emptyResolve() { ++ final MetricName name = MetricName.build(); ++ assertThat(name.resolve("foo")).isEqualTo(MetricName.build("foo")); ++ } ++ ++ @Test ++ void resolveToEmpty() { ++ final MetricName name = MetricName.build("foo"); ++ assertThat(name.resolve((String) null)).isEqualTo(MetricName.build("foo")); ++ } ++ ++ @Test ++ void resolve() { ++ final MetricName name = MetricName.build("foo"); ++ assertThat(name.resolve("bar")).isEqualTo(MetricName.build("foo.bar")); ++ } ++ ++ @Test ++ void resolveBothEmpty() { ++ final MetricName name = MetricName.build(); ++ assertThat(name.resolve((String) null)).isEqualTo(MetricName.EMPTY); ++ } ++ ++ @Test ++ void addTagsVarious() { ++ final Map refTags = new HashMap(); ++ refTags.put("foo", "bar"); ++ final MetricName test = MetricName.EMPTY.tagged("foo", "bar"); ++ final MetricName test2 = MetricName.EMPTY.tagged(refTags); ++ ++ assertThat(test).isEqualTo(new MetricName("", refTags)); ++ assertThat(test.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); ++ ++ assertThat(test2).isEqualTo(new MetricName("", refTags)); ++ assertThat(test2.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); ++ } ++ ++ @Test ++ void taggedMoreArguments() { ++ final Map refTags = new HashMap(); ++ refTags.put("foo", "bar"); ++ refTags.put("baz", "biz"); ++ assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()) ++ .containsExactlyInAnyOrderEntriesOf(refTags); ++ } ++ ++ @Test ++ void taggedNotPairs() { ++ assertThatThrownBy( ++ () -> { ++ MetricName.EMPTY.tagged("foo"); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void taggedNotPairs2() { ++ assertThatThrownBy( ++ () -> { ++ MetricName.EMPTY.tagged("foo", "bar", "baz"); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void compareTo() { ++ final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); ++ final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); ++ ++ assertThat(a).isLessThan(b); ++ assertThat(b).isGreaterThan(a); ++ assertThat(b.resolve("key")).isGreaterThan(b); ++ assertThat(b).isLessThan(b.resolve("key")); ++ } ++ ++ @Test ++ void compareTo2() { ++ final MetricName a = MetricName.EMPTY.tagged("a", "x"); ++ final MetricName b = MetricName.EMPTY.tagged("b", "x"); ++ ++ assertThat(MetricName.EMPTY).isLessThan(a); ++ assertThat(MetricName.EMPTY).isLessThan(b); ++ assertThat(a).isLessThan(b); ++ assertThat(b).isGreaterThan(a); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java +@@ -1,62 +1,62 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verifyNoInteractions; + +-class MetricRegistryListenerTest { +- private static final MetricName BLAH = MetricName.build("blah"); +- +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); +- private final MetricRegistryListener listener = new MetricRegistryListener.Base() { +- +- }; ++import org.junit.jupiter.api.Test; + +- @Test +- void noOpsOnGaugeAdded() { +- listener.onGaugeAdded(BLAH, () -> { +- throw new RuntimeException("Should not be called"); ++final class MetricRegistryListenerTest { ++ private static final MetricName BLAH = MetricName.build("blah"); ++ ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); ++ private final MetricRegistryListener listener = new MetricRegistryListener.Base() {}; ++ ++ @Test ++ void noOpsOnGaugeAdded() { ++ listener.onGaugeAdded( ++ BLAH, ++ () -> { ++ throw new RuntimeException("Should not be called"); + }); +- } ++ } + +- @Test +- void noOpsOnCounterAdded() { +- listener.onCounterAdded(BLAH, counter); ++ @Test ++ void noOpsOnCounterAdded() { ++ listener.onCounterAdded(BLAH, counter); + +- verifyNoInteractions(counter); +- } ++ verifyNoInteractions(counter); ++ } + +- @Test +- void noOpsOnHistogramAdded() { +- listener.onHistogramAdded(BLAH, histogram); ++ @Test ++ void noOpsOnHistogramAdded() { ++ listener.onHistogramAdded(BLAH, histogram); + +- verifyNoInteractions(histogram); +- } ++ verifyNoInteractions(histogram); ++ } + +- @Test +- void noOpsOnMeterAdded() { +- listener.onMeterAdded(BLAH, meter); ++ @Test ++ void noOpsOnMeterAdded() { ++ listener.onMeterAdded(BLAH, meter); + +- verifyNoInteractions(meter); +- } ++ verifyNoInteractions(meter); ++ } + +- @Test +- void noOpsOnTimerAdded() { +- listener.onTimerAdded(BLAH, timer); ++ @Test ++ void noOpsOnTimerAdded() { ++ listener.onTimerAdded(BLAH, timer); + +- verifyNoInteractions(timer); +- } ++ verifyNoInteractions(timer); ++ } + +- @Test +- void doesNotExplodeWhenMetricsAreRemoved() { +- listener.onGaugeRemoved(BLAH); +- listener.onCounterRemoved(BLAH); +- listener.onHistogramRemoved(BLAH); +- listener.onMeterRemoved(BLAH); +- listener.onTimerRemoved(BLAH); +- } ++ @Test ++ void doesNotExplodeWhenMetricsAreRemoved() { ++ listener.onGaugeRemoved(BLAH); ++ listener.onCounterRemoved(BLAH); ++ listener.onHistogramRemoved(BLAH); ++ listener.onMeterRemoved(BLAH); ++ listener.onTimerRemoved(BLAH); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java +@@ -1,13 +1,6 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import java.util.HashMap; +-import java.util.Map; +-import java.util.Set; +-import java.util.stream.Collectors; +- ++import static com.google.common.collect.ImmutableSet.toImmutableSet; + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatThrownBy; +@@ -16,665 +9,665 @@ import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; + import static org.mockito.Mockito.verify; + +-class MetricRegistryTest { +- +- private static class CustomCounter extends Counter { +- +- CustomCounter() { +- super(); +- } +- +- public void incTheAnswer() { +- inc(42); +- } +- } +- +- private static final MetricName TIMER2 = MetricName.build("timer"); +- private static final MetricName METER2 = MetricName.build("meter"); +- private static final MetricName HISTOGRAM2 = MetricName.build("histogram"); +- private static final MetricName COUNTER = MetricName.build("counter"); +- private static final MetricName COUNTER2 = MetricName.build("counter2"); +- private static final MetricName GAUGE = MetricName.build("gauge"); +- private static final MetricName GAUGE2 = MetricName.build("gauge2"); +- private static final MetricName SETTABLE_GAUGE = MetricName.build("settable-gauge"); +- private static final MetricName THING = MetricName.build("thing"); +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); +- private final MetricRegistry registry = new MetricRegistry(); +- private final Gauge gauge = () -> ""; +- private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); +- +- @BeforeEach +- void setUp() { +- registry.addListener(listener); +- } +- +- @Test +- void registeringAGaugeTriggersANotification() { +- assertThat(registry.register(THING, gauge)) +- .isEqualTo(gauge); +- +- verify(listener).onGaugeAdded(THING, gauge); +- } +- +- @Test +- void removingAGaugeTriggersANotification() { +- registry.register(THING, gauge); +- +- assertThat(registry.remove(THING)) +- .isTrue(); +- +- verify(listener).onGaugeRemoved(THING); +- } +- +- @Test +- void registeringACounterTriggersANotification() { +- assertThat(registry.register(THING, counter)) +- .isEqualTo(counter); +- +- verify(listener).onCounterAdded(THING, counter); +- } +- +- @Test +- void accessingACounterRegistersAndReusesTheCounter() { +- final Counter counter1 = registry.counter(THING); +- final Counter counter2 = registry.counter(THING); +- +- assertThat(counter1) +- .isSameAs(counter2); +- +- verify(listener).onCounterAdded(THING, counter1); +- } +- +- @Test +- void accessingACustomCounterRegistersAndReusesTheCounter() { +- final MetricRegistry.MetricSupplier supplier = () -> counter; +- final Counter counter1 = registry.counter(THING, supplier); +- final Counter counter2 = registry.counter(THING, supplier); +- +- assertThat(counter1) +- .isSameAs(counter2); ++import java.util.HashMap; ++import java.util.Map; ++import java.util.Set; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +- verify(listener).onCounterAdded(THING, counter1); +- } ++final class MetricRegistryTest { + +- @Test +- void createsTypesafeCustomCounter() { +- MetricName name = MetricName.build("custom-counter"); +- final CustomCounter customCounter = registry.counter(name, CustomCounter::new); +- customCounter.incTheAnswer(); ++ private static class CustomCounter extends Counter { + +- assertThat(registry.counter(name).getCount()).isEqualTo(42); ++ CustomCounter() { ++ super(); + } + +- @Test +- void removingACounterTriggersANotification() { +- registry.register(THING, counter); +- +- assertThat(registry.remove(THING)) +- .isTrue(); +- +- verify(listener).onCounterRemoved(THING); ++ public void incTheAnswer() { ++ inc(42); + } ++ } + +- @Test +- void registeringAHistogramTriggersANotification() { +- assertThat(registry.register(THING, histogram)) +- .isEqualTo(histogram); ++ private static final MetricName TIMER2 = MetricName.build("timer"); ++ private static final MetricName METER2 = MetricName.build("meter"); ++ private static final MetricName HISTOGRAM2 = MetricName.build("histogram"); ++ private static final MetricName COUNTER = MetricName.build("counter"); ++ private static final MetricName COUNTER2 = MetricName.build("counter2"); ++ private static final MetricName GAUGE = MetricName.build("gauge"); ++ private static final MetricName GAUGE2 = MetricName.build("gauge2"); ++ private static final MetricName SETTABLE_GAUGE = MetricName.build("settable-gauge"); ++ private static final MetricName THING = MetricName.build("thing"); ++ private final MetricRegistryListener listener = mock(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final Gauge gauge = () -> ""; ++ private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + +- verify(listener).onHistogramAdded(THING, histogram); +- } ++ @BeforeEach ++ void setUp() { ++ registry.addListener(listener); ++ } + +- @Test +- void accessingAHistogramRegistersAndReusesIt() { +- final Histogram histogram1 = registry.histogram(THING); +- final Histogram histogram2 = registry.histogram(THING); ++ @Test ++ void registeringAGaugeTriggersANotification() { ++ assertThat(registry.register(THING, gauge)).isEqualTo(gauge); + +- assertThat(histogram1) +- .isSameAs(histogram2); ++ verify(listener).onGaugeAdded(THING, gauge); ++ } + +- verify(listener).onHistogramAdded(THING, histogram1); +- } ++ @Test ++ void removingAGaugeTriggersANotification() { ++ registry.register(THING, gauge); + +- @Test +- void accessingACustomHistogramRegistersAndReusesIt() { +- final MetricRegistry.MetricSupplier supplier = () -> histogram; +- final Histogram histogram1 = registry.histogram(THING, supplier); +- final Histogram histogram2 = registry.histogram(THING, supplier); ++ assertThat(registry.remove(THING)).isTrue(); + +- assertThat(histogram1) +- .isSameAs(histogram2); ++ verify(listener).onGaugeRemoved(THING); ++ } + +- verify(listener).onHistogramAdded(THING, histogram1); +- } ++ @Test ++ void registeringACounterTriggersANotification() { ++ assertThat(registry.register(THING, counter)).isEqualTo(counter); + +- @Test +- void removingAHistogramTriggersANotification() { +- registry.register(THING, histogram); ++ verify(listener).onCounterAdded(THING, counter); ++ } + +- assertThat(registry.remove(THING)) +- .isTrue(); ++ @Test ++ void accessingACounterRegistersAndReusesTheCounter() { ++ final Counter counter1 = registry.counter(THING); ++ final Counter counter2 = registry.counter(THING); + +- verify(listener).onHistogramRemoved(THING); +- } ++ assertThat(counter1).isSameAs(counter2); + +- @Test +- void registeringAMeterTriggersANotification() { +- assertThat(registry.register(THING, meter)) +- .isEqualTo(meter); ++ verify(listener).onCounterAdded(THING, counter1); ++ } + +- verify(listener).onMeterAdded(THING, meter); +- } ++ @Test ++ void accessingACustomCounterRegistersAndReusesTheCounter() { ++ final MetricRegistry.MetricSupplier supplier = () -> counter; ++ final Counter counter1 = registry.counter(THING, supplier); ++ final Counter counter2 = registry.counter(THING, supplier); + +- @Test +- void accessingAMeterRegistersAndReusesIt() { +- final Meter meter1 = registry.meter(THING); +- final Meter meter2 = registry.meter(THING); ++ assertThat(counter1).isSameAs(counter2); + +- assertThat(meter1) +- .isSameAs(meter2); ++ verify(listener).onCounterAdded(THING, counter1); ++ } + +- verify(listener).onMeterAdded(THING, meter1); +- } ++ @Test ++ void createsTypesafeCustomCounter() { ++ MetricName name = MetricName.build("custom-counter"); ++ final CustomCounter customCounter = registry.counter(name, CustomCounter::new); ++ customCounter.incTheAnswer(); + +- @Test +- void accessingACustomMeterRegistersAndReusesIt() { +- final MetricRegistry.MetricSupplier supplier = () -> meter; +- final Meter meter1 = registry.meter(THING, supplier); +- final Meter meter2 = registry.meter(THING, supplier); ++ assertThat(registry.counter(name).getCount()).isEqualTo(42); ++ } + +- assertThat(meter1) +- .isSameAs(meter2); ++ @Test ++ void removingACounterTriggersANotification() { ++ registry.register(THING, counter); + +- verify(listener).onMeterAdded(THING, meter1); +- } ++ assertThat(registry.remove(THING)).isTrue(); + +- @Test +- void removingAMeterTriggersANotification() { +- registry.register(THING, meter); ++ verify(listener).onCounterRemoved(THING); ++ } + +- assertThat(registry.remove(THING)) +- .isTrue(); ++ @Test ++ void registeringAHistogramTriggersANotification() { ++ assertThat(registry.register(THING, histogram)).isEqualTo(histogram); + +- verify(listener).onMeterRemoved(THING); +- } ++ verify(listener).onHistogramAdded(THING, histogram); ++ } + +- @Test +- void registeringATimerTriggersANotification() { +- assertThat(registry.register(THING, timer)) +- .isEqualTo(timer); ++ @Test ++ void accessingAHistogramRegistersAndReusesIt() { ++ final Histogram histogram1 = registry.histogram(THING); ++ final Histogram histogram2 = registry.histogram(THING); + +- verify(listener).onTimerAdded(THING, timer); +- } ++ assertThat(histogram1).isSameAs(histogram2); + +- @Test +- void accessingATimerRegistersAndReusesIt() { +- final Timer timer1 = registry.timer(THING); +- final Timer timer2 = registry.timer(THING); ++ verify(listener).onHistogramAdded(THING, histogram1); ++ } + +- assertThat(timer1) +- .isSameAs(timer2); ++ @Test ++ void accessingACustomHistogramRegistersAndReusesIt() { ++ final MetricRegistry.MetricSupplier supplier = () -> histogram; ++ final Histogram histogram1 = registry.histogram(THING, supplier); ++ final Histogram histogram2 = registry.histogram(THING, supplier); + +- verify(listener).onTimerAdded(THING, timer1); +- } ++ assertThat(histogram1).isSameAs(histogram2); + +- @Test +- void accessingACustomTimerRegistersAndReusesIt() { +- final MetricRegistry.MetricSupplier supplier = () -> timer; +- final Timer timer1 = registry.timer(THING, supplier); +- final Timer timer2 = registry.timer(THING, supplier); ++ verify(listener).onHistogramAdded(THING, histogram1); ++ } + +- assertThat(timer1) +- .isSameAs(timer2); ++ @Test ++ void removingAHistogramTriggersANotification() { ++ registry.register(THING, histogram); + +- verify(listener).onTimerAdded(THING, timer1); +- } ++ assertThat(registry.remove(THING)).isTrue(); + ++ verify(listener).onHistogramRemoved(THING); ++ } + +- @Test +- void removingATimerTriggersANotification() { +- registry.register(THING, timer); ++ @Test ++ void registeringAMeterTriggersANotification() { ++ assertThat(registry.register(THING, meter)).isEqualTo(meter); + +- assertThat(registry.remove(THING)) +- .isTrue(); ++ verify(listener).onMeterAdded(THING, meter); ++ } + +- verify(listener).onTimerRemoved(THING); +- } ++ @Test ++ void accessingAMeterRegistersAndReusesIt() { ++ final Meter meter1 = registry.meter(THING); ++ final Meter meter2 = registry.meter(THING); + +- @Test +- void accessingACustomGaugeRegistersAndReusesIt() { +- final MetricRegistry.MetricSupplier> supplier = () -> gauge; +- final Gauge gauge1 = registry.gauge(THING, supplier); +- final Gauge gauge2 = registry.gauge(THING, supplier); ++ assertThat(meter1).isSameAs(meter2); + +- assertThat(gauge1) +- .isSameAs(gauge2); ++ verify(listener).onMeterAdded(THING, meter1); ++ } + +- verify(listener).onGaugeAdded(THING, gauge1); +- } ++ @Test ++ void accessingACustomMeterRegistersAndReusesIt() { ++ final MetricRegistry.MetricSupplier supplier = () -> meter; ++ final Meter meter1 = registry.meter(THING, supplier); ++ final Meter meter2 = registry.meter(THING, supplier); + +- @Test +- void accessingASettableGaugeRegistersAndReusesIt() { +- final SettableGauge gauge1 = registry.gauge(THING); +- gauge1.setValue("Test"); +- final Gauge gauge2 = registry.gauge(THING); ++ assertThat(meter1).isSameAs(meter2); + +- assertThat(gauge1).isSameAs(gauge2); +- assertThat(gauge2.getValue()).isEqualTo("Test"); ++ verify(listener).onMeterAdded(THING, meter1); ++ } + +- verify(listener).onGaugeAdded(THING, gauge1); +- } ++ @Test ++ void removingAMeterTriggersANotification() { ++ registry.register(THING, meter); + +- @Test +- void accessingAnExistingGaugeReusesIt() { +- final Gauge gauge1 = registry.gauge(THING, () -> () -> "string-gauge"); +- final Gauge gauge2 = registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); ++ assertThat(registry.remove(THING)).isTrue(); + +- assertThat(gauge1).isSameAs(gauge2); +- assertThat(gauge2.getValue()).isEqualTo("string-gauge"); ++ verify(listener).onMeterRemoved(THING); ++ } + +- verify(listener).onGaugeAdded(THING, gauge1); +- } ++ @Test ++ void registeringATimerTriggersANotification() { ++ assertThat(registry.register(THING, timer)).isEqualTo(timer); + +- @Test +- void accessingAnExistingSettableGaugeReusesIt() { +- final Gauge gauge1 = registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); +- final Gauge gauge2 = registry.gauge(THING); ++ verify(listener).onTimerAdded(THING, timer); ++ } + +- assertThat(gauge1).isSameAs(gauge2); +- assertThat(gauge2.getValue()).isEqualTo("settable-gauge"); ++ @Test ++ void accessingATimerRegistersAndReusesIt() { ++ final Timer timer1 = registry.timer(THING); ++ final Timer timer2 = registry.timer(THING); + +- verify(listener).onGaugeAdded(THING, gauge1); +- } ++ assertThat(timer1).isSameAs(timer2); + +- @Test +- void settableGaugeIsTreatedLikeAGauge() { +- final MetricRegistry.MetricSupplier> supplier = () -> settableGauge; +- final SettableGauge gauge1 = registry.gauge(THING, supplier); +- final SettableGauge gauge2 = registry.gauge(THING, supplier); ++ verify(listener).onTimerAdded(THING, timer1); ++ } + +- assertThat(gauge1) +- .isSameAs(gauge2); ++ @Test ++ void accessingACustomTimerRegistersAndReusesIt() { ++ final MetricRegistry.MetricSupplier supplier = () -> timer; ++ final Timer timer1 = registry.timer(THING, supplier); ++ final Timer timer2 = registry.timer(THING, supplier); + +- verify(listener).onGaugeAdded(THING, gauge1); +- } ++ assertThat(timer1).isSameAs(timer2); + +- @Test +- void addingAListenerWithExistingMetricsCatchesItUp() { +- registry.register(GAUGE2, gauge); +- registry.register(SETTABLE_GAUGE, settableGauge); +- registry.register(COUNTER2, counter); +- registry.register(HISTOGRAM2, histogram); +- registry.register(METER2, meter); +- registry.register(TIMER2, timer); +- +- final MetricRegistryListener other = mock(MetricRegistryListener.class); +- registry.addListener(other); +- +- verify(other).onGaugeAdded(GAUGE2, gauge); +- verify(other).onGaugeAdded(SETTABLE_GAUGE, settableGauge); +- verify(other).onCounterAdded(COUNTER2, counter); +- verify(other).onHistogramAdded(HISTOGRAM2, histogram); +- verify(other).onMeterAdded(METER2, meter); +- verify(other).onTimerAdded(TIMER2, timer); +- } ++ verify(listener).onTimerAdded(THING, timer1); ++ } + +- @Test +- void aRemovedListenerDoesNotReceiveUpdates() { +- registry.register(GAUGE, gauge); +- registry.removeListener(listener); +- registry.register(GAUGE2, gauge); ++ @Test ++ void removingATimerTriggersANotification() { ++ registry.register(THING, timer); + +- verify(listener, never()).onGaugeAdded(GAUGE2, gauge); +- } ++ assertThat(registry.remove(THING)).isTrue(); + +- @Test +- void hasAMapOfRegisteredGauges() { +- registry.register(GAUGE2, gauge); +- registry.register(SETTABLE_GAUGE, settableGauge); ++ verify(listener).onTimerRemoved(THING); ++ } + +- assertThat(registry.getGauges()) +- .containsEntry(GAUGE2, gauge) +- .containsEntry(SETTABLE_GAUGE, settableGauge); +- } ++ @Test ++ void accessingACustomGaugeRegistersAndReusesIt() { ++ final MetricRegistry.MetricSupplier> supplier = () -> gauge; ++ final Gauge gauge1 = registry.gauge(THING, supplier); ++ final Gauge gauge2 = registry.gauge(THING, supplier); + +- @Test +- void hasAMapOfRegisteredCounters() { +- registry.register(COUNTER2, counter); ++ assertThat(gauge1).isSameAs(gauge2); + +- assertThat(registry.getCounters()) +- .contains(entry(COUNTER2, counter)); +- } ++ verify(listener).onGaugeAdded(THING, gauge1); ++ } + +- @Test +- void hasAMapOfRegisteredHistograms() { +- registry.register(HISTOGRAM2, histogram); ++ @Test ++ void accessingASettableGaugeRegistersAndReusesIt() { ++ final SettableGauge gauge1 = registry.gauge(THING); ++ gauge1.setValue("Test"); ++ final Gauge gauge2 = registry.gauge(THING); + +- assertThat(registry.getHistograms()) +- .contains(entry(HISTOGRAM2, histogram)); +- } ++ assertThat(gauge1).isSameAs(gauge2); ++ assertThat(gauge2.getValue()).isEqualTo("Test"); + +- @Test +- void hasAMapOfRegisteredMeters() { +- registry.register(METER2, meter); ++ verify(listener).onGaugeAdded(THING, gauge1); ++ } + +- assertThat(registry.getMeters()) +- .contains(entry(METER2, meter)); +- } ++ @Test ++ void accessingAnExistingGaugeReusesIt() { ++ final Gauge gauge1 = registry.gauge(THING, () -> () -> "string-gauge"); ++ final Gauge gauge2 = ++ registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); + +- @Test +- void hasAMapOfRegisteredTimers() { +- registry.register(TIMER2, timer); ++ assertThat(gauge1).isSameAs(gauge2); ++ assertThat(gauge2.getValue()).isEqualTo("string-gauge"); + +- assertThat(registry.getTimers()) +- .contains(entry(TIMER2, timer)); +- } ++ verify(listener).onGaugeAdded(THING, gauge1); ++ } + +- @Test +- void hasASetOfRegisteredMetricNames() { +- registry.register(GAUGE2, gauge); +- registry.register(SETTABLE_GAUGE, settableGauge); +- registry.register(COUNTER2, counter); +- registry.register(HISTOGRAM2, histogram); +- registry.register(METER2, meter); +- registry.register(TIMER2, timer); +- +- assertThat(registry.getNames()) +- .containsOnly(GAUGE2, SETTABLE_GAUGE, COUNTER2, HISTOGRAM2, METER2, TIMER2); +- } ++ @Test ++ void accessingAnExistingSettableGaugeReusesIt() { ++ final Gauge gauge1 = ++ registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); ++ final Gauge gauge2 = registry.gauge(THING); + +- @Test +- void registersMultipleMetrics() { +- final MetricSet metrics = () -> { +- final Map m = new HashMap<>(); +- m.put(GAUGE2, gauge); +- m.put(COUNTER2, counter); +- return m; ++ assertThat(gauge1).isSameAs(gauge2); ++ assertThat(gauge2.getValue()).isEqualTo("settable-gauge"); ++ ++ verify(listener).onGaugeAdded(THING, gauge1); ++ } ++ ++ @Test ++ void settableGaugeIsTreatedLikeAGauge() { ++ final MetricRegistry.MetricSupplier> supplier = () -> settableGauge; ++ final SettableGauge gauge1 = registry.gauge(THING, supplier); ++ final SettableGauge gauge2 = registry.gauge(THING, supplier); ++ ++ assertThat(gauge1).isSameAs(gauge2); ++ ++ verify(listener).onGaugeAdded(THING, gauge1); ++ } ++ ++ @Test ++ void addingAListenerWithExistingMetricsCatchesItUp() { ++ registry.register(GAUGE2, gauge); ++ registry.register(SETTABLE_GAUGE, settableGauge); ++ registry.register(COUNTER2, counter); ++ registry.register(HISTOGRAM2, histogram); ++ registry.register(METER2, meter); ++ registry.register(TIMER2, timer); ++ ++ final MetricRegistryListener other = mock(); ++ registry.addListener(other); ++ ++ verify(other).onGaugeAdded(GAUGE2, gauge); ++ verify(other).onGaugeAdded(SETTABLE_GAUGE, settableGauge); ++ verify(other).onCounterAdded(COUNTER2, counter); ++ verify(other).onHistogramAdded(HISTOGRAM2, histogram); ++ verify(other).onMeterAdded(METER2, meter); ++ verify(other).onTimerAdded(TIMER2, timer); ++ } ++ ++ @Test ++ void aRemovedListenerDoesNotReceiveUpdates() { ++ registry.register(GAUGE, gauge); ++ registry.removeListener(listener); ++ registry.register(GAUGE2, gauge); ++ ++ verify(listener, never()).onGaugeAdded(GAUGE2, gauge); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredGauges() { ++ registry.register(GAUGE2, gauge); ++ registry.register(SETTABLE_GAUGE, settableGauge); ++ ++ assertThat(registry.getGauges()) ++ .containsEntry(GAUGE2, gauge) ++ .containsEntry(SETTABLE_GAUGE, settableGauge); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredCounters() { ++ registry.register(COUNTER2, counter); ++ ++ assertThat(registry.getCounters()).contains(entry(COUNTER2, counter)); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredHistograms() { ++ registry.register(HISTOGRAM2, histogram); ++ ++ assertThat(registry.getHistograms()).contains(entry(HISTOGRAM2, histogram)); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredMeters() { ++ registry.register(METER2, meter); ++ ++ assertThat(registry.getMeters()).contains(entry(METER2, meter)); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredTimers() { ++ registry.register(TIMER2, timer); ++ ++ assertThat(registry.getTimers()).contains(entry(TIMER2, timer)); ++ } ++ ++ @Test ++ void hasASetOfRegisteredMetricNames() { ++ registry.register(GAUGE2, gauge); ++ registry.register(SETTABLE_GAUGE, settableGauge); ++ registry.register(COUNTER2, counter); ++ registry.register(HISTOGRAM2, histogram); ++ registry.register(METER2, meter); ++ registry.register(TIMER2, timer); ++ ++ assertThat(registry.getNames()) ++ .containsOnly(GAUGE2, SETTABLE_GAUGE, COUNTER2, HISTOGRAM2, METER2, TIMER2); ++ } ++ ++ @Test ++ void registersMultipleMetrics() { ++ final MetricSet metrics = ++ () -> { ++ final Map m = new HashMap<>(); ++ m.put(GAUGE2, gauge); ++ m.put(COUNTER2, counter); ++ return m; + }; + +- registry.registerAll(metrics); ++ registry.registerAll(metrics); + +- assertThat(registry.getNames()) +- .containsOnly(GAUGE2, COUNTER2); +- } ++ assertThat(registry.getNames()).containsOnly(GAUGE2, COUNTER2); ++ } + +- @Test +- void registersMultipleMetricsWithAPrefix() { +- final MetricName myCounter = MetricName.build("my.counter"); +- final MetricName myGauge = MetricName.build("my.gauge"); ++ @Test ++ void registersMultipleMetricsWithAPrefix() { ++ final MetricName myCounter = MetricName.build("my.counter"); ++ final MetricName myGauge = MetricName.build("my.gauge"); + +- final MetricSet metrics = () -> { +- final Map m = new HashMap<>(); +- m.put(GAUGE, gauge); +- m.put(COUNTER, counter); +- return m; ++ final MetricSet metrics = ++ () -> { ++ final Map m = new HashMap<>(); ++ m.put(GAUGE, gauge); ++ m.put(COUNTER, counter); ++ return m; + }; + +- registry.register(MetricName.build("my"), metrics); ++ registry.register(MetricName.build("my"), metrics); + +- assertThat(registry.getNames()) +- .containsOnly(myGauge, myCounter); +- } ++ assertThat(registry.getNames()).containsOnly(myGauge, myCounter); ++ } + +- @Test +- void registersRecursiveMetricSets() { +- final MetricSet inner = () -> { +- final Map m = new HashMap<>(); +- m.put(GAUGE, gauge); +- return m; ++ @Test ++ void registersRecursiveMetricSets() { ++ final MetricSet inner = ++ () -> { ++ final Map m = new HashMap<>(); ++ m.put(GAUGE, gauge); ++ return m; + }; + +- final MetricSet outer = () -> { +- final Map m = new HashMap<>(); +- m.put(MetricName.build("inner"), inner); +- m.put(COUNTER, counter); +- return m; ++ final MetricSet outer = ++ () -> { ++ final Map m = new HashMap<>(); ++ m.put(MetricName.build("inner"), inner); ++ m.put(COUNTER, counter); ++ return m; + }; + +- registry.register(MetricName.build("my"), outer); +- +- final MetricName myCounter = MetricName.build("my.counter"); +- final MetricName myInnerGauge = MetricName.build("my.inner.gauge"); +- +- assertThat(registry.getNames()) +- .containsOnly(myInnerGauge, myCounter); +- } +- +- @Test +- void registersMetricsFromAnotherRegistry() { +- MetricRegistry other = new MetricRegistry(); +- other.register(GAUGE, gauge); +- registry.register(MetricName.build("nested"), other); +- assertThat(registry.getNames()).containsOnly(MetricName.build("nested.gauge")); +- } +- +- @Test +- void concatenatesStringsToFormADottedName() { +- assertThat(name("one", "two", "three")) +- .isEqualTo(MetricName.build("one.two.three")); +- } +- +- @Test +- void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { +- assertThat(name("one", (String) null)) +- .isEqualTo(MetricName.build("one")); +- } +- +- @Test +- void elidesNullValuesFromNamesWhenManyNullsPassedIn() { +- assertThat(name("one", null, null)) +- .isEqualTo(MetricName.build("one")); +- } +- +- @Test +- void elidesNullValuesFromNamesWhenNullAndNotNullPassedIn() { +- assertThat(name("one", null, "three")) +- .isEqualTo(MetricName.build("one.three")); +- } +- +- @Test +- void elidesEmptyStringsFromNames() { +- assertThat(name("one", "", "three")) +- .isEqualTo(MetricName.build("one.three")); +- } +- +- @Test +- void concatenatesClassNamesWithStringsToFormADottedName() { +- assertThat(name(MetricRegistryTest.class, "one", "two")) +- .isEqualTo(MetricName.build("io.dropwizard.metrics5.MetricRegistryTest.one.two")); +- } +- +- @Test +- void concatenatesClassesWithoutCanonicalNamesWithStrings() { +- final Gauge g = () -> null; +- +- assertThat(name(g.getClass(), "one", "two")) +- .isEqualTo(MetricName.build(g.getClass().getName() + ".one.two")); +- } +- +- @Test +- void removesMetricsMatchingAFilter() { +- final MetricName timer1 = MetricName.build("timer-1"); +- final MetricName timer2 = MetricName.build("timer-2"); +- final MetricName histogram1 = MetricName.build("histogram-1"); +- +- registry.timer(timer1); +- registry.timer(timer2); +- registry.histogram(histogram1); +- +- assertThat(registry.getNames()) +- .contains(timer1, timer2, histogram1); +- +- registry.removeMatching((name, metric) -> name.getKey().endsWith("1")); +- +- assertThat(registry.getNames()) +- .doesNotContain(timer1, histogram1); +- assertThat(registry.getNames()) +- .contains(timer2); +- +- verify(listener).onTimerRemoved(timer1); +- verify(listener).onHistogramRemoved(histogram1); +- } +- +- @Test +- void addingChildMetricAfterRegister() { +- MetricRegistry parent = new MetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- +- child.counter("test-1"); +- parent.register(MetricName.build("child"), child); +- child.counter("test-2"); +- +- Set parentMetrics = parent.getMetrics().keySet(); +- Set childMetrics = child.getMetrics().keySet(); +- +- assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); +- } +- +- @Test +- void addingMultipleChildMetricsAfterRegister() { +- MetricRegistry parent = new MetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- +- child.counter("test-1"); +- child.counter("test-2"); +- parent.register(MetricName.build("child"), child); +- child.counter("test-3"); +- child.counter("test-4"); +- +- Set parentMetrics = parent.getMetrics().keySet(); +- Set childMetrics = child.getMetrics().keySet(); +- +- assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); +- } +- +- @Test +- void addingDeepChildMetricsAfterRegister() { +- MetricRegistry parent = new MetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- MetricRegistry deepChild = new MetricRegistry(); +- +- deepChild.counter("test-1"); +- child.register(MetricName.build("deep-child"), deepChild); +- deepChild.counter("test-2"); +- +- child.counter("test-3"); +- parent.register(MetricName.build("child"), child); +- child.counter("test-4"); +- +- deepChild.counter("test-5"); +- Set parentMetrics = parent.getMetrics().keySet(); +- Set childMetrics = child.getMetrics().keySet(); +- Set deepChildMetrics = deepChild.getMetrics().keySet(); ++ registry.register(MetricName.build("my"), outer); ++ ++ final MetricName myCounter = MetricName.build("my.counter"); ++ final MetricName myInnerGauge = MetricName.build("my.inner.gauge"); ++ ++ assertThat(registry.getNames()).containsOnly(myInnerGauge, myCounter); ++ } ++ ++ @Test ++ void registersMetricsFromAnotherRegistry() { ++ MetricRegistry other = new MetricRegistry(); ++ other.register(GAUGE, gauge); ++ registry.register(MetricName.build("nested"), other); ++ assertThat(registry.getNames()).containsExactly(MetricName.build("nested.gauge")); ++ } ++ ++ @Test ++ void concatenatesStringsToFormADottedName() { ++ assertThat(name("one", "two", "three")).isEqualTo(MetricName.build("one.two.three")); ++ } ++ ++ @Test ++ void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { ++ assertThat(name("one", (String) null)).isEqualTo(MetricName.build("one")); ++ } ++ ++ @Test ++ void elidesNullValuesFromNamesWhenManyNullsPassedIn() { ++ assertThat(name("one", null, null)).isEqualTo(MetricName.build("one")); ++ } ++ ++ @Test ++ void elidesNullValuesFromNamesWhenNullAndNotNullPassedIn() { ++ assertThat(name("one", null, "three")).isEqualTo(MetricName.build("one.three")); ++ } ++ ++ @Test ++ void elidesEmptyStringsFromNames() { ++ assertThat(name("one", "", "three")).isEqualTo(MetricName.build("one.three")); ++ } ++ ++ @Test ++ void concatenatesClassNamesWithStringsToFormADottedName() { ++ assertThat(name(MetricRegistryTest.class, "one", "two")) ++ .isEqualTo(MetricName.build("io.dropwizard.metrics5.MetricRegistryTest.one.two")); ++ } ++ ++ @Test ++ void concatenatesClassesWithoutCanonicalNamesWithStrings() { ++ final Gauge g = () -> null; ++ ++ assertThat(name(g.getClass(), "one", "two")) ++ .isEqualTo(MetricName.build(g.getClass().getName() + ".one.two")); ++ } ++ ++ @Test ++ void removesMetricsMatchingAFilter() { ++ final MetricName timer1 = MetricName.build("timer-1"); ++ final MetricName timer2 = MetricName.build("timer-2"); ++ final MetricName histogram1 = MetricName.build("histogram-1"); ++ ++ registry.timer(timer1); ++ registry.timer(timer2); ++ registry.histogram(histogram1); ++ ++ assertThat(registry.getNames()).contains(timer1, timer2, histogram1); ++ ++ registry.removeMatching((name, metric) -> name.getKey().endsWith("1")); ++ ++ assertThat(registry.getNames()).doesNotContain(timer1, histogram1); ++ assertThat(registry.getNames()).contains(timer2); ++ ++ verify(listener).onTimerRemoved(timer1); ++ verify(listener).onHistogramRemoved(histogram1); ++ } ++ ++ @Test ++ void addingChildMetricAfterRegister() { ++ MetricRegistry parent = new MetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ ++ child.counter("test-1"); ++ parent.register(MetricName.build("child"), child); ++ child.counter("test-2"); ++ ++ Set parentMetrics = parent.getMetrics().keySet(); ++ Set childMetrics = child.getMetrics().keySet(); ++ ++ assertThat(parentMetrics) ++ .hasSameElementsAs( ++ childMetrics.stream() ++ .map(m -> MetricName.build("child", m.getKey())) ++ .collect(toImmutableSet())); ++ } ++ ++ @Test ++ void addingMultipleChildMetricsAfterRegister() { ++ MetricRegistry parent = new MetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ ++ child.counter("test-1"); ++ child.counter("test-2"); ++ parent.register(MetricName.build("child"), child); ++ child.counter("test-3"); ++ child.counter("test-4"); ++ ++ Set parentMetrics = parent.getMetrics().keySet(); ++ Set childMetrics = child.getMetrics().keySet(); ++ ++ assertThat(parentMetrics) ++ .hasSameElementsAs( ++ childMetrics.stream() ++ .map(m -> MetricName.build("child", m.getKey())) ++ .collect(toImmutableSet())); ++ } ++ ++ @Test ++ void addingDeepChildMetricsAfterRegister() { ++ MetricRegistry parent = new MetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ MetricRegistry deepChild = new MetricRegistry(); ++ ++ deepChild.counter("test-1"); ++ child.register(MetricName.build("deep-child"), deepChild); ++ deepChild.counter("test-2"); ++ ++ child.counter("test-3"); ++ parent.register(MetricName.build("child"), child); ++ child.counter("test-4"); ++ ++ deepChild.counter("test-5"); ++ Set parentMetrics = parent.getMetrics().keySet(); ++ Set childMetrics = child.getMetrics().keySet(); ++ Set deepChildMetrics = deepChild.getMetrics().keySet(); ++ ++ assertThat(parentMetrics) ++ .hasSameElementsAs( ++ childMetrics.stream() ++ .map(m -> MetricName.build("child", m.getKey())) ++ .collect(toImmutableSet())); ++ ++ assertThat(childMetrics) ++ .containsAll( ++ deepChildMetrics.stream() ++ .map(m -> MetricName.build("deep-child", m.getKey())) ++ .collect(toImmutableSet())); ++ ++ assertThat(deepChildMetrics).hasSize(3); ++ assertThat(childMetrics).hasSize(5); ++ } ++ ++ @Test ++ void removingChildMetricAfterRegister() { ++ MetricRegistry parent = new MetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ ++ child.counter("test-1"); ++ parent.register(MetricName.build("child"), child); ++ child.counter("test-2"); ++ ++ child.remove(MetricName.build("test-1")); ++ ++ Set parentMetrics = parent.getMetrics().keySet(); ++ Set childMetrics = child.getMetrics().keySet(); ++ ++ assertThat(parentMetrics) ++ .hasSameElementsAs( ++ childMetrics.stream() ++ .map(m -> MetricName.build("child", m.getKey())) ++ .collect(toImmutableSet())); ++ ++ assertThat(childMetrics).doesNotContain(MetricName.build("test-1")); ++ } ++ ++ @Test ++ void removingMultipleChildMetricsAfterRegister() { ++ MetricRegistry parent = new MetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ ++ child.counter("test-1"); ++ child.counter("test-2"); ++ parent.register(MetricName.build("child"), child); ++ child.counter("test-3"); ++ child.counter("test-4"); ++ ++ child.remove(MetricName.build("test-1")); ++ child.remove(MetricName.build("test-3")); ++ ++ Set parentMetrics = parent.getMetrics().keySet(); ++ Set childMetrics = child.getMetrics().keySet(); ++ ++ assertThat(parentMetrics) ++ .hasSameElementsAs( ++ childMetrics.stream() ++ .map(m -> MetricName.build("child", m.getKey())) ++ .collect(toImmutableSet())); ++ ++ assertThat(childMetrics).doesNotContain(MetricName.build("test-1"), MetricName.build("test-3")); ++ } ++ ++ @Test ++ void removingDeepChildMetricsAfterRegister() { ++ MetricRegistry parent = new MetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ MetricRegistry deepChild = new MetricRegistry(); ++ ++ deepChild.counter("test-1"); ++ child.register(MetricName.build("deep-child"), deepChild); ++ deepChild.counter("test-2"); ++ ++ child.counter("test-3"); ++ parent.register(MetricName.build("child"), child); ++ child.counter("test-4"); ++ ++ deepChild.remove(MetricName.build("test-2")); ++ ++ Set parentMetrics = parent.getMetrics().keySet(); ++ Set childMetrics = child.getMetrics().keySet(); ++ Set deepChildMetrics = deepChild.getMetrics().keySet(); ++ ++ assertThat(parentMetrics) ++ .hasSameElementsAs( ++ childMetrics.stream() ++ .map(m -> MetricName.build("child", m.getKey())) ++ .collect(toImmutableSet())); ++ ++ assertThat(childMetrics) ++ .containsAll( ++ deepChildMetrics.stream() ++ .map(m -> MetricName.build("deep-child", m.getKey())) ++ .collect(toImmutableSet())); ++ ++ assertThat(deepChildMetrics).doesNotContain(MetricName.build("test-2")); ++ ++ assertThat(deepChildMetrics).hasSize(1); ++ assertThat(childMetrics).hasSize(3); ++ } ++ ++ @Test ++ void registerNullMetric() { ++ MetricRegistry registry = new MetricRegistry(); ++ assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)) ++ .hasMessage("metric == null"); ++ } ++ ++ @Test ++ void infersGaugeType() { ++ Gauge gauge = registry.registerGauge(GAUGE, () -> 10_000_000_000L); ++ ++ assertThat(gauge.getValue()).isEqualTo(10_000_000_000L); ++ } ++ ++ @Test ++ void registersGaugeAsLambda() { ++ registry.registerGauge(GAUGE, () -> 3.14); + +- assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); +- +- assertThat(childMetrics) +- .containsAll(deepChildMetrics.stream().map(m -> MetricName.build("deep-child", m.getKey())).collect(Collectors.toSet())); +- +- assertThat(deepChildMetrics.size()).isEqualTo(3); +- assertThat(childMetrics.size()).isEqualTo(5); +- } +- +- @Test +- void removingChildMetricAfterRegister() { +- MetricRegistry parent = new MetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- +- child.counter("test-1"); +- parent.register(MetricName.build("child"), child); +- child.counter("test-2"); +- +- child.remove(MetricName.build("test-1")); +- +- Set parentMetrics = parent.getMetrics().keySet(); +- Set childMetrics = child.getMetrics().keySet(); +- +- assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); +- +- assertThat(childMetrics).doesNotContain(MetricName.build("test-1")); +- } +- +- @Test +- void removingMultipleChildMetricsAfterRegister() { +- MetricRegistry parent = new MetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- +- child.counter("test-1"); +- child.counter("test-2"); +- parent.register(MetricName.build("child"), child); +- child.counter("test-3"); +- child.counter("test-4"); +- +- child.remove(MetricName.build("test-1")); +- child.remove(MetricName.build("test-3")); +- +- Set parentMetrics = parent.getMetrics().keySet(); +- Set childMetrics = child.getMetrics().keySet(); +- +- assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); +- +- assertThat(childMetrics).doesNotContain(MetricName.build("test-1"), MetricName.build("test-3")); +- } +- +- @Test +- void removingDeepChildMetricsAfterRegister() { +- MetricRegistry parent = new MetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- MetricRegistry deepChild = new MetricRegistry(); +- +- deepChild.counter("test-1"); +- child.register(MetricName.build("deep-child"), deepChild); +- deepChild.counter("test-2"); +- +- child.counter("test-3"); +- parent.register(MetricName.build("child"), child); +- child.counter("test-4"); +- +- deepChild.remove(MetricName.build("test-2")); +- +- Set parentMetrics = parent.getMetrics().keySet(); +- Set childMetrics = child.getMetrics().keySet(); +- Set deepChildMetrics = deepChild.getMetrics().keySet(); +- +- assertThat(parentMetrics) +- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); +- +- assertThat(childMetrics) +- .containsAll(deepChildMetrics.stream().map(m -> MetricName.build("deep-child", m.getKey())).collect(Collectors.toSet())); +- +- assertThat(deepChildMetrics).doesNotContain(MetricName.build("test-2")); +- +- assertThat(deepChildMetrics.size()).isEqualTo(1); +- assertThat(childMetrics.size()).isEqualTo(3); +- } +- +- @Test +- void registerNullMetric() { +- MetricRegistry registry = new MetricRegistry(); +- assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)) +- .hasMessage("metric == null"); +- } +- +- @Test +- void infersGaugeType() { +- Gauge gauge = registry.registerGauge(GAUGE, () -> 10_000_000_000L); +- +- assertThat(gauge.getValue()).isEqualTo(10_000_000_000L); +- } +- +- @Test +- void registersGaugeAsLambda() { +- registry.registerGauge(GAUGE, () -> 3.14); +- +- assertThat(registry.gauge(GAUGE).getValue()).isEqualTo(3.14); +- } ++ assertThat(registry.gauge(GAUGE).getValue()).isEqualTo(3.14); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java +@@ -1,497 +1,498 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import java.util.HashMap; +-import java.util.Map; +-import java.util.Set; +- + import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatNullPointerException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; + import static org.mockito.Mockito.verify; + +-class NoopMetricRegistryTest { +- private static final MetricName METRIC_THING = MetricName.build("thing"); +- +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); +- private final NoopMetricRegistry registry = new NoopMetricRegistry(); +- private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); +- +- @BeforeEach +- void setUp() { +- registry.addListener(listener); +- } +- +- @Test +- void registeringAGaugeTriggersNoNotification() { +- assertThat(registry.register(METRIC_THING, gauge)).isEqualTo(gauge); +- +- verify(listener, never()).onGaugeAdded(METRIC_THING, gauge); +- } +- +- @Test +- void removingAGaugeTriggersNoNotification() { +- registry.register(METRIC_THING, gauge); +- +- assertThat(registry.remove(METRIC_THING)).isFalse(); +- +- verify(listener, never()).onGaugeRemoved(METRIC_THING); +- } +- +- @Test +- void registeringACounterTriggersNoNotification() { +- assertThat(registry.register(METRIC_THING, counter)).isEqualTo(counter); +- +- verify(listener, never()).onCounterAdded(METRIC_THING, counter); +- } +- +- @Test +- void accessingACounterRegistersAndReusesTheCounter() { +- final Counter counter1 = registry.counter(METRIC_THING); +- final Counter counter2 = registry.counter(METRIC_THING); +- +- assertThat(counter1).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); +- assertThat(counter2).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); +- assertThat(counter1).isSameAs(counter2); +- +- verify(listener, never()).onCounterAdded(METRIC_THING, counter1); +- } +- +- @Test +- void accessingACustomCounterRegistersAndReusesTheCounter() { +- final MetricRegistry.MetricSupplier supplier = () -> counter; +- final Counter counter1 = registry.counter(METRIC_THING, supplier); +- final Counter counter2 = registry.counter(METRIC_THING, supplier); +- +- assertThat(counter1).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); +- assertThat(counter2).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); +- assertThat(counter1).isSameAs(counter2); +- +- verify(listener, never()).onCounterAdded(METRIC_THING, counter1); +- } +- +- +- @Test +- void removingACounterTriggersNoNotification() { +- registry.register(METRIC_THING, counter); ++import java.util.HashMap; ++import java.util.Map; ++import java.util.Set; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +- assertThat(registry.remove(METRIC_THING)).isFalse(); ++final class NoopMetricRegistryTest { ++ private static final MetricName METRIC_THING = MetricName.build("thing"); + +- verify(listener, never()).onCounterRemoved(METRIC_THING); +- } ++ private final MetricRegistryListener listener = mock(); ++ private final NoopMetricRegistry registry = new NoopMetricRegistry(); ++ private final Gauge gauge = () -> ""; ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + +- @Test +- void registeringAHistogramTriggersNoNotification() { +- assertThat(registry.register(METRIC_THING, histogram)).isEqualTo(histogram); ++ @BeforeEach ++ void setUp() { ++ registry.addListener(listener); ++ } + +- verify(listener, never()).onHistogramAdded(METRIC_THING, histogram); +- } ++ @Test ++ void registeringAGaugeTriggersNoNotification() { ++ assertThat(registry.register(METRIC_THING, gauge)).isEqualTo(gauge); + +- @Test +- void accessingAHistogramRegistersAndReusesIt() { +- final Histogram histogram1 = registry.histogram(METRIC_THING); +- final Histogram histogram2 = registry.histogram(METRIC_THING); ++ verify(listener, never()).onGaugeAdded(METRIC_THING, gauge); ++ } + +- assertThat(histogram1).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); +- assertThat(histogram2).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); +- assertThat(histogram1).isSameAs(histogram2); ++ @Test ++ void removingAGaugeTriggersNoNotification() { ++ registry.register(METRIC_THING, gauge); + +- verify(listener, never()).onHistogramAdded(METRIC_THING, histogram1); +- } ++ assertThat(registry.remove(METRIC_THING)).isFalse(); + +- @Test +- void accessingACustomHistogramRegistersAndReusesIt() { +- final MetricRegistry.MetricSupplier supplier = () -> histogram; +- final Histogram histogram1 = registry.histogram(METRIC_THING, supplier); +- final Histogram histogram2 = registry.histogram(METRIC_THING, supplier); ++ verify(listener, never()).onGaugeRemoved(METRIC_THING); ++ } + +- assertThat(histogram1).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); +- assertThat(histogram2).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); +- assertThat(histogram1).isSameAs(histogram2); ++ @Test ++ void registeringACounterTriggersNoNotification() { ++ assertThat(registry.register(METRIC_THING, counter)).isEqualTo(counter); + +- verify(listener, never()).onHistogramAdded(METRIC_THING, histogram1); +- } ++ verify(listener, never()).onCounterAdded(METRIC_THING, counter); ++ } + +- @Test +- void removingAHistogramTriggersNoNotification() { +- registry.register(METRIC_THING, histogram); ++ @Test ++ void accessingACounterRegistersAndReusesTheCounter() { ++ final Counter counter1 = registry.counter(METRIC_THING); ++ final Counter counter2 = registry.counter(METRIC_THING); + +- assertThat(registry.remove(METRIC_THING)).isFalse(); ++ assertThat(counter1).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); ++ assertThat(counter2).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); ++ assertThat(counter1).isSameAs(counter2); + +- verify(listener, never()).onHistogramRemoved(METRIC_THING); +- } ++ verify(listener, never()).onCounterAdded(METRIC_THING, counter1); ++ } + +- @Test +- void registeringAMeterTriggersNoNotification() { +- assertThat(registry.register(METRIC_THING, meter)).isEqualTo(meter); ++ @Test ++ void accessingACustomCounterRegistersAndReusesTheCounter() { ++ final MetricRegistry.MetricSupplier supplier = () -> counter; ++ final Counter counter1 = registry.counter(METRIC_THING, supplier); ++ final Counter counter2 = registry.counter(METRIC_THING, supplier); + +- verify(listener, never()).onMeterAdded(METRIC_THING, meter); +- } ++ assertThat(counter1).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); ++ assertThat(counter2).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); ++ assertThat(counter1).isSameAs(counter2); + +- @Test +- void accessingAMeterRegistersAndReusesIt() { +- final Meter meter1 = registry.meter(METRIC_THING); +- final Meter meter2 = registry.meter(METRIC_THING); ++ verify(listener, never()).onCounterAdded(METRIC_THING, counter1); ++ } + +- assertThat(meter1).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); +- assertThat(meter2).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); +- assertThat(meter1).isSameAs(meter2); ++ @Test ++ void removingACounterTriggersNoNotification() { ++ registry.register(METRIC_THING, counter); + +- verify(listener, never()).onMeterAdded(METRIC_THING, meter1); +- } ++ assertThat(registry.remove(METRIC_THING)).isFalse(); + +- @Test +- void accessingACustomMeterRegistersAndReusesIt() { +- final MetricRegistry.MetricSupplier supplier = () -> meter; +- final Meter meter1 = registry.meter(METRIC_THING, supplier); +- final Meter meter2 = registry.meter(METRIC_THING, supplier); ++ verify(listener, never()).onCounterRemoved(METRIC_THING); ++ } + +- assertThat(meter1).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); +- assertThat(meter2).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); +- assertThat(meter1).isSameAs(meter2); ++ @Test ++ void registeringAHistogramTriggersNoNotification() { ++ assertThat(registry.register(METRIC_THING, histogram)).isEqualTo(histogram); + +- verify(listener, never()).onMeterAdded(METRIC_THING, meter1); +- } ++ verify(listener, never()).onHistogramAdded(METRIC_THING, histogram); ++ } + +- @Test +- void removingAMeterTriggersNoNotification() { +- registry.register(METRIC_THING, meter); ++ @Test ++ void accessingAHistogramRegistersAndReusesIt() { ++ final Histogram histogram1 = registry.histogram(METRIC_THING); ++ final Histogram histogram2 = registry.histogram(METRIC_THING); + +- assertThat(registry.remove(METRIC_THING)).isFalse(); ++ assertThat(histogram1).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); ++ assertThat(histogram2).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); ++ assertThat(histogram1).isSameAs(histogram2); + +- verify(listener, never()).onMeterRemoved(METRIC_THING); +- } ++ verify(listener, never()).onHistogramAdded(METRIC_THING, histogram1); ++ } + +- @Test +- void registeringATimerTriggersNoNotification() { +- assertThat(registry.register(METRIC_THING, timer)).isEqualTo(timer); ++ @Test ++ void accessingACustomHistogramRegistersAndReusesIt() { ++ final MetricRegistry.MetricSupplier supplier = () -> histogram; ++ final Histogram histogram1 = registry.histogram(METRIC_THING, supplier); ++ final Histogram histogram2 = registry.histogram(METRIC_THING, supplier); + +- verify(listener, never()).onTimerAdded(METRIC_THING, timer); +- } ++ assertThat(histogram1).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); ++ assertThat(histogram2).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); ++ assertThat(histogram1).isSameAs(histogram2); + +- @Test +- void accessingATimerRegistersAndReusesIt() { +- final Timer timer1 = registry.timer(METRIC_THING); +- final Timer timer2 = registry.timer(METRIC_THING); ++ verify(listener, never()).onHistogramAdded(METRIC_THING, histogram1); ++ } + +- assertThat(timer1).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); +- assertThat(timer2).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); +- assertThat(timer1).isSameAs(timer2); ++ @Test ++ void removingAHistogramTriggersNoNotification() { ++ registry.register(METRIC_THING, histogram); + +- verify(listener, never()).onTimerAdded(METRIC_THING, timer1); +- } ++ assertThat(registry.remove(METRIC_THING)).isFalse(); + +- @Test +- void accessingACustomTimerRegistersAndReusesIt() { +- final MetricRegistry.MetricSupplier supplier = () -> timer; +- final Timer timer1 = registry.timer(METRIC_THING, supplier); +- final Timer timer2 = registry.timer(METRIC_THING, supplier); ++ verify(listener, never()).onHistogramRemoved(METRIC_THING); ++ } + +- assertThat(timer1).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); +- assertThat(timer2).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); +- assertThat(timer1).isSameAs(timer2); ++ @Test ++ void registeringAMeterTriggersNoNotification() { ++ assertThat(registry.register(METRIC_THING, meter)).isEqualTo(meter); + +- verify(listener, never()).onTimerAdded(METRIC_THING, timer1); +- } ++ verify(listener, never()).onMeterAdded(METRIC_THING, meter); ++ } + ++ @Test ++ void accessingAMeterRegistersAndReusesIt() { ++ final Meter meter1 = registry.meter(METRIC_THING); ++ final Meter meter2 = registry.meter(METRIC_THING); + +- @Test +- void removingATimerTriggersNoNotification() { +- registry.register(METRIC_THING, timer); ++ assertThat(meter1).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); ++ assertThat(meter2).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); ++ assertThat(meter1).isSameAs(meter2); + +- assertThat(registry.remove(METRIC_THING)).isFalse(); ++ verify(listener, never()).onMeterAdded(METRIC_THING, meter1); ++ } + +- verify(listener, never()).onTimerRemoved(METRIC_THING); +- } ++ @Test ++ void accessingACustomMeterRegistersAndReusesIt() { ++ final MetricRegistry.MetricSupplier supplier = () -> meter; ++ final Meter meter1 = registry.meter(METRIC_THING, supplier); ++ final Meter meter2 = registry.meter(METRIC_THING, supplier); + +- @Test +- void accessingAGaugeRegistersAndReusesIt() { +- final Gauge gauge1 = registry.gauge(METRIC_THING); +- final Gauge gauge2 = registry.gauge(METRIC_THING); ++ assertThat(meter1).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); ++ assertThat(meter2).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); ++ assertThat(meter1).isSameAs(meter2); + +- assertThat(gauge1).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); +- assertThat(gauge2).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); +- assertThat(gauge1).isSameAs(gauge2); ++ verify(listener, never()).onMeterAdded(METRIC_THING, meter1); ++ } + +- verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); +- } ++ @Test ++ void removingAMeterTriggersNoNotification() { ++ registry.register(METRIC_THING, meter); + +- @Test +- @SuppressWarnings("rawtypes") +- void accessingACustomGaugeRegistersAndReusesIt() { +- final MetricRegistry.MetricSupplier> supplier = () -> gauge; +- final Gauge gauge1 = registry.gauge(METRIC_THING, supplier); +- final Gauge gauge2 = registry.gauge(METRIC_THING, supplier); ++ assertThat(registry.remove(METRIC_THING)).isFalse(); + +- assertThat(gauge1).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); +- assertThat(gauge2).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); +- assertThat(gauge1).isSameAs(gauge2); ++ verify(listener, never()).onMeterRemoved(METRIC_THING); ++ } + +- verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); +- } ++ @Test ++ void registeringATimerTriggersNoNotification() { ++ assertThat(registry.register(METRIC_THING, timer)).isEqualTo(timer); + ++ verify(listener, never()).onTimerAdded(METRIC_THING, timer); ++ } + +- @Test +- void addingAListenerWithExistingMetricsDoesNotNotify() { +- registry.register(MetricName.build("gauge"), gauge); +- registry.register(MetricName.build("counter"), counter); +- registry.register(MetricName.build("histogram"), histogram); +- registry.register(MetricName.build("meter"), meter); +- registry.register(MetricName.build("timer"), timer); ++ @Test ++ void accessingATimerRegistersAndReusesIt() { ++ final Timer timer1 = registry.timer(METRIC_THING); ++ final Timer timer2 = registry.timer(METRIC_THING); + +- final MetricRegistryListener other = mock(MetricRegistryListener.class); +- registry.addListener(other); ++ assertThat(timer1).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); ++ assertThat(timer2).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); ++ assertThat(timer1).isSameAs(timer2); + +- verify(other, never()).onGaugeAdded(MetricName.build("gauge"), gauge); +- verify(other, never()).onCounterAdded(MetricName.build("counter"), counter); +- verify(other, never()).onHistogramAdded(MetricName.build("histogram"), histogram); +- verify(other, never()).onMeterAdded(MetricName.build("meter"), meter); +- verify(other, never()).onTimerAdded(MetricName.build("timer"), timer); +- } ++ verify(listener, never()).onTimerAdded(METRIC_THING, timer1); ++ } + +- @Test +- void aRemovedListenerDoesNotReceiveUpdates() { +- registry.register(MetricName.build("gauge"), gauge); +- registry.removeListener(listener); +- registry.register(MetricName.build("gauge2"), gauge); ++ @Test ++ void accessingACustomTimerRegistersAndReusesIt() { ++ final MetricRegistry.MetricSupplier supplier = () -> timer; ++ final Timer timer1 = registry.timer(METRIC_THING, supplier); ++ final Timer timer2 = registry.timer(METRIC_THING, supplier); + +- verify(listener, never()).onGaugeAdded(MetricName.build("gauge2"), gauge); +- } ++ assertThat(timer1).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); ++ assertThat(timer2).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); ++ assertThat(timer1).isSameAs(timer2); + +- @Test +- void hasAMapOfRegisteredGauges() { +- registry.register(MetricName.build("gauge"), gauge); ++ verify(listener, never()).onTimerAdded(METRIC_THING, timer1); ++ } + +- assertThat(registry.getGauges()).isEmpty(); +- } ++ @Test ++ void removingATimerTriggersNoNotification() { ++ registry.register(METRIC_THING, timer); + +- @Test +- void hasAMapOfRegisteredCounters() { +- registry.register(MetricName.build("counter"), counter); ++ assertThat(registry.remove(METRIC_THING)).isFalse(); + +- assertThat(registry.getCounters()).isEmpty(); +- } +- +- @Test +- void hasAMapOfRegisteredHistograms() { +- registry.register(MetricName.build("histogram"), histogram); +- +- assertThat(registry.getHistograms()).isEmpty(); +- } +- +- @Test +- void hasAMapOfRegisteredMeters() { +- registry.register(MetricName.build("meter"), meter); +- +- assertThat(registry.getMeters()).isEmpty(); +- } ++ verify(listener, never()).onTimerRemoved(METRIC_THING); ++ } + +- @Test +- void hasAMapOfRegisteredTimers() { +- registry.register(MetricName.build("timer"), timer); ++ @Test ++ void accessingAGaugeRegistersAndReusesIt() { ++ final Gauge gauge1 = registry.gauge(METRIC_THING); ++ final Gauge gauge2 = registry.gauge(METRIC_THING); + +- assertThat(registry.getTimers()).isEmpty(); +- } ++ assertThat(gauge1).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); ++ assertThat(gauge2).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); ++ assertThat(gauge1).isSameAs(gauge2); + +- @Test +- void hasASetOfRegisteredMetricNames() { +- registry.register(MetricName.build("gauge"), gauge); +- registry.register(MetricName.build("counter"), counter); +- registry.register(MetricName.build("histogram"), histogram); +- registry.register(MetricName.build("meter"), meter); +- registry.register(MetricName.build("timer"), timer); +- +- assertThat(registry.getNames()).isEmpty(); +- } +- +- @Test +- void doesNotRegisterMultipleMetrics() { +- final MetricSet metrics = () -> { +- final Map m = new HashMap<>(); +- m.put(MetricName.build("gauge"), gauge); +- m.put(MetricName.build("counter"), counter); +- return m; ++ verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); ++ } ++ ++ @SuppressWarnings("rawtypes") ++ @Test ++ void accessingACustomGaugeRegistersAndReusesIt() { ++ final MetricRegistry.MetricSupplier> supplier = () -> gauge; ++ final Gauge gauge1 = registry.gauge(METRIC_THING, supplier); ++ final Gauge gauge2 = registry.gauge(METRIC_THING, supplier); ++ ++ assertThat(gauge1).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); ++ assertThat(gauge2).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); ++ assertThat(gauge1).isSameAs(gauge2); ++ ++ verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); ++ } ++ ++ @Test ++ void addingAListenerWithExistingMetricsDoesNotNotify() { ++ registry.register(MetricName.build("gauge"), gauge); ++ registry.register(MetricName.build("counter"), counter); ++ registry.register(MetricName.build("histogram"), histogram); ++ registry.register(MetricName.build("meter"), meter); ++ registry.register(MetricName.build("timer"), timer); ++ ++ final MetricRegistryListener other = mock(); ++ registry.addListener(other); ++ ++ verify(other, never()).onGaugeAdded(MetricName.build("gauge"), gauge); ++ verify(other, never()).onCounterAdded(MetricName.build("counter"), counter); ++ verify(other, never()).onHistogramAdded(MetricName.build("histogram"), histogram); ++ verify(other, never()).onMeterAdded(MetricName.build("meter"), meter); ++ verify(other, never()).onTimerAdded(MetricName.build("timer"), timer); ++ } ++ ++ @Test ++ void aRemovedListenerDoesNotReceiveUpdates() { ++ registry.register(MetricName.build("gauge"), gauge); ++ registry.removeListener(listener); ++ registry.register(MetricName.build("gauge2"), gauge); ++ ++ verify(listener, never()).onGaugeAdded(MetricName.build("gauge2"), gauge); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredGauges() { ++ registry.register(MetricName.build("gauge"), gauge); ++ ++ assertThat(registry.getGauges()).isEmpty(); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredCounters() { ++ registry.register(MetricName.build("counter"), counter); ++ ++ assertThat(registry.getCounters()).isEmpty(); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredHistograms() { ++ registry.register(MetricName.build("histogram"), histogram); ++ ++ assertThat(registry.getHistograms()).isEmpty(); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredMeters() { ++ registry.register(MetricName.build("meter"), meter); ++ ++ assertThat(registry.getMeters()).isEmpty(); ++ } ++ ++ @Test ++ void hasAMapOfRegisteredTimers() { ++ registry.register(MetricName.build("timer"), timer); ++ ++ assertThat(registry.getTimers()).isEmpty(); ++ } ++ ++ @Test ++ void hasASetOfRegisteredMetricNames() { ++ registry.register(MetricName.build("gauge"), gauge); ++ registry.register(MetricName.build("counter"), counter); ++ registry.register(MetricName.build("histogram"), histogram); ++ registry.register(MetricName.build("meter"), meter); ++ registry.register(MetricName.build("timer"), timer); ++ ++ assertThat(registry.getNames()).isEmpty(); ++ } ++ ++ @Test ++ void doesNotRegisterMultipleMetrics() { ++ final MetricSet metrics = ++ () -> { ++ final Map m = new HashMap<>(); ++ m.put(MetricName.build("gauge"), gauge); ++ m.put(MetricName.build("counter"), counter); ++ return m; + }; + +- registry.registerAll(metrics); ++ registry.registerAll(metrics); + +- assertThat(registry.getNames()).isEmpty(); +- } ++ assertThat(registry.getNames()).isEmpty(); ++ } + +- @Test +- void doesNotRegisterMultipleMetricsWithAPrefix() { +- final MetricSet metrics = () -> { +- final Map m = new HashMap<>(); +- m.put(MetricName.build("gauge"), gauge); +- m.put(MetricName.build("counter"), counter); +- return m; ++ @Test ++ void doesNotRegisterMultipleMetricsWithAPrefix() { ++ final MetricSet metrics = ++ () -> { ++ final Map m = new HashMap<>(); ++ m.put(MetricName.build("gauge"), gauge); ++ m.put(MetricName.build("counter"), counter); ++ return m; + }; + +- registry.register(MetricName.build("my"), metrics); ++ registry.register(MetricName.build("my"), metrics); + +- assertThat(registry.getNames()).isEmpty(); +- } ++ assertThat(registry.getNames()).isEmpty(); ++ } + +- @Test +- void doesNotRegisterRecursiveMetricSets() { +- final MetricSet inner = () -> { +- final Map m = new HashMap<>(); +- m.put(MetricName.build("gauge"), gauge); +- return m; ++ @Test ++ void doesNotRegisterRecursiveMetricSets() { ++ final MetricSet inner = ++ () -> { ++ final Map m = new HashMap<>(); ++ m.put(MetricName.build("gauge"), gauge); ++ return m; + }; + +- final MetricSet outer = () -> { +- final Map m = new HashMap<>(); +- m.put(MetricName.build("inner"), inner); +- m.put(MetricName.build("counter"), counter); +- return m; ++ final MetricSet outer = ++ () -> { ++ final Map m = new HashMap<>(); ++ m.put(MetricName.build("inner"), inner); ++ m.put(MetricName.build("counter"), counter); ++ return m; + }; + +- registry.register(MetricName.build("my"), outer); +- +- assertThat(registry.getNames()).isEmpty(); +- } +- +- @Test +- void doesNotRegisterMetricsFromAnotherRegistry() { +- MetricRegistry other = new MetricRegistry(); +- other.register(MetricName.build("gauge"), gauge); +- registry.register(MetricName.build("nested"), other); +- assertThat(registry.getNames()).isEmpty(); +- } +- +- @Test +- void removesMetricsMatchingAFilter() { +- registry.timer("timer-1"); +- registry.timer("timer-2"); +- registry.histogram("histogram-1"); ++ registry.register(MetricName.build("my"), outer); + +- assertThat(registry.getNames()).isEmpty(); ++ assertThat(registry.getNames()).isEmpty(); ++ } + +- registry.removeMatching((name, metric) -> name.getKey().endsWith("1")); ++ @Test ++ void doesNotRegisterMetricsFromAnotherRegistry() { ++ MetricRegistry other = new MetricRegistry(); ++ other.register(MetricName.build("gauge"), gauge); ++ registry.register(MetricName.build("nested"), other); ++ assertThat(registry.getNames()).isEmpty(); ++ } + +- assertThat(registry.getNames()).isEmpty(); ++ @Test ++ void removesMetricsMatchingAFilter() { ++ registry.timer("timer-1"); ++ registry.timer("timer-2"); ++ registry.histogram("histogram-1"); ++ ++ assertThat(registry.getNames()).isEmpty(); + +- verify(listener, never()).onTimerRemoved(MetricName.build("timer-1")); +- verify(listener, never()).onHistogramRemoved(MetricName.build("histogram-1")); +- } ++ registry.removeMatching((name, metric) -> name.getKey().endsWith("1")); ++ ++ assertThat(registry.getNames()).isEmpty(); + +- @Test +- void addingChildMetricAfterRegister() { +- MetricRegistry parent = new NoopMetricRegistry(); +- MetricRegistry child = new MetricRegistry(); ++ verify(listener, never()).onTimerRemoved(MetricName.build("timer-1")); ++ verify(listener, never()).onHistogramRemoved(MetricName.build("histogram-1")); ++ } + +- child.counter(MetricName.build("test-1")); +- parent.register(MetricName.build("child"), child); +- child.counter(MetricName.build("test-2")); ++ @Test ++ void addingChildMetricAfterRegister() { ++ MetricRegistry parent = new NoopMetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); + +- assertThat(parent.getMetrics()).isEmpty(); +- } +- +- @Test +- void addingMultipleChildMetricsAfterRegister() { +- MetricRegistry parent = new NoopMetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- +- child.counter(MetricName.build("test-1")); +- child.counter(MetricName.build("test-2")); +- parent.register(MetricName.build("child"), child); +- child.counter(MetricName.build("test-3")); +- child.counter(MetricName.build("test-4")); +- +- assertThat(parent.getMetrics()).isEmpty(); +- } +- +- @Test +- void addingDeepChildMetricsAfterRegister() { +- MetricRegistry parent = new NoopMetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- MetricRegistry deepChild = new MetricRegistry(); +- +- deepChild.counter(MetricName.build("test-1")); +- child.register(MetricName.build("deep-child"), deepChild); +- deepChild.counter(MetricName.build("test-2")); +- +- child.counter(MetricName.build("test-3")); +- parent.register(MetricName.build("child"), child); +- child.counter(MetricName.build("test-4")); +- +- deepChild.counter("test-5"); +- +- assertThat(parent.getMetrics()).isEmpty(); +- assertThat(deepChild.getMetrics()).hasSize(3); +- assertThat(child.getMetrics()).hasSize(5); +- } +- +- @Test +- void removingChildMetricAfterRegister() { +- MetricRegistry parent = new NoopMetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- +- child.counter(MetricName.build("test-1")); +- parent.register(MetricName.build("child"), child); +- child.counter(MetricName.build("test-2")); +- +- child.remove(MetricName.build("test-1")); +- +- assertThat(parent.getMetrics()).isEmpty(); +- assertThat(child.getMetrics()).doesNotContainKey(MetricName.build("test-1")); +- } +- +- @Test +- void removingMultipleChildMetricsAfterRegister() { +- MetricRegistry parent = new NoopMetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- +- child.counter(MetricName.build("test-1")); +- child.counter(MetricName.build("test-2")); +- parent.register(MetricName.build("child"), child); +- child.counter(MetricName.build("test-3")); +- child.counter(MetricName.build("test-4")); +- +- child.remove(MetricName.build("test-1")); +- child.remove(MetricName.build("test-3")); +- +- assertThat(parent.getMetrics()).isEmpty(); +- assertThat(child.getMetrics()).doesNotContainKeys(MetricName.build("test-1"), MetricName.build("test-3")); +- } +- +- @Test +- void removingDeepChildMetricsAfterRegister() { +- MetricRegistry parent = new NoopMetricRegistry(); +- MetricRegistry child = new MetricRegistry(); +- MetricRegistry deepChild = new MetricRegistry(); +- +- deepChild.counter(MetricName.build("test-1")); +- child.register(MetricName.build("deep-child"), deepChild); +- deepChild.counter(MetricName.build("test-2")); ++ child.counter(MetricName.build("test-1")); ++ parent.register(MetricName.build("child"), child); ++ child.counter(MetricName.build("test-2")); + +- child.counter(MetricName.build("test-3")); +- parent.register(MetricName.build("child"), child); +- child.counter(MetricName.build("test-4")); +- +- deepChild.remove(MetricName.build("test-2")); +- +- Set childMetrics = child.getMetrics().keySet(); +- Set deepChildMetrics = deepChild.getMetrics().keySet(); +- +- assertThat(parent.getMetrics()).isEmpty(); +- assertThat(deepChildMetrics).hasSize(1); +- assertThat(childMetrics).hasSize(3); +- } +- +- @Test +- void registerNullMetric() { +- MetricRegistry registry = new NoopMetricRegistry(); +- assertThatNullPointerException() +- .isThrownBy(() -> registry.register(MetricName.build("any_name"), null)) +- .withMessage("metric == null"); +- } ++ assertThat(parent.getMetrics()).isEmpty(); ++ } ++ ++ @Test ++ void addingMultipleChildMetricsAfterRegister() { ++ MetricRegistry parent = new NoopMetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ ++ child.counter(MetricName.build("test-1")); ++ child.counter(MetricName.build("test-2")); ++ parent.register(MetricName.build("child"), child); ++ child.counter(MetricName.build("test-3")); ++ child.counter(MetricName.build("test-4")); ++ ++ assertThat(parent.getMetrics()).isEmpty(); ++ } ++ ++ @Test ++ void addingDeepChildMetricsAfterRegister() { ++ MetricRegistry parent = new NoopMetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ MetricRegistry deepChild = new MetricRegistry(); ++ ++ deepChild.counter(MetricName.build("test-1")); ++ child.register(MetricName.build("deep-child"), deepChild); ++ deepChild.counter(MetricName.build("test-2")); ++ ++ child.counter(MetricName.build("test-3")); ++ parent.register(MetricName.build("child"), child); ++ child.counter(MetricName.build("test-4")); ++ ++ deepChild.counter("test-5"); ++ ++ assertThat(parent.getMetrics()).isEmpty(); ++ assertThat(deepChild.getMetrics()).hasSize(3); ++ assertThat(child.getMetrics()).hasSize(5); ++ } ++ ++ @Test ++ void removingChildMetricAfterRegister() { ++ MetricRegistry parent = new NoopMetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ ++ child.counter(MetricName.build("test-1")); ++ parent.register(MetricName.build("child"), child); ++ child.counter(MetricName.build("test-2")); ++ ++ child.remove(MetricName.build("test-1")); ++ ++ assertThat(parent.getMetrics()).isEmpty(); ++ assertThat(child.getMetrics()).doesNotContainKey(MetricName.build("test-1")); ++ } ++ ++ @Test ++ void removingMultipleChildMetricsAfterRegister() { ++ MetricRegistry parent = new NoopMetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ ++ child.counter(MetricName.build("test-1")); ++ child.counter(MetricName.build("test-2")); ++ parent.register(MetricName.build("child"), child); ++ child.counter(MetricName.build("test-3")); ++ child.counter(MetricName.build("test-4")); ++ ++ child.remove(MetricName.build("test-1")); ++ child.remove(MetricName.build("test-3")); ++ ++ assertThat(parent.getMetrics()).isEmpty(); ++ assertThat(child.getMetrics()) ++ .doesNotContainKeys(MetricName.build("test-1"), MetricName.build("test-3")); ++ } ++ ++ @Test ++ void removingDeepChildMetricsAfterRegister() { ++ MetricRegistry parent = new NoopMetricRegistry(); ++ MetricRegistry child = new MetricRegistry(); ++ MetricRegistry deepChild = new MetricRegistry(); ++ ++ deepChild.counter(MetricName.build("test-1")); ++ child.register(MetricName.build("deep-child"), deepChild); ++ deepChild.counter(MetricName.build("test-2")); ++ ++ child.counter(MetricName.build("test-3")); ++ parent.register(MetricName.build("child"), child); ++ child.counter(MetricName.build("test-4")); ++ ++ deepChild.remove(MetricName.build("test-2")); ++ ++ Set childMetrics = child.getMetrics().keySet(); ++ Set deepChildMetrics = deepChild.getMetrics().keySet(); ++ ++ assertThat(parent.getMetrics()).isEmpty(); ++ assertThat(deepChildMetrics).hasSize(1); ++ assertThat(childMetrics).hasSize(3); ++ } ++ ++ @Test ++ void registerNullMetric() { ++ MetricRegistry registry = new NoopMetricRegistry(); ++ assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)) ++ .isInstanceOf(NullPointerException.class) ++ .hasMessage("metric == null"); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java +@@ -1,67 +1,66 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-class RatioGaugeTest { +- @Test +- void ratiosAreHumanReadable() { +- final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); ++import org.junit.jupiter.api.Test; ++ ++final class RatioGaugeTest { ++ @Test ++ void ratiosAreHumanReadable() { ++ final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); + +- assertThat(ratio.toString()) +- .isEqualTo("100.0:200.0"); +- } ++ assertThat(ratio).hasToString("100.0:200.0"); ++ } + +- @Test +- void calculatesTheRatioOfTheNumeratorToTheDenominator() { +- final RatioGauge regular = new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return RatioGauge.Ratio.of(2, 4); +- } ++ @Test ++ void calculatesTheRatioOfTheNumeratorToTheDenominator() { ++ final RatioGauge regular = ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return RatioGauge.Ratio.of(2, 4); ++ } + }; + +- assertThat(regular.getValue()) +- .isEqualTo(0.5); +- } ++ assertThat(regular.getValue()).isEqualTo(0.5); ++ } + +- @Test +- void handlesDivideByZeroIssues() { +- final RatioGauge divByZero = new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(100, 0); +- } ++ @Test ++ void handlesDivideByZeroIssues() { ++ final RatioGauge divByZero = ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(100, 0); ++ } + }; + +- assertThat(divByZero.getValue()) +- .isNaN(); +- } ++ assertThat(divByZero.getValue()).isNaN(); ++ } + +- @Test +- void handlesInfiniteDenominators() { +- final RatioGauge infinite = new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(10, Double.POSITIVE_INFINITY); +- } ++ @Test ++ void handlesInfiniteDenominators() { ++ final RatioGauge infinite = ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(10, Double.POSITIVE_INFINITY); ++ } + }; + +- assertThat(infinite.getValue()) +- .isNaN(); +- } ++ assertThat(infinite.getValue()).isNaN(); ++ } + +- @Test +- void handlesNaNDenominators() { +- final RatioGauge nan = new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(10, Double.NaN); +- } ++ @Test ++ void handlesNaNDenominators() { ++ final RatioGauge nan = ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(10, Double.NaN); ++ } + }; + +- assertThat(nan.getValue()) +- .isNaN(); +- } ++ assertThat(nan.getValue()).isNaN(); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java +@@ -1,8 +1,15 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++import static org.assertj.core.api.Assertions.fail; ++import static org.junit.jupiter.api.Assertions.assertEquals; ++import static org.mockito.Mockito.any; ++import static org.mockito.Mockito.eq; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.spy; ++import static org.mockito.Mockito.times; ++import static org.mockito.Mockito.verify; + + import java.util.SortedMap; + import java.util.TreeMap; +@@ -13,279 +20,350 @@ import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.TimeoutException; + import java.util.concurrent.atomic.AtomicInteger; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +-import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertFalse; +-import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.junit.jupiter.api.Assertions.assertTrue; +-import static org.junit.jupiter.api.Assertions.fail; +-import static org.mockito.Mockito.any; +-import static org.mockito.Mockito.eq; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.spy; +-import static org.mockito.Mockito.times; +-import static org.mockito.Mockito.verify; +- +-class ScheduledReporterTest { +- private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); +- +- private final ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); +- private final ScheduledExecutorService customExecutor = Executors.newSingleThreadScheduledExecutor(); +- private final ScheduledExecutorService externalExecutor = Executors.newSingleThreadScheduledExecutor(); +- +- private final MetricRegistry registry = new MetricRegistry(); +- private final ScheduledReporter reporter = spy( +- new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS) +- ); +- private final ScheduledReporter reporterWithNullExecutor = spy( +- new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, null) +- ); +- private final ScheduledReporter reporterWithCustomMockExecutor = new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, mockExecutor); +- private final ScheduledReporter reporterWithCustomExecutor = new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, customExecutor); +- private final DummyReporter reporterWithExternallyManagedExecutor = new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, externalExecutor, false); +- private final ScheduledReporter[] reporters = new ScheduledReporter[]{reporter, reporterWithCustomExecutor, reporterWithExternallyManagedExecutor}; +- +- @BeforeEach +- void setUp() throws Exception { +- registry.register(MetricRegistry.name("gauge"), gauge); +- registry.register(MetricRegistry.name("counter"), counter); +- registry.register(MetricRegistry.name("histogram"), histogram); +- registry.register(MetricRegistry.name("meter"), meter); +- registry.register(MetricRegistry.name("timer"), timer); +- } +- +- @AfterEach +- void tearDown() throws Exception { +- customExecutor.shutdown(); +- externalExecutor.shutdown(); +- reporter.stop(); +- reporterWithNullExecutor.stop(); +- } +- +- @Test +- void createWithNullMetricRegistry() { +- ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); +- DummyReporter r = null; +- try { +- r = new DummyReporter(null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); +- fail("NullPointerException must be thrown !!!"); +- } catch (NullPointerException e) { +- assertEquals("registry == null", e.getMessage()); +- } finally { +- if (r != null) { +- r.close(); +- } +- } ++final class ScheduledReporterTest { ++ private final Gauge gauge = () -> ""; ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); ++ ++ private final ScheduledExecutorService mockExecutor = mock(); ++ private final ScheduledExecutorService customExecutor = ++ Executors.newSingleThreadScheduledExecutor(); ++ private final ScheduledExecutorService externalExecutor = ++ Executors.newSingleThreadScheduledExecutor(); ++ ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final ScheduledReporter reporter = ++ spy( ++ new DummyReporter( ++ registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS)); ++ private final ScheduledReporter reporterWithNullExecutor = ++ spy( ++ new DummyReporter( ++ registry, ++ "example", ++ MetricFilter.ALL, ++ TimeUnit.SECONDS, ++ TimeUnit.MILLISECONDS, ++ null)); ++ private final ScheduledReporter reporterWithCustomMockExecutor = ++ new DummyReporter( ++ registry, ++ "example", ++ MetricFilter.ALL, ++ TimeUnit.SECONDS, ++ TimeUnit.MILLISECONDS, ++ mockExecutor); ++ private final ScheduledReporter reporterWithCustomExecutor = ++ new DummyReporter( ++ registry, ++ "example", ++ MetricFilter.ALL, ++ TimeUnit.SECONDS, ++ TimeUnit.MILLISECONDS, ++ customExecutor); ++ private final DummyReporter reporterWithExternallyManagedExecutor = ++ new DummyReporter( ++ registry, ++ "example", ++ MetricFilter.ALL, ++ TimeUnit.SECONDS, ++ TimeUnit.MILLISECONDS, ++ externalExecutor, ++ false); ++ private final ScheduledReporter[] reporters = ++ new ScheduledReporter[] { ++ reporter, reporterWithCustomExecutor, reporterWithExternallyManagedExecutor ++ }; ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ registry.register(MetricRegistry.name("gauge"), gauge); ++ registry.register(MetricRegistry.name("counter"), counter); ++ registry.register(MetricRegistry.name("histogram"), histogram); ++ registry.register(MetricRegistry.name("meter"), meter); ++ registry.register(MetricRegistry.name("timer"), timer); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ customExecutor.shutdown(); ++ externalExecutor.shutdown(); ++ reporter.stop(); ++ reporterWithNullExecutor.stop(); ++ } ++ ++ @Test ++ void createWithNullMetricRegistry() { ++ ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); ++ DummyReporter r = null; ++ try { ++ r = ++ new DummyReporter( ++ null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); ++ fail("NullPointerException must be thrown !!!"); ++ } catch (NullPointerException e) { ++ assertEquals("registry == null", e.getMessage()); ++ } finally { ++ if (r != null) { ++ r.close(); ++ } + } +- +- @Test +- void pollsPeriodically() throws Exception { +- CountDownLatch latch = new CountDownLatch(2); +- reporter.start(100, 100, TimeUnit.MILLISECONDS, () -> { +- if (latch.getCount() > 0) { +- reporter.report(); +- latch.countDown(); +- } ++ } ++ ++ @Test ++ void pollsPeriodically() throws Exception { ++ CountDownLatch latch = new CountDownLatch(2); ++ reporter.start( ++ 100, ++ 100, ++ TimeUnit.MILLISECONDS, ++ () -> { ++ if (latch.getCount() > 0) { ++ reporter.report(); ++ latch.countDown(); ++ } + }); +- latch.await(5, TimeUnit.SECONDS); +- +- verify(reporter, times(2)).report( +- map(MetricName.build("gauge"), gauge), +- map(MetricName.build("counter"), counter), +- map(MetricName.build("histogram"), histogram), +- map(MetricName.build("meter"), meter), +- map(MetricName.build("timer"), timer) +- ); +- } +- +- @Test +- void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { +- reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); +- +- verify(mockExecutor, times(1)).scheduleWithFixedDelay( +- any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS) +- ); +- } +- +- @Test +- void shouldStartWithSpecifiedInitialDelay() throws Exception { +- reporterWithCustomMockExecutor.start(350, 100, TimeUnit.MILLISECONDS); +- +- verify(mockExecutor).scheduleWithFixedDelay( +- any(Runnable.class), eq(350L), eq(100L), eq(TimeUnit.MILLISECONDS) +- ); +- } +- +- @Test +- void shouldAutoCreateExecutorWhenItNull() throws Exception { +- CountDownLatch latch = new CountDownLatch(2); +- reporterWithNullExecutor.start(100, 100, TimeUnit.MILLISECONDS, () -> { +- if (latch.getCount() > 0) { +- reporterWithNullExecutor.report(); +- latch.countDown(); +- } ++ latch.await(5, TimeUnit.SECONDS); ++ ++ verify(reporter, times(2)) ++ .report( ++ map(MetricName.build("gauge"), gauge), ++ map(MetricName.build("counter"), counter), ++ map(MetricName.build("histogram"), histogram), ++ map(MetricName.build("meter"), meter), ++ map(MetricName.build("timer"), timer)); ++ } ++ ++ @Test ++ void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { ++ reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); ++ ++ verify(mockExecutor) ++ .scheduleWithFixedDelay(any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS)); ++ } ++ ++ @Test ++ void shouldStartWithSpecifiedInitialDelay() throws Exception { ++ reporterWithCustomMockExecutor.start(350, 100, TimeUnit.MILLISECONDS); ++ ++ verify(mockExecutor) ++ .scheduleWithFixedDelay(any(Runnable.class), eq(350L), eq(100L), eq(TimeUnit.MILLISECONDS)); ++ } ++ ++ @Test ++ void shouldAutoCreateExecutorWhenItNull() throws Exception { ++ CountDownLatch latch = new CountDownLatch(2); ++ reporterWithNullExecutor.start( ++ 100, ++ 100, ++ TimeUnit.MILLISECONDS, ++ () -> { ++ if (latch.getCount() > 0) { ++ reporterWithNullExecutor.report(); ++ latch.countDown(); ++ } + }); +- latch.await(5, TimeUnit.SECONDS); +- verify(reporterWithNullExecutor, times(2)).report( +- map(MetricName.build("gauge"), gauge), +- map(MetricName.build("counter"), counter), +- map(MetricName.build("histogram"), histogram), +- map(MetricName.build("meter"), meter), +- map(MetricName.build("timer"), timer) +- ); ++ latch.await(5, TimeUnit.SECONDS); ++ verify(reporterWithNullExecutor, times(2)) ++ .report( ++ map(MetricName.build("gauge"), gauge), ++ map(MetricName.build("counter"), counter), ++ map(MetricName.build("histogram"), histogram), ++ map(MetricName.build("meter"), meter), ++ map(MetricName.build("timer"), timer)); ++ } ++ ++ @Test ++ void shouldDisallowToStartReportingMultiple() throws Exception { ++ assertThatThrownBy( ++ () -> { ++ reporter.start(200, TimeUnit.MILLISECONDS); ++ reporter.start(200, TimeUnit.MILLISECONDS); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception { ++ assertThatThrownBy( ++ () -> { ++ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); ++ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void shouldDisallowToStartReportingMultipleTimesOnExternallyManagedExecutor() throws Exception { ++ assertThatThrownBy( ++ () -> { ++ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); ++ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void shouldNotFailOnStopIfReporterWasNotStared() { ++ for (ScheduledReporter reporter : reporters) { ++ reporter.stop(); + } +- +- @Test +- void shouldDisallowToStartReportingMultiple() throws Exception { +- assertThrows(IllegalArgumentException.class, () -> { +- reporter.start(200, TimeUnit.MILLISECONDS); +- reporter.start(200, TimeUnit.MILLISECONDS); +- }); ++ } ++ ++ @Test ++ void shouldNotFailWhenStoppingMultipleTimes() { ++ for (ScheduledReporter reporter : reporters) { ++ reporter.start(200, TimeUnit.MILLISECONDS); ++ reporter.stop(); ++ reporter.stop(); ++ reporter.stop(); + } +- +- @Test +- void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception { +- assertThrows(IllegalArgumentException.class, () -> { +- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); +- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); ++ } ++ ++ @Test ++ void shouldShutdownExecutorOnStopByDefault() { ++ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); ++ reporterWithCustomExecutor.stop(); ++ assertThat(customExecutor.isTerminated()).isTrue(); ++ } ++ ++ @Test ++ void shouldNotShutdownExternallyManagedExecutorOnStop() { ++ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); ++ reporterWithExternallyManagedExecutor.stop(); ++ assertThat(mockExecutor.isTerminated()).isFalse(); ++ assertThat(mockExecutor.isShutdown()).isFalse(); ++ } ++ ++ @Test ++ void shouldCancelScheduledFutureWhenStoppingWithExternallyManagedExecutor() ++ throws InterruptedException, ExecutionException, TimeoutException { ++ // configure very frequency rate of execution ++ reporterWithExternallyManagedExecutor.start(1, TimeUnit.MILLISECONDS); ++ reporterWithExternallyManagedExecutor.stop(); ++ Thread.sleep(100); ++ ++ // executionCount should not increase when scheduled future is canceled properly ++ int executionCount = reporterWithExternallyManagedExecutor.executionCount.get(); ++ Thread.sleep(500); ++ assertEquals(executionCount, reporterWithExternallyManagedExecutor.executionCount.get()); ++ } ++ ++ @Test ++ void shouldConvertDurationToMillisecondsPrecisely() { ++ assertEquals(2.0E-5, reporter.convertDuration(20), 0.0); ++ } ++ ++ @Test ++ void shouldReportMetricsOnShutdown() throws Exception { ++ CountDownLatch latch = new CountDownLatch(1); ++ reporterWithNullExecutor.start( ++ 0, ++ 10, ++ TimeUnit.SECONDS, ++ () -> { ++ if (latch.getCount() > 0) { ++ reporterWithNullExecutor.report(); ++ latch.countDown(); ++ } + }); +- } +- +- @Test +- void shouldDisallowToStartReportingMultipleTimesOnExternallyManagedExecutor() throws Exception { +- assertThrows(IllegalArgumentException.class, () -> { +- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); +- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); ++ latch.await(5, TimeUnit.SECONDS); ++ reporterWithNullExecutor.stop(); ++ ++ verify(reporterWithNullExecutor, times(2)) ++ .report( ++ map(MetricName.build("gauge"), gauge), ++ map(MetricName.build("counter"), counter), ++ map(MetricName.build("histogram"), histogram), ++ map(MetricName.build("meter"), meter), ++ map(MetricName.build("timer"), timer)); ++ } ++ ++ @Test ++ void shouldRescheduleAfterReportFinish() throws Exception { ++ // the first report is triggered at T + 0.1 seconds and takes 0.8 seconds ++ // after the first report finishes at T + 0.9 seconds the next report is scheduled to run at T + ++ // 1.4 seconds ++ reporter.start( ++ 100, ++ 500, ++ TimeUnit.MILLISECONDS, ++ () -> { ++ reporter.report(); ++ try { ++ Thread.sleep(800); ++ } catch (InterruptedException e) { ++ Thread.currentThread().interrupt(); ++ } + }); +- } +- +- @Test +- void shouldNotFailOnStopIfReporterWasNotStared() { +- for (ScheduledReporter reporter : reporters) { +- reporter.stop(); +- } +- } +- +- @Test +- void shouldNotFailWhenStoppingMultipleTimes() { +- for (ScheduledReporter reporter : reporters) { +- reporter.start(200, TimeUnit.MILLISECONDS); +- reporter.stop(); +- reporter.stop(); +- reporter.stop(); +- } +- } +- +- @Test +- void shouldShutdownExecutorOnStopByDefault() { +- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); +- reporterWithCustomExecutor.stop(); +- assertTrue(customExecutor.isTerminated()); +- } +- +- @Test +- void shouldNotShutdownExternallyManagedExecutorOnStop() { +- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); +- reporterWithExternallyManagedExecutor.stop(); +- assertFalse(mockExecutor.isTerminated()); +- assertFalse(mockExecutor.isShutdown()); +- } +- +- @Test +- void shouldCancelScheduledFutureWhenStoppingWithExternallyManagedExecutor() throws InterruptedException, ExecutionException, TimeoutException { +- // configure very frequency rate of execution +- reporterWithExternallyManagedExecutor.start(1, TimeUnit.MILLISECONDS); +- reporterWithExternallyManagedExecutor.stop(); +- Thread.sleep(100); +- +- // executionCount should not increase when scheduled future is canceled properly +- int executionCount = reporterWithExternallyManagedExecutor.executionCount.get(); +- Thread.sleep(500); +- assertEquals(executionCount, reporterWithExternallyManagedExecutor.executionCount.get()); +- } +- +- @Test +- void shouldConvertDurationToMillisecondsPrecisely() { +- assertEquals(2.0E-5, reporter.convertDuration(20), 0.0); +- } + +- @Test +- void shouldReportMetricsOnShutdown() throws Exception { +- CountDownLatch latch = new CountDownLatch(1); +- reporterWithNullExecutor.start(0, 10, TimeUnit.SECONDS, () -> { +- if (latch.getCount() > 0) { +- reporterWithNullExecutor.report(); +- latch.countDown(); +- } +- }); +- latch.await(5, TimeUnit.SECONDS); +- reporterWithNullExecutor.stop(); +- +- verify(reporterWithNullExecutor, times(2)).report( +- map(MetricName.build("gauge"), gauge), +- map(MetricName.build("counter"), counter), +- map(MetricName.build("histogram"), histogram), +- map(MetricName.build("meter"), meter), +- map(MetricName.build("timer"), timer) +- ); ++ Thread.sleep(1_000); ++ ++ verify(reporter) ++ .report( ++ map(MetricName.build("gauge"), gauge), ++ map(MetricName.build("counter"), counter), ++ map(MetricName.build("histogram"), histogram), ++ map(MetricName.build("meter"), meter), ++ map(MetricName.build("timer"), timer)); ++ } ++ ++ private SortedMap map(MetricName name, T value) { ++ final SortedMap map = new TreeMap<>(); ++ map.put(name, value); ++ return map; ++ } ++ ++ private static class DummyReporter extends ScheduledReporter { ++ ++ private AtomicInteger executionCount = new AtomicInteger(); ++ ++ DummyReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit) { ++ super(registry, name, filter, rateUnit, durationUnit); + } + +- @Test +- void shouldRescheduleAfterReportFinish() throws Exception { +- // the first report is triggered at T + 0.1 seconds and takes 0.8 seconds +- // after the first report finishes at T + 0.9 seconds the next report is scheduled to run at T + 1.4 seconds +- reporter.start(100, 500, TimeUnit.MILLISECONDS, () -> { +- reporter.report(); +- try { +- Thread.sleep(800); +- } catch (InterruptedException e) { +- Thread.currentThread().interrupt(); +- } +- }); +- +- Thread.sleep(1_000); +- +- verify(reporter, times(1)).report( +- map(MetricName.build("gauge"), gauge), +- map(MetricName.build("counter"), counter), +- map(MetricName.build("histogram"), histogram), +- map(MetricName.build("meter"), meter), +- map(MetricName.build("timer"), timer) +- ); ++ DummyReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor) { ++ super(registry, name, filter, rateUnit, durationUnit, executor); + } + +- private SortedMap map(MetricName name, T value) { +- final SortedMap map = new TreeMap<>(); +- map.put(name, value); +- return map; ++ DummyReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop) { ++ super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop); + } + +- private static class DummyReporter extends ScheduledReporter { +- +- private AtomicInteger executionCount = new AtomicInteger(); +- +- DummyReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit) { +- super(registry, name, filter, rateUnit, durationUnit); +- } +- +- DummyReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor) { +- super(registry, name, filter, rateUnit, durationUnit, executor); +- } +- +- DummyReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop) { +- super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop); +- } +- +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap> gauges, SortedMap counters, SortedMap histograms, SortedMap meters, SortedMap timers) { +- executionCount.incrementAndGet(); +- // nothing doing! +- } ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap> gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ executionCount.incrementAndGet(); ++ // nothing doing! + } +- ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java +@@ -1,95 +1,95 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.junit.jupiter.api.Assertions.assertTrue; + + import java.util.concurrent.atomic.AtomicReference; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +-class SharedMetricRegistriesTest { +- +- @BeforeEach +- void setUp() { +- SharedMetricRegistries.setDefaultRegistryName(new AtomicReference<>()); +- SharedMetricRegistries.clear(); +- } +- +- @Test +- void memorizesRegistriesByName() { +- final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); +- final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); +- +- assertThat(one) +- .isSameAs(two); +- } +- +- @Test +- void hasASetOfNames() { +- SharedMetricRegistries.getOrCreate("one"); +- +- assertThat(SharedMetricRegistries.names()) +- .containsOnly("one"); +- } +- +- @Test +- void removesRegistries() { +- final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); +- SharedMetricRegistries.remove("one"); +- +- assertThat(SharedMetricRegistries.names()) +- .isEmpty(); +- +- final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); +- assertThat(two) +- .isNotSameAs(one); +- } +- +- @Test +- void clearsRegistries() { +- SharedMetricRegistries.getOrCreate("one"); +- SharedMetricRegistries.getOrCreate("two"); +- +- SharedMetricRegistries.clear(); +- +- assertThat(SharedMetricRegistries.names()) +- .isEmpty(); +- } +- +- @Test +- void errorsWhenDefaultUnset() { +- Throwable exception = assertThrows(IllegalStateException.class, () -> { +- SharedMetricRegistries.getDefault(); +- }); +- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); +- } +- +- @Test +- void createsDefaultRegistries() { +- final String defaultName = "default"; +- final MetricRegistry registry = SharedMetricRegistries.setDefault(defaultName); +- assertThat(registry).isNotNull(); +- assertThat(SharedMetricRegistries.getDefault()).isEqualTo(registry); +- assertThat(SharedMetricRegistries.getOrCreate(defaultName)).isEqualTo(registry); +- } +- +- @Test +- void errorsWhenDefaultAlreadySet() { +- Throwable exception = assertThrows(IllegalStateException.class, () -> { +- SharedMetricRegistries.setDefault("foobah"); +- SharedMetricRegistries.setDefault("borg"); +- }); +- assertTrue(exception.getMessage().contains("Default metric registry name is already set.")); +- } +- +- @Test +- void setsDefaultExistingRegistries() { +- final String defaultName = "default"; +- final MetricRegistry registry = new MetricRegistry(); +- assertThat(SharedMetricRegistries.setDefault(defaultName, registry)).isEqualTo(registry); +- assertThat(SharedMetricRegistries.getDefault()).isEqualTo(registry); +- assertThat(SharedMetricRegistries.getOrCreate(defaultName)).isEqualTo(registry); +- } ++final class SharedMetricRegistriesTest { ++ ++ @BeforeEach ++ void setUp() { ++ SharedMetricRegistries.setDefaultRegistryName(new AtomicReference<>()); ++ SharedMetricRegistries.clear(); ++ } ++ ++ @Test ++ void memorizesRegistriesByName() { ++ final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); ++ final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); ++ ++ assertThat(one).isSameAs(two); ++ } ++ ++ @Test ++ void hasASetOfNames() { ++ SharedMetricRegistries.getOrCreate("one"); ++ ++ assertThat(SharedMetricRegistries.names()).containsExactly("one"); ++ } ++ ++ @Test ++ void removesRegistries() { ++ final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); ++ SharedMetricRegistries.remove("one"); ++ ++ assertThat(SharedMetricRegistries.names()).isEmpty(); ++ ++ final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); ++ assertThat(two).isNotSameAs(one); ++ } ++ ++ @Test ++ void clearsRegistries() { ++ SharedMetricRegistries.getOrCreate("one"); ++ SharedMetricRegistries.getOrCreate("two"); ++ ++ SharedMetricRegistries.clear(); ++ ++ assertThat(SharedMetricRegistries.names()).isEmpty(); ++ } ++ ++ @Test ++ void errorsWhenDefaultUnset() { ++ Throwable exception = ++ assertThrows( ++ IllegalStateException.class, ++ () -> { ++ SharedMetricRegistries.getDefault(); ++ }); ++ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); ++ } ++ ++ @Test ++ void createsDefaultRegistries() { ++ final String defaultName = "default"; ++ final MetricRegistry registry = SharedMetricRegistries.setDefault(defaultName); ++ assertThat(registry).isNotNull(); ++ assertThat(SharedMetricRegistries.getDefault()).isEqualTo(registry); ++ assertThat(SharedMetricRegistries.getOrCreate(defaultName)).isEqualTo(registry); ++ } ++ ++ @Test ++ void errorsWhenDefaultAlreadySet() { ++ Throwable exception = ++ assertThrows( ++ IllegalStateException.class, ++ () -> { ++ SharedMetricRegistries.setDefault("foobah"); ++ SharedMetricRegistries.setDefault("borg"); ++ }); ++ assertThat(exception.getMessage().contains("Default metric registry name is already set.")) ++ .isTrue(); ++ } ++ ++ @Test ++ void setsDefaultExistingRegistries() { ++ final String defaultName = "default"; ++ final MetricRegistry registry = new MetricRegistry(); ++ assertThat(SharedMetricRegistries.setDefault(defaultName, registry)).isEqualTo(registry); ++ assertThat(SharedMetricRegistries.getDefault()).isEqualTo(registry); ++ assertThat(SharedMetricRegistries.getOrCreate(defaultName)).isEqualTo(registry); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java +@@ -1,29 +1,26 @@ + package io.dropwizard.metrics5; + +-import io.dropwizard.metrics5.DefaultSettableGauge; +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-class SimpleSettableGaugeTest { ++import org.junit.jupiter.api.Test; ++ ++final class SimpleSettableGaugeTest { + +- @Test +- void defaultValue() { +- DefaultSettableGauge settable = new DefaultSettableGauge<>(1); ++ @Test ++ void defaultValue() { ++ DefaultSettableGauge settable = new DefaultSettableGauge<>(1); + +- assertThat(settable.getValue()).isEqualTo(1); +- } ++ assertThat(settable.getValue()).isEqualTo(1); ++ } + +- @Test +- void setValueAndThenGetValue() { +- DefaultSettableGauge settable = new DefaultSettableGauge<>("default"); ++ @Test ++ void setValueAndThenGetValue() { ++ DefaultSettableGauge settable = new DefaultSettableGauge<>("default"); + +- settable.setValue("first"); +- assertThat(settable.getValue()) +- .isEqualTo("first"); ++ settable.setValue("first"); ++ assertThat(settable.getValue()).isEqualTo("first"); + +- settable.setValue("second"); +- assertThat(settable.getValue()) +- .isEqualTo("second"); +- } ++ settable.setValue("second"); ++ assertThat(settable.getValue()).isEqualTo("second"); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java +@@ -1,19 +1,8 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +-import org.slf4j.Logger; +-import org.slf4j.Marker; +- +-import java.util.EnumSet; +-import java.util.Set; +-import java.util.SortedMap; +-import java.util.TreeMap; +-import java.util.concurrent.TimeUnit; +- + import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; +@@ -21,342 +10,330 @@ import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +-class Slf4jReporterTest { +- +- private final Logger logger = mock(Logger.class); +- private final Marker marker = mock(Marker.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); +- +- /** +- * The set of disabled metric attributes to pass to the Slf4jReporter builder +- * in the default factory methods of {@link #infoReporter} +- * and {@link #errorReporter}. +- * +- * This value can be overridden by tests before calling the {@link #infoReporter} +- * and {@link #errorReporter} factory methods. +- */ +- private Set disabledMetricAttributes = null; +- +- private Slf4jReporter infoReporter() { +- return Slf4jReporter.forRegistry(registry) +- .outputTo(logger) +- .markWith(marker) +- .prefixedWith("prefix") +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(disabledMetricAttributes) +- .build(); +- } +- +- private Slf4jReporter errorReporter() { +- return Slf4jReporter.forRegistry(registry) +- .outputTo(logger) +- .markWith(marker) +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .withLoggingLevel(Slf4jReporter.LoggingLevel.ERROR) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(disabledMetricAttributes) +- .build(); +- } +- +- @Test +- void reportsGaugeValuesAtErrorDefault() { +- reportsGaugeValuesAtError(); +- } +- +- @Test +- void reportsGaugeValuesAtErrorAllDisabled() { +- disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect +- reportsGaugeValuesAtError(); +- } +- +- private void reportsGaugeValuesAtError() { +- when(logger.isErrorEnabled(marker)).thenReturn(true); +- errorReporter().report(map("gauge", () -> "value"), +- map(), +- map(), +- map(), +- map()); +- +- verify(logger).error(marker, "type=GAUGE, name=gauge, value=value"); +- } +- +- +- private Timer timer() { +- final Timer timer = mock(Timer.class); +- when(timer.getCount()).thenReturn(1L); +- +- when(timer.getMeanRate()).thenReturn(2.0); +- when(timer.getOneMinuteRate()).thenReturn(3.0); +- when(timer.getFiveMinuteRate()).thenReturn(4.0); +- when(timer.getFifteenMinuteRate()).thenReturn(5.0); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); +- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); +- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); +- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); +- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); +- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); +- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); +- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); +- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS +- .toNanos(1000)); +- +- when(timer.getSnapshot()).thenReturn(snapshot); +- return timer; +- } +- +- private Histogram histogram() { +- final Histogram histogram = mock(Histogram.class); +- when(histogram.getCount()).thenReturn(1L); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(2L); +- when(snapshot.getMean()).thenReturn(3.0); +- when(snapshot.getMin()).thenReturn(4L); +- when(snapshot.getStdDev()).thenReturn(5.0); +- when(snapshot.getMedian()).thenReturn(6.0); +- when(snapshot.get75thPercentile()).thenReturn(7.0); +- when(snapshot.get95thPercentile()).thenReturn(8.0); +- when(snapshot.get98thPercentile()).thenReturn(9.0); +- when(snapshot.get99thPercentile()).thenReturn(10.0); +- when(snapshot.get999thPercentile()).thenReturn(11.0); +- +- when(histogram.getSnapshot()).thenReturn(snapshot); +- return histogram; +- } +- +- private Meter meter() { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getMeanRate()).thenReturn(2.0); +- when(meter.getOneMinuteRate()).thenReturn(3.0); +- when(meter.getFiveMinuteRate()).thenReturn(4.0); +- when(meter.getFifteenMinuteRate()).thenReturn(5.0); +- return meter; +- } +- +- private Counter counter() { +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(100L); +- return counter; +- } +- +- @Test +- void reportsCounterValuesAtErrorDefault() { +- reportsCounterValuesAtError(); +- } +- +- @Test +- void reportsCounterValuesAtErrorAllDisabled() { +- disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect +- reportsCounterValuesAtError(); +- } +- +- private void reportsCounterValuesAtError() { +- final Counter counter = counter(); +- when(logger.isErrorEnabled(marker)).thenReturn(true); +- +- errorReporter().report(map(), +- map("test.counter", counter), +- map(), +- map(), +- map()); +- +- verify(logger).error(marker, "type=COUNTER, name=test.counter, count=100"); +- } +- +- @Test +- void reportsHistogramValuesAtErrorDefault() { +- reportsHistogramValuesAtError("type=HISTOGRAM, name=test.histogram, count=1, min=4, " + +- "max=2, mean=3.0, stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); +- } +- +- @Test +- void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); +- reportsHistogramValuesAtError("type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " + +- "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); +- } +- +- private void reportsHistogramValuesAtError(final String expectedLog) { +- final Histogram histogram = histogram(); +- when(logger.isErrorEnabled(marker)).thenReturn(true); +- +- errorReporter().report(map(), +- map(), +- map("test.histogram", histogram), +- map(), +- map()); +- +- verify(logger).error(marker, expectedLog); +- } +- +- @Test +- void reportsMeterValuesAtErrorDefault() { +- reportsMeterValuesAtError("type=METER, name=test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " + +- "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); +- } +- +- @Test +- void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); +- reportsMeterValuesAtError("type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " + +- "mean_rate=2.0, rate_unit=events/second"); +- } +- +- private void reportsMeterValuesAtError(final String expectedLog) { +- final Meter meter = meter(); +- when(logger.isErrorEnabled(marker)).thenReturn(true); +- +- errorReporter().report(map(), +- map(), +- map(), +- map("test.meter", meter), +- map()); +- +- verify(logger).error(marker, expectedLog); +- } +- +- +- @Test +- void reportsTimerValuesAtErrorDefault() { +- reportsTimerValuesAtError("type=TIMER, name=test.another.timer, count=1, min=300.0, max=100.0, " + +- "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0, " + +- "m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, " + +- "duration_unit=milliseconds"); +- } +- +- @Test +- void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); +- reportsTimerValuesAtError("type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " + +- "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " + +- "rate_unit=events/second, duration_unit=milliseconds"); +- } +- +- private void reportsTimerValuesAtError(final String expectedLog) { +- final Timer timer = timer(); +- +- when(logger.isErrorEnabled(marker)).thenReturn(true); +- +- errorReporter().report(map(), +- map(), +- map(), +- map(), +- map("test.another.timer", timer)); +- +- verify(logger).error(marker, expectedLog); +- } +- +- @Test +- void reportsGaugeValuesDefault() { +- when(logger.isInfoEnabled(marker)).thenReturn(true); +- infoReporter().report(map("gauge", () -> "value"), +- map(), +- map(), +- map(), +- map()); +- +- verify(logger).info(marker, "type=GAUGE, name=prefix.gauge, value=value"); +- } +- +- +- @Test +- void reportsCounterValuesDefault() { +- final Counter counter = counter(); +- when(logger.isInfoEnabled(marker)).thenReturn(true); +- +- infoReporter().report(map(), +- map("test.counter", counter), +- map(), +- map(), +- map()); +- +- verify(logger).info(marker, "type=COUNTER, name=prefix.test.counter, count=100"); +- } +- +- @Test +- void reportsHistogramValuesDefault() { +- final Histogram histogram = histogram(); +- when(logger.isInfoEnabled(marker)).thenReturn(true); +- +- infoReporter().report(map(), +- map(), +- map("test.histogram", histogram), +- map(), +- map()); +- +- verify(logger).info(marker, "type=HISTOGRAM, name=prefix.test.histogram, count=1, min=4, max=2, mean=3.0, " + +- "stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); +- } +- +- @Test +- void reportsMeterValuesDefault() { +- final Meter meter = meter(); +- when(logger.isInfoEnabled(marker)).thenReturn(true); +- +- infoReporter().report(map(), +- map(), +- map(), +- map("test.meter", meter), +- map()); +- +- verify(logger).info(marker, "type=METER, name=prefix.test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " + +- "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); +- } +- +- @Test +- void reportsTimerValuesDefault() { +- final Timer timer = timer(); +- when(logger.isInfoEnabled(marker)).thenReturn(true); +- +- infoReporter().report(map(), +- map(), +- map(), +- map(), +- map("test.another.timer", timer)); +- +- verify(logger).info(marker, "type=TIMER, name=prefix.test.another.timer, count=1, min=300.0, max=100.0, " + +- "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0," + +- " m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, duration_unit=milliseconds"); +- } +- +- +- @Test +- void reportsAllMetricsDefault() { +- when(logger.isInfoEnabled(marker)).thenReturn(true); +- +- infoReporter().report(map("test.gauge", () -> "value"), +- map("test.counter", counter()), +- map("test.histogram", histogram()), +- map("test.meter", meter()), +- map("test.timer", timer())); +- +- verify(logger).info(marker, "type=GAUGE, name=prefix.test.gauge, value=value"); +- verify(logger).info(marker, "type=COUNTER, name=prefix.test.counter, count=100"); +- verify(logger).info(marker, "type=HISTOGRAM, name=prefix.test.histogram, count=1, min=4, max=2, mean=3.0, " + +- "stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); +- verify(logger).info(marker, "type=METER, name=prefix.test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " + +- "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); +- verify(logger).info(marker, "type=TIMER, name=prefix.test.timer, count=1, min=300.0, max=100.0, " + +- "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0," + +- " m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, duration_unit=milliseconds"); +- } +- +- private SortedMap map() { +- return new TreeMap<>(); +- } +- +- private SortedMap map(String name, T metric) { +- final SortedMap map = new TreeMap<>(); +- map.put(MetricName.build(name), metric); +- return map; +- } ++import java.util.EnumSet; ++import java.util.Set; ++import java.util.SortedMap; ++import java.util.TreeMap; ++import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.Test; ++import org.slf4j.Logger; ++import org.slf4j.Marker; + ++final class Slf4jReporterTest { ++ ++ private final Logger logger = mock(); ++ private final Marker marker = mock(); ++ private final MetricRegistry registry = mock(); ++ ++ /** ++ * The set of disabled metric attributes to pass to the Slf4jReporter builder in the default ++ * factory methods of {@link #infoReporter} and {@link #errorReporter}. ++ * ++ *

This value can be overridden by tests before calling the {@link #infoReporter} and {@link ++ * #errorReporter} factory methods. ++ */ ++ private Set disabledMetricAttributes = null; ++ ++ private Slf4jReporter infoReporter() { ++ return Slf4jReporter.forRegistry(registry) ++ .outputTo(logger) ++ .markWith(marker) ++ .prefixedWith("prefix") ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(disabledMetricAttributes) ++ .build(); ++ } ++ ++ private Slf4jReporter errorReporter() { ++ return Slf4jReporter.forRegistry(registry) ++ .outputTo(logger) ++ .markWith(marker) ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .withLoggingLevel(Slf4jReporter.LoggingLevel.ERROR) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(disabledMetricAttributes) ++ .build(); ++ } ++ ++ @Test ++ void reportsGaugeValuesAtErrorDefault() { ++ reportsGaugeValuesAtError(); ++ } ++ ++ @Test ++ void reportsGaugeValuesAtErrorAllDisabled() { ++ disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect ++ reportsGaugeValuesAtError(); ++ } ++ ++ private void reportsGaugeValuesAtError() { ++ when(logger.isErrorEnabled(marker)).thenReturn(true); ++ errorReporter().report(map("gauge", () -> "value"), map(), map(), map(), map()); ++ ++ verify(logger).error(marker, "type=GAUGE, name=gauge, value=value"); ++ } ++ ++ private Timer timer() { ++ final Timer timer = mock(); ++ when(timer.getCount()).thenReturn(1L); ++ ++ when(timer.getMeanRate()).thenReturn(2.0); ++ when(timer.getOneMinuteRate()).thenReturn(3.0); ++ when(timer.getFiveMinuteRate()).thenReturn(4.0); ++ when(timer.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); ++ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); ++ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ++ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); ++ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); ++ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); ++ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); ++ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); ++ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); ++ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); ++ ++ when(timer.getSnapshot()).thenReturn(snapshot); ++ return timer; ++ } ++ ++ private Histogram histogram() { ++ final Histogram histogram = mock(); ++ when(histogram.getCount()).thenReturn(1L); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(2L); ++ when(snapshot.getMean()).thenReturn(3.0); ++ when(snapshot.getMin()).thenReturn(4L); ++ when(snapshot.getStdDev()).thenReturn(5.0); ++ when(snapshot.getMedian()).thenReturn(6.0); ++ when(snapshot.get75thPercentile()).thenReturn(7.0); ++ when(snapshot.get95thPercentile()).thenReturn(8.0); ++ when(snapshot.get98thPercentile()).thenReturn(9.0); ++ when(snapshot.get99thPercentile()).thenReturn(10.0); ++ when(snapshot.get999thPercentile()).thenReturn(11.0); ++ ++ when(histogram.getSnapshot()).thenReturn(snapshot); ++ return histogram; ++ } ++ ++ private Meter meter() { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getMeanRate()).thenReturn(2.0); ++ when(meter.getOneMinuteRate()).thenReturn(3.0); ++ when(meter.getFiveMinuteRate()).thenReturn(4.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(5.0); ++ return meter; ++ } ++ ++ private Counter counter() { ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(100L); ++ return counter; ++ } ++ ++ @Test ++ void reportsCounterValuesAtErrorDefault() { ++ reportsCounterValuesAtError(); ++ } ++ ++ @Test ++ void reportsCounterValuesAtErrorAllDisabled() { ++ disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect ++ reportsCounterValuesAtError(); ++ } ++ ++ private void reportsCounterValuesAtError() { ++ final Counter counter = counter(); ++ when(logger.isErrorEnabled(marker)).thenReturn(true); ++ ++ errorReporter().report(map(), map("test.counter", counter), map(), map(), map()); ++ ++ verify(logger).error(marker, "type=COUNTER, name=test.counter, count=100"); ++ } ++ ++ @Test ++ void reportsHistogramValuesAtErrorDefault() { ++ reportsHistogramValuesAtError( ++ "type=HISTOGRAM, name=test.histogram, count=1, min=4, " ++ + "max=2, mean=3.0, stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); ++ } ++ ++ @Test ++ void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { ++ disabledMetricAttributes = EnumSet.of(COUNT, MetricAttribute.MIN, P50); ++ reportsHistogramValuesAtError( ++ "type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " ++ + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); ++ } ++ ++ private void reportsHistogramValuesAtError(final String expectedLog) { ++ final Histogram histogram = histogram(); ++ when(logger.isErrorEnabled(marker)).thenReturn(true); ++ ++ errorReporter().report(map(), map(), map("test.histogram", histogram), map(), map()); ++ ++ verify(logger).error(marker, expectedLog); ++ } ++ ++ @Test ++ void reportsMeterValuesAtErrorDefault() { ++ reportsMeterValuesAtError( ++ "type=METER, name=test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " ++ + "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); ++ } ++ ++ @Test ++ void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, P50, M1_RATE); ++ reportsMeterValuesAtError( ++ "type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " ++ + "mean_rate=2.0, rate_unit=events/second"); ++ } ++ ++ private void reportsMeterValuesAtError(final String expectedLog) { ++ final Meter meter = meter(); ++ when(logger.isErrorEnabled(marker)).thenReturn(true); ++ ++ errorReporter().report(map(), map(), map(), map("test.meter", meter), map()); ++ ++ verify(logger).error(marker, expectedLog); ++ } ++ ++ @Test ++ void reportsTimerValuesAtErrorDefault() { ++ reportsTimerValuesAtError( ++ "type=TIMER, name=test.another.timer, count=1, min=300.0, max=100.0, " ++ + "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0, " ++ + "m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, " ++ + "duration_unit=milliseconds"); ++ } ++ ++ @Test ++ void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, STDDEV, P999, MEAN_RATE); ++ reportsTimerValuesAtError( ++ "type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " ++ + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " ++ + "rate_unit=events/second, duration_unit=milliseconds"); ++ } ++ ++ private void reportsTimerValuesAtError(final String expectedLog) { ++ final Timer timer = timer(); ++ ++ when(logger.isErrorEnabled(marker)).thenReturn(true); ++ ++ errorReporter().report(map(), map(), map(), map(), map("test.another.timer", timer)); ++ ++ verify(logger).error(marker, expectedLog); ++ } ++ ++ @Test ++ void reportsGaugeValuesDefault() { ++ when(logger.isInfoEnabled(marker)).thenReturn(true); ++ infoReporter().report(map("gauge", () -> "value"), map(), map(), map(), map()); ++ ++ verify(logger).info(marker, "type=GAUGE, name=prefix.gauge, value=value"); ++ } ++ ++ @Test ++ void reportsCounterValuesDefault() { ++ final Counter counter = counter(); ++ when(logger.isInfoEnabled(marker)).thenReturn(true); ++ ++ infoReporter().report(map(), map("test.counter", counter), map(), map(), map()); ++ ++ verify(logger).info(marker, "type=COUNTER, name=prefix.test.counter, count=100"); ++ } ++ ++ @Test ++ void reportsHistogramValuesDefault() { ++ final Histogram histogram = histogram(); ++ when(logger.isInfoEnabled(marker)).thenReturn(true); ++ ++ infoReporter().report(map(), map(), map("test.histogram", histogram), map(), map()); ++ ++ verify(logger) ++ .info( ++ marker, ++ "type=HISTOGRAM, name=prefix.test.histogram, count=1, min=4, max=2, mean=3.0, " ++ + "stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); ++ } ++ ++ @Test ++ void reportsMeterValuesDefault() { ++ final Meter meter = meter(); ++ when(logger.isInfoEnabled(marker)).thenReturn(true); ++ ++ infoReporter().report(map(), map(), map(), map("test.meter", meter), map()); ++ ++ verify(logger) ++ .info( ++ marker, ++ "type=METER, name=prefix.test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " ++ + "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); ++ } ++ ++ @Test ++ void reportsTimerValuesDefault() { ++ final Timer timer = timer(); ++ when(logger.isInfoEnabled(marker)).thenReturn(true); ++ ++ infoReporter().report(map(), map(), map(), map(), map("test.another.timer", timer)); ++ ++ verify(logger) ++ .info( ++ marker, ++ "type=TIMER, name=prefix.test.another.timer, count=1, min=300.0, max=100.0, " ++ + "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0," ++ + " m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, duration_unit=milliseconds"); ++ } ++ ++ @Test ++ void reportsAllMetricsDefault() { ++ when(logger.isInfoEnabled(marker)).thenReturn(true); ++ ++ infoReporter() ++ .report( ++ map("test.gauge", () -> "value"), ++ map("test.counter", counter()), ++ map("test.histogram", histogram()), ++ map("test.meter", meter()), ++ map("test.timer", timer())); ++ ++ verify(logger).info(marker, "type=GAUGE, name=prefix.test.gauge, value=value"); ++ verify(logger).info(marker, "type=COUNTER, name=prefix.test.counter, count=100"); ++ verify(logger) ++ .info( ++ marker, ++ "type=HISTOGRAM, name=prefix.test.histogram, count=1, min=4, max=2, mean=3.0, " ++ + "stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); ++ verify(logger) ++ .info( ++ marker, ++ "type=METER, name=prefix.test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " ++ + "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); ++ verify(logger) ++ .info( ++ marker, ++ "type=TIMER, name=prefix.test.timer, count=1, min=300.0, max=100.0, " ++ + "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0," ++ + " m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, duration_unit=milliseconds"); ++ } ++ ++ private SortedMap map() { ++ return new TreeMap<>(); ++ } ++ ++ private SortedMap map(String name, T metric) { ++ final SortedMap map = new TreeMap<>(); ++ map.put(MetricName.build(name), metric); ++ return map; ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java +@@ -1,150 +1,166 @@ + package io.dropwizard.metrics5; + ++import static java.util.concurrent.TimeUnit.NANOSECONDS; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; +-import static java.util.concurrent.TimeUnit.NANOSECONDS; +- +-import org.junit.jupiter.api.Test; + + import java.util.Arrays; + import java.util.Random; + import java.util.concurrent.ThreadLocalRandom; + import java.util.concurrent.atomic.AtomicLong; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("Duplicates") +-class SlidingTimeWindowArrayReservoirTest { +- +- @Test +- void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); +- final SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); +- +- when(clock.getTick()).thenReturn(20L); +- +- reservoir.update(1); +- reservoir.update(2); +- +- assertThat(reservoir.getSnapshot().getValues()) +- .containsOnly(1, 2); +- } +- +- @Test +- void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); +- final SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); +- +- when(clock.getTick()).thenReturn(0L); +- reservoir.update(1); +- +- when(clock.getTick()).thenReturn(5L); +- reservoir.update(2); +- +- when(clock.getTick()).thenReturn(10L); +- reservoir.update(3); +- +- when(clock.getTick()).thenReturn(15L); +- reservoir.update(4); +- +- when(clock.getTick()).thenReturn(20L); +- reservoir.update(5); +- +- assertThat(reservoir.getSnapshot().getValues()) +- .containsOnly(4, 5); ++final class SlidingTimeWindowArrayReservoirTest { ++ ++ @Test ++ void storesMeasurementsWithDuplicateTicks() { ++ final Clock clock = mock(); ++ final SlidingTimeWindowArrayReservoir reservoir = ++ new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); ++ ++ when(clock.getTick()).thenReturn(20L); ++ ++ reservoir.update(1); ++ reservoir.update(2); ++ ++ assertThat(reservoir.getSnapshot().getValues()).containsOnly(1, 2); ++ } ++ ++ @Test ++ void boundsMeasurementsToATimeWindow() { ++ final Clock clock = mock(); ++ final SlidingTimeWindowArrayReservoir reservoir = ++ new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); ++ ++ when(clock.getTick()).thenReturn(0L); ++ reservoir.update(1); ++ ++ when(clock.getTick()).thenReturn(5L); ++ reservoir.update(2); ++ ++ when(clock.getTick()).thenReturn(10L); ++ reservoir.update(3); ++ ++ when(clock.getTick()).thenReturn(15L); ++ reservoir.update(4); ++ ++ when(clock.getTick()).thenReturn(20L); ++ reservoir.update(5); ++ ++ assertThat(reservoir.getSnapshot().getValues()).containsOnly(4, 5); ++ } ++ ++ @Test ++ void comparisonResultsTest() { ++ int cycles = 1000000; ++ long time = (Long.MAX_VALUE / 256) - (long) (cycles * 0.5); ++ ManualClock manualClock = new ManualClock(); ++ manualClock.addNanos(time); ++ int window = 300; ++ Random random = new Random(ThreadLocalRandom.current().nextInt()); ++ ++ SlidingTimeWindowReservoir treeReservoir = ++ new SlidingTimeWindowReservoir(window, NANOSECONDS, manualClock); ++ SlidingTimeWindowArrayReservoir arrayReservoir = ++ new SlidingTimeWindowArrayReservoir(window, NANOSECONDS, manualClock); ++ ++ for (int i = 0; i < cycles; i++) { ++ manualClock.addNanos(1); ++ treeReservoir.update(i); ++ arrayReservoir.update(i); ++ if (random.nextDouble() < 0.01) { ++ long[] treeValues = treeReservoir.getSnapshot().getValues(); ++ long[] arrValues = arrayReservoir.getSnapshot().getValues(); ++ assertThat(arrValues).isEqualTo(treeValues); ++ } ++ if (random.nextDouble() < 0.05) { ++ assertThat(arrayReservoir.size()).isEqualTo(treeReservoir.size()); ++ } + } +- +- @Test +- void comparisonResultsTest() { +- int cycles = 1000000; +- long time = (Long.MAX_VALUE / 256) - (long) (cycles * 0.5); +- ManualClock manualClock = new ManualClock(); +- manualClock.addNanos(time); +- int window = 300; +- Random random = new Random(ThreadLocalRandom.current().nextInt()); +- +- SlidingTimeWindowReservoir treeReservoir = new SlidingTimeWindowReservoir(window, NANOSECONDS, manualClock); +- SlidingTimeWindowArrayReservoir arrayReservoir = new SlidingTimeWindowArrayReservoir(window, NANOSECONDS, manualClock); +- +- for (int i = 0; i < cycles; i++) { +- manualClock.addNanos(1); +- treeReservoir.update(i); +- arrayReservoir.update(i); +- if (random.nextDouble() < 0.01) { +- long[] treeValues = treeReservoir.getSnapshot().getValues(); +- long[] arrValues = arrayReservoir.getSnapshot().getValues(); +- assertThat(arrValues).isEqualTo(treeValues); +- } +- if (random.nextDouble() < 0.05) { +- assertThat(arrayReservoir.size()).isEqualTo(treeReservoir.size()); ++ } ++ ++ @Test ++ void getTickOverflow() { ++ final Random random = new Random(0); ++ final int window = 128; ++ AtomicLong counter = new AtomicLong(0L); ++ ++ // Note: 'threshold' defines the number of updates submitted to the reservoir after overflowing ++ for (int threshold : Arrays.asList(0, 1, 2, 127, 128, 129, 255, 256, 257)) { ++ ++ // Note: 'updatePerTick' defines the number of updates submitted to the reservoir between each ++ // tick ++ for (int updatesPerTick : Arrays.asList(1, 2, 127, 128, 129, 255, 256, 257)) { ++ // logger.info("Executing test: threshold={}, updatesPerTick={}", threshold, ++ // updatesPerTick); ++ ++ // Set the clock to overflow in (2*window+1)ns ++ final ManualClock clock = new ManualClock(); ++ clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); ++ assertThat(clock.getTick() * 256).isPositive(); ++ ++ // Create the reservoir ++ final SlidingTimeWindowArrayReservoir reservoir = ++ new SlidingTimeWindowArrayReservoir(window, NANOSECONDS, clock); ++ int updatesAfterThreshold = 0; ++ while (true) { ++ // Update the reservoir ++ for (int i = 0; i < updatesPerTick; i++) { ++ long l = counter.incrementAndGet(); ++ reservoir.update(l); ++ } ++ ++ // Randomly check the reservoir size ++ if (random.nextDouble() < 0.1) { ++ assertThat(reservoir.size()) ++ .as( ++ "Bad reservoir size with: threshold=%d, updatesPerTick=%d", ++ threshold, updatesPerTick) ++ .isLessThanOrEqualTo(window * 256); ++ } ++ ++ // Update the clock ++ clock.addNanos(1); ++ ++ // If the clock has overflowed start counting updates ++ if ((clock.getTick() * 256) < 0) { ++ if (updatesAfterThreshold++ >= threshold) { ++ break; + } ++ } + } +- } + +- @Test +- void testGetTickOverflow() { +- final Random random = new Random(0); +- final int window = 128; +- AtomicLong counter = new AtomicLong(0L); +- +- // Note: 'threshold' defines the number of updates submitted to the reservoir after overflowing +- for (int threshold : Arrays.asList(0, 1, 2, 127, 128, 129, 255, 256, 257)) { +- +- // Note: 'updatePerTick' defines the number of updates submitted to the reservoir between each tick +- for (int updatesPerTick : Arrays.asList(1, 2, 127, 128, 129, 255, 256, 257)) { +- //logger.info("Executing test: threshold={}, updatesPerTick={}", threshold, updatesPerTick); +- +- // Set the clock to overflow in (2*window+1)ns +- final ManualClock clock = new ManualClock(); +- clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); +- +- // Create the reservoir +- final SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(window, NANOSECONDS, clock); +- int updatesAfterThreshold = 0; +- while (true) { +- // Update the reservoir +- for (int i = 0; i < updatesPerTick; i++) { +- long l = counter.incrementAndGet(); +- reservoir.update(l); +- } +- +- // Randomly check the reservoir size +- if (random.nextDouble() < 0.1) { +- assertThat(reservoir.size()) +- .as("Bad reservoir size with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) +- .isLessThanOrEqualTo(window * 256); +- } +- +- // Update the clock +- clock.addNanos(1); +- +- // If the clock has overflowed start counting updates +- if ((clock.getTick() * 256) < 0) { +- if (updatesAfterThreshold++ >= threshold) { +- break; +- } +- } +- } +- +- // Check the final reservoir size +- assertThat(reservoir.size()) +- .as("Bad final reservoir size with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) +- .isLessThanOrEqualTo(window * 256); +- +- // Advance the clock far enough to clear the reservoir. Note that here the window only loosely defines +- // the reservoir window; when updatesPerTick is greater than 128 the sliding window will always be well +- // ahead of the current clock time, and advances in getTick while in trim (called randomly above from +- // size and every 256 updates). Until the clock "catches up" advancing the clock will have no effect on +- // the reservoir, and reservoir.size() will merely move the window forward 1/256th of a ns - as such, an +- // arbitrary increment of 1s here was used instead to advance the clock well beyond any updates recorded +- // above. +- clock.addSeconds(1); +- +- // The reservoir should now be empty +- assertThat(reservoir.size()) +- .as("Bad reservoir size after delay with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) +- .isEqualTo(0); +- } +- } ++ // Check the final reservoir size ++ assertThat(reservoir.size()) ++ .as( ++ "Bad final reservoir size with: threshold=%d, updatesPerTick=%d", ++ threshold, updatesPerTick) ++ .isLessThanOrEqualTo(window * 256); ++ ++ // Advance the clock far enough to clear the reservoir. Note that here the window only ++ // loosely defines ++ // the reservoir window; when updatesPerTick is greater than 128 the sliding window will ++ // always be well ++ // ahead of the current clock time, and advances in getTick while in trim (called randomly ++ // above from ++ // size and every 256 updates). Until the clock "catches up" advancing the clock will have ++ // no effect on ++ // the reservoir, and reservoir.size() will merely move the window forward 1/256th of a ns - ++ // as such, an ++ // arbitrary increment of 1s here was used instead to advance the clock well beyond any ++ // updates recorded ++ // above. ++ clock.addSeconds(1); ++ ++ // The reservoir should now be empty ++ assertThat(reservoir.size()) ++ .as( ++ "Bad reservoir size after delay with: threshold=%d, updatesPerTick=%d", ++ threshold, updatesPerTick) ++ .isEqualTo(0); ++ } + } +-} +\ No newline at end of file ++ } ++} +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java +@@ -1,166 +1,165 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import java.time.Instant; +- + import static io.dropwizard.metrics5.SlidingTimeWindowMovingAverages.NUMBER_OF_BUCKETS; + import static org.assertj.core.api.Assertions.assertThat; + +-class SlidingTimeWindowMovingAveragesTest { +- +- private ManualClock clock; +- private SlidingTimeWindowMovingAverages movingAverages; +- private Meter meter; ++import java.time.Instant; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +- @BeforeEach +- void init() { +- clock = new ManualClock(); +- movingAverages = new SlidingTimeWindowMovingAverages(clock); +- meter = new Meter(movingAverages, clock); +- } ++final class SlidingTimeWindowMovingAveragesTest { + +- @Test +- void normalizeIndex() { ++ private ManualClock clock; ++ private SlidingTimeWindowMovingAverages movingAverages; ++ private Meter meter; + +- SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(); ++ @BeforeEach ++ void init() { ++ clock = new ManualClock(); ++ movingAverages = new SlidingTimeWindowMovingAverages(clock); ++ meter = new Meter(movingAverages, clock); ++ } + +- assertThat(stwm.normalizeIndex(0)).isEqualTo(0); +- assertThat(stwm.normalizeIndex(900)).isEqualTo(0); +- assertThat(stwm.normalizeIndex(9000)).isEqualTo(0); +- assertThat(stwm.normalizeIndex(-900)).isEqualTo(0); ++ @Test ++ void normalizeIndex() { + +- assertThat(stwm.normalizeIndex(1)).isEqualTo(1); ++ SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(); + +- assertThat(stwm.normalizeIndex(899)).isEqualTo(899); +- assertThat(stwm.normalizeIndex(-1)).isEqualTo(899); +- assertThat(stwm.normalizeIndex(-901)).isEqualTo(899); +- } ++ assertThat(stwm.normalizeIndex(0)).isEqualTo(0); ++ assertThat(stwm.normalizeIndex(900)).isEqualTo(0); ++ assertThat(stwm.normalizeIndex(9000)).isEqualTo(0); ++ assertThat(stwm.normalizeIndex(-900)).isEqualTo(0); + +- @Test +- void calculateIndexOfTick() { ++ assertThat(stwm.normalizeIndex(1)).isEqualTo(1); + +- SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); ++ assertThat(stwm.normalizeIndex(899)).isEqualTo(899); ++ assertThat(stwm.normalizeIndex(-1)).isEqualTo(899); ++ assertThat(stwm.normalizeIndex(-901)).isEqualTo(899); ++ } + +- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(0L))).isEqualTo(0); +- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L))).isEqualTo(1); +- } ++ @Test ++ void calculateIndexOfTick() { + +- @Test +- void mark_max_without_cleanup() { ++ SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); + +- int markCount = NUMBER_OF_BUCKETS; ++ assertThat(stwm.calculateIndexOfTick(Instant.EPOCH)).isEqualTo(0); ++ assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L))).isEqualTo(1); ++ } + +- // compensate the first addSeconds in the loop; first tick should be at zero +- clock.addSeconds(-1); ++ @Test ++ void mark_max_without_cleanup() { + +- for (int i = 0; i < markCount; i++) { +- clock.addSeconds(1); +- meter.mark(); +- } ++ int markCount = NUMBER_OF_BUCKETS; + +- // verify that no cleanup happened yet +- assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.ofEpochSecond(0L)); ++ // compensate the first addSeconds in the loop; first tick should be at zero ++ clock.addSeconds(-1); + +- assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); ++ for (int i = 0; i < markCount; i++) { ++ clock.addSeconds(1); ++ meter.mark(); + } + +- @Test +- void mark_first_cleanup() { ++ // verify that no cleanup happened yet ++ assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.EPOCH); + +- int markCount = NUMBER_OF_BUCKETS + 1; ++ assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); ++ assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); ++ assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); ++ } + +- // compensate the first addSeconds in the loop; first tick should be at zero +- clock.addSeconds(-1); ++ @Test ++ void mark_first_cleanup() { + +- for (int i = 0; i < markCount; i++) { +- clock.addSeconds(1); +- meter.mark(); +- } ++ int markCount = NUMBER_OF_BUCKETS + 1; + +- // verify that at least one cleanup happened +- assertThat(movingAverages.oldestBucketTime).isNotEqualTo(Instant.EPOCH); ++ // compensate the first addSeconds in the loop; first tick should be at zero ++ clock.addSeconds(-1); + +- assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); ++ for (int i = 0; i < markCount; i++) { ++ clock.addSeconds(1); ++ meter.mark(); + } + +- @Test +- void mark_10_values() { ++ // verify that at least one cleanup happened ++ assertThat(movingAverages.oldestBucketTime).isNotEqualTo(Instant.EPOCH); + +- // compensate the first addSeconds in the loop; first tick should be at zero +- clock.addSeconds(-1); ++ assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); ++ assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); ++ assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); ++ } + +- for (int i = 0; i < 10; i++) { +- clock.addSeconds(1); +- meter.mark(); +- } ++ @Test ++ void mark_10_values() { + +- assertThat(meter.getCount()).isEqualTo(10L); +- assertThat(meter.getOneMinuteRate()).isEqualTo(10.0); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); +- } +- +- @Test +- void mark_1000_values() { +- +- for (int i = 0; i < 1000; i++) { +- clock.addSeconds(1); +- meter.mark(); +- } ++ // compensate the first addSeconds in the loop; first tick should be at zero ++ clock.addSeconds(-1); + +- // only 60/300/900 of the 1000 events took place in the last 1/5/15 minute(s) +- assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); ++ for (int i = 0; i < 10; i++) { ++ clock.addSeconds(1); ++ meter.mark(); + } + +- @Test +- void cleanup_pause_shorter_than_window() { ++ assertThat(meter.getCount()).isEqualTo(10L); ++ assertThat(meter.getOneMinuteRate()).isEqualTo(10.0); ++ assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); ++ assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); ++ } + +- meter.mark(10); ++ @Test ++ void mark_1000_values() { + +- // no mark for three minutes +- clock.addSeconds(180); +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); ++ for (int i = 0; i < 1000; i++) { ++ clock.addSeconds(1); ++ meter.mark(); + } + +- @Test +- void cleanup_window_wrap_around() { +- +- // mark at 14:40 minutes of the 15 minute window... +- clock.addSeconds(880); +- meter.mark(10); +- +- // and query at 15:30 minutes (the bucket index must have wrapped around) +- clock.addSeconds(50); +- assertThat(meter.getOneMinuteRate()).isEqualTo(10.0); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); +- +- // and query at 30:10 minutes (the bucket index must have wrapped around for the second time) +- clock.addSeconds(880); +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0); +- } +- +- @Test +- void cleanup_pause_longer_than_two_windows() { +- +- meter.mark(10); +- +- // after forty minutes all rates should be zero +- clock.addSeconds(2400); +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0); +- } +-} +\ No newline at end of file ++ // only 60/300/900 of the 1000 events took place in the last 1/5/15 minute(s) ++ assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); ++ assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); ++ assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); ++ } ++ ++ @Test ++ void cleanup_pause_shorter_than_window() { ++ ++ meter.mark(10); ++ ++ // no mark for three minutes ++ clock.addSeconds(180); ++ assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); ++ assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); ++ assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); ++ } ++ ++ @Test ++ void cleanup_window_wrap_around() { ++ ++ // mark at 14:40 minutes of the 15 minute window... ++ clock.addSeconds(880); ++ meter.mark(10); ++ ++ // and query at 15:30 minutes (the bucket index must have wrapped around) ++ clock.addSeconds(50); ++ assertThat(meter.getOneMinuteRate()).isEqualTo(10.0); ++ assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); ++ assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); ++ ++ // and query at 30:10 minutes (the bucket index must have wrapped around for the second time) ++ clock.addSeconds(880); ++ assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); ++ assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0); ++ assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0); ++ } ++ ++ @Test ++ void cleanup_pause_longer_than_two_windows() { ++ ++ meter.mark(10); ++ ++ // after forty minutes all rates should be zero ++ clock.addSeconds(2400); ++ assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); ++ assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0); ++ assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0); ++ } ++} +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java +@@ -1,119 +1,131 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- +-import java.util.Arrays; +-import java.util.Random; +- + import static java.util.concurrent.TimeUnit.NANOSECONDS; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + +-class SlidingTimeWindowReservoirTest { +- @Test +- void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); +- final SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); ++import java.util.Arrays; ++import java.util.Random; ++import org.junit.jupiter.api.Test; + +- when(clock.getTick()).thenReturn(20L); ++final class SlidingTimeWindowReservoirTest { ++ @Test ++ void storesMeasurementsWithDuplicateTicks() { ++ final Clock clock = mock(); ++ final SlidingTimeWindowReservoir reservoir = ++ new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); + +- reservoir.update(1); +- reservoir.update(2); ++ when(clock.getTick()).thenReturn(20L); + +- assertThat(reservoir.getSnapshot().getValues()) +- .containsOnly(1, 2); +- } ++ reservoir.update(1); ++ reservoir.update(2); + +- @Test +- void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); +- when(clock.getTick()).thenReturn(0L); ++ assertThat(reservoir.getSnapshot().getValues()).containsOnly(1, 2); ++ } + +- final SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); ++ @Test ++ void boundsMeasurementsToATimeWindow() { ++ final Clock clock = mock(); ++ when(clock.getTick()).thenReturn(0L); + +- when(clock.getTick()).thenReturn(0L); +- reservoir.update(1); ++ final SlidingTimeWindowReservoir reservoir = ++ new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); + +- when(clock.getTick()).thenReturn(5L); +- reservoir.update(2); ++ when(clock.getTick()).thenReturn(0L); ++ reservoir.update(1); + +- when(clock.getTick()).thenReturn(10L); +- reservoir.update(3); ++ when(clock.getTick()).thenReturn(5L); ++ reservoir.update(2); + +- when(clock.getTick()).thenReturn(15L); +- reservoir.update(4); ++ when(clock.getTick()).thenReturn(10L); ++ reservoir.update(3); + +- when(clock.getTick()).thenReturn(20L); +- reservoir.update(5); ++ when(clock.getTick()).thenReturn(15L); ++ reservoir.update(4); + +- assertThat(reservoir.getSnapshot().getValues()) +- .containsOnly(4, 5); +- } ++ when(clock.getTick()).thenReturn(20L); ++ reservoir.update(5); ++ ++ assertThat(reservoir.getSnapshot().getValues()).containsOnly(4, 5); ++ } + +- @Test +- void testGetTickOverflow() { +- final Random random = new Random(0); +- final int window = 128; +- +- // Note: 'threshold' defines the number of updates submitted to the reservoir after overflowing +- for (int threshold : Arrays.asList(0, 1, 2, 127, 128, 129, 255, 256, 257)) { +- +- // Note: 'updatePerTick' defines the number of updates submitted to the reservoir between each tick +- for (int updatesPerTick : Arrays.asList(1, 2, 127, 128, 129, 255, 256, 257)) { +- //logger.info("Executing test: threshold={}, updatesPerTick={}", threshold, updatesPerTick); +- +- final ManualClock clock = new ManualClock(); +- +- // Create the reservoir +- final SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(window, NANOSECONDS, clock); +- +- // Set the clock to overflow in (2*window+1)ns +- clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); +- +- int updatesAfterThreshold = 0; +- while (true) { +- // Update the reservoir +- for (int i = 0; i < updatesPerTick; i++) +- reservoir.update(0); +- +- // Randomly check the reservoir size +- if (random.nextDouble() < 0.1) { +- assertThat(reservoir.size()) +- .as("Bad reservoir size with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) +- .isLessThanOrEqualTo(window * 256); +- } +- +- // Update the clock +- clock.addNanos(1); +- +- // If the clock has overflowed start counting updates +- if ((clock.getTick() * 256) < 0) { +- if (updatesAfterThreshold++ >= threshold) +- break; +- } +- } +- +- // Check the final reservoir size +- assertThat(reservoir.size()) +- .as("Bad final reservoir size with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) +- .isLessThanOrEqualTo(window * 256); +- +- // Advance the clock far enough to clear the reservoir. Note that here the window only loosely defines +- // the reservoir window; when updatesPerTick is greater than 128 the sliding window will always be well +- // ahead of the current clock time, and advances in getTick while in trim (called randomly above from +- // size and every 256 updates). Until the clock "catches up" advancing the clock will have no effect on +- // the reservoir, and reservoir.size() will merely move the window forward 1/256th of a ns - as such, an +- // arbitrary increment of 1s here was used instead to advance the clock well beyond any updates recorded +- // above. +- clock.addSeconds(1); +- +- // The reservoir should now be empty +- assertThat(reservoir.size()) +- .as("Bad reservoir size after delay with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) +- .isEqualTo(0); +- } ++ @Test ++ void getTickOverflow() { ++ final Random random = new Random(0); ++ final int window = 128; ++ ++ // Note: 'threshold' defines the number of updates submitted to the reservoir after overflowing ++ for (int threshold : Arrays.asList(0, 1, 2, 127, 128, 129, 255, 256, 257)) { ++ ++ // Note: 'updatePerTick' defines the number of updates submitted to the reservoir between each ++ // tick ++ for (int updatesPerTick : Arrays.asList(1, 2, 127, 128, 129, 255, 256, 257)) { ++ // logger.info("Executing test: threshold={}, updatesPerTick={}", threshold, ++ // updatesPerTick); ++ ++ final ManualClock clock = new ManualClock(); ++ ++ // Create the reservoir ++ final SlidingTimeWindowReservoir reservoir = ++ new SlidingTimeWindowReservoir(window, NANOSECONDS, clock); ++ ++ // Set the clock to overflow in (2*window+1)ns ++ clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); ++ assertThat(clock.getTick() * 256).isPositive(); ++ ++ int updatesAfterThreshold = 0; ++ while (true) { ++ // Update the reservoir ++ for (int i = 0; i < updatesPerTick; i++) reservoir.update(0); ++ ++ // Randomly check the reservoir size ++ if (random.nextDouble() < 0.1) { ++ assertThat(reservoir.size()) ++ .as( ++ "Bad reservoir size with: threshold=%d, updatesPerTick=%d", ++ threshold, updatesPerTick) ++ .isLessThanOrEqualTo(window * 256); ++ } ++ ++ // Update the clock ++ clock.addNanos(1); ++ ++ // If the clock has overflowed start counting updates ++ if ((clock.getTick() * 256) < 0) { ++ if (updatesAfterThreshold++ >= threshold) break; ++ } + } ++ ++ // Check the final reservoir size ++ assertThat(reservoir.size()) ++ .as( ++ "Bad final reservoir size with: threshold=%d, updatesPerTick=%d", ++ threshold, updatesPerTick) ++ .isLessThanOrEqualTo(window * 256); ++ ++ // Advance the clock far enough to clear the reservoir. Note that here the window only ++ // loosely defines ++ // the reservoir window; when updatesPerTick is greater than 128 the sliding window will ++ // always be well ++ // ahead of the current clock time, and advances in getTick while in trim (called randomly ++ // above from ++ // size and every 256 updates). Until the clock "catches up" advancing the clock will have ++ // no effect on ++ // the reservoir, and reservoir.size() will merely move the window forward 1/256th of a ns - ++ // as such, an ++ // arbitrary increment of 1s here was used instead to advance the clock well beyond any ++ // updates recorded ++ // above. ++ clock.addSeconds(1); ++ ++ // The reservoir should now be empty ++ assertThat(reservoir.size()) ++ .as( ++ "Bad reservoir size after delay with: threshold=%d, updatesPerTick=%d", ++ threshold, updatesPerTick) ++ .isEqualTo(0); ++ } + } +-} +\ No newline at end of file ++ } ++} +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java +@@ -1,29 +1,27 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-class SlidingWindowReservoirTest { +- private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); ++import org.junit.jupiter.api.Test; ++ ++final class SlidingWindowReservoirTest { ++ private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); + +- @Test +- void handlesSmallDataStreams() { +- reservoir.update(1); +- reservoir.update(2); ++ @Test ++ void handlesSmallDataStreams() { ++ reservoir.update(1); ++ reservoir.update(2); + +- assertThat(reservoir.getSnapshot().getValues()) +- .containsOnly(1, 2); +- } ++ assertThat(reservoir.getSnapshot().getValues()).containsOnly(1, 2); ++ } + +- @Test +- void onlyKeepsTheMostRecentFromBigDataStreams() { +- reservoir.update(1); +- reservoir.update(2); +- reservoir.update(3); +- reservoir.update(4); ++ @Test ++ void onlyKeepsTheMostRecentFromBigDataStreams() { ++ reservoir.update(1); ++ reservoir.update(2); ++ reservoir.update(3); ++ reservoir.update(4); + +- assertThat(reservoir.getSnapshot().getValues()) +- .containsOnly(2, 3, 4); +- } ++ assertThat(reservoir.getSnapshot().getValues()).containsOnly(2, 3, 4); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java +@@ -1,11 +1,5 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- +-import java.time.Duration; +-import java.util.concurrent.TimeUnit; +-import java.util.concurrent.atomic.AtomicBoolean; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.offset; + import static org.mockito.Mockito.mock; +@@ -13,168 +7,148 @@ import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.verifyNoInteractions; + import static org.mockito.Mockito.when; + +-class TimerTest { +- private final Reservoir reservoir = mock(Reservoir.class); +- private final Clock clock = new Clock() { ++import java.time.Duration; ++import java.util.concurrent.TimeUnit; ++import java.util.concurrent.atomic.AtomicBoolean; ++import org.junit.jupiter.api.Test; ++ ++final class TimerTest { ++ private final Reservoir reservoir = mock(); ++ private final Clock clock = ++ new Clock() { + // a mock clock that increments its ticker by 50msec per call + private long val = 0; + + @Override + public long getTick() { +- return val += 50000000; ++ return val += 50000000; + } +- }; +- private final Timer timer = new Timer(reservoir, clock); ++ }; ++ private final Timer timer = new Timer(reservoir, clock); + +- @Test +- void hasRates() { +- assertThat(timer.getCount()) +- .isZero(); ++ @Test ++ void hasRates() { ++ assertThat(timer.getCount()).isEqualTo(0); + +- assertThat(timer.getSum()) +- .isZero(); ++ assertThat(timer.getSum()).isEqualTo(0); + +- assertThat(timer.getMeanRate()) +- .isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getOneMinuteRate()) +- .isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getFiveMinuteRate()) +- .isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getFifteenMinuteRate()) +- .isEqualTo(0.0, offset(0.001)); +- } ++ assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); ++ } + +- @Test +- void updatesTheCountAndSumOnUpdates() { +- assertThat(timer.getCount()) +- .isZero(); +- assertThat(timer.getSum()) +- .isZero(); ++ @Test ++ void updatesTheCountAndSumOnUpdates() { ++ assertThat(timer.getCount()).isEqualTo(0); ++ assertThat(timer.getSum()).isEqualTo(0); + +- timer.update(1, TimeUnit.SECONDS); +- timer.update(5, TimeUnit.SECONDS); ++ timer.update(1, TimeUnit.SECONDS); ++ timer.update(5, TimeUnit.SECONDS); + +- assertThat(timer.getCount()) +- .isEqualTo(2); +- assertThat(timer.getSum()) +- .isEqualTo(6000000000L); +- } ++ assertThat(timer.getCount()).isEqualTo(2); ++ assertThat(timer.getSum()).isEqualTo(6000000000L); ++ } + +- @Test +- void timesCallableInstances() throws Exception { +- final String value = timer.time(() -> "one"); ++ @Test ++ void timesCallableInstances() throws Exception { ++ final String value = timer.time(() -> "one"); + +- assertThat(timer.getCount()) +- .isEqualTo(1); +- assertThat(timer.getSum()) +- .isEqualTo(50000000); ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSum()).isEqualTo(50000000); + +- assertThat(value) +- .isEqualTo("one"); ++ assertThat(value).isEqualTo("one"); + +- verify(reservoir).update(50000000); +- } ++ verify(reservoir).update(50000000); ++ } + +- @Test +- void timesSuppliedInstances() { +- final String value = timer.timeSupplier(() -> "one"); ++ @Test ++ void timesSuppliedInstances() { ++ final String value = timer.timeSupplier(() -> "one"); + +- assertThat(timer.getCount()) +- .isEqualTo(1); ++ assertThat(timer.getCount()).isEqualTo(1); + +- assertThat(value) +- .isEqualTo("one"); ++ assertThat(value).isEqualTo("one"); + +- verify(reservoir).update(50000000); +- } ++ verify(reservoir).update(50000000); ++ } + +- @Test +- void timesRunnableInstances() { +- final AtomicBoolean called = new AtomicBoolean(); +- timer.time(() -> called.set(true)); ++ @Test ++ void timesRunnableInstances() { ++ final AtomicBoolean called = new AtomicBoolean(); ++ timer.time(() -> called.set(true)); + +- assertThat(timer.getCount()) +- .isEqualTo(1); +- assertThat(timer.getSum()) +- .isEqualTo(50000000); ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSum()).isEqualTo(50000000); + +- assertThat(called.get()) +- .isTrue(); ++ assertThat(called.get()).isTrue(); + +- verify(reservoir).update(50000000); +- } ++ verify(reservoir).update(50000000); ++ } + +- @Test +- void timesContexts() { +- timer.time().stop(); ++ @Test ++ void timesContexts() { ++ timer.time().stop(); + +- assertThat(timer.getCount()) +- .isEqualTo(1); +- assertThat(timer.getSum()) +- .isEqualTo(50000000); ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSum()).isEqualTo(50000000); + +- verify(reservoir).update(50000000); +- } ++ verify(reservoir).update(50000000); ++ } + +- @Test +- void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); +- when(reservoir.getSnapshot()).thenReturn(snapshot); ++ @Test ++ void returnsTheSnapshotFromTheReservoir() { ++ final Snapshot snapshot = mock(); ++ when(reservoir.getSnapshot()).thenReturn(snapshot); + +- assertThat(timer.getSnapshot()) +- .isEqualTo(snapshot); +- } ++ assertThat(timer.getSnapshot()).isEqualTo(snapshot); ++ } + +- @Test +- void ignoresNegativeValues() { +- timer.update(-1, TimeUnit.SECONDS); ++ @Test ++ void ignoresNegativeValues() { ++ timer.update(-1, TimeUnit.SECONDS); + +- assertThat(timer.getCount()) +- .isZero(); +- assertThat(timer.getSum()) +- .isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); ++ assertThat(timer.getSum()).isEqualTo(0); + +- verifyNoInteractions(reservoir); +- } ++ verifyNoInteractions(reservoir); ++ } + +- @Test +- void java8Duration() { +- timer.update(Duration.ofSeconds(1234)); ++ @Test ++ void java8Duration() { ++ timer.update(Duration.ofSeconds(1234)); + +- assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getCount()).isEqualTo(1); + +- verify(reservoir).update((long) 1234e9); +- } ++ verify(reservoir).update((long) 1234e9); ++ } + +- @Test +- void java8NegativeDuration() { +- timer.update(Duration.ofMillis(-5678)); ++ @Test ++ void java8NegativeDuration() { ++ timer.update(Duration.ofMillis(-5678)); + +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + +- verifyNoInteractions(reservoir); +- } ++ verifyNoInteractions(reservoir); ++ } + +- @Test +- void tryWithResourcesWork() { +- assertThat(timer.getCount()).isZero(); +- assertThat(timer.getSum()).isZero(); +- +- int dummy = 0; +- try (Timer.Context context = timer.time()) { +- assertThat(context).isNotNull(); +- dummy += 1; +- } +- assertThat(dummy).isEqualTo(1); +- assertThat(timer.getCount()) +- .isEqualTo(1); +- assertThat(timer.getSum()) +- .isEqualTo(50000000); ++ @Test ++ void tryWithResourcesWork() { ++ assertThat(timer.getCount()).isEqualTo(0); ++ assertThat(timer.getSum()).isEqualTo(0); + +- verify(reservoir).update(50000000); ++ int dummy = 0; ++ try (Timer.Context context = timer.time()) { ++ assertThat(context).isNotNull(); ++ dummy += 1; + } ++ assertThat(dummy).isEqualTo(1); ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSum()).isEqualTo(50000000); + ++ verify(reservoir).update(50000000); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java +@@ -1,31 +1,26 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-class UniformReservoirTest { +- @Test +- @SuppressWarnings("unchecked") +- void aReservoirOf100OutOf1000Elements() { +- final UniformReservoir reservoir = new UniformReservoir(100); +- for (int i = 0; i < 1000; i++) { +- reservoir.update(i); +- } ++import org.junit.jupiter.api.Test; ++ ++final class UniformReservoirTest { ++ @SuppressWarnings("unchecked") ++ @Test ++ void aReservoirOf100OutOf1000Elements() { ++ final UniformReservoir reservoir = new UniformReservoir(100); ++ for (int i = 0; i < 1000; i++) { ++ reservoir.update(i); ++ } + +- final Snapshot snapshot = reservoir.getSnapshot(); ++ final Snapshot snapshot = reservoir.getSnapshot(); + +- assertThat(reservoir.size()) +- .isEqualTo(100); ++ assertThat(reservoir.size()).isEqualTo(100); + +- assertThat(snapshot.size()) +- .isEqualTo(100); ++ assertThat(snapshot.size()).isEqualTo(100); + +- for (double i : snapshot.getValues()) { +- assertThat(i) +- .isLessThan(1000) +- .isGreaterThanOrEqualTo(0); +- } ++ for (double i : snapshot.getValues()) { ++ assertThat(i).isLessThan(1000).isNotNegative(); + } +- ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java +@@ -1,205 +1,198 @@ + package io.dropwizard.metrics5; + +-import org.junit.jupiter.api.Test; ++import static java.util.Arrays.asList; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++import static org.assertj.core.api.Assertions.offset; + + import java.io.ByteArrayOutputStream; + import java.util.Random; + import java.util.concurrent.ConcurrentSkipListSet; + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.Test; + +-import static java.util.Arrays.asList; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.offset; +-import static org.junit.jupiter.api.Assertions.assertThrows; +- +-class UniformSnapshotTest { +- private final Snapshot snapshot = new UniformSnapshot(new long[]{5, 1, 2, 3, 4}); +- +- @Test +- void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)) +- .isEqualTo(1, offset(0.1)); +- } +- +- @Test +- void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)) +- .isEqualTo(5, offset(0.1)); +- } +- +- @Test +- void disallowsNotANumberQuantile() { +- assertThrows(IllegalArgumentException.class, () -> { +- snapshot.getValue(Double.NaN); +- }); +- } +- +- @Test +- void disallowsNegativeQuantile() { +- assertThrows(IllegalArgumentException.class, () -> { +- snapshot.getValue(-0.5); +- }); +- } +- +- @Test +- void disallowsQuantileOverOne() { +- assertThrows(IllegalArgumentException.class, () -> { +- snapshot.getValue(1.5); +- }); +- } +- +- @Test +- void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); +- } +- +- @Test +- void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); +- } +- +- @Test +- void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); +- } +- +- @Test +- void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); +- } +- +- @Test +- void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); +- } +- +- @Test +- void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); +- } +- +- @Test +- void hasValues() { +- assertThat(snapshot.getValues()) +- .containsOnly(1, 2, 3, 4, 5); +- } +- +- @Test +- void hasASize() { +- assertThat(snapshot.size()) +- .isEqualTo(5); +- } +- +- @Test +- void canAlsoBeCreatedFromACollectionOfLongs() { +- final Snapshot other = new UniformSnapshot(asList(5L, 1L, 2L, 3L, 4L)); +- +- assertThat(other.getValues()) +- .containsOnly(1, 2, 3, 4, 5); +- } +- +- @Test +- void correctlyCreatedFromCollectionWithWeakIterator() throws Exception { +- final ConcurrentSkipListSet values = new ConcurrentSkipListSet<>(); +- +- // Create a latch to make sure that the background thread has started and +- // pushed some data to the collection. +- final CountDownLatch latch = new CountDownLatch(10); +- final Thread backgroundThread = new Thread(() -> { +- final Random random = new Random(); +- // Update the collection in the loop to trigger a potential `ArrayOutOfBoundException` +- // and verify that the snapshot doesn't make assumptions about the size of the iterator. +- while (!Thread.currentThread().isInterrupted()) { ++final class UniformSnapshotTest { ++ private final Snapshot snapshot = new UniformSnapshot(new long[] {5, 1, 2, 3, 4}); ++ ++ @Test ++ void smallQuantilesAreTheFirstValue() { ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1)); ++ } ++ ++ @Test ++ void bigQuantilesAreTheLastValue() { ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1)); ++ } ++ ++ @Test ++ void disallowsNotANumberQuantile() { ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(Double.NaN); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void disallowsNegativeQuantile() { ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(-0.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void disallowsQuantileOverOne() { ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(1.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void hasAMedian() { ++ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp75() { ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp95() { ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp98() { ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp99() { ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp999() { ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasValues() { ++ assertThat(snapshot.getValues()).containsOnly(1, 2, 3, 4, 5); ++ } ++ ++ @Test ++ void hasASize() { ++ assertThat(snapshot.size()).isEqualTo(5); ++ } ++ ++ @Test ++ void canAlsoBeCreatedFromACollectionOfLongs() { ++ final Snapshot other = new UniformSnapshot(asList(5L, 1L, 2L, 3L, 4L)); ++ ++ assertThat(other.getValues()).containsOnly(1, 2, 3, 4, 5); ++ } ++ ++ @Test ++ void correctlyCreatedFromCollectionWithWeakIterator() throws Exception { ++ final ConcurrentSkipListSet values = new ConcurrentSkipListSet<>(); ++ ++ // Create a latch to make sure that the background thread has started and ++ // pushed some data to the collection. ++ final CountDownLatch latch = new CountDownLatch(10); ++ final Thread backgroundThread = ++ new Thread( ++ () -> { ++ final Random random = new Random(); ++ // Update the collection in the loop to trigger a potential `ArrayOutOfBoundException` ++ // and verify that the snapshot doesn't make assumptions about the size of the ++ // iterator. ++ while (!Thread.currentThread().isInterrupted()) { + values.add(random.nextLong()); + latch.countDown(); +- } +- }); +- backgroundThread.start(); +- +- try { +- latch.await(5, TimeUnit.SECONDS); +- assertThat(latch.getCount()).isEqualTo(0); +- +- // Create a snapshot while the collection is being updated. +- final Snapshot snapshot = new UniformSnapshot(values); +- assertThat(snapshot.getValues().length).isGreaterThanOrEqualTo(10); +- } finally { +- backgroundThread.interrupt(); +- } ++ } ++ }); ++ backgroundThread.start(); ++ ++ try { ++ latch.await(5, TimeUnit.SECONDS); ++ assertThat(latch.getCount()).isEqualTo(0); ++ ++ // Create a snapshot while the collection is being updated. ++ final Snapshot snapshot = new UniformSnapshot(values); ++ assertThat(snapshot.getValues().length).isGreaterThanOrEqualTo(10); ++ } finally { ++ backgroundThread.interrupt(); + } ++ } + +- @Test +- void dumpsToAStream() { +- final ByteArrayOutputStream output = new ByteArrayOutputStream(); ++ @Test ++ void dumpsToAStream() { ++ final ByteArrayOutputStream output = new ByteArrayOutputStream(); + +- snapshot.dump(output); ++ snapshot.dump(output); + +- assertThat(output.toString()) +- .isEqualTo(String.format("1%n2%n3%n4%n5%n")); +- } ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); ++ } + +- @Test +- void calculatesTheMinimumValue() { +- assertThat(snapshot.getMin()) +- .isEqualTo(1); +- } ++ @Test ++ void calculatesTheMinimumValue() { ++ assertThat(snapshot.getMin()).isEqualTo(1); ++ } + +- @Test +- void calculatesTheMaximumValue() { +- assertThat(snapshot.getMax()) +- .isEqualTo(5); +- } ++ @Test ++ void calculatesTheMaximumValue() { ++ assertThat(snapshot.getMax()).isEqualTo(5); ++ } + +- @Test +- void calculatesTheMeanValue() { +- assertThat(snapshot.getMean()) +- .isEqualTo(3.0); +- } ++ @Test ++ void calculatesTheMeanValue() { ++ assertThat(snapshot.getMean()).isEqualTo(3.0); ++ } + +- @Test +- void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()) +- .isEqualTo(1.5811, offset(0.0001)); +- } ++ @Test ++ void calculatesTheStdDev() { ++ assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001)); ++ } + +- @Test +- void calculatesAMinOfZeroForAnEmptySnapshot() { +- final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); ++ @Test ++ void calculatesAMinOfZeroForAnEmptySnapshot() { ++ final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMin()) +- .isZero(); +- } ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); ++ } + +- @Test +- void calculatesAMaxOfZeroForAnEmptySnapshot() { +- final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); ++ @Test ++ void calculatesAMaxOfZeroForAnEmptySnapshot() { ++ final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMax()) +- .isZero(); +- } ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); ++ } + +- @Test +- void calculatesAMeanOfZeroForAnEmptySnapshot() { +- final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); ++ @Test ++ void calculatesAMeanOfZeroForAnEmptySnapshot() { ++ final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMean()) +- .isZero(); +- } ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); ++ } + +- @Test +- void calculatesAStdDevOfZeroForAnEmptySnapshot() { +- final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); ++ @Test ++ void calculatesAStdDevOfZeroForAnEmptySnapshot() { ++ final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getStdDev()) +- .isZero(); +- } ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); ++ } + +- @Test +- void calculatesAStdDevOfZeroForASingletonSnapshot() { +- final Snapshot singleItemSnapshot = new UniformSnapshot(new long[]{1}); ++ @Test ++ void calculatesAStdDevOfZeroForASingletonSnapshot() { ++ final Snapshot singleItemSnapshot = new UniformSnapshot(new long[] {1}); + +- assertThat(singleItemSnapshot.getStdDev()) +- .isZero(); +- } ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); ++ } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java +@@ -1,235 +1,232 @@ + package io.dropwizard.metrics5; + +-import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; +-import org.junit.jupiter.api.Test; +-import org.mockito.ArgumentMatchers; +- +-import java.io.ByteArrayOutputStream; +-import java.util.ArrayList; +-import java.util.List; +- ++import static com.google.common.base.Preconditions.checkArgument; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.assertj.core.api.Assertions.offset; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.mockito.ArgumentMatchers.any; + import static org.mockito.Mockito.doReturn; + import static org.mockito.Mockito.spy; + import static org.mockito.Mockito.when; + +-class WeightedSnapshotTest { +- +- private static List weightedArray(long[] values, double[] weights) { +- if (values.length != weights.length) { +- throw new IllegalArgumentException("Mismatched lengths: " + values.length + " vs " + weights.length); +- } +- +- final List samples = new ArrayList<>(); +- for (int i = 0; i < values.length; i++) { +- samples.add(new WeightedSnapshot.WeightedSample(values[i], weights[i])); +- } +- +- return samples; +- } +- +- private final Snapshot snapshot = new WeightedSnapshot( +- weightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2})); +- +- @Test +- void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)) +- .isEqualTo(1.0, offset(0.1)); +- } +- +- @Test +- void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)) +- .isEqualTo(5.0, offset(0.1)); +- } +- +- @Test +- void disallowsNotANumberQuantile() { +- assertThrows(IllegalArgumentException.class, () -> { +- snapshot.getValue(Double.NaN); +- }); +- } +- +- @Test +- void disallowsNegativeQuantile() { +- assertThrows(IllegalArgumentException.class, () -> { +- snapshot.getValue(-0.5); +- }); +- } +- +- @Test +- void disallowsQuantileOverOne() { +- assertThrows(IllegalArgumentException.class, () -> { +- snapshot.getValue(1.5); +- }); +- } +- +- @Test +- void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); +- } +- +- @Test +- void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); +- } +- +- @Test +- void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); +- } +- +- @Test +- void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); +- } +- +- @Test +- void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); +- } +- +- @Test +- void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); +- } +- +- @Test +- void hasValues() { +- assertThat(snapshot.getValues()) +- .containsOnly(1, 2, 3, 4, 5); +- } +- +- @Test +- void hasASize() { +- assertThat(snapshot.size()) +- .isEqualTo(5); +- } +- +- @Test +- void worksWithUnderestimatedCollections() { +- final List originalItems = weightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2}); +- final List spyItems = spy(originalItems); +- doReturn(originalItems.toArray(new WeightedSample[]{})).when(spyItems).toArray(ArgumentMatchers.any(WeightedSample[].class)); +- when(spyItems.size()).thenReturn(4, 5); +- +- final Snapshot other = new WeightedSnapshot(spyItems); +- +- assertThat(other.getValues()) +- .containsOnly(1, 2, 3, 4, 5); +- } +- +- @Test +- void worksWithOverestimatedCollections() { +- final List originalItems = weightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2}); +- final List spyItems = spy(originalItems); +- doReturn(originalItems.toArray(new WeightedSample[]{})).when(spyItems).toArray(ArgumentMatchers.any(WeightedSample[].class)); +- when(spyItems.size()).thenReturn(6, 5); +- +- final Snapshot other = new WeightedSnapshot(spyItems); +- +- assertThat(other.getValues()) +- .containsOnly(1, 2, 3, 4, 5); +- } +- +- @Test +- void dumpsToAStream() { +- final ByteArrayOutputStream output = new ByteArrayOutputStream(); +- +- snapshot.dump(output); +- +- assertThat(output.toString()) +- .isEqualTo(String.format("1%n2%n3%n4%n5%n")); +- } +- +- @Test +- void calculatesTheMinimumValue() { +- assertThat(snapshot.getMin()) +- .isEqualTo(1); +- } +- +- @Test +- void calculatesTheMaximumValue() { +- assertThat(snapshot.getMax()) +- .isEqualTo(5); +- } +- +- @Test +- void calculatesTheMeanValue() { +- assertThat(snapshot.getMean()) +- .isEqualTo(2.7); +- } +- +- @Test +- void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()) +- .isEqualTo(1.2688, offset(0.0001)); +- } +- +- @Test +- void calculatesAMinOfZeroForAnEmptySnapshot() { +- final Snapshot emptySnapshot = new WeightedSnapshot( +- weightedArray(new long[]{}, new double[]{})); +- +- assertThat(emptySnapshot.getMin()) +- .isZero(); +- } +- +- @Test +- void calculatesAMaxOfZeroForAnEmptySnapshot() { +- final Snapshot emptySnapshot = new WeightedSnapshot( +- weightedArray(new long[]{}, new double[]{})); +- +- assertThat(emptySnapshot.getMax()) +- .isZero(); +- } +- +- @Test +- void calculatesAMeanOfZeroForAnEmptySnapshot() { +- final Snapshot emptySnapshot = new WeightedSnapshot( +- weightedArray(new long[]{}, new double[]{})); +- +- assertThat(emptySnapshot.getMean()) +- .isZero(); +- } +- +- @Test +- void calculatesAStdDevOfZeroForAnEmptySnapshot() { +- final Snapshot emptySnapshot = new WeightedSnapshot( +- weightedArray(new long[]{}, new double[]{})); +- +- assertThat(emptySnapshot.getStdDev()) +- .isZero(); +- } +- +- @Test +- void calculatesAStdDevOfZeroForASingletonSnapshot() { +- final Snapshot singleItemSnapshot = new WeightedSnapshot( +- weightedArray(new long[]{1}, new double[]{1.0})); +- +- assertThat(singleItemSnapshot.getStdDev()) +- .isZero(); +- } +- +- @Test +- void expectNoOverflowForLowWeights() { +- final Snapshot scatteredSnapshot = new WeightedSnapshot( +- weightedArray( +- new long[]{1, 2, 3}, +- new double[]{Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE} +- ) +- ); +- +- assertThat(scatteredSnapshot.getMean()) +- .isEqualTo(2); +- } ++import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; ++import java.io.ByteArrayOutputStream; ++import java.util.ArrayList; ++import java.util.List; ++import org.junit.jupiter.api.Test; + +- @Test +- void doesNotProduceNaNValues() { +- WeightedSnapshot weightedSnapshot = new WeightedSnapshot( +- weightedArray(new long[]{1, 2, 3}, new double[]{0, 0, 0})); +- assertThat(weightedSnapshot.getMean()).isEqualTo(0); +- } ++final class WeightedSnapshotTest { ++ ++ private static List weightedArray( ++ long[] values, double[] weights) { ++ checkArgument( ++ values.length == weights.length, ++ "Mismatched lengths: %s vs %s", ++ values.length, ++ weights.length); ++ ++ final List samples = new ArrayList<>(); ++ for (int i = 0; i < values.length; i++) { ++ samples.add(new WeightedSnapshot.WeightedSample(values[i], weights[i])); ++ } ++ ++ return samples; ++ } ++ ++ private final Snapshot snapshot = ++ new WeightedSnapshot(weightedArray(new long[] {5, 1, 2, 3, 4}, new double[] {1, 2, 3, 2, 2})); ++ ++ @Test ++ void smallQuantilesAreTheFirstValue() { ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1)); ++ } ++ ++ @Test ++ void bigQuantilesAreTheLastValue() { ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1)); ++ } ++ ++ @Test ++ void disallowsNotANumberQuantile() { ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(Double.NaN); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void disallowsNegativeQuantile() { ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(-0.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void disallowsQuantileOverOne() { ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(1.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void hasAMedian() { ++ assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp75() { ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp95() { ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp98() { ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp99() { ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasAp999() { ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); ++ } ++ ++ @Test ++ void hasValues() { ++ assertThat(snapshot.getValues()).containsOnly(1, 2, 3, 4, 5); ++ } ++ ++ @Test ++ void hasASize() { ++ assertThat(snapshot.size()).isEqualTo(5); ++ } ++ ++ @Test ++ void worksWithUnderestimatedCollections() { ++ final List originalItems = ++ weightedArray(new long[] {5, 1, 2, 3, 4}, new double[] {1, 2, 3, 2, 2}); ++ final List spyItems = spy(originalItems); ++ doReturn(originalItems.toArray(new WeightedSample[] {})) ++ .when(spyItems) ++ .toArray(any(WeightedSample[].class)); ++ when(spyItems.size()).thenReturn(4, 5); ++ ++ final Snapshot other = new WeightedSnapshot(spyItems); ++ ++ assertThat(other.getValues()).containsOnly(1, 2, 3, 4, 5); ++ } ++ ++ @Test ++ void worksWithOverestimatedCollections() { ++ final List originalItems = ++ weightedArray(new long[] {5, 1, 2, 3, 4}, new double[] {1, 2, 3, 2, 2}); ++ final List spyItems = spy(originalItems); ++ doReturn(originalItems.toArray(new WeightedSample[] {})) ++ .when(spyItems) ++ .toArray(any(WeightedSample[].class)); ++ when(spyItems.size()).thenReturn(6, 5); ++ ++ final Snapshot other = new WeightedSnapshot(spyItems); ++ ++ assertThat(other.getValues()).containsOnly(1, 2, 3, 4, 5); ++ } ++ ++ @Test ++ void dumpsToAStream() { ++ final ByteArrayOutputStream output = new ByteArrayOutputStream(); ++ ++ snapshot.dump(output); ++ ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); ++ } ++ ++ @Test ++ void calculatesTheMinimumValue() { ++ assertThat(snapshot.getMin()).isEqualTo(1); ++ } ++ ++ @Test ++ void calculatesTheMaximumValue() { ++ assertThat(snapshot.getMax()).isEqualTo(5); ++ } ++ ++ @Test ++ void calculatesTheMeanValue() { ++ assertThat(snapshot.getMean()).isEqualTo(2.7); ++ } ++ ++ @Test ++ void calculatesTheStdDev() { ++ assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001)); ++ } ++ ++ @Test ++ void calculatesAMinOfZeroForAnEmptySnapshot() { ++ final Snapshot emptySnapshot = ++ new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); ++ ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); ++ } ++ ++ @Test ++ void calculatesAMaxOfZeroForAnEmptySnapshot() { ++ final Snapshot emptySnapshot = ++ new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); ++ ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); ++ } ++ ++ @Test ++ void calculatesAMeanOfZeroForAnEmptySnapshot() { ++ final Snapshot emptySnapshot = ++ new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); ++ ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); ++ } ++ ++ @Test ++ void calculatesAStdDevOfZeroForAnEmptySnapshot() { ++ final Snapshot emptySnapshot = ++ new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); ++ ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); ++ } ++ ++ @Test ++ void calculatesAStdDevOfZeroForASingletonSnapshot() { ++ final Snapshot singleItemSnapshot = ++ new WeightedSnapshot(weightedArray(new long[] {1}, new double[] {1.0})); ++ ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); ++ } ++ ++ @Test ++ void expectNoOverflowForLowWeights() { ++ final Snapshot scatteredSnapshot = ++ new WeightedSnapshot( ++ weightedArray( ++ new long[] {1, 2, 3}, ++ new double[] {Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE})); ++ ++ assertThat(scatteredSnapshot.getMean()).isEqualTo(2); ++ } ++ ++ @Test ++ void doesNotProduceNaNValues() { ++ WeightedSnapshot weightedSnapshot = ++ new WeightedSnapshot(weightedArray(new long[] {1, 2, 3}, new double[] {0, 0, 0})); ++ assertThat(weightedSnapshot.getMean()).isEqualTo(0); ++ } + } +--- a/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactory.java ++++ b/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactory.java +@@ -2,23 +2,22 @@ package io.dropwizard.metrics5.ehcache; + + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.SharedMetricRegistries; ++import java.util.Properties; + import net.sf.ehcache.Ehcache; + import net.sf.ehcache.constructs.CacheDecoratorFactory; + +-import java.util.Properties; +- + public class InstrumentedCacheDecoratorFactory extends CacheDecoratorFactory { +- @Override +- public Ehcache createDecoratedEhcache(Ehcache cache, Properties properties) { +- final String name = properties.getProperty("metric-registry-name"); +- final MetricRegistry registry = SharedMetricRegistries.getOrCreate(name); +- return InstrumentedEhcache.instrument(registry, cache); +- } ++ @Override ++ public Ehcache createDecoratedEhcache(Ehcache cache, Properties properties) { ++ final String name = properties.getProperty("metric-registry-name"); ++ final MetricRegistry registry = SharedMetricRegistries.getOrCreate(name); ++ return InstrumentedEhcache.instrument(registry, cache); ++ } + +- @Override +- public Ehcache createDefaultDecoratedEhcache(Ehcache cache, Properties properties) { +- final String name = properties.getProperty("metric-registry-name"); +- final MetricRegistry registry = SharedMetricRegistries.getOrCreate(name); +- return InstrumentedEhcache.instrument(registry, cache); +- } ++ @Override ++ public Ehcache createDefaultDecoratedEhcache(Ehcache cache, Properties properties) { ++ final String name = properties.getProperty("metric-registry-name"); ++ final MetricRegistry registry = SharedMetricRegistries.getOrCreate(name); ++ return InstrumentedEhcache.instrument(registry, cache); ++ } + } +--- a/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcache.java ++++ b/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcache.java +@@ -1,232 +1,233 @@ + package io.dropwizard.metrics5.ehcache; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; ++import java.io.Serializable; + import net.sf.ehcache.CacheException; + import net.sf.ehcache.Ehcache; + import net.sf.ehcache.Element; + import net.sf.ehcache.constructs.EhcacheDecoratorAdapter; + import net.sf.ehcache.statistics.StatisticsGateway; + +-import java.io.Serializable; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +- +-/** +- * An instrumented {@link Ehcache} instance. +- */ ++/** An instrumented {@link Ehcache} instance. */ + public class InstrumentedEhcache extends EhcacheDecoratorAdapter { +- /** +- * Instruments the given {@link Ehcache} instance with get and put timers +- * and a set of gauges for Ehcache's built-in statistics: +- *

+- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- *
Ehcache timered metrics
{@code hits}The number of times a requested item was found in the +- * cache.
{@code in-memory-hits}Number of times a requested item was found in the memory +- * store.
{@code off-heap-hits}Number of times a requested item was found in the off-heap +- * store.
{@code on-disk-hits}Number of times a requested item was found in the disk +- * store.
{@code misses}Number of times a requested item was not found in the +- * cache.
{@code in-memory-misses}Number of times a requested item was not found in the memory +- * store.
{@code off-heap-misses}Number of times a requested item was not found in the +- * off-heap store.
{@code on-disk-misses}Number of times a requested item was not found in the disk +- * store.
{@code objects}Number of elements stored in the cache.
{@code in-memory-objects}Number of objects in the memory store.
{@code off-heap-objects}Number of objects in the off-heap store.
{@code on-disk-objects}Number of objects in the disk store.
{@code mean-get-time}The average get time. Because ehcache support JDK1.4.2, each +- * get time uses {@link System#currentTimeMillis()}, rather than +- * nanoseconds. The accuracy is thus limited.
{@code mean-search-time}The average execution time (in milliseconds) within the last +- * sample period.
{@code eviction-count}The number of cache evictions, since the cache was created, +- * or statistics were cleared.
{@code searches-per-second}The number of search executions that have completed in the +- * last second.
{@code accuracy}A human readable description of the accuracy setting. One of +- * "None", "Best Effort" or "Guaranteed".
+- *

+- * N.B.: This enables Ehcache's sampling statistics with an accuracy +- * level of "none." +- * +- * @param cache an {@link Ehcache} instance +- * @param registry a {@link MetricRegistry} +- * @return an instrumented decorator for {@code cache} +- * @see StatisticsGateway +- */ +- public static Ehcache instrument(MetricRegistry registry, final Ehcache cache) { +- +- final MetricName prefix = name(cache.getClass(), cache.getName()); +- registry.registerGauge(prefix.resolve("hits"), +- () -> cache.getStatistics().cacheHitCount()); +- +- registry.registerGauge(prefix.resolve("in-memory-hits"), +- () -> cache.getStatistics().localHeapHitCount()); +- +- registry.registerGauge(prefix.resolve("off-heap-hits"), +- () -> cache.getStatistics().localOffHeapHitCount()); +- +- registry.registerGauge(prefix.resolve("on-disk-hits"), +- () -> cache.getStatistics().localDiskHitCount()); +- +- registry.registerGauge(prefix.resolve("misses"), +- () -> cache.getStatistics().cacheMissCount()); +- +- registry.registerGauge(prefix.resolve("in-memory-misses"), +- () -> cache.getStatistics().localHeapMissCount()); +- +- registry.registerGauge(prefix.resolve("off-heap-misses"), +- () -> cache.getStatistics().localOffHeapMissCount()); +- +- registry.registerGauge(prefix.resolve("on-disk-misses"), +- () -> cache.getStatistics().localDiskMissCount()); +- +- registry.registerGauge(prefix.resolve("objects"), +- () -> cache.getStatistics().getSize()); +- +- registry.registerGauge(prefix.resolve("in-memory-objects"), +- () -> cache.getStatistics().getLocalHeapSize()); +- +- registry.registerGauge(prefix.resolve("off-heap-objects"), +- () -> cache.getStatistics().getLocalOffHeapSize()); +- +- registry.registerGauge(prefix.resolve("on-disk-objects"), +- () -> cache.getStatistics().getLocalDiskSize()); +- +- registry.registerGauge(prefix.resolve("mean-get-time"), +- () -> cache.getStatistics().cacheGetOperation().latency().average().value()); +- +- registry.registerGauge(prefix.resolve("mean-search-time"), +- () -> cache.getStatistics().cacheSearchOperation().latency().average().value()); +- +- registry.registerGauge(prefix.resolve("eviction-count"), +- () -> cache.getStatistics().cacheEvictionOperation().count().value()); +- +- registry.registerGauge(prefix.resolve("searches-per-second"), +- () -> cache.getStatistics().cacheSearchOperation().rate().value()); +- +- registry.registerGauge(prefix.resolve("writer-queue-size"), +- () -> cache.getStatistics().getWriterQueueLength()); +- +- return new InstrumentedEhcache(registry, cache); +- } +- +- private final Timer getTimer, putTimer; +- +- private InstrumentedEhcache(MetricRegistry registry, Ehcache cache) { +- super(cache); +- this.getTimer = registry.timer(MetricRegistry.name(cache.getClass(), cache.getName(), "gets")); +- this.putTimer = registry.timer(MetricRegistry.name(cache.getClass(), cache.getName(), "puts")); +- } +- +- @Override +- public Element get(Object key) throws IllegalStateException, CacheException { +- final Timer.Context ctx = getTimer.time(); +- try { +- return underlyingCache.get(key); +- } finally { +- ctx.stop(); +- } ++ /** ++ * Instruments the given {@link Ehcache} instance with get and put timers and a set of gauges for ++ * Ehcache's built-in statistics: ++ * ++ *

++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ *
Ehcache timered metrics
{@code hits}The number of times a requested item was found in the ++ * cache.
{@code in-memory-hits}Number of times a requested item was found in the memory ++ * store.
{@code off-heap-hits}Number of times a requested item was found in the off-heap ++ * store.
{@code on-disk-hits}Number of times a requested item was found in the disk ++ * store.
{@code misses}Number of times a requested item was not found in the ++ * cache.
{@code in-memory-misses}Number of times a requested item was not found in the memory ++ * store.
{@code off-heap-misses}Number of times a requested item was not found in the ++ * off-heap store.
{@code on-disk-misses}Number of times a requested item was not found in the disk ++ * store.
{@code objects}Number of elements stored in the cache.
{@code in-memory-objects}Number of objects in the memory store.
{@code off-heap-objects}Number of objects in the off-heap store.
{@code on-disk-objects}Number of objects in the disk store.
{@code mean-get-time}The average get time. Because ehcache support JDK1.4.2, each ++ * get time uses {@link System#currentTimeMillis()}, rather than ++ * nanoseconds. The accuracy is thus limited.
{@code mean-search-time}The average execution time (in milliseconds) within the last ++ * sample period.
{@code eviction-count}The number of cache evictions, since the cache was created, ++ * or statistics were cleared.
{@code searches-per-second}The number of search executions that have completed in the ++ * last second.
{@code accuracy}A human readable description of the accuracy setting. One of ++ * "None", "Best Effort" or "Guaranteed".
++ * ++ *

N.B.: This enables Ehcache's sampling statistics with an accuracy level of "none." ++ * ++ * @param cache an {@link Ehcache} instance ++ * @param registry a {@link MetricRegistry} ++ * @return an instrumented decorator for {@code cache} ++ * @see StatisticsGateway ++ */ ++ public static Ehcache instrument(MetricRegistry registry, final Ehcache cache) { ++ ++ final MetricName prefix = name(cache.getClass(), cache.getName()); ++ registry.registerGauge(prefix.resolve("hits"), () -> cache.getStatistics().cacheHitCount()); ++ ++ registry.registerGauge( ++ prefix.resolve("in-memory-hits"), () -> cache.getStatistics().localHeapHitCount()); ++ ++ registry.registerGauge( ++ prefix.resolve("off-heap-hits"), () -> cache.getStatistics().localOffHeapHitCount()); ++ ++ registry.registerGauge( ++ prefix.resolve("on-disk-hits"), () -> cache.getStatistics().localDiskHitCount()); ++ ++ registry.registerGauge(prefix.resolve("misses"), () -> cache.getStatistics().cacheMissCount()); ++ ++ registry.registerGauge( ++ prefix.resolve("in-memory-misses"), () -> cache.getStatistics().localHeapMissCount()); ++ ++ registry.registerGauge( ++ prefix.resolve("off-heap-misses"), () -> cache.getStatistics().localOffHeapMissCount()); ++ ++ registry.registerGauge( ++ prefix.resolve("on-disk-misses"), () -> cache.getStatistics().localDiskMissCount()); ++ ++ registry.registerGauge(prefix.resolve("objects"), () -> cache.getStatistics().getSize()); ++ ++ registry.registerGauge( ++ prefix.resolve("in-memory-objects"), () -> cache.getStatistics().getLocalHeapSize()); ++ ++ registry.registerGauge( ++ prefix.resolve("off-heap-objects"), () -> cache.getStatistics().getLocalOffHeapSize()); ++ ++ registry.registerGauge( ++ prefix.resolve("on-disk-objects"), () -> cache.getStatistics().getLocalDiskSize()); ++ ++ registry.registerGauge( ++ prefix.resolve("mean-get-time"), ++ () -> cache.getStatistics().cacheGetOperation().latency().average().value()); ++ ++ registry.registerGauge( ++ prefix.resolve("mean-search-time"), ++ () -> cache.getStatistics().cacheSearchOperation().latency().average().value()); ++ ++ registry.registerGauge( ++ prefix.resolve("eviction-count"), ++ () -> cache.getStatistics().cacheEvictionOperation().count().value()); ++ ++ registry.registerGauge( ++ prefix.resolve("searches-per-second"), ++ () -> cache.getStatistics().cacheSearchOperation().rate().value()); ++ ++ registry.registerGauge( ++ prefix.resolve("writer-queue-size"), () -> cache.getStatistics().getWriterQueueLength()); ++ ++ return new InstrumentedEhcache(registry, cache); ++ } ++ ++ private final Timer getTimer, putTimer; ++ ++ private InstrumentedEhcache(MetricRegistry registry, Ehcache cache) { ++ super(cache); ++ this.getTimer = registry.timer(MetricRegistry.name(cache.getClass(), cache.getName(), "gets")); ++ this.putTimer = registry.timer(MetricRegistry.name(cache.getClass(), cache.getName(), "puts")); ++ } ++ ++ @Override ++ public Element get(Object key) throws IllegalStateException, CacheException { ++ final Timer.Context ctx = getTimer.time(); ++ try { ++ return underlyingCache.get(key); ++ } finally { ++ ctx.stop(); + } +- +- @Override +- public Element get(Serializable key) throws IllegalStateException, CacheException { +- final Timer.Context ctx = getTimer.time(); +- try { +- return underlyingCache.get(key); +- } finally { +- ctx.stop(); +- } ++ } ++ ++ @Override ++ public Element get(Serializable key) throws IllegalStateException, CacheException { ++ final Timer.Context ctx = getTimer.time(); ++ try { ++ return underlyingCache.get(key); ++ } finally { ++ ctx.stop(); + } +- +- @Override +- public void put(Element element) throws IllegalArgumentException, IllegalStateException, CacheException { +- final Timer.Context ctx = putTimer.time(); +- try { +- underlyingCache.put(element); +- } finally { +- ctx.stop(); +- } ++ } ++ ++ @Override ++ public void put(Element element) ++ throws IllegalArgumentException, IllegalStateException, CacheException { ++ final Timer.Context ctx = putTimer.time(); ++ try { ++ underlyingCache.put(element); ++ } finally { ++ ctx.stop(); + } +- +- @Override +- public void put(Element element, boolean doNotNotifyCacheReplicators) throws IllegalArgumentException, IllegalStateException, CacheException { +- final Timer.Context ctx = putTimer.time(); +- try { +- underlyingCache.put(element, doNotNotifyCacheReplicators); +- } finally { +- ctx.stop(); +- } ++ } ++ ++ @Override ++ public void put(Element element, boolean doNotNotifyCacheReplicators) ++ throws IllegalArgumentException, IllegalStateException, CacheException { ++ final Timer.Context ctx = putTimer.time(); ++ try { ++ underlyingCache.put(element, doNotNotifyCacheReplicators); ++ } finally { ++ ctx.stop(); + } +- +- @Override +- public Element putIfAbsent(Element element) throws NullPointerException { +- final Timer.Context ctx = putTimer.time(); +- try { +- return underlyingCache.putIfAbsent(element); +- } finally { +- ctx.stop(); +- } ++ } ++ ++ @Override ++ public Element putIfAbsent(Element element) throws NullPointerException { ++ final Timer.Context ctx = putTimer.time(); ++ try { ++ return underlyingCache.putIfAbsent(element); ++ } finally { ++ ctx.stop(); + } ++ } + } +--- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java ++++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java +@@ -1,5 +1,8 @@ + package io.dropwizard.metrics5.ehcache; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assumptions.assumeThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.SharedMetricRegistries; + import net.sf.ehcache.Cache; +@@ -9,37 +12,33 @@ import net.sf.ehcache.Element; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assumptions.assumeThat; +- +-class InstrumentedCacheDecoratorFactoryTest { +- private static final CacheManager MANAGER = CacheManager.create(); +- +- private MetricRegistry registry; +- private Ehcache cache; ++final class InstrumentedCacheDecoratorFactoryTest { ++ private static final CacheManager MANAGER = CacheManager.create(); + +- @BeforeEach +- void setUp() { +- this.cache = MANAGER.getEhcache("test-config"); +- assumeThat(cache).isNotNull(); ++ private MetricRegistry registry; ++ private Ehcache cache; + +- this.registry = SharedMetricRegistries.getOrCreate("cache-metrics"); +- } ++ @BeforeEach ++ void setUp() { ++ this.cache = MANAGER.getEhcache("test-config"); ++ assumeThat(cache).isNotNull(); + +- @Test +- void measuresGets() { +- cache.get("woo"); ++ this.registry = SharedMetricRegistries.getOrCreate("cache-metrics"); ++ } + +- assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "gets")).getCount()) +- .isEqualTo(1); ++ @Test ++ void measuresGets() { ++ cache.get("woo"); + +- } ++ assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "gets")).getCount()) ++ .isEqualTo(1); ++ } + +- @Test +- void measuresPuts() { +- cache.put(new Element("woo", "whee")); ++ @Test ++ void measuresPuts() { ++ cache.put(new Element("woo", "whee")); + +- assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "puts")).getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "puts")).getCount()) ++ .isEqualTo(1); ++ } + } +--- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java ++++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java +@@ -1,5 +1,8 @@ + package io.dropwizard.metrics5.ehcache; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.entry; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import net.sf.ehcache.Cache; +@@ -10,57 +13,52 @@ import net.sf.ehcache.config.CacheConfiguration; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.entry; +- +-class InstrumentedEhcacheTest { +- private static final CacheManager MANAGER = CacheManager.create(); ++final class InstrumentedEhcacheTest { ++ private static final CacheManager MANAGER = CacheManager.create(); + +- private final MetricRegistry registry = new MetricRegistry(); +- private Ehcache cache; ++ private final MetricRegistry registry = new MetricRegistry(); ++ private Ehcache cache; + +- @BeforeEach +- void setUp() { +- final Cache c = new Cache(new CacheConfiguration("test", 100)); +- MANAGER.addCache(c); +- this.cache = InstrumentedEhcache.instrument(registry, c); +- assertThat(registry.getGauges().entrySet().stream() ++ @BeforeEach ++ void setUp() { ++ final Cache c = new Cache(new CacheConfiguration("test", 100)); ++ MANAGER.addCache(c); ++ this.cache = InstrumentedEhcache.instrument(registry, c); ++ assertThat( ++ registry.getGauges().entrySet().stream() + .map(e -> entry(e.getKey().getKey(), (Number) e.getValue().getValue()))) +- .containsOnly( +- entry("net.sf.ehcache.Cache.test.eviction-count", 0L), +- entry("net.sf.ehcache.Cache.test.hits", 0L), +- entry("net.sf.ehcache.Cache.test.in-memory-hits", 0L), +- entry("net.sf.ehcache.Cache.test.in-memory-misses", 0L), +- entry("net.sf.ehcache.Cache.test.in-memory-objects", 0L), +- entry("net.sf.ehcache.Cache.test.mean-get-time", Double.NaN), +- entry("net.sf.ehcache.Cache.test.mean-search-time", Double.NaN), +- entry("net.sf.ehcache.Cache.test.misses", 0L), +- entry("net.sf.ehcache.Cache.test.objects", 0L), +- entry("net.sf.ehcache.Cache.test.off-heap-hits", 0L), +- entry("net.sf.ehcache.Cache.test.off-heap-misses", 0L), +- entry("net.sf.ehcache.Cache.test.off-heap-objects", 0L), +- entry("net.sf.ehcache.Cache.test.on-disk-hits", 0L), +- entry("net.sf.ehcache.Cache.test.on-disk-misses", 0L), +- entry("net.sf.ehcache.Cache.test.on-disk-objects", 0L), +- entry("net.sf.ehcache.Cache.test.searches-per-second", 0.0), +- entry("net.sf.ehcache.Cache.test.writer-queue-size", 0L) +- ); +- } ++ .containsOnly( ++ entry("net.sf.ehcache.Cache.test.eviction-count", 0L), ++ entry("net.sf.ehcache.Cache.test.hits", 0L), ++ entry("net.sf.ehcache.Cache.test.in-memory-hits", 0L), ++ entry("net.sf.ehcache.Cache.test.in-memory-misses", 0L), ++ entry("net.sf.ehcache.Cache.test.in-memory-objects", 0L), ++ entry("net.sf.ehcache.Cache.test.mean-get-time", Double.NaN), ++ entry("net.sf.ehcache.Cache.test.mean-search-time", Double.NaN), ++ entry("net.sf.ehcache.Cache.test.misses", 0L), ++ entry("net.sf.ehcache.Cache.test.objects", 0L), ++ entry("net.sf.ehcache.Cache.test.off-heap-hits", 0L), ++ entry("net.sf.ehcache.Cache.test.off-heap-misses", 0L), ++ entry("net.sf.ehcache.Cache.test.off-heap-objects", 0L), ++ entry("net.sf.ehcache.Cache.test.on-disk-hits", 0L), ++ entry("net.sf.ehcache.Cache.test.on-disk-misses", 0L), ++ entry("net.sf.ehcache.Cache.test.on-disk-objects", 0L), ++ entry("net.sf.ehcache.Cache.test.searches-per-second", 0.0), ++ entry("net.sf.ehcache.Cache.test.writer-queue-size", 0L)); ++ } + +- @Test +- void measuresGetsAndPuts() { +- cache.get("woo"); ++ @Test ++ void measuresGetsAndPuts() { ++ cache.get("woo"); + +- cache.put(new Element("woo", "whee")); ++ cache.put(new Element("woo", "whee")); + +- final Timer gets = registry.timer(MetricRegistry.name(Cache.class, "test", "gets")); ++ final Timer gets = registry.timer(MetricRegistry.name(Cache.class, "test", "gets")); + +- assertThat(gets.getCount()) +- .isEqualTo(1); ++ assertThat(gets.getCount()).isEqualTo(1); + +- final Timer puts = registry.timer(MetricRegistry.name(Cache.class, "test", "puts")); ++ final Timer puts = registry.timer(MetricRegistry.name(Cache.class, "test", "puts")); + +- assertThat(puts.getCount()) +- .isEqualTo(1); +- } ++ assertThat(puts.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java +@@ -1,9 +1,11 @@ + package io.dropwizard.metrics5.graphite; + +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; ++import static com.google.common.base.Preconditions.checkArgument; ++import static com.google.common.base.Preconditions.checkState; ++import static java.nio.charset.StandardCharsets.UTF_8; ++import static java.util.Objects.requireNonNull; + +-import javax.net.SocketFactory; ++import com.google.common.base.Strings; + import java.io.BufferedWriter; + import java.io.IOException; + import java.io.OutputStreamWriter; +@@ -12,190 +14,184 @@ import java.net.InetSocketAddress; + import java.net.Socket; + import java.net.UnknownHostException; + import java.nio.charset.Charset; ++import javax.net.SocketFactory; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + +-import static java.nio.charset.StandardCharsets.UTF_8; +-import static java.util.Objects.requireNonNull; +- +-/** +- * A client to a Carbon server via TCP. +- */ ++/** A client to a Carbon server via TCP. */ + public class Graphite implements GraphiteSender { +- // this may be optimistic about Carbon/Graphite +- +- private final String hostname; +- private final int port; +- private final InetSocketAddress address; +- private final SocketFactory socketFactory; +- private final Charset charset; +- +- private Socket socket; +- private Writer writer; +- private int failures; +- +- private static final Logger LOGGER = LoggerFactory.getLogger(Graphite.class); +- +- /** +- * Creates a new client which connects to the given address using the default +- * {@link SocketFactory}. +- * +- * @param hostname The hostname of the Carbon server +- * @param port The port of the Carbon server +- */ +- public Graphite(String hostname, int port) { +- this(hostname, port, SocketFactory.getDefault()); +- } +- +- /** +- * Creates a new client which connects to the given address and socket factory. +- * +- * @param hostname The hostname of the Carbon server +- * @param port The port of the Carbon server +- * @param socketFactory the socket factory +- */ +- public Graphite(String hostname, int port, SocketFactory socketFactory) { +- this(hostname, port, socketFactory, UTF_8); +- } +- +- /** +- * Creates a new client which connects to the given address and socket factory using the given +- * character set. +- * +- * @param hostname The hostname of the Carbon server +- * @param port The port of the Carbon server +- * @param socketFactory the socket factory +- * @param charset the character set used by the server +- */ +- public Graphite(String hostname, int port, SocketFactory socketFactory, Charset charset) { +- if (hostname == null || hostname.isEmpty()) { +- throw new IllegalArgumentException("hostname must not be null or empty"); +- } +- +- if (port < 0 || port > 65535) { +- throw new IllegalArgumentException("port must be a valid IP port (0-65535)"); +- } +- +- this.hostname = hostname; +- this.port = port; +- this.address = null; +- this.socketFactory = requireNonNull(socketFactory, "socketFactory must not be null"); +- this.charset = requireNonNull(charset, "charset must not be null"); +- } +- +- /** +- * Creates a new client which connects to the given address using the default +- * {@link SocketFactory}. +- * +- * @param address the address of the Carbon server +- */ +- public Graphite(InetSocketAddress address) { +- this(address, SocketFactory.getDefault()); +- } +- +- /** +- * Creates a new client which connects to the given address and socket factory. +- * +- * @param address the address of the Carbon server +- * @param socketFactory the socket factory +- */ +- public Graphite(InetSocketAddress address, SocketFactory socketFactory) { +- this(address, socketFactory, UTF_8); +- } +- +- /** +- * Creates a new client which connects to the given address and socket factory using the given +- * character set. +- * +- * @param address the address of the Carbon server +- * @param socketFactory the socket factory +- * @param charset the character set used by the server +- */ +- public Graphite(InetSocketAddress address, SocketFactory socketFactory, Charset charset) { +- this.hostname = null; +- this.port = -1; +- this.address = requireNonNull(address, "address must not be null"); +- this.socketFactory = requireNonNull(socketFactory, "socketFactory must not be null"); +- this.charset = requireNonNull(charset, "charset must not be null"); ++ // this may be optimistic about Carbon/Graphite ++ ++ private final String hostname; ++ private final int port; ++ private final InetSocketAddress address; ++ private final SocketFactory socketFactory; ++ private final Charset charset; ++ ++ private Socket socket; ++ private Writer writer; ++ private int failures; ++ ++ private static final Logger LOG = LoggerFactory.getLogger(Graphite.class); ++ ++ /** ++ * Creates a new client which connects to the given address using the default {@link ++ * SocketFactory}. ++ * ++ * @param hostname The hostname of the Carbon server ++ * @param port The port of the Carbon server ++ */ ++ public Graphite(String hostname, int port) { ++ this(hostname, port, SocketFactory.getDefault()); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address and socket factory. ++ * ++ * @param hostname The hostname of the Carbon server ++ * @param port The port of the Carbon server ++ * @param socketFactory the socket factory ++ */ ++ public Graphite(String hostname, int port, SocketFactory socketFactory) { ++ this(hostname, port, socketFactory, UTF_8); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address and socket factory using the given ++ * character set. ++ * ++ * @param hostname The hostname of the Carbon server ++ * @param port The port of the Carbon server ++ * @param socketFactory the socket factory ++ * @param charset the character set used by the server ++ */ ++ public Graphite(String hostname, int port, SocketFactory socketFactory, Charset charset) { ++ checkArgument(!Strings.isNullOrEmpty(hostname), "hostname must not be null or empty"); ++ ++ checkArgument(port >= 0 && port <= 65535, "port must be a valid IP port (0-65535)"); ++ ++ this.hostname = hostname; ++ this.port = port; ++ this.address = null; ++ this.socketFactory = requireNonNull(socketFactory, "socketFactory must not be null"); ++ this.charset = requireNonNull(charset, "charset must not be null"); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address using the default {@link ++ * SocketFactory}. ++ * ++ * @param address the address of the Carbon server ++ */ ++ public Graphite(InetSocketAddress address) { ++ this(address, SocketFactory.getDefault()); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address and socket factory. ++ * ++ * @param address the address of the Carbon server ++ * @param socketFactory the socket factory ++ */ ++ public Graphite(InetSocketAddress address, SocketFactory socketFactory) { ++ this(address, socketFactory, UTF_8); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address and socket factory using the given ++ * character set. ++ * ++ * @param address the address of the Carbon server ++ * @param socketFactory the socket factory ++ * @param charset the character set used by the server ++ */ ++ public Graphite(InetSocketAddress address, SocketFactory socketFactory, Charset charset) { ++ this.hostname = null; ++ this.port = -1; ++ this.address = requireNonNull(address, "address must not be null"); ++ this.socketFactory = requireNonNull(socketFactory, "socketFactory must not be null"); ++ this.charset = requireNonNull(charset, "charset must not be null"); ++ } ++ ++ @Override ++ public void connect() throws IllegalStateException, IOException { ++ checkState(!isConnected(), "Already connected"); ++ InetSocketAddress address = this.address; ++ // the previous dns retry logic did not work, as address.getAddress would always return the ++ // cached value ++ // this version of the simplified logic will always cause a dns request if hostname has been ++ // supplied. ++ // InetAddress.getByName forces the dns lookup ++ // if an InetSocketAddress was supplied at create time that will take precedence. ++ if (address == null || address.getHostName() == null && hostname != null) { ++ address = new InetSocketAddress(hostname, port); + } + +- @Override +- public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } +- InetSocketAddress address = this.address; +- // the previous dns retry logic did not work, as address.getAddress would always return the cached value +- // this version of the simplified logic will always cause a dns request if hostname has been supplied. +- // InetAddress.getByName forces the dns lookup +- // if an InetSocketAddress was supplied at create time that will take precedence. +- if (address == null || address.getHostName() == null && hostname != null) { +- address = new InetSocketAddress(hostname, port); +- } +- +- if (address.getAddress() == null) { +- throw new UnknownHostException(address.getHostName()); +- } +- +- this.socket = socketFactory.createSocket(address.getAddress(), address.getPort()); +- this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); ++ if (address.getAddress() == null) { ++ throw new UnknownHostException(address.getHostName()); + } + +- @Override +- public boolean isConnected() { +- return socket != null && socket.isConnected() && !socket.isClosed(); ++ this.socket = socketFactory.createSocket(address.getAddress(), address.getPort()); ++ this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); ++ } ++ ++ @Override ++ public boolean isConnected() { ++ return socket != null && socket.isConnected() && !socket.isClosed(); ++ } ++ ++ @Override ++ public void send(String name, String value, long timestamp) throws IOException { ++ try { ++ writer.write(sanitize(name)); ++ writer.write(' '); ++ writer.write(sanitize(value)); ++ writer.write(' '); ++ writer.write(Long.toString(timestamp)); ++ writer.write('\n'); ++ this.failures = 0; ++ } catch (IOException e) { ++ failures++; ++ throw e; + } ++ } + +- @Override +- public void send(String name, String value, long timestamp) throws IOException { +- try { +- writer.write(sanitize(name)); +- writer.write(' '); +- writer.write(sanitize(value)); +- writer.write(' '); +- writer.write(Long.toString(timestamp)); +- writer.write('\n'); +- this.failures = 0; +- } catch (IOException e) { +- failures++; +- throw e; +- } +- } ++ @Override ++ public int getFailures() { ++ return failures; ++ } + +- @Override +- public int getFailures() { +- return failures; ++ @Override ++ public void flush() throws IOException { ++ if (writer != null) { ++ writer.flush(); + } +- +- @Override +- public void flush() throws IOException { +- if (writer != null) { +- writer.flush(); +- } ++ } ++ ++ @Override ++ public void close() throws IOException { ++ try { ++ if (writer != null) { ++ writer.close(); ++ } ++ } catch (IOException ex) { ++ LOG.debug("Error closing writer", ex); ++ } finally { ++ this.writer = null; + } + +- @Override +- public void close() throws IOException { +- try { +- if (writer != null) { +- writer.close(); +- } +- } catch (IOException ex) { +- LOGGER.debug("Error closing writer", ex); +- } finally { +- this.writer = null; +- } +- +- try { +- if (socket != null) { +- socket.close(); +- } +- } catch (IOException ex) { +- LOGGER.debug("Error closing socket", ex); +- } finally { +- this.socket = null; +- } ++ try { ++ if (socket != null) { ++ socket.close(); ++ } ++ } catch (IOException ex) { ++ LOG.debug("Error closing socket", ex); ++ } finally { ++ this.socket = null; + } ++ } + +- protected String sanitize(String s) { +- return GraphiteSanitize.sanitize(s); +- } ++ protected String sanitize(String s) { ++ return GraphiteSanitize.sanitize(s); ++ } + } +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java +@@ -1,163 +1,162 @@ + package io.dropwizard.metrics5.graphite; + ++import static com.google.common.base.Preconditions.checkState; ++import static java.nio.charset.StandardCharsets.UTF_8; ++ + import com.rabbitmq.client.Channel; + import com.rabbitmq.client.Connection; + import com.rabbitmq.client.ConnectionFactory; + import com.rabbitmq.client.DefaultSocketConfigurator; +- + import java.io.IOException; + import java.net.Socket; + import java.util.concurrent.TimeoutException; + +-import static java.nio.charset.StandardCharsets.UTF_8; +- +-/** +- * A rabbit-mq client to a Carbon server. +- */ ++/** A rabbit-mq client to a Carbon server. */ + public class GraphiteRabbitMQ implements GraphiteSender { + +- private static final Integer DEFAULT_RABBIT_CONNECTION_TIMEOUT_MS = 500; +- private static final Integer DEFAULT_RABBIT_SOCKET_TIMEOUT_MS = 5000; +- private static final Integer DEFAULT_RABBIT_REQUESTED_HEARTBEAT_SEC = 10; +- +- private ConnectionFactory connectionFactory; +- private Connection connection; +- private Channel channel; +- private String exchange; +- +- private int failures; +- +- /** +- * Creates a new client with a given a {@link com.rabbitmq.client.ConnectionFactory} and an amqp exchange +- * +- * @param connectionFactory the {@link com.rabbitmq.client.ConnectionFactory} used to establish connection and publish to graphite server +- * @param exchange the amqp exchange +- */ +- public GraphiteRabbitMQ(final ConnectionFactory connectionFactory, final String exchange) { +- this.connectionFactory = connectionFactory; +- this.exchange = exchange; +- } +- +- /** +- * Creates a new client given connection details +- * +- * @param rabbitHost the rabbitmq server host +- * @param rabbitPort the rabbitmq server port +- * @param rabbitUsername the rabbitmq server username +- * @param rabbitPassword the rabbitmq server password +- * @param exchange the amqp exchange +- */ +- public GraphiteRabbitMQ( +- final String rabbitHost, +- final Integer rabbitPort, +- final String rabbitUsername, +- final String rabbitPassword, +- final String exchange) { +- +- this(rabbitHost, +- rabbitPort, +- rabbitUsername, +- rabbitPassword, +- exchange, +- DEFAULT_RABBIT_CONNECTION_TIMEOUT_MS, +- DEFAULT_RABBIT_SOCKET_TIMEOUT_MS, +- DEFAULT_RABBIT_REQUESTED_HEARTBEAT_SEC); +- } +- +- /** +- * Creates a new client given connection details +- * +- * @param rabbitHost the rabbitmq server host +- * @param rabbitPort the rabbitmq server port +- * @param rabbitUsername the rabbitmq server username +- * @param rabbitPassword the rabbitmq server password +- * @param exchange the amqp exchange +- * @param rabbitConnectionTimeoutMS the connection timeout in milliseconds +- * @param rabbitSocketTimeoutMS the socket timeout in milliseconds +- * @param rabbitRequestedHeartbeatInSeconds the hearthbeat in seconds +- */ +- public GraphiteRabbitMQ( +- final String rabbitHost, +- final Integer rabbitPort, +- final String rabbitUsername, +- final String rabbitPassword, +- final String exchange, +- final Integer rabbitConnectionTimeoutMS, +- final Integer rabbitSocketTimeoutMS, +- final Integer rabbitRequestedHeartbeatInSeconds) { +- +- this.exchange = exchange; +- +- this.connectionFactory = new ConnectionFactory(); +- +- connectionFactory.setSocketConfigurator(new DefaultSocketConfigurator() { +- @Override +- public void configure(Socket socket) throws IOException { +- super.configure(socket); +- socket.setSoTimeout(rabbitSocketTimeoutMS); +- } ++ private static final Integer DEFAULT_RABBIT_CONNECTION_TIMEOUT_MS = 500; ++ private static final Integer DEFAULT_RABBIT_SOCKET_TIMEOUT_MS = 5000; ++ private static final Integer DEFAULT_RABBIT_REQUESTED_HEARTBEAT_SEC = 10; ++ ++ private ConnectionFactory connectionFactory; ++ private Connection connection; ++ private Channel channel; ++ private String exchange; ++ ++ private int failures; ++ ++ /** ++ * Creates a new client with a given a {@link com.rabbitmq.client.ConnectionFactory} and an amqp ++ * exchange ++ * ++ * @param connectionFactory the {@link com.rabbitmq.client.ConnectionFactory} used to establish ++ * connection and publish to graphite server ++ * @param exchange the amqp exchange ++ */ ++ public GraphiteRabbitMQ(final ConnectionFactory connectionFactory, final String exchange) { ++ this.connectionFactory = connectionFactory; ++ this.exchange = exchange; ++ } ++ ++ /** ++ * Creates a new client given connection details ++ * ++ * @param rabbitHost the rabbitmq server host ++ * @param rabbitPort the rabbitmq server port ++ * @param rabbitUsername the rabbitmq server username ++ * @param rabbitPassword the rabbitmq server password ++ * @param exchange the amqp exchange ++ */ ++ public GraphiteRabbitMQ( ++ final String rabbitHost, ++ final Integer rabbitPort, ++ final String rabbitUsername, ++ final String rabbitPassword, ++ final String exchange) { ++ ++ this( ++ rabbitHost, ++ rabbitPort, ++ rabbitUsername, ++ rabbitPassword, ++ exchange, ++ DEFAULT_RABBIT_CONNECTION_TIMEOUT_MS, ++ DEFAULT_RABBIT_SOCKET_TIMEOUT_MS, ++ DEFAULT_RABBIT_REQUESTED_HEARTBEAT_SEC); ++ } ++ ++ /** ++ * Creates a new client given connection details ++ * ++ * @param rabbitHost the rabbitmq server host ++ * @param rabbitPort the rabbitmq server port ++ * @param rabbitUsername the rabbitmq server username ++ * @param rabbitPassword the rabbitmq server password ++ * @param exchange the amqp exchange ++ * @param rabbitConnectionTimeoutMS the connection timeout in milliseconds ++ * @param rabbitSocketTimeoutMS the socket timeout in milliseconds ++ * @param rabbitRequestedHeartbeatInSeconds the hearthbeat in seconds ++ */ ++ public GraphiteRabbitMQ( ++ final String rabbitHost, ++ final Integer rabbitPort, ++ final String rabbitUsername, ++ final String rabbitPassword, ++ final String exchange, ++ final Integer rabbitConnectionTimeoutMS, ++ final Integer rabbitSocketTimeoutMS, ++ final Integer rabbitRequestedHeartbeatInSeconds) { ++ ++ this.exchange = exchange; ++ ++ this.connectionFactory = new ConnectionFactory(); ++ ++ connectionFactory.setSocketConfigurator( ++ new DefaultSocketConfigurator() { ++ @Override ++ public void configure(Socket socket) throws IOException { ++ super.configure(socket); ++ socket.setSoTimeout(rabbitSocketTimeoutMS); ++ } + }); + +- connectionFactory.setConnectionTimeout(rabbitConnectionTimeoutMS); +- connectionFactory.setRequestedHeartbeat(rabbitRequestedHeartbeatInSeconds); +- connectionFactory.setHost(rabbitHost); +- connectionFactory.setPort(rabbitPort); +- connectionFactory.setUsername(rabbitUsername); +- connectionFactory.setPassword(rabbitPassword); ++ connectionFactory.setConnectionTimeout(rabbitConnectionTimeoutMS); ++ connectionFactory.setRequestedHeartbeat(rabbitRequestedHeartbeatInSeconds); ++ connectionFactory.setHost(rabbitHost); ++ connectionFactory.setPort(rabbitPort); ++ connectionFactory.setUsername(rabbitUsername); ++ connectionFactory.setPassword(rabbitPassword); ++ } ++ ++ @Override ++ public void connect() throws IllegalStateException, IOException { ++ checkState(!isConnected(), "Already connected"); ++ ++ try { ++ connection = connectionFactory.newConnection(); ++ } catch (TimeoutException e) { ++ throw new IllegalStateException(e); + } +- +- @Override +- public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } +- +- try { +- connection = connectionFactory.newConnection(); +- } catch (TimeoutException e) { +- throw new IllegalStateException(e); +- } +- channel = connection.createChannel(); ++ channel = connection.createChannel(); ++ } ++ ++ @Override ++ public boolean isConnected() { ++ return connection != null && connection.isOpen(); ++ } ++ ++ @Override ++ public void send(String name, String value, long timestamp) throws IOException { ++ try { ++ final String sanitizedName = sanitize(name); ++ final String sanitizedValue = sanitize(value); ++ ++ final String message = sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n'; ++ channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); ++ } catch (IOException e) { ++ failures++; ++ throw e; + } ++ } + +- @Override +- public boolean isConnected() { +- return connection != null && connection.isOpen(); +- } ++ @Override ++ public void flush() throws IOException { ++ // Nothing to do ++ } + +- @Override +- public void send(String name, String value, long timestamp) throws IOException { +- try { +- final String sanitizedName = sanitize(name); +- final String sanitizedValue = sanitize(value); +- +- final String message = sanitizedName + ' ' + sanitizedValue + ' ' + Long.toString(timestamp) + '\n'; +- channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); +- } catch (IOException e) { +- failures++; +- throw e; +- } ++ @Override ++ public void close() throws IOException { ++ if (connection != null) { ++ connection.close(); + } ++ } + +- @Override +- public void flush() throws IOException { +- // Nothing to do +- } +- +- @Override +- public void close() throws IOException { +- if (connection != null) { +- connection.close(); +- } +- } +- +- @Override +- public int getFailures() { +- return failures; +- } +- +- public String sanitize(String s) { +- return GraphiteSanitize.sanitize(s); +- } ++ @Override ++ public int getFailures() { ++ return failures; ++ } + ++ public String sanitize(String s) { ++ return GraphiteSanitize.sanitize(s); ++ } + } +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java +@@ -1,5 +1,21 @@ + package io.dropwizard.metrics5.graphite; + ++import static io.dropwizard.metrics5.MetricAttribute.COUNT; ++import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; ++import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; ++import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; ++import static io.dropwizard.metrics5.MetricAttribute.MEAN; ++import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; ++import static io.dropwizard.metrics5.MetricAttribute.P50; ++import static io.dropwizard.metrics5.MetricAttribute.P75; ++import static io.dropwizard.metrics5.MetricAttribute.P95; ++import static io.dropwizard.metrics5.MetricAttribute.P98; ++import static io.dropwizard.metrics5.MetricAttribute.P99; ++import static io.dropwizard.metrics5.MetricAttribute.P999; ++import static io.dropwizard.metrics5.MetricAttribute.STDDEV; ++import static io.dropwizard.metrics5.MetricAttribute.SUM; ++ ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -13,11 +29,7 @@ import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.ScheduledReporter; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; +- + import java.io.IOException; +-import java.util.Collections; + import java.util.Locale; + import java.util.Map; + import java.util.Set; +@@ -25,23 +37,8 @@ import java.util.SortedMap; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; + import java.util.function.DoubleFunction; +- +-import static io.dropwizard.metrics5.MetricAttribute.COUNT; +-import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MAX; +-import static io.dropwizard.metrics5.MetricAttribute.MEAN; +-import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; +-import static io.dropwizard.metrics5.MetricAttribute.P50; +-import static io.dropwizard.metrics5.MetricAttribute.P75; +-import static io.dropwizard.metrics5.MetricAttribute.P95; +-import static io.dropwizard.metrics5.MetricAttribute.P98; +-import static io.dropwizard.metrics5.MetricAttribute.P99; +-import static io.dropwizard.metrics5.MetricAttribute.P999; +-import static io.dropwizard.metrics5.MetricAttribute.STDDEV; +-import static io.dropwizard.metrics5.MetricAttribute.SUM; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + + /** + * A reporter which publishes metric values to a Graphite server. +@@ -49,477 +46,521 @@ import static io.dropwizard.metrics5.MetricAttribute.SUM; + * @see Graphite - Scalable Realtime Graphing + */ + public class GraphiteReporter extends ScheduledReporter { ++ /** ++ * Returns a new {@link Builder} for {@link GraphiteReporter}. ++ * ++ * @param registry the registry to report ++ * @return a {@link Builder} instance for a {@link GraphiteReporter} ++ */ ++ public static Builder forRegistry(MetricRegistry registry) { ++ return new Builder(registry); ++ } ++ ++ /** ++ * A builder for {@link GraphiteReporter} instances. Defaults to not using a prefix, using the ++ * default clock, converting rates to events/second, converting durations to milliseconds, and not ++ * filtering metrics. ++ */ ++ public static class Builder { ++ private final MetricRegistry registry; ++ private Clock clock; ++ private String prefix; ++ private TimeUnit rateUnit; ++ private TimeUnit durationUnit; ++ private MetricFilter filter; ++ private ScheduledExecutorService executor; ++ private boolean shutdownExecutorOnStop; ++ private Set disabledMetricAttributes; ++ private boolean addMetricAttributesAsTags; ++ private DoubleFunction floatingPointFormatter; ++ ++ private Builder(MetricRegistry registry) { ++ this.registry = registry; ++ this.clock = Clock.defaultClock(); ++ this.prefix = null; ++ this.rateUnit = TimeUnit.SECONDS; ++ this.durationUnit = TimeUnit.MILLISECONDS; ++ this.filter = MetricFilter.ALL; ++ this.executor = null; ++ this.shutdownExecutorOnStop = true; ++ this.disabledMetricAttributes = ImmutableSet.of(); ++ this.addMetricAttributesAsTags = false; ++ this.floatingPointFormatter = DEFAULT_FP_FORMATTER; ++ } ++ + /** +- * Returns a new {@link Builder} for {@link GraphiteReporter}. ++ * Specifies whether or not, the executor (used for reporting) will be stopped with same time ++ * with reporter. Default value is true. Setting this parameter to false, has the sense in ++ * combining with providing external managed executor via {@link ++ * #scheduleOn(ScheduledExecutorService)}. + * +- * @param registry the registry to report +- * @return a {@link Builder} instance for a {@link GraphiteReporter} ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ * @return {@code this} + */ +- public static Builder forRegistry(MetricRegistry registry) { +- return new Builder(registry); ++ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { ++ this.shutdownExecutorOnStop = shutdownExecutorOnStop; ++ return this; + } + + /** +- * A builder for {@link GraphiteReporter} instances. Defaults to not using a prefix, using the +- * default clock, converting rates to events/second, converting durations to milliseconds, and +- * not filtering metrics. ++ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. ++ * Null value leads to executor will be auto created on start. ++ * ++ * @param executor the executor to use while scheduling reporting of metrics. ++ * @return {@code this} + */ +- public static class Builder { +- private final MetricRegistry registry; +- private Clock clock; +- private String prefix; +- private TimeUnit rateUnit; +- private TimeUnit durationUnit; +- private MetricFilter filter; +- private ScheduledExecutorService executor; +- private boolean shutdownExecutorOnStop; +- private Set disabledMetricAttributes; +- private boolean addMetricAttributesAsTags; +- private DoubleFunction floatingPointFormatter; +- +- private Builder(MetricRegistry registry) { +- this.registry = registry; +- this.clock = Clock.defaultClock(); +- this.prefix = null; +- this.rateUnit = TimeUnit.SECONDS; +- this.durationUnit = TimeUnit.MILLISECONDS; +- this.filter = MetricFilter.ALL; +- this.executor = null; +- this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); +- this.addMetricAttributesAsTags = false; +- this.floatingPointFormatter = DEFAULT_FP_FORMATTER; +- } +- +- /** +- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. +- * Default value is true. +- * Setting this parameter to false, has the sense in combining with providing external managed executor via {@link #scheduleOn(ScheduledExecutorService)}. +- * +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- * @return {@code this} +- */ +- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { +- this.shutdownExecutorOnStop = shutdownExecutorOnStop; +- return this; +- } +- +- /** +- * Specifies the executor to use while scheduling reporting of metrics. +- * Default value is null. +- * Null value leads to executor will be auto created on start. +- * +- * @param executor the executor to use while scheduling reporting of metrics. +- * @return {@code this} +- */ +- public Builder scheduleOn(ScheduledExecutorService executor) { +- this.executor = executor; +- return this; +- } +- +- /** +- * Use the given {@link Clock} instance for the time. +- * +- * @param clock a {@link Clock} instance +- * @return {@code this} +- */ +- public Builder withClock(Clock clock) { +- this.clock = clock; +- return this; +- } +- +- /** +- * Prefix all metric names with the given string. +- * +- * @param prefix the prefix for all metric names +- * @return {@code this} +- */ +- public Builder prefixedWith(String prefix) { +- this.prefix = prefix; +- return this; +- } +- +- /** +- * Convert rates to the given time unit. +- * +- * @param rateUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertRatesTo(TimeUnit rateUnit) { +- this.rateUnit = rateUnit; +- return this; +- } +- +- /** +- * Convert durations to the given time unit. +- * +- * @param durationUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertDurationsTo(TimeUnit durationUnit) { +- this.durationUnit = durationUnit; +- return this; +- } +- +- /** +- * Only report metrics which match the given filter. +- * +- * @param filter a {@link MetricFilter} +- * @return {@code this} +- */ +- public Builder filter(MetricFilter filter) { +- this.filter = filter; +- return this; +- } +- +- /** +- * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). +- * See {@link MetricAttribute}. +- * +- * @param disabledMetricAttributes a set of {@link MetricAttribute} +- * @return {@code this} +- */ +- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { +- this.disabledMetricAttributes = disabledMetricAttributes; +- return this; +- } +- +- +- /** +- * Specifies whether or not metric attributes (e.g. "p999", "stddev" or "m15") should be reported in the traditional dot delimited format or in the tag based format. +- * Without tags (default): `my.metric.p99` +- * With tags: `my.metric;metricattribute=p99` +- *

+- * Note that this setting only modifies the metric attribute, and will not convert any other portion of the metric name to use tags. +- * For mor information on Graphite tag support see https://graphite.readthedocs.io/en/latest/tags.html +- * See {@link MetricAttribute}. +- * +- * @param addMetricAttributesAsTags if true, then metric attributes will be added as tags +- * @return {@code this} +- */ +- public Builder addMetricAttributesAsTags(boolean addMetricAttributesAsTags) { +- this.addMetricAttributesAsTags = addMetricAttributesAsTags; +- return this; +- } +- +- /** +- * Use custom floating point formatter. +- * +- * @param floatingPointFormatter a custom formatter for floating point values +- * @return {@code this} +- */ +- public Builder withFloatingPointFormatter(DoubleFunction floatingPointFormatter) { +- this.floatingPointFormatter = floatingPointFormatter; +- return this; +- } +- +- /** +- * Builds a {@link GraphiteReporter} with the given properties, sending metrics using the +- * given {@link GraphiteSender}. +- *

+- * Present for binary compatibility +- * +- * @param graphite a {@link Graphite} +- * @return a {@link GraphiteReporter} +- */ +- public GraphiteReporter build(Graphite graphite) { +- return build((GraphiteSender) graphite); +- } +- +- /** +- * Builds a {@link GraphiteReporter} with the given properties, sending metrics using the +- * given {@link GraphiteSender}. +- * +- * @param graphite a {@link GraphiteSender} +- * @return a {@link GraphiteReporter} +- */ +- public GraphiteReporter build(GraphiteSender graphite) { +- return new GraphiteReporter(registry, +- graphite, +- clock, +- prefix, +- rateUnit, +- durationUnit, +- filter, +- executor, +- shutdownExecutorOnStop, +- disabledMetricAttributes, +- addMetricAttributesAsTags, +- floatingPointFormatter); +- } ++ public Builder scheduleOn(ScheduledExecutorService executor) { ++ this.executor = executor; ++ return this; + } + +- private static final Logger LOGGER = LoggerFactory.getLogger(GraphiteReporter.class); +- // the Carbon plaintext format is pretty underspecified, but it seems like it just wants US-formatted digits +- private static final DoubleFunction DEFAULT_FP_FORMATTER = fp -> String.format(Locale.US, "%2.2f", fp); +- +- private final GraphiteSender graphite; +- private final Clock clock; +- private final String prefix; +- private final boolean addMetricAttributesAsTags; +- private final DoubleFunction floatingPointFormatter; +- + /** +- * Creates a new {@link GraphiteReporter} instance. ++ * Use the given {@link Clock} instance for the time. + * +- * @param registry the {@link MetricRegistry} containing the metrics this +- * reporter will report +- * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon server +- * via a transport protocol +- * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default +- * @param prefix the prefix of all metric names (may be null) +- * @param rateUnit the time unit of in which rates will be converted +- * @param durationUnit the time unit of in which durations will be converted +- * @param filter the filter for which metrics to report +- * @param executor the executor to use while scheduling reporting of metrics (may be null). +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- * @param disabledMetricAttributes do not report specific metric attributes ++ * @param clock a {@link Clock} instance ++ * @return {@code this} + */ +- protected GraphiteReporter(MetricRegistry registry, +- GraphiteSender graphite, +- Clock clock, +- String prefix, +- TimeUnit rateUnit, +- TimeUnit durationUnit, +- MetricFilter filter, +- ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop, +- Set disabledMetricAttributes) { +- this(registry, graphite, clock, prefix, rateUnit, durationUnit, filter, executor, shutdownExecutorOnStop, +- disabledMetricAttributes, false); ++ public Builder withClock(Clock clock) { ++ this.clock = clock; ++ return this; + } + +- + /** +- * Creates a new {@link GraphiteReporter} instance. ++ * Prefix all metric names with the given string. + * +- * @param registry the {@link MetricRegistry} containing the metrics this +- * reporter will report +- * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon server +- * via a transport protocol +- * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default +- * @param prefix the prefix of all metric names (may be null) +- * @param rateUnit the time unit of in which rates will be converted +- * @param durationUnit the time unit of in which durations will be converted +- * @param filter the filter for which metrics to report +- * @param executor the executor to use while scheduling reporting of metrics (may be null). +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- * @param disabledMetricAttributes do not report specific metric attributes +- * @param addMetricAttributesAsTags if true, then add metric attributes as tags instead of suffixes ++ * @param prefix the prefix for all metric names ++ * @return {@code this} + */ +- protected GraphiteReporter(MetricRegistry registry, +- GraphiteSender graphite, +- Clock clock, +- String prefix, +- TimeUnit rateUnit, +- TimeUnit durationUnit, +- MetricFilter filter, +- ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop, +- Set disabledMetricAttributes, +- boolean addMetricAttributesAsTags) { +- this(registry, graphite, clock, prefix, rateUnit, durationUnit, filter, executor, shutdownExecutorOnStop, +- disabledMetricAttributes, addMetricAttributesAsTags, DEFAULT_FP_FORMATTER); ++ public Builder prefixedWith(String prefix) { ++ this.prefix = prefix; ++ return this; + } + + /** +- * Creates a new {@link GraphiteReporter} instance. ++ * Convert rates to the given time unit. + * +- * @param registry the {@link MetricRegistry} containing the metrics this +- * reporter will report +- * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon server +- * via a transport protocol +- * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default +- * @param prefix the prefix of all metric names (may be null) +- * @param rateUnit the time unit of in which rates will be converted +- * @param durationUnit the time unit of in which durations will be converted +- * @param filter the filter for which metrics to report +- * @param executor the executor to use while scheduling reporting of metrics (may be null). +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- * @param disabledMetricAttributes do not report specific metric attributes +- * @param addMetricAttributesAsTags if true, then add metric attributes as tags instead of suffixes +- * @param floatingPointFormatter custom floating point formatter ++ * @param rateUnit a unit of time ++ * @return {@code this} + */ +- protected GraphiteReporter(MetricRegistry registry, +- GraphiteSender graphite, +- Clock clock, +- String prefix, +- TimeUnit rateUnit, +- TimeUnit durationUnit, +- MetricFilter filter, +- ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop, +- Set disabledMetricAttributes, +- boolean addMetricAttributesAsTags, +- DoubleFunction floatingPointFormatter) { +- super(registry, "graphite-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, +- disabledMetricAttributes); +- this.graphite = graphite; +- this.clock = clock; +- this.prefix = prefix; +- this.addMetricAttributesAsTags = addMetricAttributesAsTags; +- this.floatingPointFormatter = floatingPointFormatter; ++ public Builder convertRatesTo(TimeUnit rateUnit) { ++ this.rateUnit = rateUnit; ++ return this; + } + +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap> gauges, +- SortedMap counters, +- SortedMap histograms, +- SortedMap meters, +- SortedMap timers) { +- final long timestamp = clock.getTime() / 1000; +- +- // oh it'd be lovely to use Java 7 here +- try { +- graphite.connect(); +- +- for (Map.Entry> entry : gauges.entrySet()) { +- reportGauge(entry.getKey(), entry.getValue(), timestamp); +- } +- +- for (Map.Entry entry : counters.entrySet()) { +- reportCounter(entry.getKey(), entry.getValue(), timestamp); +- } +- +- for (Map.Entry entry : histograms.entrySet()) { +- reportHistogram(entry.getKey(), entry.getValue(), timestamp); +- } +- +- for (Map.Entry entry : meters.entrySet()) { +- reportMetered(entry.getKey(), entry.getValue(), timestamp, false); +- } +- +- for (Map.Entry entry : timers.entrySet()) { +- reportTimer(entry.getKey(), entry.getValue(), timestamp); +- } +- graphite.flush(); +- } catch (IOException e) { +- LOGGER.warn("Unable to report to Graphite", graphite, e); +- } finally { +- try { +- graphite.close(); +- } catch (IOException e1) { +- LOGGER.warn("Error closing Graphite", graphite, e1); +- } +- } ++ /** ++ * Convert durations to the given time unit. ++ * ++ * @param durationUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertDurationsTo(TimeUnit durationUnit) { ++ this.durationUnit = durationUnit; ++ return this; + } + +- @Override +- public void stop() { +- try { +- super.stop(); +- } finally { +- try { +- graphite.close(); +- } catch (IOException e) { +- LOGGER.debug("Error disconnecting from Graphite", graphite, e); +- } +- } ++ /** ++ * Only report metrics which match the given filter. ++ * ++ * @param filter a {@link MetricFilter} ++ * @return {@code this} ++ */ ++ public Builder filter(MetricFilter filter) { ++ this.filter = filter; ++ return this; + } + +- private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { +- final Snapshot snapshot = timer.getSnapshot(); +- sendIfEnabled(MAX, name, convertDuration(snapshot.getMax()), timestamp); +- sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); +- sendIfEnabled(MIN, name, convertDuration(snapshot.getMin()), timestamp); +- sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); +- sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); +- sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); +- sendIfEnabled(P95, name, convertDuration(snapshot.get95thPercentile()), timestamp); +- sendIfEnabled(P98, name, convertDuration(snapshot.get98thPercentile()), timestamp); +- sendIfEnabled(P99, name, convertDuration(snapshot.get99thPercentile()), timestamp); +- sendIfEnabled(P999, name, convertDuration(snapshot.get999thPercentile()), timestamp); +- reportMetered(name, timer, timestamp, true); ++ /** ++ * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). ++ * See {@link MetricAttribute}. ++ * ++ * @param disabledMetricAttributes a set of {@link MetricAttribute} ++ * @return {@code this} ++ */ ++ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { ++ this.disabledMetricAttributes = disabledMetricAttributes; ++ return this; + } + +- private void reportMetered(MetricName name, Metered meter, long timestamp, boolean sumIsDuration) throws IOException { +- sendIfEnabled(COUNT, name, meter.getCount(), timestamp); +- sendIfEnabled(SUM, name, sumIsDuration ? convertDuration(meter.getSum()) : meter.getSum(), timestamp); +- sendIfEnabled(M1_RATE, name, convertRate(meter.getOneMinuteRate()), timestamp); +- sendIfEnabled(M5_RATE, name, convertRate(meter.getFiveMinuteRate()), timestamp); +- sendIfEnabled(M15_RATE, name, convertRate(meter.getFifteenMinuteRate()), timestamp); +- sendIfEnabled(MEAN_RATE, name, convertRate(meter.getMeanRate()), timestamp); ++ /** ++ * Specifies whether or not metric attributes (e.g. "p999", "stddev" or "m15") should be ++ * reported in the traditional dot delimited format or in the tag based format. Without tags ++ * (default): `my.metric.p99` With tags: `my.metric;metricattribute=p99` ++ * ++ *

Note that this setting only modifies the metric attribute, and will not convert any other ++ * portion of the metric name to use tags. For mor information on Graphite tag support see ++ * https://graphite.readthedocs.io/en/latest/tags.html See {@link MetricAttribute}. ++ * ++ * @param addMetricAttributesAsTags if true, then metric attributes will be added as tags ++ * @return {@code this} ++ */ ++ public Builder addMetricAttributesAsTags(boolean addMetricAttributesAsTags) { ++ this.addMetricAttributesAsTags = addMetricAttributesAsTags; ++ return this; + } + +- private void reportHistogram(MetricName name, Histogram histogram, long timestamp) throws IOException { +- final Snapshot snapshot = histogram.getSnapshot(); +- sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); +- sendIfEnabled(SUM, name, histogram.getSum(), timestamp); +- sendIfEnabled(MAX, name, snapshot.getMax(), timestamp); +- sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); +- sendIfEnabled(MIN, name, snapshot.getMin(), timestamp); +- sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); +- sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); +- sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); +- sendIfEnabled(P95, name, snapshot.get95thPercentile(), timestamp); +- sendIfEnabled(P98, name, snapshot.get98thPercentile(), timestamp); +- sendIfEnabled(P99, name, snapshot.get99thPercentile(), timestamp); +- sendIfEnabled(P999, name, snapshot.get999thPercentile(), timestamp); ++ /** ++ * Use custom floating point formatter. ++ * ++ * @param floatingPointFormatter a custom formatter for floating point values ++ * @return {@code this} ++ */ ++ public Builder withFloatingPointFormatter(DoubleFunction floatingPointFormatter) { ++ this.floatingPointFormatter = floatingPointFormatter; ++ return this; + } + +- private void sendIfEnabled(MetricAttribute type, MetricName name, double value, long timestamp) throws IOException { +- if (getDisabledMetricAttributes().contains(type)) { +- return; +- } +- graphite.send(prefix(appendMetricAttribute(name, type.getCode())), format(value), timestamp); ++ /** ++ * Builds a {@link GraphiteReporter} with the given properties, sending metrics using the given ++ * {@link GraphiteSender}. ++ * ++ *

Present for binary compatibility ++ * ++ * @param graphite a {@link Graphite} ++ * @return a {@link GraphiteReporter} ++ */ ++ public GraphiteReporter build(Graphite graphite) { ++ return build((GraphiteSender) graphite); + } + +- private void sendIfEnabled(MetricAttribute type, MetricName name, long value, long timestamp) throws IOException { +- if (getDisabledMetricAttributes().contains(type)) { +- return; +- } +- graphite.send(prefix(appendMetricAttribute(name, type.getCode())), format(value), timestamp); ++ /** ++ * Builds a {@link GraphiteReporter} with the given properties, sending metrics using the given ++ * {@link GraphiteSender}. ++ * ++ * @param graphite a {@link GraphiteSender} ++ * @return a {@link GraphiteReporter} ++ */ ++ public GraphiteReporter build(GraphiteSender graphite) { ++ return new GraphiteReporter( ++ registry, ++ graphite, ++ clock, ++ prefix, ++ rateUnit, ++ durationUnit, ++ filter, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes, ++ addMetricAttributesAsTags, ++ floatingPointFormatter); + } +- +- private void reportCounter(MetricName name, Counter counter, long timestamp) throws IOException { +- graphite.send(prefix(appendMetricAttribute(name, COUNT.getCode())), format(counter.getCount()), timestamp); ++ } ++ ++ private static final Logger LOG = LoggerFactory.getLogger(GraphiteReporter.class); ++ // the Carbon plaintext format is pretty underspecified, but it seems like it just wants ++ // US-formatted digits ++ private static final DoubleFunction DEFAULT_FP_FORMATTER = ++ fp -> String.format(Locale.US, "%2.2f", fp); ++ ++ private final GraphiteSender graphite; ++ private final Clock clock; ++ private final String prefix; ++ private final boolean addMetricAttributesAsTags; ++ private final DoubleFunction floatingPointFormatter; ++ ++ /** ++ * Creates a new {@link GraphiteReporter} instance. ++ * ++ * @param registry the {@link MetricRegistry} containing the metrics this reporter will report ++ * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon ++ * server via a transport protocol ++ * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default ++ * @param prefix the prefix of all metric names (may be null) ++ * @param rateUnit the time unit of in which rates will be converted ++ * @param durationUnit the time unit of in which durations will be converted ++ * @param filter the filter for which metrics to report ++ * @param executor the executor to use while scheduling reporting of metrics (may be null). ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ * @param disabledMetricAttributes do not report specific metric attributes ++ */ ++ protected GraphiteReporter( ++ MetricRegistry registry, ++ GraphiteSender graphite, ++ Clock clock, ++ String prefix, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ MetricFilter filter, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes) { ++ this( ++ registry, ++ graphite, ++ clock, ++ prefix, ++ rateUnit, ++ durationUnit, ++ filter, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes, ++ false); ++ } ++ ++ /** ++ * Creates a new {@link GraphiteReporter} instance. ++ * ++ * @param registry the {@link MetricRegistry} containing the metrics this reporter will report ++ * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon ++ * server via a transport protocol ++ * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default ++ * @param prefix the prefix of all metric names (may be null) ++ * @param rateUnit the time unit of in which rates will be converted ++ * @param durationUnit the time unit of in which durations will be converted ++ * @param filter the filter for which metrics to report ++ * @param executor the executor to use while scheduling reporting of metrics (may be null). ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ * @param disabledMetricAttributes do not report specific metric attributes ++ * @param addMetricAttributesAsTags if true, then add metric attributes as tags instead of ++ * suffixes ++ */ ++ protected GraphiteReporter( ++ MetricRegistry registry, ++ GraphiteSender graphite, ++ Clock clock, ++ String prefix, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ MetricFilter filter, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes, ++ boolean addMetricAttributesAsTags) { ++ this( ++ registry, ++ graphite, ++ clock, ++ prefix, ++ rateUnit, ++ durationUnit, ++ filter, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes, ++ addMetricAttributesAsTags, ++ DEFAULT_FP_FORMATTER); ++ } ++ ++ /** ++ * Creates a new {@link GraphiteReporter} instance. ++ * ++ * @param registry the {@link MetricRegistry} containing the metrics this reporter will report ++ * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon ++ * server via a transport protocol ++ * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default ++ * @param prefix the prefix of all metric names (may be null) ++ * @param rateUnit the time unit of in which rates will be converted ++ * @param durationUnit the time unit of in which durations will be converted ++ * @param filter the filter for which metrics to report ++ * @param executor the executor to use while scheduling reporting of metrics (may be null). ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ * @param disabledMetricAttributes do not report specific metric attributes ++ * @param addMetricAttributesAsTags if true, then add metric attributes as tags instead of ++ * suffixes ++ * @param floatingPointFormatter custom floating point formatter ++ */ ++ protected GraphiteReporter( ++ MetricRegistry registry, ++ GraphiteSender graphite, ++ Clock clock, ++ String prefix, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ MetricFilter filter, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes, ++ boolean addMetricAttributesAsTags, ++ DoubleFunction floatingPointFormatter) { ++ super( ++ registry, ++ "graphite-reporter", ++ filter, ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes); ++ this.graphite = graphite; ++ this.clock = clock; ++ this.prefix = prefix; ++ this.addMetricAttributesAsTags = addMetricAttributesAsTags; ++ this.floatingPointFormatter = floatingPointFormatter; ++ } ++ ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap> gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ final long timestamp = clock.getTime() / 1000; ++ ++ // oh it'd be lovely to use Java 7 here ++ try { ++ graphite.connect(); ++ ++ for (Map.Entry> entry : gauges.entrySet()) { ++ reportGauge(entry.getKey(), entry.getValue(), timestamp); ++ } ++ ++ for (Map.Entry entry : counters.entrySet()) { ++ reportCounter(entry.getKey(), entry.getValue(), timestamp); ++ } ++ ++ for (Map.Entry entry : histograms.entrySet()) { ++ reportHistogram(entry.getKey(), entry.getValue(), timestamp); ++ } ++ ++ for (Map.Entry entry : meters.entrySet()) { ++ reportMetered(entry.getKey(), entry.getValue(), timestamp, false); ++ } ++ ++ for (Map.Entry entry : timers.entrySet()) { ++ reportTimer(entry.getKey(), entry.getValue(), timestamp); ++ } ++ graphite.flush(); ++ } catch (IOException e) { ++ LOG.warn("Unable to report to Graphite", graphite, e); ++ } finally { ++ try { ++ graphite.close(); ++ } catch (IOException e1) { ++ LOG.warn("Error closing Graphite", graphite, e1); ++ } + } +- +- private void reportGauge(MetricName name, Gauge gauge, long timestamp) throws IOException { +- final String value = format(gauge.getValue()); +- if (value != null) { +- graphite.send(prefix(name.getKey()), value, timestamp); +- } ++ } ++ ++ @Override ++ public void stop() { ++ try { ++ super.stop(); ++ } finally { ++ try { ++ graphite.close(); ++ } catch (IOException e) { ++ LOG.debug("Error disconnecting from Graphite", graphite, e); ++ } + } +- +- private String format(Object o) { +- if (o instanceof Float) { +- return format(((Float) o).doubleValue()); +- } else if (o instanceof Double) { +- return format(((Double) o).doubleValue()); +- } else if (o instanceof Byte) { +- return format(((Byte) o).longValue()); +- } else if (o instanceof Short) { +- return format(((Short) o).longValue()); +- } else if (o instanceof Integer) { +- return format(((Integer) o).longValue()); +- } else if (o instanceof Long) { +- return format(((Long) o).longValue()); +- } else if (o instanceof Number) { +- return format(((Number) o).doubleValue()); +- } else if (o instanceof Boolean) { +- return format(((Boolean) o) ? 1 : 0); +- } +- return null; ++ } ++ ++ private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { ++ final Snapshot snapshot = timer.getSnapshot(); ++ sendIfEnabled(MetricAttribute.MAX, name, convertDuration(snapshot.getMax()), timestamp); ++ sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, convertDuration(snapshot.getMin()), timestamp); ++ sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); ++ sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); ++ sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); ++ sendIfEnabled(P95, name, convertDuration(snapshot.get95thPercentile()), timestamp); ++ sendIfEnabled(P98, name, convertDuration(snapshot.get98thPercentile()), timestamp); ++ sendIfEnabled(P99, name, convertDuration(snapshot.get99thPercentile()), timestamp); ++ sendIfEnabled(P999, name, convertDuration(snapshot.get999thPercentile()), timestamp); ++ reportMetered(name, timer, timestamp, true); ++ } ++ ++ private void reportMetered(MetricName name, Metered meter, long timestamp, boolean sumIsDuration) ++ throws IOException { ++ sendIfEnabled(COUNT, name, meter.getCount(), timestamp); ++ sendIfEnabled( ++ SUM, name, sumIsDuration ? convertDuration(meter.getSum()) : meter.getSum(), timestamp); ++ sendIfEnabled(M1_RATE, name, convertRate(meter.getOneMinuteRate()), timestamp); ++ sendIfEnabled(M5_RATE, name, convertRate(meter.getFiveMinuteRate()), timestamp); ++ sendIfEnabled(M15_RATE, name, convertRate(meter.getFifteenMinuteRate()), timestamp); ++ sendIfEnabled(MEAN_RATE, name, convertRate(meter.getMeanRate()), timestamp); ++ } ++ ++ private void reportHistogram(MetricName name, Histogram histogram, long timestamp) ++ throws IOException { ++ final Snapshot snapshot = histogram.getSnapshot(); ++ sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); ++ sendIfEnabled(SUM, name, histogram.getSum(), timestamp); ++ sendIfEnabled(MetricAttribute.MAX, name, snapshot.getMax(), timestamp); ++ sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, snapshot.getMin(), timestamp); ++ sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); ++ sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); ++ sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); ++ sendIfEnabled(P95, name, snapshot.get95thPercentile(), timestamp); ++ sendIfEnabled(P98, name, snapshot.get98thPercentile(), timestamp); ++ sendIfEnabled(P99, name, snapshot.get99thPercentile(), timestamp); ++ sendIfEnabled(P999, name, snapshot.get999thPercentile(), timestamp); ++ } ++ ++ private void sendIfEnabled(MetricAttribute type, MetricName name, double value, long timestamp) ++ throws IOException { ++ if (getDisabledMetricAttributes().contains(type)) { ++ return; + } ++ graphite.send(prefix(appendMetricAttribute(name, type.getCode())), format(value), timestamp); ++ } + +- private String prefix(String name) { +- return prefix + "." + name; ++ private void sendIfEnabled(MetricAttribute type, MetricName name, long value, long timestamp) ++ throws IOException { ++ if (getDisabledMetricAttributes().contains(type)) { ++ return; + } +- +- private String appendMetricAttribute(MetricName name, String metricAttribute) { +- if (addMetricAttributesAsTags) { +- return name.getKey() + ";metricattribute=" + metricAttribute; +- } +- return name.getKey() + "." + metricAttribute; ++ graphite.send(prefix(appendMetricAttribute(name, type.getCode())), format(value), timestamp); ++ } ++ ++ private void reportCounter(MetricName name, Counter counter, long timestamp) throws IOException { ++ graphite.send( ++ prefix(appendMetricAttribute(name, COUNT.getCode())), ++ format(counter.getCount()), ++ timestamp); ++ } ++ ++ private void reportGauge(MetricName name, Gauge gauge, long timestamp) throws IOException { ++ final String value = format(gauge.getValue()); ++ if (value != null) { ++ graphite.send(prefix(name.getKey()), value, timestamp); + } +- +- private String format(long n) { +- return Long.toString(n); ++ } ++ ++ private String format(Object o) { ++ if (o instanceof Float) { ++ return format(((Float) o).doubleValue()); ++ } else if (o instanceof Double) { ++ return format(((Double) o).doubleValue()); ++ } else if (o instanceof Byte) { ++ return format(((Byte) o).longValue()); ++ } else if (o instanceof Short) { ++ return format(((Short) o).longValue()); ++ } else if (o instanceof Integer) { ++ return format(((Integer) o).longValue()); ++ } else if (o instanceof Long) { ++ return format(((Long) o).longValue()); ++ } else if (o instanceof Number) { ++ return format(((Number) o).doubleValue()); ++ } else if (o instanceof Boolean) { ++ return format(((Boolean) o) ? 1 : 0); + } ++ return null; ++ } ++ ++ private String prefix(String name) { ++ return prefix + "." + name; ++ } + +- protected String format(double v) { +- return floatingPointFormatter.apply(v); ++ private String appendMetricAttribute(MetricName name, String metricAttribute) { ++ if (addMetricAttributesAsTags) { ++ return name.getKey() + ";metricattribute=" + metricAttribute; + } ++ return name.getKey() + "." + metricAttribute; ++ } ++ ++ private String format(long n) { ++ return Long.toString(n); ++ } ++ ++ protected String format(double v) { ++ return floatingPointFormatter.apply(v); ++ } + } +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteSanitize.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteSanitize.java +@@ -4,13 +4,11 @@ import java.util.regex.Pattern; + + class GraphiteSanitize { + +- private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); +- private static final String DASH = "-"; ++ private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); ++ private static final String DASH = "-"; + +- /** +- * Trims the string and replaces all whitespace characters with the provided symbol +- */ +- static String sanitize(String string) { +- return WHITESPACE.matcher(string.trim()).replaceAll(DASH); +- } ++ /** Trims the string and replaces all whitespace characters with the provided symbol */ ++ static String sanitize(String string) { ++ return WHITESPACE.matcher(string.trim()).replaceAll(DASH); ++ } + } +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteSender.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteSender.java +@@ -5,41 +5,38 @@ import java.io.IOException; + + public interface GraphiteSender extends Closeable { + +- /** +- * Connects to the server. +- * +- * @throws IllegalStateException if the client is already connected +- * @throws IOException if there is an error connecting +- */ +- void connect() throws IllegalStateException, IOException; +- +- /** +- * Sends the given measurement to the server. +- * +- * @param name the name of the metric +- * @param value the value of the metric +- * @param timestamp the timestamp of the metric +- * @throws IOException if there was an error sending the metric +- */ +- void send(String name, String value, long timestamp) throws IOException; +- +- /** +- * Flushes buffer, if applicable +- * +- * @throws IOException if there was an error during flushing metrics to the socket +- */ +- void flush() throws IOException; +- +- /** +- * Returns true if ready to send data +- */ +- boolean isConnected(); +- +- /** +- * Returns the number of failed writes to the server. +- * +- * @return the number of failed writes to the server +- */ +- int getFailures(); +- +-} +\ No newline at end of file ++ /** ++ * Connects to the server. ++ * ++ * @throws IllegalStateException if the client is already connected ++ * @throws IOException if there is an error connecting ++ */ ++ void connect() throws IllegalStateException, IOException; ++ ++ /** ++ * Sends the given measurement to the server. ++ * ++ * @param name the name of the metric ++ * @param value the value of the metric ++ * @param timestamp the timestamp of the metric ++ * @throws IOException if there was an error sending the metric ++ */ ++ void send(String name, String value, long timestamp) throws IOException; ++ ++ /** ++ * Flushes buffer, if applicable ++ * ++ * @throws IOException if there was an error during flushing metrics to the socket ++ */ ++ void flush() throws IOException; ++ ++ /** Returns true if ready to send data */ ++ boolean isConnected(); ++ ++ /** ++ * Returns the number of failed writes to the server. ++ * ++ * @return the number of failed writes to the server ++ */ ++ int getFailures(); ++} +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java +@@ -1,118 +1,115 @@ + package io.dropwizard.metrics5.graphite; + ++import static com.google.common.base.Preconditions.checkState; ++import static java.nio.charset.StandardCharsets.UTF_8; ++ + import java.io.IOException; +-import java.net.InetSocketAddress; + import java.net.InetAddress; ++import java.net.InetSocketAddress; + import java.nio.ByteBuffer; + import java.nio.channels.DatagramChannel; + +-import static java.nio.charset.StandardCharsets.UTF_8; +- +-/** +- * A client to a Carbon server using unconnected UDP +- */ ++/** A client to a Carbon server using unconnected UDP */ + public class GraphiteUDP implements GraphiteSender { + +- private final String hostname; +- private final int port; +- private InetSocketAddress address; +- +- private DatagramChannel datagramChannel = null; +- private int failures; +- +- /** +- * Creates a new client which sends data to given address using UDP +- * +- * @param hostname The hostname of the Carbon server +- * @param port The port of the Carbon server +- */ +- public GraphiteUDP(String hostname, int port) { +- this.hostname = hostname; +- this.port = port; +- this.address = null; +- } +- +- /** +- * Creates a new client which sends data to given address using UDP +- * +- * @param address the address of the Carbon server +- */ +- public GraphiteUDP(InetSocketAddress address) { +- this.hostname = null; +- this.port = -1; +- this.address = address; +- } +- +- @Override +- public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } +- +- // Resolve hostname +- if (hostname != null) { +- address = new InetSocketAddress(InetAddress.getByName(hostname), port); +- } +- +- datagramChannel = DatagramChannel.open(); ++ private final String hostname; ++ private final int port; ++ private InetSocketAddress address; ++ ++ private DatagramChannel datagramChannel = null; ++ private int failures; ++ ++ /** ++ * Creates a new client which sends data to given address using UDP ++ * ++ * @param hostname The hostname of the Carbon server ++ * @param port The port of the Carbon server ++ */ ++ public GraphiteUDP(String hostname, int port) { ++ this.hostname = hostname; ++ this.port = port; ++ this.address = null; ++ } ++ ++ /** ++ * Creates a new client which sends data to given address using UDP ++ * ++ * @param address the address of the Carbon server ++ */ ++ public GraphiteUDP(InetSocketAddress address) { ++ this.hostname = null; ++ this.port = -1; ++ this.address = address; ++ } ++ ++ @Override ++ public void connect() throws IllegalStateException, IOException { ++ checkState(!isConnected(), "Already connected"); ++ ++ // Resolve hostname ++ if (hostname != null) { ++ address = new InetSocketAddress(InetAddress.getByName(hostname), port); + } + +- @Override +- public boolean isConnected() { +- return datagramChannel != null && !datagramChannel.socket().isClosed(); ++ datagramChannel = DatagramChannel.open(); ++ } ++ ++ @Override ++ public boolean isConnected() { ++ return datagramChannel != null && !datagramChannel.socket().isClosed(); ++ } ++ ++ @Override ++ public void send(String name, String value, long timestamp) throws IOException { ++ try { ++ String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n'; ++ ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); ++ datagramChannel.send(byteBuffer, address); ++ this.failures = 0; ++ } catch (IOException e) { ++ failures++; ++ throw e; + } +- +- @Override +- public void send(String name, String value, long timestamp) throws IOException { +- try { +- String str = sanitize(name) + ' ' + sanitize(value) + ' ' + Long.toString(timestamp) + '\n'; +- ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); +- datagramChannel.send(byteBuffer, address); +- this.failures = 0; +- } catch (IOException e) { +- failures++; +- throw e; +- } +- } +- +- @Override +- public int getFailures() { +- return failures; +- } +- +- @Override +- public void flush() throws IOException { +- // Nothing to do +- } +- +- @Override +- public void close() throws IOException { +- if (datagramChannel != null) { +- try { +- datagramChannel.close(); +- } finally { +- datagramChannel = null; +- } +- } ++ } ++ ++ @Override ++ public int getFailures() { ++ return failures; ++ } ++ ++ @Override ++ public void flush() throws IOException { ++ // Nothing to do ++ } ++ ++ @Override ++ public void close() throws IOException { ++ if (datagramChannel != null) { ++ try { ++ datagramChannel.close(); ++ } finally { ++ datagramChannel = null; ++ } + } ++ } + +- protected String sanitize(String s) { +- return GraphiteSanitize.sanitize(s); +- } ++ protected String sanitize(String s) { ++ return GraphiteSanitize.sanitize(s); ++ } + +- DatagramChannel getDatagramChannel() { +- return datagramChannel; +- } ++ DatagramChannel getDatagramChannel() { ++ return datagramChannel; ++ } + +- void setDatagramChannel(DatagramChannel datagramChannel) { +- this.datagramChannel = datagramChannel; +- } ++ void setDatagramChannel(DatagramChannel datagramChannel) { ++ this.datagramChannel = datagramChannel; ++ } + +- InetSocketAddress getAddress() { +- return address; +- } ++ InetSocketAddress getAddress() { ++ return address; ++ } + +- void setAddress(InetSocketAddress address) { +- this.address = address; +- } ++ void setAddress(InetSocketAddress address) { ++ this.address = address; ++ } + } +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java +@@ -1,9 +1,7 @@ + package io.dropwizard.metrics5.graphite; + +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; +- +-import javax.net.SocketFactory; ++import static com.google.common.base.Preconditions.checkState; ++import static java.nio.charset.StandardCharsets.UTF_8; + + import java.io.BufferedWriter; + import java.io.ByteArrayOutputStream; +@@ -18,320 +16,320 @@ import java.nio.ByteBuffer; + import java.nio.charset.Charset; + import java.util.ArrayList; + import java.util.List; +- +-import static java.nio.charset.StandardCharsets.UTF_8; ++import javax.net.SocketFactory; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + + /** +- * A client to a Carbon server that sends all metrics after they have been pickled in configurable sized batches ++ * A client to a Carbon server that sends all metrics after they have been pickled in configurable ++ * sized batches + */ + public class PickledGraphite implements GraphiteSender { + +- static class MetricTuple { +- String name; +- long timestamp; +- String value; ++ static class MetricTuple { ++ String name; ++ long timestamp; ++ String value; + +- MetricTuple(String name, long timestamp, String value) { +- this.name = name; +- this.timestamp = timestamp; +- this.value = value; +- } ++ MetricTuple(String name, long timestamp, String value) { ++ this.name = name; ++ this.timestamp = timestamp; ++ this.value = value; + } +- +- /** +- * Minimally necessary pickle opcodes. +- */ +- private static final char +- MARK = '(', +- STOP = '.', +- LONG = 'L', +- STRING = 'S', +- APPEND = 'a', +- LIST = 'l', +- TUPLE = 't', +- QUOTE = '\'', +- LF = '\n'; +- +- private static final Logger LOGGER = LoggerFactory.getLogger(PickledGraphite.class); +- private final static int DEFAULT_BATCH_SIZE = 100; +- +- private int batchSize; +- // graphite expects a python-pickled list of nested tuples. +- private List metrics = new ArrayList<>(); +- +- private final String hostname; +- private final int port; +- private final InetSocketAddress address; +- private final SocketFactory socketFactory; +- private final Charset charset; +- +- private Socket socket; +- private Writer writer; +- private int failures; +- +- /** +- * Creates a new client which connects to the given address using the default {@link SocketFactory}. This defaults +- * to a batchSize of 100 +- * +- * @param address the address of the Carbon server +- */ +- public PickledGraphite(InetSocketAddress address) { +- this(address, DEFAULT_BATCH_SIZE); ++ } ++ ++ /** Minimally necessary pickle opcodes. */ ++ private static final char MARK = '(', ++ STOP = '.', ++ LONG = 'L', ++ STRING = 'S', ++ APPEND = 'a', ++ LIST = 'l', ++ TUPLE = 't', ++ QUOTE = '\'', ++ LF = '\n'; ++ ++ private static final Logger LOG = LoggerFactory.getLogger(PickledGraphite.class); ++ private static final int DEFAULT_BATCH_SIZE = 100; ++ ++ private int batchSize; ++ // graphite expects a python-pickled list of nested tuples. ++ private List metrics = new ArrayList<>(); ++ ++ private final String hostname; ++ private final int port; ++ private final InetSocketAddress address; ++ private final SocketFactory socketFactory; ++ private final Charset charset; ++ ++ private Socket socket; ++ private Writer writer; ++ private int failures; ++ ++ /** ++ * Creates a new client which connects to the given address using the default {@link ++ * SocketFactory}. This defaults to a batchSize of 100 ++ * ++ * @param address the address of the Carbon server ++ */ ++ public PickledGraphite(InetSocketAddress address) { ++ this(address, DEFAULT_BATCH_SIZE); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address using the default {@link ++ * SocketFactory}. ++ * ++ * @param address the address of the Carbon server ++ * @param batchSize how many metrics are bundled into a single pickle request to graphite ++ */ ++ public PickledGraphite(InetSocketAddress address, int batchSize) { ++ this(address, SocketFactory.getDefault(), batchSize); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address and socket factory. ++ * ++ * @param address the address of the Carbon server ++ * @param socketFactory the socket factory ++ * @param batchSize how many metrics are bundled into a single pickle request to graphite ++ */ ++ public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, int batchSize) { ++ this(address, socketFactory, UTF_8, batchSize); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address and socket factory using the given ++ * character set. ++ * ++ * @param address the address of the Carbon server ++ * @param socketFactory the socket factory ++ * @param charset the character set used by the server ++ * @param batchSize how many metrics are bundled into a single pickle request to graphite ++ */ ++ public PickledGraphite( ++ InetSocketAddress address, SocketFactory socketFactory, Charset charset, int batchSize) { ++ this.address = address; ++ this.hostname = null; ++ this.port = -1; ++ this.socketFactory = socketFactory; ++ this.charset = charset; ++ this.batchSize = batchSize; ++ } ++ ++ /** ++ * Creates a new client which connects to the given address using the default {@link ++ * SocketFactory}. This defaults to a batchSize of 100 ++ * ++ * @param hostname the hostname of the Carbon server ++ * @param port the port of the Carbon server ++ */ ++ public PickledGraphite(String hostname, int port) { ++ this(hostname, port, DEFAULT_BATCH_SIZE); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address using the default {@link ++ * SocketFactory}. ++ * ++ * @param hostname the hostname of the Carbon server ++ * @param port the port of the Carbon server ++ * @param batchSize how many metrics are bundled into a single pickle request to graphite ++ */ ++ public PickledGraphite(String hostname, int port, int batchSize) { ++ this(hostname, port, SocketFactory.getDefault(), batchSize); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address and socket factory. ++ * ++ * @param hostname the hostname of the Carbon server ++ * @param port the port of the Carbon server ++ * @param socketFactory the socket factory ++ * @param batchSize how many metrics are bundled into a single pickle request to graphite ++ */ ++ public PickledGraphite(String hostname, int port, SocketFactory socketFactory, int batchSize) { ++ this(hostname, port, socketFactory, UTF_8, batchSize); ++ } ++ ++ /** ++ * Creates a new client which connects to the given address and socket factory using the given ++ * character set. ++ * ++ * @param hostname the hostname of the Carbon server ++ * @param port the port of the Carbon server ++ * @param socketFactory the socket factory ++ * @param charset the character set used by the server ++ * @param batchSize how many metrics are bundled into a single pickle request to graphite ++ */ ++ public PickledGraphite( ++ String hostname, int port, SocketFactory socketFactory, Charset charset, int batchSize) { ++ this.address = null; ++ this.hostname = hostname; ++ this.port = port; ++ this.socketFactory = socketFactory; ++ this.charset = charset; ++ this.batchSize = batchSize; ++ } ++ ++ @Override ++ public void connect() throws IllegalStateException, IOException { ++ checkState(!isConnected(), "Already connected"); ++ InetSocketAddress address = this.address; ++ if (address == null) { ++ address = new InetSocketAddress(hostname, port); + } +- +- /** +- * Creates a new client which connects to the given address using the default {@link SocketFactory}. +- * +- * @param address the address of the Carbon server +- * @param batchSize how many metrics are bundled into a single pickle request to graphite +- */ +- public PickledGraphite(InetSocketAddress address, int batchSize) { +- this(address, SocketFactory.getDefault(), batchSize); +- } +- +- /** +- * Creates a new client which connects to the given address and socket factory. +- * +- * @param address the address of the Carbon server +- * @param socketFactory the socket factory +- * @param batchSize how many metrics are bundled into a single pickle request to graphite +- */ +- public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, int batchSize) { +- this(address, socketFactory, UTF_8, batchSize); ++ if (address.getAddress() == null) { ++ throw new UnknownHostException(address.getHostName()); + } + +- /** +- * Creates a new client which connects to the given address and socket factory using the given character set. +- * +- * @param address the address of the Carbon server +- * @param socketFactory the socket factory +- * @param charset the character set used by the server +- * @param batchSize how many metrics are bundled into a single pickle request to graphite +- */ +- public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, Charset charset, int batchSize) { +- this.address = address; +- this.hostname = null; +- this.port = -1; +- this.socketFactory = socketFactory; +- this.charset = charset; +- this.batchSize = batchSize; ++ this.socket = socketFactory.createSocket(address.getAddress(), address.getPort()); ++ this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); ++ } ++ ++ @Override ++ public boolean isConnected() { ++ return socket != null && socket.isConnected() && !socket.isClosed(); ++ } ++ ++ /** ++ * Convert the metric to a python tuple of the form: ++ * ++ *

(timestamp, (name, value)) ++ * ++ *

And add it to the list of metrics. If we reach the batch size, write them out. ++ * ++ * @param name the name of the metric ++ * @param value the value of the metric ++ * @param timestamp the timestamp of the metric ++ * @throws IOException if there was an error sending the metric ++ */ ++ @Override ++ public void send(String name, String value, long timestamp) throws IOException { ++ metrics.add(new MetricTuple(sanitize(name), timestamp, sanitize(value))); ++ ++ if (metrics.size() >= batchSize) { ++ writeMetrics(); + } ++ } + +- /** +- * Creates a new client which connects to the given address using the default {@link SocketFactory}. This defaults +- * to a batchSize of 100 +- * +- * @param hostname the hostname of the Carbon server +- * @param port the port of the Carbon server +- */ +- public PickledGraphite(String hostname, int port) { +- this(hostname, port, DEFAULT_BATCH_SIZE); ++ @Override ++ public void flush() throws IOException { ++ writeMetrics(); ++ if (writer != null) { ++ writer.flush(); + } +- +- /** +- * Creates a new client which connects to the given address using the default {@link SocketFactory}. +- * +- * @param hostname the hostname of the Carbon server +- * @param port the port of the Carbon server +- * @param batchSize how many metrics are bundled into a single pickle request to graphite +- */ +- public PickledGraphite(String hostname, int port, int batchSize) { +- this(hostname, port, SocketFactory.getDefault(), batchSize); +- } +- +- /** +- * Creates a new client which connects to the given address and socket factory. +- * +- * @param hostname the hostname of the Carbon server +- * @param port the port of the Carbon server +- * @param socketFactory the socket factory +- * @param batchSize how many metrics are bundled into a single pickle request to graphite +- */ +- public PickledGraphite(String hostname, int port, SocketFactory socketFactory, int batchSize) { +- this(hostname, port, socketFactory, UTF_8, batchSize); ++ } ++ ++ @Override ++ public void close() throws IOException { ++ try { ++ flush(); ++ if (writer != null) { ++ writer.close(); ++ } ++ } catch (IOException ex) { ++ if (socket != null) { ++ socket.close(); ++ } ++ } finally { ++ this.socket = null; ++ this.writer = null; + } +- +- /** +- * Creates a new client which connects to the given address and socket factory using the given character set. +- * +- * @param hostname the hostname of the Carbon server +- * @param port the port of the Carbon server +- * @param socketFactory the socket factory +- * @param charset the character set used by the server +- * @param batchSize how many metrics are bundled into a single pickle request to graphite +- */ +- public PickledGraphite(String hostname, int port, SocketFactory socketFactory, Charset charset, int batchSize) { +- this.address = null; +- this.hostname = hostname; +- this.port = port; +- this.socketFactory = socketFactory; +- this.charset = charset; +- this.batchSize = batchSize; +- } +- +- @Override +- public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } +- InetSocketAddress address = this.address; +- if (address == null) { +- address = new InetSocketAddress(hostname, port); +- } +- if (address.getAddress() == null) { +- throw new UnknownHostException(address.getHostName()); +- } +- +- this.socket = socketFactory.createSocket(address.getAddress(), address.getPort()); +- this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); +- } +- +- @Override +- public boolean isConnected() { +- return socket != null && socket.isConnected() && !socket.isClosed(); +- } +- +- /** +- * Convert the metric to a python tuple of the form: +- *

+- * (timestamp, (name, value)) +- *

+- * And add it to the list of metrics. If we reach the batch size, write them out. +- * +- * @param name the name of the metric +- * @param value the value of the metric +- * @param timestamp the timestamp of the metric +- * @throws IOException if there was an error sending the metric +- */ +- @Override +- public void send(String name, String value, long timestamp) throws IOException { +- metrics.add(new MetricTuple(sanitize(name), timestamp, sanitize(value))); +- +- if (metrics.size() >= batchSize) { +- writeMetrics(); +- } +- } +- +- @Override +- public void flush() throws IOException { +- writeMetrics(); +- if (writer != null) { +- writer.flush(); +- } +- } +- +- @Override +- public void close() throws IOException { +- try { +- flush(); +- if (writer != null) { +- writer.close(); +- } +- } catch (IOException ex) { +- if (socket != null) { +- socket.close(); +- } +- } finally { +- this.socket = null; +- this.writer = null; ++ } ++ ++ @Override ++ public int getFailures() { ++ return failures; ++ } ++ ++ /** ++ * 1. Run the pickler script to package all the pending metrics into a single message 2. Send the ++ * message to graphite 3. Clear out the list of metrics ++ */ ++ private void writeMetrics() throws IOException { ++ if (!metrics.isEmpty()) { ++ try { ++ byte[] payload = pickleMetrics(metrics); ++ byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); ++ ++ @SuppressWarnings("resource") ++ OutputStream outputStream = socket.getOutputStream(); ++ outputStream.write(header); ++ outputStream.write(payload); ++ outputStream.flush(); ++ ++ if (LOG.isDebugEnabled()) { ++ LOG.debug("Wrote {} metrics", metrics.size()); + } ++ } catch (IOException e) { ++ this.failures++; ++ throw e; ++ } finally { ++ // if there was an error, we might miss some data. for now, drop those on the floor and ++ // try to keep going. ++ metrics.clear(); ++ } + } +- +- @Override +- public int getFailures() { +- return failures; ++ } ++ ++ /** ++ * See: http://readthedocs.org/docs/graphite/en/1.0/feeding-carbon.html ++ * ++ * @throws IOException shouldn't happen because we write to memory. ++ */ ++ byte[] pickleMetrics(List metrics) throws IOException { ++ // Extremely rough estimate of 75 bytes per message ++ ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75); ++ Writer pickled = new OutputStreamWriter(out, charset); ++ ++ pickled.append(MARK); ++ pickled.append(LIST); ++ ++ for (MetricTuple tuple : metrics) { ++ // start the outer tuple ++ pickled.append(MARK); ++ ++ // the metric name is a string. ++ pickled.append(STRING); ++ // the single quotes are to match python's repr("abcd") ++ pickled.append(QUOTE); ++ pickled.append(tuple.name); ++ pickled.append(QUOTE); ++ pickled.append(LF); ++ ++ // start the inner tuple ++ pickled.append(MARK); ++ ++ // timestamp is a long ++ pickled.append(LONG); ++ pickled.append(Long.toString(tuple.timestamp)); ++ // the trailing L is to match python's repr(long(1234)) ++ pickled.append(LONG); ++ pickled.append(LF); ++ ++ // and the value is a string. ++ pickled.append(STRING); ++ pickled.append(QUOTE); ++ pickled.append(tuple.value); ++ pickled.append(QUOTE); ++ pickled.append(LF); ++ ++ pickled.append(TUPLE); // inner close ++ pickled.append(TUPLE); // outer close ++ ++ pickled.append(APPEND); + } + +- /** +- * 1. Run the pickler script to package all the pending metrics into a single message +- * 2. Send the message to graphite +- * 3. Clear out the list of metrics +- */ +- private void writeMetrics() throws IOException { +- if (metrics.size() > 0) { +- try { +- byte[] payload = pickleMetrics(metrics); +- byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); +- +- @SuppressWarnings("resource") +- OutputStream outputStream = socket.getOutputStream(); +- outputStream.write(header); +- outputStream.write(payload); +- outputStream.flush(); +- +- if (LOGGER.isDebugEnabled()) { +- LOGGER.debug("Wrote {} metrics", metrics.size()); +- } +- } catch (IOException e) { +- this.failures++; +- throw e; +- } finally { +- // if there was an error, we might miss some data. for now, drop those on the floor and +- // try to keep going. +- metrics.clear(); +- } +- +- } +- } ++ // every pickle ends with STOP ++ pickled.append(STOP); + +- /** +- * See: http://readthedocs.org/docs/graphite/en/1.0/feeding-carbon.html +- * +- * @throws IOException shouldn't happen because we write to memory. +- */ +- byte[] pickleMetrics(List metrics) throws IOException { +- // Extremely rough estimate of 75 bytes per message +- ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75); +- Writer pickled = new OutputStreamWriter(out, charset); +- +- pickled.append(MARK); +- pickled.append(LIST); +- +- for (MetricTuple tuple : metrics) { +- // start the outer tuple +- pickled.append(MARK); +- +- // the metric name is a string. +- pickled.append(STRING); +- // the single quotes are to match python's repr("abcd") +- pickled.append(QUOTE); +- pickled.append(tuple.name); +- pickled.append(QUOTE); +- pickled.append(LF); +- +- // start the inner tuple +- pickled.append(MARK); +- +- // timestamp is a long +- pickled.append(LONG); +- pickled.append(Long.toString(tuple.timestamp)); +- // the trailing L is to match python's repr(long(1234)) +- pickled.append(LONG); +- pickled.append(LF); +- +- // and the value is a string. +- pickled.append(STRING); +- pickled.append(QUOTE); +- pickled.append(tuple.value); +- pickled.append(QUOTE); +- pickled.append(LF); +- +- pickled.append(TUPLE); // inner close +- pickled.append(TUPLE); // outer close +- +- pickled.append(APPEND); +- } ++ pickled.flush(); + +- // every pickle ends with STOP +- pickled.append(STOP); +- +- pickled.flush(); +- +- return out.toByteArray(); +- } +- +- protected String sanitize(String s) { +- return GraphiteSanitize.sanitize(s); +- } ++ return out.toByteArray(); ++ } + ++ protected String sanitize(String s) { ++ return GraphiteSanitize.sanitize(s); ++ } + } +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java +@@ -1,14 +1,5 @@ + package io.dropwizard.metrics5.graphite; + +-import com.rabbitmq.client.Channel; +-import com.rabbitmq.client.Connection; +-import com.rabbitmq.client.ConnectionFactory; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import java.io.IOException; +-import java.net.UnknownHostException; +- + import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown; +@@ -17,111 +8,118 @@ import static org.mockito.Mockito.anyString; + import static org.mockito.Mockito.atMost; + import static org.mockito.Mockito.doThrow; + import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +-class GraphiteRabbitMQTest { +- private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); +- private final Connection connection = mock(Connection.class); +- private final Channel channel = mock(Channel.class); +- +- private final ConnectionFactory bogusConnectionFactory = mock(ConnectionFactory.class); +- private final Connection bogusConnection = mock(Connection.class); +- private final Channel bogusChannel = mock(Channel.class); +- +- private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); +- +- @BeforeEach +- void setUp() throws Exception { +- when(connectionFactory.newConnection()).thenReturn(connection); +- when(connection.createChannel()).thenReturn(channel); +- when(connection.isOpen()).thenReturn(true); +- +- when(bogusConnectionFactory.newConnection()).thenReturn(bogusConnection); +- when(bogusConnection.createChannel()).thenReturn(bogusChannel); +- doThrow(new IOException()) +- .when(bogusChannel) +- .basicPublish(anyString(), anyString(), any(), any(byte[].class)); +- } +- +- @Test +- void shouldConnectToGraphiteServer() throws Exception { +- graphite.connect(); +- +- verify(connectionFactory, atMost(1)).newConnection(); +- verify(connection, atMost(1)).createChannel(); +- +- } ++import com.rabbitmq.client.Channel; ++import com.rabbitmq.client.Connection; ++import com.rabbitmq.client.ConnectionFactory; ++import java.io.IOException; ++import java.net.UnknownHostException; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +- @Test +- void measuresFailures() throws Exception { +- try (final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(bogusConnectionFactory, "graphite")) { +- graphite.connect(); +- try { +- graphite.send("name", "value", 0); +- failBecauseExceptionWasNotThrown(IOException.class); +- } catch (IOException e) { +- assertThat(graphite.getFailures()).isEqualTo(1); +- } +- } ++final class GraphiteRabbitMQTest { ++ private final ConnectionFactory connectionFactory = mock(); ++ private final Connection connection = mock(); ++ private final Channel channel = mock(); ++ ++ private final ConnectionFactory bogusConnectionFactory = mock(); ++ private final Connection bogusConnection = mock(); ++ private final Channel bogusChannel = mock(); ++ ++ private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ when(connectionFactory.newConnection()).thenReturn(connection); ++ when(connection.createChannel()).thenReturn(channel); ++ when(connection.isOpen()).thenReturn(true); ++ ++ when(bogusConnectionFactory.newConnection()).thenReturn(bogusConnection); ++ when(bogusConnection.createChannel()).thenReturn(bogusChannel); ++ doThrow(new IOException()) ++ .when(bogusChannel) ++ .basicPublish(anyString(), anyString(), any(), any(byte[].class)); ++ } ++ ++ @Test ++ void shouldConnectToGraphiteServer() throws Exception { ++ graphite.connect(); ++ ++ verify(connectionFactory, atMost(1)).newConnection(); ++ verify(connection, atMost(1)).createChannel(); ++ } ++ ++ @Test ++ void measuresFailures() throws Exception { ++ try (final GraphiteRabbitMQ graphite = ++ new GraphiteRabbitMQ(bogusConnectionFactory, "graphite")) { ++ graphite.connect(); ++ try { ++ graphite.send("name", "value", 0); ++ failBecauseExceptionWasNotThrown(IOException.class); ++ } catch (IOException e) { ++ assertThat(graphite.getFailures()).isEqualTo(1); ++ } + } +- +- @Test +- void shouldDisconnectsFromGraphiteServer() throws Exception { +- graphite.connect(); +- graphite.close(); +- +- verify(connection).close(); ++ } ++ ++ @Test ++ void shouldDisconnectsFromGraphiteServer() throws Exception { ++ graphite.connect(); ++ graphite.close(); ++ ++ verify(connection).close(); ++ } ++ ++ @Test ++ void shouldNotConnectToGraphiteServerMoreThenOnce() throws Exception { ++ graphite.connect(); ++ try { ++ graphite.connect(); ++ failBecauseExceptionWasNotThrown(IllegalStateException.class); ++ } catch (IllegalStateException e) { ++ assertThat(e.getMessage()).isEqualTo("Already connected"); + } ++ } + +- @Test +- void shouldNotConnectToGraphiteServerMoreThenOnce() throws Exception { +- graphite.connect(); +- try { +- graphite.connect(); +- failBecauseExceptionWasNotThrown(IllegalStateException.class); +- } catch (IllegalStateException e) { +- assertThat(e.getMessage()).isEqualTo("Already connected"); +- } +- } ++ @Test ++ void shouldSendMetricsToGraphiteServer() throws Exception { ++ graphite.connect(); ++ graphite.send("name", "value", 100); + +- @Test +- void shouldSendMetricsToGraphiteServer() throws Exception { +- graphite.connect(); +- graphite.send("name", "value", 100); ++ String expectedMessage = "name value 100\n"; + +- String expectedMessage = "name value 100\n"; ++ verify(channel).basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); + +- verify(channel, times(1)).basicPublish("graphite", "name", null, +- expectedMessage.getBytes(UTF_8)); ++ assertThat(graphite.getFailures()).isEqualTo(0); ++ } + +- assertThat(graphite.getFailures()).isZero(); +- } ++ @Test ++ void shouldSanitizeAndSendMetricsToGraphiteServer() throws Exception { ++ graphite.connect(); ++ graphite.send("name to sanitize", "value to sanitize", 100); + +- @Test +- void shouldSanitizeAndSendMetricsToGraphiteServer() throws Exception { +- graphite.connect(); +- graphite.send("name to sanitize", "value to sanitize", 100); ++ String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; + +- String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; ++ verify(channel) ++ .basicPublish("graphite", "name-to-sanitize", null, expectedMessage.getBytes(UTF_8)); + +- verify(channel, times(1)).basicPublish("graphite", "name-to-sanitize", null, +- expectedMessage.getBytes(UTF_8)); ++ assertThat(graphite.getFailures()).isEqualTo(0); ++ } + +- assertThat(graphite.getFailures()).isZero(); +- } ++ @Test ++ void shouldFailWhenGraphiteHostUnavailable() { ++ ConnectionFactory connectionFactory = new ConnectionFactory(); ++ connectionFactory.setHost("some-unknown-host"); + +- @Test +- void shouldFailWhenGraphiteHostUnavailable() { +- ConnectionFactory connectionFactory = new ConnectionFactory(); +- connectionFactory.setHost("some-unknown-host"); +- +- try (GraphiteRabbitMQ unavailableGraphite = new GraphiteRabbitMQ(connectionFactory, "graphite")) { +- unavailableGraphite.connect(); +- failBecauseExceptionWasNotThrown(UnknownHostException.class); +- } catch (Exception e) { +- assertThat(e.getMessage()).contains("some-unknown-host"); +- } ++ try (GraphiteRabbitMQ unavailableGraphite = ++ new GraphiteRabbitMQ(connectionFactory, "graphite")) { ++ unavailableGraphite.connect(); ++ failBecauseExceptionWasNotThrown(UnknownHostException.class); ++ } catch (Exception e) { ++ assertThat(e.getMessage()).contains("some-unknown-host"); + } ++ } + } +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java +@@ -1,5 +1,14 @@ + package io.dropwizard.metrics5.graphite; + ++import static org.mockito.Mockito.doThrow; ++import static org.mockito.Mockito.inOrder; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.never; ++import static org.mockito.Mockito.times; ++import static org.mockito.Mockito.verifyNoMoreInteractions; ++import static org.mockito.Mockito.when; ++ ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -11,479 +20,411 @@ import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +-import org.mockito.InOrder; +- + import java.net.UnknownHostException; + import java.text.DecimalFormat; + import java.text.DecimalFormatSymbols; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.Locale; + import java.util.Set; + import java.util.SortedMap; + import java.util.TreeMap; + import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; ++import org.mockito.InOrder; + +-import static org.mockito.Mockito.doThrow; +-import static org.mockito.Mockito.inOrder; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; +-import static org.mockito.Mockito.verifyNoMoreInteractions; +-import static org.mockito.Mockito.when; +- +-class GraphiteReporterTest { +- private static final MetricName GAUGE = MetricName.build("gauge"); +- private static final MetricName METER = MetricName.build("meter"); +- private static final MetricName COUNTER = MetricName.build("counter"); +- +- private final long timestamp = 1000198; +- private final Clock clock = mock(Clock.class); +- private final Graphite graphite = mock(Graphite.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final GraphiteReporter reporter = GraphiteReporter.forRegistry(registry) +- .withClock(clock) +- .prefixedWith("prefix") +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) +- .build(graphite); +- +- private final GraphiteReporter minuteRateReporter = GraphiteReporter +- .forRegistry(registry) +- .withClock(clock) +- .prefixedWith("prefix") +- .convertRatesTo(TimeUnit.MINUTES) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) +- .build(graphite); +- +- @BeforeEach +- void setUp() { +- when(clock.getTime()).thenReturn(timestamp * 1000); +- } +- +- @Test +- void doesNotReportStringGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge("value")), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite, never()).send("prefix.gauge", "value", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsByteGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge((byte) 1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsShortGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge((short) 1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsIntegerGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsLongGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(1L)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsFloatGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(1.1f)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.gauge", "1.10", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsDoubleGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(1.1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.gauge", "1.10", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsDoubleGaugeValuesWithCustomFormat() throws Exception { +- try (final GraphiteReporter graphiteReporter = getReporterWithCustomFormat()) { +- reportGaugeValue(graphiteReporter, 1.13574); +- verifyGraphiteSentCorrectMetricValue("prefix.gauge", "1.1357", timestamp); +- verifyNoMoreInteractions(graphite); +- } ++final class GraphiteReporterTest { ++ private static final MetricName GAUGE = MetricName.build("gauge"); ++ private static final MetricName METER = MetricName.build("meter"); ++ private static final MetricName COUNTER = MetricName.build("counter"); ++ ++ private final long timestamp = 1000198; ++ private final Clock clock = mock(); ++ private final Graphite graphite = mock(); ++ private final MetricRegistry registry = mock(); ++ private final GraphiteReporter reporter = ++ GraphiteReporter.forRegistry(registry) ++ .withClock(clock) ++ .prefixedWith("prefix") ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(ImmutableSet.of()) ++ .build(graphite); ++ ++ private final GraphiteReporter minuteRateReporter = ++ GraphiteReporter.forRegistry(registry) ++ .withClock(clock) ++ .prefixedWith("prefix") ++ .convertRatesTo(TimeUnit.MINUTES) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(ImmutableSet.of()) ++ .build(graphite); ++ ++ @BeforeEach ++ void setUp() { ++ when(clock.getTime()).thenReturn(timestamp * 1000); ++ } ++ ++ @Test ++ void doesNotReportStringGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge("value")), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite, never()).send("prefix.gauge", "value", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsByteGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge((byte) 1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsShortGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge((short) 1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsIntegerGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsLongGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(1L)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsFloatGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(1.1f)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.gauge", "1.10", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsDoubleGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(1.1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.gauge", "1.10", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsDoubleGaugeValuesWithCustomFormat() throws Exception { ++ try (final GraphiteReporter graphiteReporter = getReporterWithCustomFormat()) { ++ reportGaugeValue(graphiteReporter, 1.13574); ++ verifyGraphiteSentCorrectMetricValue("prefix.gauge", "1.1357", timestamp); ++ verifyNoMoreInteractions(graphite); + } ++ } + +- @Test +- void reportDoubleGaugeValuesUsingCustomFormatter() throws Exception { +- DecimalFormat formatter = new DecimalFormat("##.##########", DecimalFormatSymbols.getInstance(Locale.US)); ++ @Test ++ void reportDoubleGaugeValuesUsingCustomFormatter() throws Exception { ++ DecimalFormat formatter = ++ new DecimalFormat("##.##########", DecimalFormatSymbols.getInstance(Locale.US)); + +- try (GraphiteReporter graphiteReporter = GraphiteReporter.forRegistry(registry) ++ try (GraphiteReporter graphiteReporter = ++ GraphiteReporter.forRegistry(registry) + .withClock(clock) + .prefixedWith("prefix") + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .withFloatingPointFormatter(formatter::format) + .build(graphite)) { +- reportGaugeValue(graphiteReporter, 0.000045322); +- verifyGraphiteSentCorrectMetricValue("prefix.gauge", "0.000045322", timestamp); +- verifyNoMoreInteractions(graphite); +- } ++ reportGaugeValue(graphiteReporter, 0.000045322); ++ verifyGraphiteSentCorrectMetricValue("prefix.gauge", "0.000045322", timestamp); ++ verifyNoMoreInteractions(graphite); + } +- +- private void reportGaugeValue(GraphiteReporter graphiteReporter, double value) { +- graphiteReporter.report(map(MetricName.build("gauge"), gauge(value)), +- map(), +- map(), +- map(), +- map()); +- } +- +- private void verifyGraphiteSentCorrectMetricValue(String metricName, String value, long timestamp) throws Exception { +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send(metricName, value, timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- } +- +- @Test +- void reportsBooleanGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(true)), +- map(), +- map(), +- map(), +- map()); +- +- reporter.report(map(GAUGE, gauge(false)), +- map(), +- map(), +- map(), +- map()); +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.gauge", "0", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsCounters() throws Exception { +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(100L); +- +- reporter.report(map(), +- map(COUNTER, counter), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.counter.count", "100", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); +- when(histogram.getCount()).thenReturn(1L); +- when(histogram.getSum()).thenReturn(12L); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(2L); +- when(snapshot.getMean()).thenReturn(3.0); +- when(snapshot.getMin()).thenReturn(4L); +- when(snapshot.getStdDev()).thenReturn(5.0); +- when(snapshot.getMedian()).thenReturn(6.0); +- when(snapshot.get75thPercentile()).thenReturn(7.0); +- when(snapshot.get95thPercentile()).thenReturn(8.0); +- when(snapshot.get98thPercentile()).thenReturn(9.0); +- when(snapshot.get99thPercentile()).thenReturn(10.0); +- when(snapshot.get999thPercentile()).thenReturn(11.0); +- +- when(histogram.getSnapshot()).thenReturn(snapshot); +- +- reporter.report(map(), +- map(), +- map(MetricName.build("histogram"), histogram), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.histogram.count", "1", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.sum", "12", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.max", "2", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.mean", "3.00", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.min", "4", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.stddev", "5.00", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.p50", "6.00", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.p75", "7.00", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.p95", "8.00", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.p98", "9.00", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.p99", "10.00", timestamp); +- inOrder.verify(graphite).send("prefix.histogram.p999", "11.00", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsMeters() throws Exception { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(6L); +- when(meter.getOneMinuteRate()).thenReturn(2.0); +- when(meter.getFiveMinuteRate()).thenReturn(3.0); +- when(meter.getFifteenMinuteRate()).thenReturn(4.0); +- when(meter.getMeanRate()).thenReturn(5.0); +- +- reporter.report(map(), +- map(), +- map(), +- map(METER, meter), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); +- inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.m1_rate", "2.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.m5_rate", "3.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.m15_rate", "4.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.mean_rate", "5.00", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsMetersInMinutes() throws Exception { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(6L); +- when(meter.getOneMinuteRate()).thenReturn(2.0); +- when(meter.getFiveMinuteRate()).thenReturn(3.0); +- when(meter.getFifteenMinuteRate()).thenReturn(4.0); +- when(meter.getMeanRate()).thenReturn(5.0); +- +- minuteRateReporter.report(this.map(), +- this.map(), +- this.map(), +- this.map(METER, meter), +- this.map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); +- inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.m1_rate", "120.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.m5_rate", "180.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.m15_rate", "240.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.mean_rate", "300.00", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void reportsTimers() throws Exception { +- final Timer timer = mock(Timer.class); +- when(timer.getCount()).thenReturn(1L); +- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); +- when(timer.getMeanRate()).thenReturn(2.0); +- when(timer.getOneMinuteRate()).thenReturn(3.0); +- when(timer.getFiveMinuteRate()).thenReturn(4.0); +- when(timer.getFifteenMinuteRate()).thenReturn(5.0); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); +- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); +- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); +- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); +- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); +- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); +- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); +- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); +- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS +- .toNanos(1000)); +- +- when(timer.getSnapshot()).thenReturn(snapshot); +- +- reporter.report(map(), +- map(), +- map(), +- map(), +- map(MetricName.build("timer"), timer)); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.timer.max", "100.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.mean", "200.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.min", "300.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.stddev", "400.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.p50", "500.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.p75", "600.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.p95", "700.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.p98", "800.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.p99", "900.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.p999", "1000.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.count", "1", timestamp); +- inOrder.verify(graphite).send("prefix.timer.sum", "6.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.m1_rate", "3.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.m5_rate", "4.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.m15_rate", "5.00", timestamp); +- inOrder.verify(graphite).send("prefix.timer.mean_rate", "2.00", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- +- reporter.close(); +- } +- +- @Test +- void closesConnectionIfGraphiteIsUnavailable() throws Exception { +- doThrow(new UnknownHostException("UNKNOWN-HOST")).when(graphite).connect(); +- reporter.report(map(GAUGE, gauge(1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).close(); +- +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void closesConnectionOnReporterStop() throws Exception { +- reporter.start(1, TimeUnit.SECONDS); +- reporter.stop(); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite, times(2)).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void disabledMetricsAttribute() throws Exception { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(6L); +- when(meter.getOneMinuteRate()).thenReturn(2.0); +- when(meter.getFiveMinuteRate()).thenReturn(3.0); +- when(meter.getFifteenMinuteRate()).thenReturn(4.0); +- when(meter.getMeanRate()).thenReturn(5.0); +- +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(11L); +- +- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE); +- GraphiteReporter reporterWithdisabledMetricAttributes = GraphiteReporter.forRegistry(registry) ++ } ++ ++ private void reportGaugeValue(GraphiteReporter graphiteReporter, double value) { ++ graphiteReporter.report( ++ map(MetricName.build("gauge"), gauge(value)), map(), map(), map(), map()); ++ } ++ ++ private void verifyGraphiteSentCorrectMetricValue(String metricName, String value, long timestamp) ++ throws Exception { ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send(metricName, value, timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ } ++ ++ @Test ++ void reportsBooleanGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(true)), map(), map(), map(), map()); ++ ++ reporter.report(map(GAUGE, gauge(false)), map(), map(), map(), map()); ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.gauge", "0", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsCounters() throws Exception { ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(100L); ++ ++ reporter.report(map(), map(COUNTER, counter), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.counter.count", "100", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsHistograms() throws Exception { ++ final Histogram histogram = mock(); ++ when(histogram.getCount()).thenReturn(1L); ++ when(histogram.getSum()).thenReturn(12L); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(2L); ++ when(snapshot.getMean()).thenReturn(3.0); ++ when(snapshot.getMin()).thenReturn(4L); ++ when(snapshot.getStdDev()).thenReturn(5.0); ++ when(snapshot.getMedian()).thenReturn(6.0); ++ when(snapshot.get75thPercentile()).thenReturn(7.0); ++ when(snapshot.get95thPercentile()).thenReturn(8.0); ++ when(snapshot.get98thPercentile()).thenReturn(9.0); ++ when(snapshot.get99thPercentile()).thenReturn(10.0); ++ when(snapshot.get999thPercentile()).thenReturn(11.0); ++ ++ when(histogram.getSnapshot()).thenReturn(snapshot); ++ ++ reporter.report(map(), map(), map(MetricName.build("histogram"), histogram), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.histogram.count", "1", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.sum", "12", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.max", "2", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.mean", "3.00", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.min", "4", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.stddev", "5.00", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.p50", "6.00", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.p75", "7.00", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.p95", "8.00", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.p98", "9.00", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.p99", "10.00", timestamp); ++ inOrder.verify(graphite).send("prefix.histogram.p999", "11.00", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsMeters() throws Exception { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(6L); ++ when(meter.getOneMinuteRate()).thenReturn(2.0); ++ when(meter.getFiveMinuteRate()).thenReturn(3.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(4.0); ++ when(meter.getMeanRate()).thenReturn(5.0); ++ ++ reporter.report(map(), map(), map(), map(METER, meter), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.m1_rate", "2.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.m5_rate", "3.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.m15_rate", "4.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.mean_rate", "5.00", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsMetersInMinutes() throws Exception { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(6L); ++ when(meter.getOneMinuteRate()).thenReturn(2.0); ++ when(meter.getFiveMinuteRate()).thenReturn(3.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(4.0); ++ when(meter.getMeanRate()).thenReturn(5.0); ++ ++ minuteRateReporter.report( ++ this.map(), this.map(), this.map(), this.map(METER, meter), this.map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.m1_rate", "120.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.m5_rate", "180.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.m15_rate", "240.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.mean_rate", "300.00", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void reportsTimers() throws Exception { ++ final Timer timer = mock(); ++ when(timer.getCount()).thenReturn(1L); ++ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); ++ when(timer.getMeanRate()).thenReturn(2.0); ++ when(timer.getOneMinuteRate()).thenReturn(3.0); ++ when(timer.getFiveMinuteRate()).thenReturn(4.0); ++ when(timer.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); ++ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); ++ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ++ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); ++ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); ++ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); ++ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); ++ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); ++ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); ++ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); ++ ++ when(timer.getSnapshot()).thenReturn(snapshot); ++ ++ reporter.report(map(), map(), map(), map(), map(MetricName.build("timer"), timer)); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.timer.max", "100.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.mean", "200.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.min", "300.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.stddev", "400.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.p50", "500.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.p75", "600.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.p95", "700.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.p98", "800.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.p99", "900.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.p999", "1000.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.count", "1", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.sum", "6.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.m1_rate", "3.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.m5_rate", "4.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.m15_rate", "5.00", timestamp); ++ inOrder.verify(graphite).send("prefix.timer.mean_rate", "2.00", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ ++ reporter.close(); ++ } ++ ++ @Test ++ void closesConnectionIfGraphiteIsUnavailable() throws Exception { ++ doThrow(new UnknownHostException("UNKNOWN-HOST")).when(graphite).connect(); ++ reporter.report(map(GAUGE, gauge(1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void closesConnectionOnReporterStop() throws Exception { ++ reporter.start(1, TimeUnit.SECONDS); ++ reporter.stop(); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite, times(2)).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void disabledMetricsAttribute() throws Exception { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(6L); ++ when(meter.getOneMinuteRate()).thenReturn(2.0); ++ when(meter.getFiveMinuteRate()).thenReturn(3.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(4.0); ++ when(meter.getMeanRate()).thenReturn(5.0); ++ ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(11L); ++ ++ Set disabledMetricAttributes = ++ EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE); ++ GraphiteReporter reporterWithdisabledMetricAttributes = ++ GraphiteReporter.forRegistry(registry) + .withClock(clock) + .prefixedWith("prefix") + .convertRatesTo(TimeUnit.SECONDS) +@@ -491,79 +432,82 @@ class GraphiteReporterTest { + .filter(MetricFilter.ALL) + .disabledMetricAttributes(disabledMetricAttributes) + .build(graphite); +- reporterWithdisabledMetricAttributes.report(map(), +- map(COUNTER, counter), +- map(), +- map(METER, meter), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.counter.count", "11", timestamp); +- inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); +- inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.m1_rate", "2.00", timestamp); +- inOrder.verify(graphite).send("prefix.meter.mean_rate", "5.00", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- @Test +- void sendsMetricAttributesAsTagsIfEnabled() throws Exception { +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(100L); +- +- getReporterThatSendsMetricAttributesAsTags().report(map(), +- map(COUNTER, counter), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(graphite); +- inOrder.verify(graphite).connect(); +- inOrder.verify(graphite).send("prefix.counter;metricattribute=count", "100", timestamp); +- inOrder.verify(graphite).flush(); +- inOrder.verify(graphite).close(); +- +- verifyNoMoreInteractions(graphite); +- } +- +- private GraphiteReporter getReporterWithCustomFormat() { +- return new GraphiteReporter(registry, graphite, clock, "prefix", +- TimeUnit.SECONDS, TimeUnit.MICROSECONDS, MetricFilter.ALL, null, false, +- Collections.emptySet(), false) { +- @Override +- protected String format(double v) { +- return String.format(Locale.US, "%4.4f", v); +- } +- }; +- } +- +- private GraphiteReporter getReporterThatSendsMetricAttributesAsTags() { +- return GraphiteReporter.forRegistry(registry) +- .withClock(clock) +- .prefixedWith("prefix") +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) +- .addMetricAttributesAsTags(true) +- .build(graphite); +- } ++ reporterWithdisabledMetricAttributes.report( ++ map(), map(COUNTER, counter), map(), map(METER, meter), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.counter.count", "11", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.m1_rate", "2.00", timestamp); ++ inOrder.verify(graphite).send("prefix.meter.mean_rate", "5.00", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ @Test ++ void sendsMetricAttributesAsTagsIfEnabled() throws Exception { ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(100L); ++ ++ getReporterThatSendsMetricAttributesAsTags() ++ .report(map(), map(COUNTER, counter), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(graphite); ++ inOrder.verify(graphite).connect(); ++ inOrder.verify(graphite).send("prefix.counter;metricattribute=count", "100", timestamp); ++ inOrder.verify(graphite).flush(); ++ inOrder.verify(graphite).close(); ++ ++ verifyNoMoreInteractions(graphite); ++ } ++ ++ private GraphiteReporter getReporterWithCustomFormat() { ++ return new GraphiteReporter( ++ registry, ++ graphite, ++ clock, ++ "prefix", ++ TimeUnit.SECONDS, ++ TimeUnit.MICROSECONDS, ++ MetricFilter.ALL, ++ null, ++ false, ++ ImmutableSet.of(), ++ false) { ++ @Override ++ protected String format(double v) { ++ return String.format(Locale.US, "%4.4f", v); ++ } ++ }; ++ } ++ ++ private GraphiteReporter getReporterThatSendsMetricAttributesAsTags() { ++ return GraphiteReporter.forRegistry(registry) ++ .withClock(clock) ++ .prefixedWith("prefix") ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(ImmutableSet.of()) ++ .addMetricAttributesAsTags(true) ++ .build(graphite); ++ } + +- private SortedMap map() { +- return new TreeMap<>(); +- } ++ private SortedMap map() { ++ return new TreeMap<>(); ++ } + +- private SortedMap map(MetricName name, T metric) { +- final TreeMap map = new TreeMap<>(); +- map.put(name, metric); +- return map; +- } ++ private SortedMap map(MetricName name, T metric) { ++ final TreeMap map = new TreeMap<>(); ++ map.put(name, metric); ++ return map; ++ } + +- private Gauge gauge(T value) { +- return () -> value; +- } ++ private Gauge gauge(T value) { ++ return () -> value; ++ } + } +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java +@@ -3,25 +3,27 @@ package io.dropwizard.metrics5.graphite; + import org.assertj.core.api.SoftAssertions; + import org.junit.jupiter.api.Test; + +-class GraphiteSanitizeTest { +- @Test +- void sanitizeGraphiteValues() { +- SoftAssertions softly = new SoftAssertions(); ++final class GraphiteSanitizeTest { ++ @Test ++ void sanitizeGraphiteValues() { ++ SoftAssertions softly = new SoftAssertions(); + +- softly.assertThat(GraphiteSanitize.sanitize("Foo Bar")).isEqualTo("Foo-Bar"); +- softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar ")).isEqualTo("Foo-Bar"); +- softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar")).isEqualTo("Foo-Bar"); +- softly.assertThat(GraphiteSanitize.sanitize("Foo Bar ")).isEqualTo("Foo-Bar"); +- softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar ")).isEqualTo("Foo-Bar"); +- softly.assertThat(GraphiteSanitize.sanitize("Foo@Bar")).isEqualTo("Foo@Bar"); +- softly.assertThat(GraphiteSanitize.sanitize("Foó Bar")).isEqualTo("Foó-Bar"); +- softly.assertThat(GraphiteSanitize.sanitize("||ó/.")).isEqualTo("||ó/."); +- softly.assertThat(GraphiteSanitize.sanitize("${Foo:Bar:baz}")).isEqualTo("${Foo:Bar:baz}"); +- softly.assertThat(GraphiteSanitize.sanitize("St. Foo's of Bar")).isEqualTo("St.-Foo's-of-Bar"); +- softly.assertThat(GraphiteSanitize.sanitize("(Foo and (Bar and (Baz)))")).isEqualTo("(Foo-and-(Bar-and-(Baz)))"); +- softly.assertThat(GraphiteSanitize.sanitize("Foo.bar.baz")).isEqualTo("Foo.bar.baz"); +- softly.assertThat(GraphiteSanitize.sanitize("FooBar")).isEqualTo("FooBar"); ++ softly.assertThat(GraphiteSanitize.sanitize("Foo Bar")).isEqualTo("Foo-Bar"); ++ softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar ")).isEqualTo("Foo-Bar"); ++ softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar")).isEqualTo("Foo-Bar"); ++ softly.assertThat(GraphiteSanitize.sanitize("Foo Bar ")).isEqualTo("Foo-Bar"); ++ softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar ")).isEqualTo("Foo-Bar"); ++ softly.assertThat(GraphiteSanitize.sanitize("Foo@Bar")).isEqualTo("Foo@Bar"); ++ softly.assertThat(GraphiteSanitize.sanitize("Foó Bar")).isEqualTo("Foó-Bar"); ++ softly.assertThat(GraphiteSanitize.sanitize("||ó/.")).isEqualTo("||ó/."); ++ softly.assertThat(GraphiteSanitize.sanitize("${Foo:Bar:baz}")).isEqualTo("${Foo:Bar:baz}"); ++ softly.assertThat(GraphiteSanitize.sanitize("St. Foo's of Bar")).isEqualTo("St.-Foo's-of-Bar"); ++ softly ++ .assertThat(GraphiteSanitize.sanitize("(Foo and (Bar and (Baz)))")) ++ .isEqualTo("(Foo-and-(Bar-and-(Baz)))"); ++ softly.assertThat(GraphiteSanitize.sanitize("Foo.bar.baz")).isEqualTo("Foo.bar.baz"); ++ softly.assertThat(GraphiteSanitize.sanitize("FooBar")).isEqualTo("FooBar"); + +- softly.assertAll(); +- } ++ softly.assertAll(); ++ } + } +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java +@@ -1,17 +1,5 @@ + package io.dropwizard.metrics5.graphite; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import javax.net.SocketFactory; +-import java.io.ByteArrayOutputStream; +-import java.io.IOException; +-import java.net.InetAddress; +-import java.net.InetSocketAddress; +-import java.net.Socket; +-import java.net.UnknownHostException; +-import java.util.concurrent.atomic.AtomicBoolean; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatNoException; + import static org.assertj.core.api.Assertions.assertThatThrownBy; +@@ -24,120 +12,137 @@ import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +-class GraphiteTest { +- private final String host = "example.com"; +- private final int port = 1234; +- private final SocketFactory socketFactory = mock(SocketFactory.class); +- private final InetSocketAddress address = new InetSocketAddress(host, port); +- +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); +- +- @BeforeEach +- void setUp() throws Exception { +- final AtomicBoolean connected = new AtomicBoolean(true); +- final AtomicBoolean closed = new AtomicBoolean(false); +- +- when(socket.isConnected()).thenAnswer(invocation -> connected.get()); +- +- when(socket.isClosed()).thenAnswer(invocation -> closed.get()); +- +- doAnswer(invocation -> { +- connected.set(false); +- closed.set(true); +- return null; +- }).when(socket).close(); +- +- when(socket.getOutputStream()).thenReturn(output); +- +- // Mock behavior of socket.getOutputStream().close() calling socket.close(); +- doAnswer(invocation -> { +- invocation.callRealMethod(); +- socket.close(); +- return null; +- }).when(output).close(); ++import java.io.ByteArrayOutputStream; ++import java.io.IOException; ++import java.net.InetAddress; ++import java.net.InetSocketAddress; ++import java.net.Socket; ++import java.net.UnknownHostException; ++import java.util.concurrent.atomic.AtomicBoolean; ++import javax.net.SocketFactory; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +- when(socketFactory.createSocket(any(InetAddress.class), anyInt())).thenReturn(socket); ++final class GraphiteTest { ++ private final String host = "example.com"; ++ private final int port = 1234; ++ private final SocketFactory socketFactory = mock(); ++ private final InetSocketAddress address = new InetSocketAddress(host, port); ++ ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ final AtomicBoolean connected = new AtomicBoolean(true); ++ final AtomicBoolean closed = new AtomicBoolean(false); ++ ++ when(socket.isConnected()).thenAnswer(invocation -> connected.get()); ++ ++ when(socket.isClosed()).thenAnswer(invocation -> closed.get()); ++ ++ doAnswer( ++ invocation -> { ++ connected.set(false); ++ closed.set(true); ++ return null; ++ }) ++ .when(socket) ++ .close(); ++ ++ when(socket.getOutputStream()).thenReturn(output); ++ ++ // Mock behavior of socket.getOutputStream().close() calling socket.close(); ++ doAnswer( ++ invocation -> { ++ invocation.callRealMethod(); ++ socket.close(); ++ return null; ++ }) ++ .when(output) ++ .close(); ++ ++ when(socketFactory.createSocket(any(InetAddress.class), anyInt())).thenReturn(socket); ++ } ++ ++ @Test ++ void connectsToGraphiteWithInetSocketAddress() throws Exception { ++ try (Graphite graphite = new Graphite(address, socketFactory)) { ++ graphite.connect(); + } ++ verify(socketFactory).createSocket(address.getAddress(), address.getPort()); ++ } + +- @Test +- void connectsToGraphiteWithInetSocketAddress() throws Exception { +- try (Graphite graphite = new Graphite(address, socketFactory)) { +- graphite.connect(); +- } +- verify(socketFactory).createSocket(address.getAddress(), address.getPort()); ++ @Test ++ void connectsToGraphiteWithHostAndPort() throws Exception { ++ try (Graphite graphite = new Graphite(host, port, socketFactory)) { ++ graphite.connect(); + } ++ verify(socketFactory).createSocket(address.getAddress(), port); ++ } + +- @Test +- void connectsToGraphiteWithHostAndPort() throws Exception { +- try (Graphite graphite = new Graphite(host, port, socketFactory)) { +- graphite.connect(); +- } +- verify(socketFactory).createSocket(address.getAddress(), port); ++ @Test ++ void measuresFailures() throws IOException { ++ try (Graphite graphite = new Graphite(address, socketFactory)) { ++ assertThat(graphite.getFailures()).isEqualTo(0); + } ++ } + +- @Test +- void measuresFailures() throws IOException { +- try (Graphite graphite = new Graphite(address, socketFactory)) { +- assertThat(graphite.getFailures()).isZero(); +- } ++ @Test ++ void disconnectsFromGraphite() throws Exception { ++ try (Graphite graphite = new Graphite(address, socketFactory)) { ++ graphite.connect(); + } + +- @Test +- void disconnectsFromGraphite() throws Exception { +- try (Graphite graphite = new Graphite(address, socketFactory)) { +- graphite.connect(); +- } +- +- verify(socket, times(2)).close(); +- } ++ verify(socket, times(2)).close(); ++ } + +- @Test +- void doesNotAllowDoubleConnections() throws Exception { +- try (Graphite graphite = new Graphite(address, socketFactory)) { +- assertThatNoException().isThrownBy(graphite::connect); +- assertThatThrownBy(graphite::connect) +- .isInstanceOf(IllegalStateException.class) +- .hasMessage("Already connected"); +- } ++ @Test ++ void doesNotAllowDoubleConnections() throws Exception { ++ try (Graphite graphite = new Graphite(address, socketFactory)) { ++ assertThatNoException().isThrownBy(graphite::connect); ++ assertThatThrownBy(graphite::connect) ++ .isInstanceOf(IllegalStateException.class) ++ .hasMessage("Already connected"); + } ++ } + +- @Test +- void writesValuesToGraphite() throws Exception { +- try (Graphite graphite = new Graphite(address, socketFactory)) { +- graphite.connect(); +- graphite.send("name", "value", 100); +- } +- assertThat(output).hasToString("name value 100\n"); ++ @Test ++ void writesValuesToGraphite() throws Exception { ++ try (Graphite graphite = new Graphite(address, socketFactory)) { ++ graphite.connect(); ++ graphite.send("name", "value", 100); + } +- +- @Test +- void sanitizesNames() throws Exception { +- try (Graphite graphite = new Graphite(address, socketFactory)) { +- graphite.connect(); +- graphite.send("name woo", "value", 100); +- } +- assertThat(output).hasToString("name-woo value 100\n"); ++ assertThat(output).hasToString("name value 100\n"); ++ } ++ ++ @Test ++ void sanitizesNames() throws Exception { ++ try (Graphite graphite = new Graphite(address, socketFactory)) { ++ graphite.connect(); ++ graphite.send("name woo", "value", 100); + } +- +- @Test +- void sanitizesValues() throws Exception { +- try (Graphite graphite = new Graphite(address, socketFactory)) { +- graphite.connect(); +- graphite.send("name", "value woo", 100); +- } +- assertThat(output).hasToString("name value-woo 100\n"); ++ assertThat(output).hasToString("name-woo value 100\n"); ++ } ++ ++ @Test ++ void sanitizesValues() throws Exception { ++ try (Graphite graphite = new Graphite(address, socketFactory)) { ++ graphite.connect(); ++ graphite.send("name", "value woo", 100); + } +- +- @Test +- void notifiesIfGraphiteIsUnavailable() throws IOException { +- final String unavailableHost = "unknown-host-10el6m7yg56ge7dmcom"; +- InetSocketAddress unavailableAddress = new InetSocketAddress(unavailableHost, 1234); +- +- try (Graphite unavailableGraphite = new Graphite(unavailableAddress, socketFactory)) { +- assertThatThrownBy(unavailableGraphite::connect) +- .isInstanceOf(UnknownHostException.class) +- .hasMessage(unavailableHost); +- } ++ assertThat(output).hasToString("name value-woo 100\n"); ++ } ++ ++ @Test ++ void notifiesIfGraphiteIsUnavailable() throws IOException { ++ final String unavailableHost = "unknown-host-10el6m7yg56ge7dmcom"; ++ InetSocketAddress unavailableAddress = new InetSocketAddress(unavailableHost, 1234); ++ ++ try (Graphite unavailableGraphite = new Graphite(unavailableAddress, socketFactory)) { ++ assertThatThrownBy(unavailableGraphite::connect) ++ .isInstanceOf(UnknownHostException.class) ++ .hasMessage(unavailableHost); + } ++ } + } +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java +@@ -1,43 +1,43 @@ + package io.dropwizard.metrics5.graphite; + +-import org.junit.jupiter.api.Test; +-import org.mockito.Mockito; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; + import java.nio.channels.DatagramChannel; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.verify; +- +-class GraphiteUDPTest { ++final class GraphiteUDPTest { + +- private final String host = "example.com"; +- private final int port = 1234; ++ private final String host = "example.com"; ++ private final int port = 1234; + +- private GraphiteUDP graphiteUDP; ++ private GraphiteUDP graphiteUDP; + +- @Test +- void connects() throws Exception { +- graphiteUDP = new GraphiteUDP(host, port); +- graphiteUDP.connect(); ++ @Test ++ void connects() throws Exception { ++ graphiteUDP = new GraphiteUDP(host, port); ++ graphiteUDP.connect(); + +- assertThat(graphiteUDP.getDatagramChannel()).isNotNull(); +- assertThat(graphiteUDP.getAddress()).isEqualTo(new InetSocketAddress(host, port)); ++ assertThat(graphiteUDP.getDatagramChannel()).isNotNull(); ++ assertThat(graphiteUDP.getAddress()).isEqualTo(new InetSocketAddress(host, port)); + +- graphiteUDP.close(); +- } ++ graphiteUDP.close(); ++ } + +- @Test +- void writesValue() throws Exception { +- graphiteUDP = new GraphiteUDP(host, port); +- DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); +- graphiteUDP.setDatagramChannel(mockDatagramChannel); +- graphiteUDP.setAddress(new InetSocketAddress(host, port)); ++ @Test ++ void writesValue() throws Exception { ++ graphiteUDP = new GraphiteUDP(host, port); ++ DatagramChannel mockDatagramChannel = mock(); ++ graphiteUDP.setDatagramChannel(mockDatagramChannel); ++ graphiteUDP.setAddress(new InetSocketAddress(host, port)); + +- graphiteUDP.send("name woo", "value", 100); +- verify(mockDatagramChannel).send(ByteBuffer.wrap("name-woo value 100\n".getBytes("UTF-8")), ++ graphiteUDP.send("name woo", "value", 100); ++ verify(mockDatagramChannel) ++ .send( ++ ByteBuffer.wrap("name-woo value 100\n".getBytes("UTF-8")), + new InetSocketAddress(host, port)); +- } +- +-} +\ No newline at end of file ++ } ++} +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java +@@ -1,26 +1,5 @@ + package io.dropwizard.metrics5.graphite; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +-import org.python.core.PyList; +-import org.python.core.PyTuple; +- +-import javax.net.SocketFactory; +-import javax.script.Bindings; +-import javax.script.Compilable; +-import javax.script.CompiledScript; +-import javax.script.ScriptEngine; +-import javax.script.ScriptEngineManager; +-import javax.script.SimpleBindings; +-import java.io.ByteArrayOutputStream; +-import java.io.InputStream; +-import java.io.InputStreamReader; +-import java.math.BigInteger; +-import java.net.InetAddress; +-import java.net.InetSocketAddress; +-import java.net.Socket; +-import java.util.concurrent.atomic.AtomicBoolean; +- + import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown; +@@ -32,150 +11,169 @@ import static org.mockito.Mockito.spy; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +-class PickledGraphiteTest { +- private final SocketFactory socketFactory = mock(SocketFactory.class); +- private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); +- private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); +- +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); +- +- private CompiledScript unpickleScript; +- +- @BeforeEach +- void setUp() throws Exception { +- final AtomicBoolean connected = new AtomicBoolean(true); +- final AtomicBoolean closed = new AtomicBoolean(false); +- +- when(socket.isConnected()).thenAnswer(invocation -> connected.get()); +- +- when(socket.isClosed()).thenAnswer(invocation -> closed.get()); ++import java.io.ByteArrayOutputStream; ++import java.io.InputStream; ++import java.io.InputStreamReader; ++import java.math.BigInteger; ++import java.net.InetAddress; ++import java.net.InetSocketAddress; ++import java.net.Socket; ++import java.util.concurrent.atomic.AtomicBoolean; ++import javax.net.SocketFactory; ++import javax.script.Bindings; ++import javax.script.Compilable; ++import javax.script.CompiledScript; ++import javax.script.ScriptEngine; ++import javax.script.ScriptEngineManager; ++import javax.script.SimpleBindings; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; ++import org.python.core.PyList; ++import org.python.core.PyTuple; + +- doAnswer(invocation -> { +- connected.set(false); +- closed.set(true); +- return null; +- }).when(socket).close(); ++final class PickledGraphiteTest { ++ private final SocketFactory socketFactory = mock(); ++ private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); ++ private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); + +- when(socket.getOutputStream()).thenReturn(output); ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); + +- // Mock behavior of socket.getOutputStream().close() calling socket.close(); +- doAnswer(invocation -> { +- invocation.callRealMethod(); +- socket.close(); +- return null; +- }).when(output).close(); ++ private CompiledScript unpickleScript; + +- when(socketFactory.createSocket(any(InetAddress.class), +- anyInt())).thenReturn(socket); ++ @BeforeEach ++ void setUp() throws Exception { ++ final AtomicBoolean connected = new AtomicBoolean(true); ++ final AtomicBoolean closed = new AtomicBoolean(false); + +- ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); +- Compilable compilable = (Compilable) engine; +- try (InputStream is = PickledGraphiteTest.class.getResource("/upickle.py").openStream()) { +- unpickleScript = compilable.compile(new InputStreamReader(is, UTF_8)); +- } +- } ++ when(socket.isConnected()).thenAnswer(invocation -> connected.get()); + +- @Test +- void disconnectsFromGraphite() throws Exception { +- graphite.connect(); +- graphite.close(); ++ when(socket.isClosed()).thenAnswer(invocation -> closed.get()); + +- verify(socket).close(); +- } ++ doAnswer( ++ invocation -> { ++ connected.set(false); ++ closed.set(true); ++ return null; ++ }) ++ .when(socket) ++ .close(); + +- @Test +- void writesValuesToGraphite() throws Exception { +- graphite.connect(); +- graphite.send("name", "value", 100); +- graphite.close(); ++ when(socket.getOutputStream()).thenReturn(output); + +- assertThat(unpickleOutput()) +- .isEqualTo("name value 100\n"); +- } ++ // Mock behavior of socket.getOutputStream().close() calling socket.close(); ++ doAnswer( ++ invocation -> { ++ invocation.callRealMethod(); ++ socket.close(); ++ return null; ++ }) ++ .when(output) ++ .close(); + +- @Test +- void writesFullBatch() throws Exception { +- graphite.connect(); +- graphite.send("name", "value", 100); +- graphite.send("name", "value2", 100); +- graphite.close(); ++ when(socketFactory.createSocket(any(InetAddress.class), anyInt())).thenReturn(socket); + +- assertThat(unpickleOutput()) +- .isEqualTo("name value 100\nname value2 100\n"); ++ ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); ++ Compilable compilable = (Compilable) engine; ++ try (InputStream is = PickledGraphiteTest.class.getResource("/upickle.py").openStream()) { ++ unpickleScript = compilable.compile(new InputStreamReader(is, UTF_8)); + } +- +- @Test +- void writesPastFullBatch() throws Exception { +- graphite.connect(); +- graphite.send("name", "value", 100); +- graphite.send("name", "value2", 100); +- graphite.send("name", "value3", 100); +- graphite.close(); +- +- assertThat(unpickleOutput()) +- .isEqualTo("name value 100\nname value2 100\nname value3 100\n"); ++ } ++ ++ @Test ++ void disconnectsFromGraphite() throws Exception { ++ graphite.connect(); ++ graphite.close(); ++ ++ verify(socket).close(); ++ } ++ ++ @Test ++ void writesValuesToGraphite() throws Exception { ++ graphite.connect(); ++ graphite.send("name", "value", 100); ++ graphite.close(); ++ ++ assertThat(unpickleOutput()).isEqualTo("name value 100\n"); ++ } ++ ++ @Test ++ void writesFullBatch() throws Exception { ++ graphite.connect(); ++ graphite.send("name", "value", 100); ++ graphite.send("name", "value2", 100); ++ graphite.close(); ++ ++ assertThat(unpickleOutput()).isEqualTo("name value 100\nname value2 100\n"); ++ } ++ ++ @Test ++ void writesPastFullBatch() throws Exception { ++ graphite.connect(); ++ graphite.send("name", "value", 100); ++ graphite.send("name", "value2", 100); ++ graphite.send("name", "value3", 100); ++ graphite.close(); ++ ++ assertThat(unpickleOutput()).isEqualTo("name value 100\nname value2 100\nname value3 100\n"); ++ } ++ ++ @Test ++ void sanitizesNames() throws Exception { ++ graphite.connect(); ++ graphite.send("name woo", "value", 100); ++ graphite.close(); ++ ++ assertThat(unpickleOutput()).isEqualTo("name-woo value 100\n"); ++ } ++ ++ @Test ++ void sanitizesValues() throws Exception { ++ graphite.connect(); ++ graphite.send("name", "value woo", 100); ++ graphite.close(); ++ ++ assertThat(unpickleOutput()).isEqualTo("name value-woo 100\n"); ++ } ++ ++ @Test ++ void doesNotAllowDoubleConnections() throws Exception { ++ graphite.connect(); ++ try { ++ graphite.connect(); ++ failBecauseExceptionWasNotThrown(IllegalStateException.class); ++ } catch (IllegalStateException e) { ++ assertThat(e.getMessage()).isEqualTo("Already connected"); + } +- +- @Test +- void sanitizesNames() throws Exception { +- graphite.connect(); +- graphite.send("name woo", "value", 100); +- graphite.close(); +- +- assertThat(unpickleOutput()) +- .isEqualTo("name-woo value 100\n"); ++ } ++ ++ private String unpickleOutput() throws Exception { ++ StringBuilder results = new StringBuilder(); ++ ++ // the charset is important. if the GraphitePickleReporter and this test ++ // don't agree, the header is not always correctly unpacked. ++ String payload = output.toString("UTF-8"); ++ ++ PyList result = new PyList(); ++ int nextIndex = 0; ++ while (nextIndex < payload.length()) { ++ Bindings bindings = new SimpleBindings(); ++ bindings.put("payload", payload.substring(nextIndex)); ++ unpickleScript.eval(bindings); ++ result.addAll(result.size(), (PyList) bindings.get("metrics")); ++ nextIndex += ((BigInteger) bindings.get("batchLength")).intValue(); + } + +- @Test +- void sanitizesValues() throws Exception { +- graphite.connect(); +- graphite.send("name", "value woo", 100); +- graphite.close(); ++ for (Object aResult : result) { ++ PyTuple datapoint = (PyTuple) aResult; ++ String name = datapoint.get(0).toString(); ++ PyTuple valueTuple = (PyTuple) datapoint.get(1); ++ Object timestamp = valueTuple.get(0); ++ Object value = valueTuple.get(1); + +- assertThat(unpickleOutput()) +- .isEqualTo("name value-woo 100\n"); ++ results.append(name).append(" ").append(value).append(" ").append(timestamp).append("\n"); + } + +- @Test +- void doesNotAllowDoubleConnections() throws Exception { +- graphite.connect(); +- try { +- graphite.connect(); +- failBecauseExceptionWasNotThrown(IllegalStateException.class); +- } catch (IllegalStateException e) { +- assertThat(e.getMessage()) +- .isEqualTo("Already connected"); +- } +- } +- +- private String unpickleOutput() throws Exception { +- StringBuilder results = new StringBuilder(); +- +- // the charset is important. if the GraphitePickleReporter and this test +- // don't agree, the header is not always correctly unpacked. +- String payload = output.toString("UTF-8"); +- +- PyList result = new PyList(); +- int nextIndex = 0; +- while (nextIndex < payload.length()) { +- Bindings bindings = new SimpleBindings(); +- bindings.put("payload", payload.substring(nextIndex)); +- unpickleScript.eval(bindings); +- result.addAll(result.size(), (PyList) bindings.get("metrics")); +- nextIndex += ((BigInteger) bindings.get("batchLength")).intValue(); +- } +- +- for (Object aResult : result) { +- PyTuple datapoint = (PyTuple) aResult; +- String name = datapoint.get(0).toString(); +- PyTuple valueTuple = (PyTuple) datapoint.get(1); +- Object timestamp = valueTuple.get(0); +- Object value = valueTuple.get(1); +- +- results.append(name).append(" ").append(value).append(" ").append(timestamp).append("\n"); +- } +- +- return results.toString(); +- } ++ return results.toString(); ++ } + } +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java +@@ -1,81 +1,84 @@ + package io.dropwizard.metrics5.health; + +-import io.dropwizard.metrics5.health.annotation.Async; +-import io.dropwizard.metrics5.Clock; +- ++import static com.google.common.base.Preconditions.checkArgument; + ++import io.dropwizard.metrics5.Clock; ++import io.dropwizard.metrics5.health.annotation.Async; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.ScheduledFuture; + +-/** +- * A health check decorator to manage asynchronous executions. +- */ ++/** A health check decorator to manage asynchronous executions. */ + public class AsyncHealthCheckDecorator implements HealthCheck, Runnable { +- private static final String NO_RESULT_YET_MESSAGE = "Waiting for first asynchronous check result."; +- private final HealthCheck healthCheck; +- private final ScheduledFuture future; +- private final long healthyTtl; +- private final Clock clock; +- private volatile Result result; +- +- AsyncHealthCheckDecorator(HealthCheck healthCheck, ScheduledExecutorService executorService, Clock clock) { +- check(healthCheck != null, "healthCheck cannot be null"); +- check(executorService != null, "executorService cannot be null"); +- Async async = healthCheck.getClass().getAnnotation(Async.class); +- check(async != null, "healthCheck must contain Async annotation"); +- check(async.period() > 0, "period cannot be less than or equal to zero"); +- check(async.initialDelay() >= 0, "initialDelay cannot be less than zero"); +- ++ private static final String NO_RESULT_YET_MESSAGE = ++ "Waiting for first asynchronous check result."; ++ private final HealthCheck healthCheck; ++ private final ScheduledFuture future; ++ private final long healthyTtl; ++ private final Clock clock; ++ private volatile Result result; + +- this.clock = clock; +- this.healthCheck = healthCheck; +- this.healthyTtl = async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); +- result = Async.InitialState.HEALTHY.equals(async.initialState()) ? Result.healthy(NO_RESULT_YET_MESSAGE) : +- Result.unhealthy(NO_RESULT_YET_MESSAGE); +- if (Async.ScheduleType.FIXED_RATE.equals(async.scheduleType())) { +- future = executorService.scheduleAtFixedRate(this, async.initialDelay(), async.period(), async.unit()); +- } else { +- future = executorService.scheduleWithFixedDelay(this, async.initialDelay(), async.period(), async.unit()); +- } ++ AsyncHealthCheckDecorator( ++ HealthCheck healthCheck, ScheduledExecutorService executorService, Clock clock) { ++ check(healthCheck != null, "healthCheck cannot be null"); ++ check(executorService != null, "executorService cannot be null"); ++ Async async = healthCheck.getClass().getAnnotation(Async.class); ++ check(async != null, "healthCheck must contain Async annotation"); ++ check(async.period() > 0, "period cannot be less than or equal to zero"); ++ check(async.initialDelay() >= 0, "initialDelay cannot be less than zero"); + ++ this.clock = clock; ++ this.healthCheck = healthCheck; ++ this.healthyTtl = ++ async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); ++ result = ++ Async.InitialState.HEALTHY == async.initialState() ++ ? Result.healthy(NO_RESULT_YET_MESSAGE) ++ : Result.unhealthy(NO_RESULT_YET_MESSAGE); ++ if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) { ++ future = ++ executorService.scheduleAtFixedRate( ++ this, async.initialDelay(), async.period(), async.unit()); ++ } else { ++ future = ++ executorService.scheduleWithFixedDelay( ++ this, async.initialDelay(), async.period(), async.unit()); + } ++ } + +- AsyncHealthCheckDecorator(HealthCheck healthCheck, ScheduledExecutorService executorService) { +- this(healthCheck, executorService, Clock.defaultClock()); +- } +- +- @Override +- public void run() { +- result = healthCheck.execute(); +- } ++ AsyncHealthCheckDecorator(HealthCheck healthCheck, ScheduledExecutorService executorService) { ++ this(healthCheck, executorService, Clock.defaultClock()); ++ } + +- @Override +- public Result check() throws Exception { +- long expiration = clock.getTime() - result.getTime() - healthyTtl; +- if (expiration > 0) { +- return Result.builder() +- .unhealthy() +- .usingClock(clock) +- .withMessage("Result was %s but it expired %d milliseconds ago", +- result.isHealthy() ? "healthy" : "unhealthy", +- expiration) +- .build(); +- } ++ @Override ++ public void run() { ++ result = healthCheck.execute(); ++ } + +- return result; ++ @Override ++ public Result check() throws Exception { ++ long expiration = clock.getTime() - result.getTime() - healthyTtl; ++ if (expiration > 0) { ++ return Result.builder() ++ .unhealthy() ++ .usingClock(clock) ++ .withMessage( ++ "Result was %s but it expired %d milliseconds ago", ++ result.isHealthy() ? "healthy" : "unhealthy", expiration) ++ .build(); + } + +- boolean tearDown() { +- return future.cancel(true); +- } ++ return result; ++ } + +- public HealthCheck getHealthCheck() { +- return healthCheck; +- } ++ boolean tearDown() { ++ return future.cancel(true); ++ } + +- private static void check(boolean expression, String message) { +- if (!expression) { +- throw new IllegalArgumentException(message); +- } +- } ++ public HealthCheck getHealthCheck() { ++ return healthCheck; ++ } ++ ++ private static void check(boolean expression, String message) { ++ checkArgument(expression, message); ++ } + } +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java +@@ -1,384 +1,386 @@ + package io.dropwizard.metrics5.health; + +-import io.dropwizard.metrics5.Clock; ++import static java.util.Collections.unmodifiableMap; + ++import io.dropwizard.metrics5.Clock; + import java.time.Instant; + import java.time.ZoneId; + import java.time.ZonedDateTime; + import java.time.format.DateTimeFormatter; +-import java.util.Collections; + import java.util.LinkedHashMap; + import java.util.Map; + import java.util.concurrent.TimeUnit; + +-/** +- * A health check for a component of your application. +- */ ++/** A health check for a component of your application. */ + public interface HealthCheck { ++ /** ++ * The result of a {@link HealthCheck} being run. It can be healthy (with an optional message and ++ * optional details) or unhealthy (with either an error message or a thrown exception and optional ++ * details). ++ */ ++ class Result { ++ private static final DateTimeFormatter DATE_FORMAT_PATTERN = ++ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); ++ private static final int PRIME = 31; ++ + /** +- * The result of a {@link HealthCheck} being run. It can be healthy (with an optional message and optional details) +- * or unhealthy (with either an error message or a thrown exception and optional details). ++ * Returns a healthy {@link Result} with no additional message. ++ * ++ * @return a healthy {@link Result} with no additional message + */ +- class Result { +- private static final DateTimeFormatter DATE_FORMAT_PATTERN = +- DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); +- private static final int PRIME = 31; +- +- /** +- * Returns a healthy {@link Result} with no additional message. +- * +- * @return a healthy {@link Result} with no additional message +- */ +- public static Result healthy() { +- return new Result(true, null, null); +- } +- +- /** +- * Returns a healthy {@link Result} with an additional message. +- * +- * @param message an informative message +- * @return a healthy {@link Result} with an additional message +- */ +- public static Result healthy(String message) { +- return new Result(true, message, null); +- } ++ public static Result healthy() { ++ return new Result(true, null, null); ++ } + +- /** +- * Returns a healthy {@link Result} with a formatted message. +- *

+- * Message formatting follows the same rules as {@link String#format(String, Object...)}. +- * +- * @param message a message format +- * @param args the arguments apply to the message format +- * @return a healthy {@link Result} with an additional message +- * @see String#format(String, Object...) +- */ +- public static Result healthy(String message, Object... args) { +- return healthy(String.format(message, args)); +- } ++ /** ++ * Returns a healthy {@link Result} with an additional message. ++ * ++ * @param message an informative message ++ * @return a healthy {@link Result} with an additional message ++ */ ++ public static Result healthy(String message) { ++ return new Result(true, message, null); ++ } + +- /** +- * Returns an unhealthy {@link Result} with the given message. +- * +- * @param message an informative message describing how the health check failed +- * @return an unhealthy {@link Result} with the given message +- */ +- public static Result unhealthy(String message) { +- return new Result(false, message, null); +- } ++ /** ++ * Returns a healthy {@link Result} with a formatted message. ++ * ++ *

Message formatting follows the same rules as {@link String#format(String, Object...)}. ++ * ++ * @param message a message format ++ * @param args the arguments apply to the message format ++ * @return a healthy {@link Result} with an additional message ++ * @see String#format(String, Object...) ++ */ ++ public static Result healthy(String message, Object... args) { ++ return healthy(String.format(message, args)); ++ } + +- /** +- * Returns an unhealthy {@link Result} with a formatted message. +- *

+- * Message formatting follows the same rules as {@link String#format(String, Object...)}. +- * +- * @param message a message format +- * @param args the arguments apply to the message format +- * @return an unhealthy {@link Result} with an additional message +- * @see String#format(String, Object...) +- */ +- public static Result unhealthy(String message, Object... args) { +- return unhealthy(String.format(message, args)); +- } ++ /** ++ * Returns an unhealthy {@link Result} with the given message. ++ * ++ * @param message an informative message describing how the health check failed ++ * @return an unhealthy {@link Result} with the given message ++ */ ++ public static Result unhealthy(String message) { ++ return new Result(false, message, null); ++ } + +- /** +- * Returns an unhealthy {@link Result} with the given error. +- * +- * @param error an exception thrown during the health check +- * @return an unhealthy {@link Result} with the given {@code error} +- */ +- public static Result unhealthy(Throwable error) { +- return new Result(false, error.getMessage(), error); +- } ++ /** ++ * Returns an unhealthy {@link Result} with a formatted message. ++ * ++ *

Message formatting follows the same rules as {@link String#format(String, Object...)}. ++ * ++ * @param message a message format ++ * @param args the arguments apply to the message format ++ * @return an unhealthy {@link Result} with an additional message ++ * @see String#format(String, Object...) ++ */ ++ public static Result unhealthy(String message, Object... args) { ++ return unhealthy(String.format(message, args)); ++ } + ++ /** ++ * Returns an unhealthy {@link Result} with the given error. ++ * ++ * @param error an exception thrown during the health check ++ * @return an unhealthy {@link Result} with the given {@code error} ++ */ ++ public static Result unhealthy(Throwable error) { ++ return new Result(false, error.getMessage(), error); ++ } + +- /** +- * Returns a new {@link ResultBuilder} +- * +- * @return the {@link ResultBuilder} +- */ +- public static ResultBuilder builder() { +- return new ResultBuilder(); +- } ++ /** ++ * Returns a new {@link ResultBuilder} ++ * ++ * @return the {@link ResultBuilder} ++ */ ++ public static ResultBuilder builder() { ++ return new ResultBuilder(); ++ } + +- private final boolean healthy; +- private final String message; +- private final Throwable error; +- private final Map details; +- private final long time; ++ private final boolean healthy; ++ private final String message; ++ private final Throwable error; ++ private final Map details; ++ private final long time; + +- private long duration; // Calculated field ++ private long duration; // Calculated field + +- private Result(boolean isHealthy, String message, Throwable error) { +- this(isHealthy, message, error, null, Clock.defaultClock()); +- } ++ private Result(boolean isHealthy, String message, Throwable error) { ++ this(isHealthy, message, error, null, Clock.defaultClock()); ++ } + +- private Result(ResultBuilder builder) { +- this(builder.healthy, builder.message, builder.error, builder.details, builder.clock); +- } ++ private Result(ResultBuilder builder) { ++ this(builder.healthy, builder.message, builder.error, builder.details, builder.clock); ++ } + +- private Result(boolean isHealthy, String message, Throwable error, Map details, Clock clock) { +- this.healthy = isHealthy; +- this.message = message; +- this.error = error; +- this.details = details == null ? null : Collections.unmodifiableMap(details); +- this.time = clock.getTime(); +- } ++ private Result( ++ boolean isHealthy, ++ String message, ++ Throwable error, ++ Map details, ++ Clock clock) { ++ this.healthy = isHealthy; ++ this.message = message; ++ this.error = error; ++ this.details = details == null ? null : unmodifiableMap(details); ++ this.time = clock.getTime(); ++ } + +- /** +- * Returns {@code true} if the result indicates the component is healthy; {@code false} +- * otherwise. +- * +- * @return {@code true} if the result indicates the component is healthy +- */ +- public boolean isHealthy() { +- return healthy; +- } ++ /** ++ * Returns {@code true} if the result indicates the component is healthy; {@code false} ++ * otherwise. ++ * ++ * @return {@code true} if the result indicates the component is healthy ++ */ ++ public boolean isHealthy() { ++ return healthy; ++ } + +- /** +- * Returns any additional message for the result, or {@code null} if the result has no +- * message. +- * +- * @return any additional message for the result, or {@code null} +- */ +- public String getMessage() { +- return message; +- } ++ /** ++ * Returns any additional message for the result, or {@code null} if the result has no message. ++ * ++ * @return any additional message for the result, or {@code null} ++ */ ++ public String getMessage() { ++ return message; ++ } + +- /** +- * Returns any exception for the result, or {@code null} if the result has no exception. +- * +- * @return any exception for the result, or {@code null} +- */ +- public Throwable getError() { +- return error; +- } ++ /** ++ * Returns any exception for the result, or {@code null} if the result has no exception. ++ * ++ * @return any exception for the result, or {@code null} ++ */ ++ public Throwable getError() { ++ return error; ++ } + +- /** +- * Returns the timestamp when the result was created as a formatted String. +- * +- * @return a formatted timestamp +- */ +- public String getTimestamp() { +- Instant currentInstant = Instant.ofEpochMilli(time); +- ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(currentInstant, ZoneId.systemDefault()); +- return DATE_FORMAT_PATTERN.format(zonedDateTime); +- } ++ /** ++ * Returns the timestamp when the result was created as a formatted String. ++ * ++ * @return a formatted timestamp ++ */ ++ public String getTimestamp() { ++ Instant currentInstant = Instant.ofEpochMilli(time); ++ ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault()); ++ return DATE_FORMAT_PATTERN.format(zonedDateTime); ++ } + +- /** +- * Returns the time when the result was created, in milliseconds since Epoch +- * +- * @return the time when the result was created +- */ +- public long getTime() { +- return time; +- } ++ /** ++ * Returns the time when the result was created, in milliseconds since Epoch ++ * ++ * @return the time when the result was created ++ */ ++ public long getTime() { ++ return time; ++ } + +- /** +- * Returns the duration in milliseconds that the healthcheck took to run +- * +- * @return the duration +- */ +- public long getDuration() { +- return duration; +- } ++ /** ++ * Returns the duration in milliseconds that the healthcheck took to run ++ * ++ * @return the duration ++ */ ++ public long getDuration() { ++ return duration; ++ } + +- /** +- * Sets the duration in milliseconds. This will indicate the time it took to run the individual healthcheck +- * +- * @param duration The duration in milliseconds +- */ +- public void setDuration(long duration) { +- this.duration = duration; +- } ++ /** ++ * Sets the duration in milliseconds. This will indicate the time it took to run the individual ++ * healthcheck ++ * ++ * @param duration The duration in milliseconds ++ */ ++ public void setDuration(long duration) { ++ this.duration = duration; ++ } + +- public Map getDetails() { +- return details; +- } ++ public Map getDetails() { ++ return details; ++ } + +- @Override +- public boolean equals(Object o) { +- if (this == o) { +- return true; +- } +- if (o == null || getClass() != o.getClass()) { +- return false; +- } +- final Result result = (Result) o; +- return healthy == result.healthy && +- !(error != null ? !error.equals(result.error) : result.error != null) && +- !(message != null ? !message.equals(result.message) : result.message != null) && +- time == result.time; +- } ++ @Override ++ public boolean equals(Object o) { ++ if (this == o) { ++ return true; ++ } ++ if (o == null || getClass() != o.getClass()) { ++ return false; ++ } ++ final Result result = (Result) o; ++ return healthy == result.healthy ++ && !(error != null ? !error.equals(result.error) : result.error != null) ++ && !(message != null ? !message.equals(result.message) : result.message != null) ++ && time == result.time; ++ } + +- @Override +- public int hashCode() { +- int result = healthy ? 1 : 0; +- result = PRIME * result + (message != null ? message.hashCode() : 0); +- result = PRIME * result + (error != null ? error.hashCode() : 0); +- result = PRIME * result + (Long.hashCode(time)); +- return result; +- } ++ @Override ++ public int hashCode() { ++ int result = healthy ? 1 : 0; ++ result = PRIME * result + (message != null ? message.hashCode() : 0); ++ result = PRIME * result + (error != null ? error.hashCode() : 0); ++ return PRIME * result + (Long.hashCode(time)); ++ } + +- @Override +- public String toString() { +- final StringBuilder builder = new StringBuilder("Result{isHealthy="); +- builder.append(healthy); +- if (message != null) { +- builder.append(", message=").append(message); +- } +- if (error != null) { +- builder.append(", error=").append(error); +- } +- builder.append(", duration=").append(duration); +- builder.append(", timestamp=").append(getTimestamp()); +- if (details != null) { +- for (Map.Entry e : details.entrySet()) { +- builder.append(", "); +- builder.append(e.getKey()) +- .append("=") +- .append(String.valueOf(e.getValue())); +- } +- } +- builder.append('}'); +- return builder.toString(); ++ @Override ++ public String toString() { ++ final StringBuilder builder = new StringBuilder("Result{isHealthy="); ++ builder.append(healthy); ++ if (message != null) { ++ builder.append(", message=").append(message); ++ } ++ if (error != null) { ++ builder.append(", error=").append(error); ++ } ++ builder.append(", duration=").append(duration); ++ builder.append(", timestamp=").append(getTimestamp()); ++ if (details != null) { ++ for (Map.Entry e : details.entrySet()) { ++ builder.append(", "); ++ builder.append(e.getKey()).append("=").append(e.getValue()); + } ++ } ++ builder.append('}'); ++ return builder.toString(); ++ } ++ } ++ ++ /** ++ * This a convenient builder for an {@link HealthCheck.Result}. It can be health (with optional ++ * message and detail) or unhealthy (with optional message, error and detail) ++ */ ++ class ResultBuilder { ++ private boolean healthy; ++ private String message; ++ private Throwable error; ++ private Map details; ++ private Clock clock; ++ ++ protected ResultBuilder() { ++ this.healthy = true; ++ this.details = new LinkedHashMap<>(); ++ this.clock = Clock.defaultClock(); + } + + /** +- * This a convenient builder for an {@link HealthCheck.Result}. It can be health (with optional message and detail) +- * or unhealthy (with optional message, error and detail) ++ * Configure an healthy result ++ * ++ * @return this builder with healthy status + */ +- class ResultBuilder { +- private boolean healthy; +- private String message; +- private Throwable error; +- private Map details; +- private Clock clock; +- +- protected ResultBuilder() { +- this.healthy = true; +- this.details = new LinkedHashMap<>(); +- this.clock = Clock.defaultClock(); +- } +- +- /** +- * Configure an healthy result +- * +- * @return this builder with healthy status +- */ +- public ResultBuilder healthy() { +- this.healthy = true; +- return this; +- } +- +- /** +- * Configure an unhealthy result +- * +- * @return this builder with unhealthy status +- */ +- public ResultBuilder unhealthy() { +- this.healthy = false; +- return this; +- } +- +- /** +- * Configure an unhealthy result with an {@code error} +- * +- * @param error the error +- * @return this builder with the given error +- */ +- public ResultBuilder unhealthy(Throwable error) { +- this.error = error; +- return this.unhealthy().withMessage(error.getMessage()); +- } +- +- /** +- * Set an optional message +- * +- * @param message an informative message +- * @return this builder with the given {@code message} +- */ +- public ResultBuilder withMessage(String message) { +- this.message = message; +- return this; +- } ++ public ResultBuilder healthy() { ++ this.healthy = true; ++ return this; ++ } + +- /** +- * Set an optional formatted message +- *

+- * Message formatting follows the same rules as {@link String#format(String, Object...)}. +- * +- * @param message a message format +- * @param args the arguments apply to the message format +- * @return this builder with the given formatted {@code message} +- * @see String#format(String, Object...) +- */ +- public ResultBuilder withMessage(String message, Object... args) { +- return withMessage(String.format(message, args)); +- } ++ /** ++ * Configure an unhealthy result ++ * ++ * @return this builder with unhealthy status ++ */ ++ public ResultBuilder unhealthy() { ++ this.healthy = false; ++ return this; ++ } + +- /** +- * Add an optional detail +- * +- * @param key a key for this detail +- * @param data an object representing the detail data +- * @return this builder with the given detail added +- */ +- public ResultBuilder withDetail(String key, Object data) { +- if (this.details == null) { +- this.details = new LinkedHashMap<>(); +- } +- this.details.put(key, data); +- return this; +- } ++ /** ++ * Configure an unhealthy result with an {@code error} ++ * ++ * @param error the error ++ * @return this builder with the given error ++ */ ++ public ResultBuilder unhealthy(Throwable error) { ++ this.error = error; ++ return this.unhealthy().withMessage(error.getMessage()); ++ } + +- /** +- * Configure this {@link ResultBuilder} to use the given {@code clock} instead of the default clock. +- * If not specified, the default clock is {@link Clock#defaultClock()}. +- * +- * @param clock the {@link Clock} to use when generating the health check timestamp (useful for unit testing) +- * @return this builder configured to use the given {@code clock} +- */ +- public ResultBuilder usingClock(Clock clock) { +- this.clock = clock; +- return this; +- } ++ /** ++ * Set an optional message ++ * ++ * @param message an informative message ++ * @return this builder with the given {@code message} ++ */ ++ public ResultBuilder withMessage(String message) { ++ this.message = message; ++ return this; ++ } + +- public Result build() { +- return new Result(this); +- } ++ /** ++ * Set an optional formatted message ++ * ++ *

Message formatting follows the same rules as {@link String#format(String, Object...)}. ++ * ++ * @param message a message format ++ * @param args the arguments apply to the message format ++ * @return this builder with the given formatted {@code message} ++ * @see String#format(String, Object...) ++ */ ++ public ResultBuilder withMessage(String message, Object... args) { ++ return withMessage(String.format(message, args)); + } + + /** +- * Perform a check of the application component. ++ * Add an optional detail + * +- * @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link +- * Result} with a descriptive error message or exception +- * @throws Exception if there is an unhandled error during the health check; this will result in +- * a failed health check ++ * @param key a key for this detail ++ * @param data an object representing the detail data ++ * @return this builder with the given detail added + */ +- Result check() throws Exception; ++ public ResultBuilder withDetail(String key, Object data) { ++ if (this.details == null) { ++ this.details = new LinkedHashMap<>(); ++ } ++ this.details.put(key, data); ++ return this; ++ } + + /** +- * Executes the health check, catching and handling any exceptions raised by {@link #check()}. ++ * Configure this {@link ResultBuilder} to use the given {@code clock} instead of the default ++ * clock. If not specified, the default clock is {@link Clock#defaultClock()}. + * +- * @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link +- * Result} with a descriptive error message or exception ++ * @param clock the {@link Clock} to use when generating the health check timestamp (useful for ++ * unit testing) ++ * @return this builder configured to use the given {@code clock} + */ +- default Result execute() { +- long start = clock().getTick(); +- Result result; +- try { +- result = check(); +- } catch (Exception e) { +- result = Result.unhealthy(e); +- } +- result.setDuration(TimeUnit.MILLISECONDS.convert(clock().getTick() - start, TimeUnit.NANOSECONDS)); +- return result; ++ public ResultBuilder usingClock(Clock clock) { ++ this.clock = clock; ++ return this; + } + +- default Clock clock() { +- return Clock.defaultClock(); ++ public Result build() { ++ return new Result(this); ++ } ++ } ++ ++ /** ++ * Perform a check of the application component. ++ * ++ * @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link ++ * Result} with a descriptive error message or exception ++ * @throws Exception if there is an unhandled error during the health check; this will result in a ++ * failed health check ++ */ ++ Result check() throws Exception; ++ ++ /** ++ * Executes the health check, catching and handling any exceptions raised by {@link #check()}. ++ * ++ * @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link ++ * Result} with a descriptive error message or exception ++ */ ++ default Result execute() { ++ long start = clock().getTick(); ++ Result result; ++ try { ++ result = check(); ++ } catch (Exception e) { ++ result = Result.unhealthy(e); + } ++ result.setDuration( ++ TimeUnit.MILLISECONDS.convert(clock().getTick() - start, TimeUnit.NANOSECONDS)); ++ return result; ++ } ++ ++ default Clock clock() { ++ return Clock.defaultClock(); ++ } + } +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckFilter.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckFilter.java +@@ -1,21 +1,17 @@ + package io.dropwizard.metrics5.health; + +-/** +- * A filter used to determine whether or not a health check should be reported. +- */ ++/** A filter used to determine whether or not a health check should be reported. */ + @FunctionalInterface + public interface HealthCheckFilter { +- /** +- * Matches all health checks, regardless of type or name. +- */ +- HealthCheckFilter ALL = (name, healthCheck) -> true; ++ /** Matches all health checks, regardless of type or name. */ ++ HealthCheckFilter ALL = (name, healthCheck) -> true; + +- /** +- * Returns {@code true} if the health check matches the filter; {@code false} otherwise. +- * +- * @param name the health check's name +- * @param healthCheck the health check +- * @return {@code true} if the health check matches the filter +- */ +- boolean matches(String name, HealthCheck healthCheck); ++ /** ++ * Returns {@code true} if the health check matches the filter; {@code false} otherwise. ++ * ++ * @param name the health check's name ++ * @param healthCheck the health check ++ * @return {@code true} if the health check matches the filter ++ */ ++ boolean matches(String name, HealthCheck healthCheck); + } +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java +@@ -1,10 +1,11 @@ + package io.dropwizard.metrics5.health; + +-import io.dropwizard.metrics5.health.annotation.Async; +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; ++import static com.google.common.base.Preconditions.checkArgument; ++import static io.dropwizard.metrics5.health.HealthCheck.Result; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; + +-import java.util.Collections; ++import io.dropwizard.metrics5.health.annotation.Async; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -23,266 +24,260 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; + import java.util.concurrent.ThreadFactory; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicInteger; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + +-import static io.dropwizard.metrics5.health.HealthCheck.Result; +- +-/** +- * A registry for health checks. +- */ ++/** A registry for health checks. */ + public class HealthCheckRegistry { +- private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckRegistry.class); +- private static final int ASYNC_EXECUTOR_POOL_SIZE = 2; ++ private static final Logger LOG = LoggerFactory.getLogger(HealthCheckRegistry.class); ++ private static final int ASYNC_EXECUTOR_POOL_SIZE = 2; + +- private final ConcurrentMap healthChecks; +- private final List listeners; +- private final ScheduledExecutorService asyncExecutorService; +- private final Object lock = new Object(); ++ private final ConcurrentMap healthChecks; ++ private final List listeners; ++ private final ScheduledExecutorService asyncExecutorService; ++ private final Object lock = new Object(); + +- /** +- * Creates a new {@link HealthCheckRegistry}. +- */ +- public HealthCheckRegistry() { +- this(ASYNC_EXECUTOR_POOL_SIZE); +- } ++ /** Creates a new {@link HealthCheckRegistry}. */ ++ public HealthCheckRegistry() { ++ this(ASYNC_EXECUTOR_POOL_SIZE); ++ } + +- /** +- * Creates a new {@link HealthCheckRegistry}. +- * +- * @param asyncExecutorPoolSize core pool size for async health check executions +- */ +- public HealthCheckRegistry(int asyncExecutorPoolSize) { +- this(createExecutorService(asyncExecutorPoolSize)); +- } ++ /** ++ * Creates a new {@link HealthCheckRegistry}. ++ * ++ * @param asyncExecutorPoolSize core pool size for async health check executions ++ */ ++ public HealthCheckRegistry(int asyncExecutorPoolSize) { ++ this(createExecutorService(asyncExecutorPoolSize)); ++ } + +- /** +- * Creates a new {@link HealthCheckRegistry}. +- * +- * @param asyncExecutorService executor service for async health check executions +- */ +- public HealthCheckRegistry(ScheduledExecutorService asyncExecutorService) { +- this.healthChecks = new ConcurrentHashMap<>(); +- this.listeners = new CopyOnWriteArrayList<>(); +- this.asyncExecutorService = asyncExecutorService; +- } ++ /** ++ * Creates a new {@link HealthCheckRegistry}. ++ * ++ * @param asyncExecutorService executor service for async health check executions ++ */ ++ public HealthCheckRegistry(ScheduledExecutorService asyncExecutorService) { ++ this.healthChecks = new ConcurrentHashMap<>(); ++ this.listeners = new CopyOnWriteArrayList<>(); ++ this.asyncExecutorService = asyncExecutorService; ++ } + +- /** +- * Adds a {@link HealthCheckRegistryListener} to a collection of listeners that will be notified on health check +- * registration. Listeners will be notified in the order in which they are added. The listener will be notified of all +- * existing health checks when it first registers. +- * +- * @param listener listener to add +- */ +- public void addListener(HealthCheckRegistryListener listener) { +- listeners.add(listener); +- for (Map.Entry entry : healthChecks.entrySet()) { +- listener.onHealthCheckAdded(entry.getKey(), entry.getValue()); +- } ++ /** ++ * Adds a {@link HealthCheckRegistryListener} to a collection of listeners that will be notified ++ * on health check registration. Listeners will be notified in the order in which they are added. ++ * The listener will be notified of all existing health checks when it first registers. ++ * ++ * @param listener listener to add ++ */ ++ public void addListener(HealthCheckRegistryListener listener) { ++ listeners.add(listener); ++ for (Map.Entry entry : healthChecks.entrySet()) { ++ listener.onHealthCheckAdded(entry.getKey(), entry.getValue()); + } ++ } + +- /** +- * Removes a {@link HealthCheckRegistryListener} from this registry's collection of listeners. +- * +- * @param listener listener to remove +- */ +- public void removeListener(HealthCheckRegistryListener listener) { +- listeners.remove(listener); +- } ++ /** ++ * Removes a {@link HealthCheckRegistryListener} from this registry's collection of listeners. ++ * ++ * @param listener listener to remove ++ */ ++ public void removeListener(HealthCheckRegistryListener listener) { ++ listeners.remove(listener); ++ } + +- /** +- * Registers an application {@link HealthCheck}. +- * +- * @param name the name of the health check +- * @param healthCheck the {@link HealthCheck} instance +- */ +- public void register(String name, HealthCheck healthCheck) { +- HealthCheck registered; +- synchronized (lock) { +- if (healthChecks.containsKey(name)) { +- throw new IllegalArgumentException("A health check named " + name + " already exists"); +- } +- registered = healthCheck; +- if (healthCheck.getClass().isAnnotationPresent(Async.class)) { +- registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); +- } +- healthChecks.put(name, registered); +- } +- onHealthCheckAdded(name, registered); ++ /** ++ * Registers an application {@link HealthCheck}. ++ * ++ * @param name the name of the health check ++ * @param healthCheck the {@link HealthCheck} instance ++ */ ++ public void register(String name, HealthCheck healthCheck) { ++ HealthCheck registered; ++ synchronized (lock) { ++ checkArgument( ++ !healthChecks.containsKey(name), "A health check named %s already exists", name); ++ registered = healthCheck; ++ if (healthCheck.getClass().isAnnotationPresent(Async.class)) { ++ registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); ++ } ++ healthChecks.put(name, registered); + } ++ onHealthCheckAdded(name, registered); ++ } + +- /** +- * Unregisters the application {@link HealthCheck} with the given name. +- * +- * @param name the name of the {@link HealthCheck} instance +- */ +- public void unregister(String name) { +- HealthCheck healthCheck; +- synchronized (lock) { +- healthCheck = healthChecks.remove(name); +- if (healthCheck instanceof AsyncHealthCheckDecorator) { +- ((AsyncHealthCheckDecorator) healthCheck).tearDown(); +- } +- } +- if (healthCheck != null) { +- onHealthCheckRemoved(name, healthCheck); +- } ++ /** ++ * Unregisters the application {@link HealthCheck} with the given name. ++ * ++ * @param name the name of the {@link HealthCheck} instance ++ */ ++ public void unregister(String name) { ++ HealthCheck healthCheck; ++ synchronized (lock) { ++ healthCheck = healthChecks.remove(name); ++ if (healthCheck instanceof AsyncHealthCheckDecorator) { ++ ((AsyncHealthCheckDecorator) healthCheck).tearDown(); ++ } + } +- +- /** +- * Returns a set of the names of all registered health checks. +- * +- * @return the names of all registered health checks +- */ +- public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); ++ if (healthCheck != null) { ++ onHealthCheckRemoved(name, healthCheck); + } ++ } + +- /** +- * Returns the {@link HealthCheck} instance with a given name +- * +- * @param name the name of the {@link HealthCheck} instance +- */ +- public HealthCheck getHealthCheck(String name) { +- return healthChecks.get(name); +- } ++ /** ++ * Returns a set of the names of all registered health checks. ++ * ++ * @return the names of all registered health checks ++ */ ++ public SortedSet getNames() { ++ return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); ++ } + +- /** +- * Runs the health check with the given name. +- * +- * @param name the health check's name +- * @return the result of the health check +- * @throws NoSuchElementException if there is no health check with the given name +- */ +- public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException { +- final HealthCheck healthCheck = healthChecks.get(name); +- if (healthCheck == null) { +- throw new NoSuchElementException("No health check named " + name + " exists"); +- } +- return healthCheck.execute(); +- } ++ /** ++ * Returns the {@link HealthCheck} instance with a given name ++ * ++ * @param name the name of the {@link HealthCheck} instance ++ */ ++ public HealthCheck getHealthCheck(String name) { ++ return healthChecks.get(name); ++ } + +- /** +- * Runs the registered health checks and returns a map of the results. +- * +- * @return a map of the health check results +- */ +- public SortedMap runHealthChecks() { +- return runHealthChecks(HealthCheckFilter.ALL); ++ /** ++ * Runs the health check with the given name. ++ * ++ * @param name the health check's name ++ * @return the result of the health check ++ * @throws NoSuchElementException if there is no health check with the given name ++ */ ++ public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException { ++ final HealthCheck healthCheck = healthChecks.get(name); ++ if (healthCheck == null) { ++ throw new NoSuchElementException("No health check named " + name + " exists"); + } ++ return healthCheck.execute(); ++ } + +- /** +- * Runs the registered health checks matching the filter and returns a map of the results. +- * +- * @param filter health check filter +- * @return a map of the health check results +- */ +- public SortedMap runHealthChecks(HealthCheckFilter filter) { +- final SortedMap results = new TreeMap<>(); +- for (Map.Entry entry : healthChecks.entrySet()) { +- final String name = entry.getKey(); +- final HealthCheck healthCheck = entry.getValue(); +- if (filter.matches(name, healthCheck)) { +- final Result result = entry.getValue().execute(); +- results.put(entry.getKey(), result); +- } +- } +- return Collections.unmodifiableSortedMap(results); +- } ++ /** ++ * Runs the registered health checks and returns a map of the results. ++ * ++ * @return a map of the health check results ++ */ ++ public SortedMap runHealthChecks() { ++ return runHealthChecks(HealthCheckFilter.ALL); ++ } + +- /** +- * Runs the registered health checks in parallel and returns a map of the results. +- * +- * @param executor object to launch and track health checks progress +- * @return a map of the health check results +- */ +- public SortedMap runHealthChecks(ExecutorService executor) { +- return runHealthChecks(executor, HealthCheckFilter.ALL); ++ /** ++ * Runs the registered health checks matching the filter and returns a map of the results. ++ * ++ * @param filter health check filter ++ * @return a map of the health check results ++ */ ++ public SortedMap runHealthChecks(HealthCheckFilter filter) { ++ final SortedMap results = new TreeMap<>(); ++ for (Map.Entry entry : healthChecks.entrySet()) { ++ final String name = entry.getKey(); ++ final HealthCheck healthCheck = entry.getValue(); ++ if (filter.matches(name, healthCheck)) { ++ final Result result = entry.getValue().execute(); ++ results.put(entry.getKey(), result); ++ } + } ++ return unmodifiableSortedMap(results); ++ } + +- /** +- * Runs the registered health checks matching the filter in parallel and returns a map of the results. +- * +- * @param executor object to launch and track health checks progress +- * @param filter health check filter +- * @return a map of the health check results +- */ +- public SortedMap runHealthChecks(ExecutorService executor, HealthCheckFilter filter) { +- final Map> futures = new HashMap<>(); +- for (final Map.Entry entry : healthChecks.entrySet()) { +- final String name = entry.getKey(); +- final HealthCheck healthCheck = entry.getValue(); +- if (filter.matches(name, healthCheck)) { +- futures.put(name, executor.submit(healthCheck::execute)); +- } +- } ++ /** ++ * Runs the registered health checks in parallel and returns a map of the results. ++ * ++ * @param executor object to launch and track health checks progress ++ * @return a map of the health check results ++ */ ++ public SortedMap runHealthChecks(ExecutorService executor) { ++ return runHealthChecks(executor, HealthCheckFilter.ALL); ++ } + +- final SortedMap results = new TreeMap<>(); +- for (Map.Entry> entry : futures.entrySet()) { +- try { +- results.put(entry.getKey(), entry.getValue().get()); +- } catch (Exception e) { +- LOGGER.warn("Error executing health check {}", entry.getKey(), e); +- results.put(entry.getKey(), HealthCheck.Result.unhealthy(e)); +- } +- } ++ /** ++ * Runs the registered health checks matching the filter in parallel and returns a map of the ++ * results. ++ * ++ * @param executor object to launch and track health checks progress ++ * @param filter health check filter ++ * @return a map of the health check results ++ */ ++ public SortedMap runHealthChecks( ++ ExecutorService executor, HealthCheckFilter filter) { ++ final Map> futures = new HashMap<>(); ++ for (final Map.Entry entry : healthChecks.entrySet()) { ++ final String name = entry.getKey(); ++ final HealthCheck healthCheck = entry.getValue(); ++ if (filter.matches(name, healthCheck)) { ++ futures.put(name, executor.submit(healthCheck::execute)); ++ } ++ } + +- return Collections.unmodifiableSortedMap(results); ++ final SortedMap results = new TreeMap<>(); ++ for (Map.Entry> entry : futures.entrySet()) { ++ try { ++ results.put(entry.getKey(), entry.getValue().get()); ++ } catch (Exception e) { ++ LOG.warn("Error executing health check {}", entry.getKey(), e); ++ results.put(entry.getKey(), HealthCheck.Result.unhealthy(e)); ++ } + } + ++ return unmodifiableSortedMap(results); ++ } + +- private void onHealthCheckAdded(String name, HealthCheck healthCheck) { +- for (HealthCheckRegistryListener listener : listeners) { +- listener.onHealthCheckAdded(name, healthCheck); +- } ++ private void onHealthCheckAdded(String name, HealthCheck healthCheck) { ++ for (HealthCheckRegistryListener listener : listeners) { ++ listener.onHealthCheckAdded(name, healthCheck); + } ++ } + +- private void onHealthCheckRemoved(String name, HealthCheck healthCheck) { +- for (HealthCheckRegistryListener listener : listeners) { +- listener.onHealthCheckRemoved(name, healthCheck); +- } ++ private void onHealthCheckRemoved(String name, HealthCheck healthCheck) { ++ for (HealthCheckRegistryListener listener : listeners) { ++ listener.onHealthCheckRemoved(name, healthCheck); + } ++ } + +- /** +- * Shuts down the scheduled executor for async health checks +- */ +- public void shutdown() { +- asyncExecutorService.shutdown(); // Disable new health checks from being submitted +- try { +- // Give some time to the current healtch checks to finish gracefully +- if (!asyncExecutorService.awaitTermination(1, TimeUnit.SECONDS)) { +- asyncExecutorService.shutdownNow(); +- } +- } catch (InterruptedException ie) { +- asyncExecutorService.shutdownNow(); +- Thread.currentThread().interrupt(); +- } ++ /** Shuts down the scheduled executor for async health checks */ ++ public void shutdown() { ++ asyncExecutorService.shutdown(); // Disable new health checks from being submitted ++ try { ++ // Give some time to the current healtch checks to finish gracefully ++ if (!asyncExecutorService.awaitTermination(1, TimeUnit.SECONDS)) { ++ asyncExecutorService.shutdownNow(); ++ } ++ } catch (InterruptedException ie) { ++ asyncExecutorService.shutdownNow(); ++ Thread.currentThread().interrupt(); + } ++ } + +- private static ScheduledExecutorService createExecutorService(int corePoolSize) { +- final ScheduledThreadPoolExecutor asyncExecutorService = new ScheduledThreadPoolExecutor(corePoolSize, +- new NamedThreadFactory("healthcheck-async-executor-")); +- asyncExecutorService.setRemoveOnCancelPolicy(true); +- return asyncExecutorService; +- } ++ private static ScheduledExecutorService createExecutorService(int corePoolSize) { ++ final ScheduledThreadPoolExecutor asyncExecutorService = ++ new ScheduledThreadPoolExecutor( ++ corePoolSize, new NamedThreadFactory("healthcheck-async-executor-")); ++ asyncExecutorService.setRemoveOnCancelPolicy(true); ++ return asyncExecutorService; ++ } + +- private static class NamedThreadFactory implements ThreadFactory { ++ private static class NamedThreadFactory implements ThreadFactory { + +- private final ThreadGroup group; +- private final AtomicInteger threadNumber = new AtomicInteger(1); +- private final String namePrefix; ++ private final ThreadGroup group; ++ private final AtomicInteger threadNumber = new AtomicInteger(1); ++ private final String namePrefix; + +- NamedThreadFactory(String namePrefix) { +- SecurityManager s = System.getSecurityManager(); +- group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); +- this.namePrefix = namePrefix; +- } ++ NamedThreadFactory(String namePrefix) { ++ SecurityManager s = System.getSecurityManager(); ++ group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); ++ this.namePrefix = namePrefix; ++ } + +- @Override +- public Thread newThread(Runnable r) { +- Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); +- t.setDaemon(true); +- if (t.getPriority() != Thread.NORM_PRIORITY) +- t.setPriority(Thread.NORM_PRIORITY); +- return t; +- } ++ @Override ++ public Thread newThread(Runnable r) { ++ Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); ++ t.setDaemon(true); ++ if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); ++ return t; + } ++ } + } +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistryListener.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistryListener.java +@@ -2,25 +2,22 @@ package io.dropwizard.metrics5.health; + + import java.util.EventListener; + +-/** +- * A listener contract for {@link HealthCheckRegistry} events. +- */ ++/** A listener contract for {@link HealthCheckRegistry} events. */ + public interface HealthCheckRegistryListener extends EventListener { + +- /** +- * Called when a new {@link HealthCheck} is added to the registry. +- * +- * @param name the name of the health check +- * @param healthCheck the health check +- */ +- void onHealthCheckAdded(String name, HealthCheck healthCheck); +- +- /** +- * Called when a {@link HealthCheck} is removed from the registry. +- * +- * @param name the name of the health check +- * @param healthCheck the health check +- */ +- void onHealthCheckRemoved(String name, HealthCheck healthCheck); ++ /** ++ * Called when a new {@link HealthCheck} is added to the registry. ++ * ++ * @param name the name of the health check ++ * @param healthCheck the health check ++ */ ++ void onHealthCheckAdded(String name, HealthCheck healthCheck); + ++ /** ++ * Called when a {@link HealthCheck} is removed from the registry. ++ * ++ * @param name the name of the health check ++ * @param healthCheck the health check ++ */ ++ void onHealthCheckRemoved(String name, HealthCheck healthCheck); + } +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistries.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistries.java +@@ -5,102 +5,103 @@ import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; + import java.util.concurrent.atomic.AtomicReference; + +-/** +- * A map of shared, named health registries. +- */ ++/** A map of shared, named health registries. */ + public class SharedHealthCheckRegistries { +- private static final ConcurrentMap REGISTRIES = +- new ConcurrentHashMap<>(); ++ private static final ConcurrentMap REGISTRIES = ++ new ConcurrentHashMap<>(); + +- private static AtomicReference defaultRegistryName = new AtomicReference<>(); ++ private static AtomicReference defaultRegistryName = new AtomicReference<>(); + +- /* Visible for testing */ +- static void setDefaultRegistryName(AtomicReference defaultRegistryName) { +- SharedHealthCheckRegistries.defaultRegistryName = defaultRegistryName; +- } ++ /* Visible for testing */ ++ static void setDefaultRegistryName(AtomicReference defaultRegistryName) { ++ SharedHealthCheckRegistries.defaultRegistryName = defaultRegistryName; ++ } + +- private SharedHealthCheckRegistries() { /* singleton */ } ++ private SharedHealthCheckRegistries() { ++ /* singleton */ ++ } + +- public static void clear() { +- REGISTRIES.clear(); +- } ++ public static void clear() { ++ REGISTRIES.clear(); ++ } + +- public static Set names() { +- return REGISTRIES.keySet(); +- } ++ public static Set names() { ++ return REGISTRIES.keySet(); ++ } + +- public static void remove(String key) { +- REGISTRIES.remove(key); +- } ++ public static void remove(String key) { ++ REGISTRIES.remove(key); ++ } + +- public static HealthCheckRegistry add(String name, HealthCheckRegistry registry) { +- return REGISTRIES.putIfAbsent(name, registry); +- } ++ public static HealthCheckRegistry add(String name, HealthCheckRegistry registry) { ++ return REGISTRIES.putIfAbsent(name, registry); ++ } + +- public static HealthCheckRegistry getOrCreate(String name) { +- final HealthCheckRegistry existing = REGISTRIES.get(name); +- if (existing == null) { +- final HealthCheckRegistry created = new HealthCheckRegistry(); +- final HealthCheckRegistry raced = add(name, created); +- if (raced == null) { +- return created; +- } +- return raced; +- } +- return existing; ++ public static HealthCheckRegistry getOrCreate(String name) { ++ final HealthCheckRegistry existing = REGISTRIES.get(name); ++ if (existing == null) { ++ final HealthCheckRegistry created = new HealthCheckRegistry(); ++ final HealthCheckRegistry raced = add(name, created); ++ if (raced == null) { ++ return created; ++ } ++ return raced; + } ++ return existing; ++ } + +- /** +- * Creates a new registry and sets it as the default one under the provided name. +- * +- * @param name the registry name +- * @return the default registry +- * @throws IllegalStateException if the name has already been set +- */ +- public synchronized static HealthCheckRegistry setDefault(String name) { +- final HealthCheckRegistry registry = getOrCreate(name); +- return setDefault(name, registry); +- } ++ /** ++ * Creates a new registry and sets it as the default one under the provided name. ++ * ++ * @param name the registry name ++ * @return the default registry ++ * @throws IllegalStateException if the name has already been set ++ */ ++ public static synchronized HealthCheckRegistry setDefault(String name) { ++ final HealthCheckRegistry registry = getOrCreate(name); ++ return setDefault(name, registry); ++ } + +- /** +- * Sets the provided registry as the default one under the provided name +- * +- * @param name the default registry name +- * @param healthCheckRegistry the default registry +- * @throws IllegalStateException if the default registry has already been set +- */ +- public static HealthCheckRegistry setDefault(String name, HealthCheckRegistry healthCheckRegistry) { +- if (defaultRegistryName.compareAndSet(null, name)) { +- add(name, healthCheckRegistry); +- return healthCheckRegistry; +- } +- throw new IllegalStateException("Default health check registry is already set."); ++ /** ++ * Sets the provided registry as the default one under the provided name ++ * ++ * @param name the default registry name ++ * @param healthCheckRegistry the default registry ++ * @throws IllegalStateException if the default registry has already been set ++ */ ++ public static HealthCheckRegistry setDefault( ++ String name, HealthCheckRegistry healthCheckRegistry) { ++ if (defaultRegistryName.compareAndSet(null, name)) { ++ add(name, healthCheckRegistry); ++ return healthCheckRegistry; + } ++ throw new IllegalStateException("Default health check registry is already set."); ++ } + +- /** +- * Gets the name of the default registry, if it has been set +- * +- * @return the default registry +- * @throws IllegalStateException if the default has not been set +- */ +- public static HealthCheckRegistry getDefault() { +- final HealthCheckRegistry healthCheckRegistry = tryGetDefault(); +- if (healthCheckRegistry != null) { +- return healthCheckRegistry; +- } +- throw new IllegalStateException("Default registry name has not been set."); ++ /** ++ * Gets the name of the default registry, if it has been set ++ * ++ * @return the default registry ++ * @throws IllegalStateException if the default has not been set ++ */ ++ public static HealthCheckRegistry getDefault() { ++ final HealthCheckRegistry healthCheckRegistry = tryGetDefault(); ++ if (healthCheckRegistry != null) { ++ return healthCheckRegistry; + } ++ throw new IllegalStateException("Default registry name has not been set."); ++ } + +- /** +- * Same as {@link #getDefault()} except returns null when the default registry has not been set. +- * +- * @return the default registry or null +- */ +- public static HealthCheckRegistry tryGetDefault() { +- final String name = defaultRegistryName.get(); +- if (name != null) { +- return getOrCreate(name); +- } +- return null; ++ /** ++ * Same as {@link #getDefault()} except returns null when the default registry has not been set. ++ * ++ * @return the default registry or null ++ */ ++ public static HealthCheckRegistry tryGetDefault() { ++ final String name = defaultRegistryName.get(); ++ if (name != null) { ++ return getOrCreate(name); + } ++ return null; ++ } + } +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/annotation/Async.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/annotation/Async.java +@@ -6,70 +6,66 @@ import java.lang.annotation.RetentionPolicy; + import java.lang.annotation.Target; + import java.util.concurrent.TimeUnit; + +-/** +- * An annotation for marking asynchronous health check execution. +- */ ++/** An annotation for marking asynchronous health check execution. */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + public @interface Async { +- /** +- * Enum representing the initial health states. +- */ +- enum InitialState { +- HEALTHY, UNHEALTHY +- } ++ /** Enum representing the initial health states. */ ++ enum InitialState { ++ HEALTHY, ++ UNHEALTHY ++ } + +- /** +- * Enum representing the possible schedule types. +- */ +- enum ScheduleType { +- FIXED_RATE, FIXED_DELAY +- } ++ /** Enum representing the possible schedule types. */ ++ enum ScheduleType { ++ FIXED_RATE, ++ FIXED_DELAY ++ } + +- /** +- * Period between executions. +- * +- * @return period +- */ +- long period(); ++ /** ++ * Period between executions. ++ * ++ * @return period ++ */ ++ long period(); + +- /** +- * Scheduling type of asynchronous executions. +- * +- * @return schedule type +- */ +- ScheduleType scheduleType() default ScheduleType.FIXED_RATE; ++ /** ++ * Scheduling type of asynchronous executions. ++ * ++ * @return schedule type ++ */ ++ ScheduleType scheduleType() default ScheduleType.FIXED_RATE; + +- /** +- * Initial delay of first execution. +- * +- * @return initial delay +- */ +- long initialDelay() default 0; ++ /** ++ * Initial delay of first execution. ++ * ++ * @return initial delay ++ */ ++ long initialDelay() default 0; + +- /** +- * Time unit of initial delay, period and healthyTtl. +- * +- * @return time unit +- */ +- TimeUnit unit() default TimeUnit.SECONDS; ++ /** ++ * Time unit of initial delay, period and healthyTtl. ++ * ++ * @return time unit ++ */ ++ TimeUnit unit() default TimeUnit.SECONDS; + +- /** +- * Initial health state until first asynchronous execution completes. +- * +- * @return initial health state +- */ +- InitialState initialState() default InitialState.HEALTHY; +- +- /** +- * How long a healthy result is considered valid before being ignored. +- * +- * Handles cases where the asynchronous healthcheck did not run (for example thread starvation). +- * +- * Defaults to 2 * period +- * +- * @return healthy result time to live +- */ +- long healthyTtl() default -1; ++ /** ++ * Initial health state until first asynchronous execution completes. ++ * ++ * @return initial health state ++ */ ++ InitialState initialState() default InitialState.HEALTHY; + ++ /** ++ * How long a healthy result is considered valid before being ignored. ++ * ++ *

Handles cases where the asynchronous healthcheck did not run (for example thread ++ * starvation). ++ * ++ *

Defaults to 2 * period ++ * ++ * @return healthy result time to live ++ */ ++ long healthyTtl() default -1; + } +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheck.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheck.java +@@ -2,37 +2,32 @@ package io.dropwizard.metrics5.health.jvm; + + import io.dropwizard.metrics5.health.HealthCheck; + import io.dropwizard.metrics5.jvm.ThreadDeadlockDetector; +- + import java.util.Set; + +-/** +- * A health check which returns healthy if no threads are deadlocked. +- */ ++/** A health check which returns healthy if no threads are deadlocked. */ + public class ThreadDeadlockHealthCheck implements HealthCheck { +- private final ThreadDeadlockDetector detector; ++ private final ThreadDeadlockDetector detector; + +- /** +- * Creates a new health check. +- */ +- public ThreadDeadlockHealthCheck() { +- this(new ThreadDeadlockDetector()); +- } ++ /** Creates a new health check. */ ++ public ThreadDeadlockHealthCheck() { ++ this(new ThreadDeadlockDetector()); ++ } + +- /** +- * Creates a new health check with the given detector. +- * +- * @param detector a thread deadlock detector +- */ +- public ThreadDeadlockHealthCheck(ThreadDeadlockDetector detector) { +- this.detector = detector; +- } ++ /** ++ * Creates a new health check with the given detector. ++ * ++ * @param detector a thread deadlock detector ++ */ ++ public ThreadDeadlockHealthCheck(ThreadDeadlockDetector detector) { ++ this.detector = detector; ++ } + +- @Override +- public Result check() throws Exception { +- final Set threads = detector.getDeadlockedThreads(); +- if (threads.isEmpty()) { +- return Result.healthy(); +- } +- return Result.unhealthy(threads.toString()); ++ @Override ++ public Result check() throws Exception { ++ final Set threads = detector.getDeadlockedThreads(); ++ if (threads.isEmpty()) { ++ return Result.healthy(); + } ++ return Result.unhealthy(threads.toString()); ++ } + } +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java +@@ -1,340 +1,388 @@ + package io.dropwizard.metrics5.health; + +-import io.dropwizard.metrics5.Clock; +-import io.dropwizard.metrics5.health.annotation.Async; +-import org.junit.jupiter.api.Test; +-import org.mockito.ArgumentCaptor; +- +-import java.util.concurrent.ScheduledExecutorService; +-import java.util.concurrent.ScheduledFuture; +-import java.util.concurrent.TimeUnit; +- + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.ArgumentCaptor.forClass; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.*; ++import static org.mockito.Mockito.verify; + +-/** +- * Unit tests for {@link AsyncHealthCheckDecorator}. +- */ +-class AsyncHealthCheckDecoratorTest { +- +- private static final long CURRENT_TIME = 1551002401000L; +- +- private static final Clock FIXED_CLOCK = clockWithFixedTime(CURRENT_TIME); +- +- private static final HealthCheck.Result EXPECTED_EXPIRED_RESULT = HealthCheck.Result +- .builder() +- .usingClock(FIXED_CLOCK) +- .unhealthy() +- .withMessage("Result was healthy but it expired 1 milliseconds ago") +- .build(); +- +- private final HealthCheck mockHealthCheck = mock(HealthCheck.class); +- private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); +- +- @SuppressWarnings("rawtypes") +- private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); +- +- @Test +- void nullHealthCheckTriggersInstantiationFailure() { +- assertThrows(IllegalArgumentException.class, () -> { +- new AsyncHealthCheckDecorator(null, mockExecutorService); +- }); +- } +- +- @Test +- void nullExecutorServiceTriggersInstantiationFailure() { +- assertThrows(IllegalArgumentException.class, () -> { +- new AsyncHealthCheckDecorator(mockHealthCheck, null); +- }); +- } +- +- @Test +- void nonAsyncHealthCheckTriggersInstantiationFailure() { +- assertThrows(IllegalArgumentException.class, () -> { +- new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); +- }); +- } +- +- @Test +- void negativePeriodTriggersInstantiationFailure() { +- assertThrows(IllegalArgumentException.class, () -> { +- new AsyncHealthCheckDecorator(new NegativePeriodAsyncHealthCheck(), mockExecutorService); +- }); +- } +- +- @Test +- void zeroPeriodTriggersInstantiationFailure() { +- assertThrows(IllegalArgumentException.class, () -> { +- new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); +- }); +- } +- +- @Test +- void negativeInitialValueTriggersInstantiationFailure() { +- assertThrows(IllegalArgumentException.class, () -> { +- new AsyncHealthCheckDecorator(new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); +- }); +- } +- +- @Test +- void defaultAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedRateAndHealthyState() throws Exception { +- HealthCheck asyncHealthCheck = new DefaultAsyncHealthCheck(); +- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); +- +- verify(mockExecutorService, times(1)).scheduleAtFixedRate(any(Runnable.class), eq(0L), +- eq(1L), eq(TimeUnit.SECONDS)); +- assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); +- assertThat(asyncDecorator.check().isHealthy()).isTrue(); +- } +- +- @Test +- void fixedDelayAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedDelay() throws Exception { +- HealthCheck asyncHealthCheck = new FixedDelayAsyncHealthCheck(); +- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); +- +- verify(mockExecutorService, times(1)).scheduleWithFixedDelay(any(Runnable.class), eq(0L), +- eq(1L), eq(TimeUnit.SECONDS)); +- assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); +- } +- +- @Test +- void unhealthyAsyncHealthCheckTriggersSuccessfulInstantiationWithUnhealthyState() throws Exception { +- HealthCheck asyncHealthCheck = new UnhealthyAsyncHealthCheck(); +- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); +- +- assertThat(asyncDecorator.check().isHealthy()).isFalse(); +- } +- +- @Test +- @SuppressWarnings("unchecked") +- void tearDownTriggersCancellation() throws Exception { +- when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))). +- thenReturn(mockFuture); +- when(mockFuture.cancel(true)).thenReturn(true); +- +- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); +- asyncDecorator.tearDown(); +- +- verify(mockExecutorService, times(1)).scheduleAtFixedRate(any(Runnable.class), eq(0L), +- eq(1L), eq(TimeUnit.SECONDS)); +- verify(mockFuture, times(1)).cancel(eq(true)); +- } +- +- @Test +- @SuppressWarnings("unchecked") +- void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { +- HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); +- when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) +- .thenReturn(mockFuture); +- +- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(new ConfigurableAsyncHealthCheck(expectedResult), +- mockExecutorService); +- HealthCheck.Result initialResult = asyncDecorator.check(); +- +- ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), +- eq(0L), eq(1L), eq(TimeUnit.SECONDS)); +- Runnable capturedRunnable = runnableCaptor.getValue(); +- capturedRunnable.run(); +- HealthCheck.Result actualResult = asyncDecorator.check(); +- +- assertThat(actualResult).isEqualTo(expectedResult); +- assertThat(actualResult).isNotEqualTo(initialResult); +- } +- +- @Test +- @SuppressWarnings("unchecked") +- void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { +- Exception exception = new Exception("TestException"); +- when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) +- .thenReturn(mockFuture); +- +- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(new ConfigurableAsyncHealthCheck(exception), +- mockExecutorService); +- +- ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), +- eq(0L), eq(1L), eq(TimeUnit.SECONDS)); +- Runnable capturedRunnable = runnableCaptor.getValue(); +- capturedRunnable.run(); +- HealthCheck.Result result = asyncDecorator.check(); +- +- assertThat(result.isHealthy()).isFalse(); +- assertThat(result.getError()).isEqualTo(exception); +- } +- +- @Test +- void returnUnhealthyIfPreviousResultIsExpiredBasedOnTtl() throws Exception { +- HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInMilliseconds(); +- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); +- +- ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), +- eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); +- Runnable capturedRunnable = runnableCaptor.getValue(); +- capturedRunnable.run(); +- +- HealthCheck.Result result = asyncDecorator.check(); +- +- assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); +- } +- +- @Test +- void returnUnhealthyIfPreviousResultIsExpiredBasedOnPeriod() throws Exception { +- HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredTtlInMillisecondsBasedOnPeriod(); +- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); +- +- ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), +- eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); +- Runnable capturedRunnable = runnableCaptor.getValue(); +- capturedRunnable.run(); +- +- HealthCheck.Result result = asyncDecorator.check(); ++import io.dropwizard.metrics5.Clock; ++import io.dropwizard.metrics5.health.annotation.Async; ++import java.util.concurrent.ScheduledExecutorService; ++import java.util.concurrent.ScheduledFuture; ++import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.Test; ++import org.mockito.ArgumentCaptor; + +- assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); ++/** Unit tests for {@link AsyncHealthCheckDecorator}. */ ++final class AsyncHealthCheckDecoratorTest { ++ ++ private static final long CURRENT_TIME = 1551002401000L; ++ ++ private static final Clock FIXED_CLOCK = clockWithFixedTime(CURRENT_TIME); ++ ++ private static final HealthCheck.Result EXPECTED_EXPIRED_RESULT = ++ HealthCheck.Result.builder() ++ .usingClock(FIXED_CLOCK) ++ .unhealthy() ++ .withMessage("Result was healthy but it expired 1 milliseconds ago") ++ .build(); ++ ++ private final HealthCheck mockHealthCheck = mock(); ++ private final ScheduledExecutorService mockExecutorService = mock(); ++ ++ @SuppressWarnings("rawtypes") ++ private final ScheduledFuture mockFuture = mock(); ++ ++ @Test ++ void nullHealthCheckTriggersInstantiationFailure() { ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(null, mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void nullExecutorServiceTriggersInstantiationFailure() { ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(mockHealthCheck, null); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void nonAsyncHealthCheckTriggersInstantiationFailure() { ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void negativePeriodTriggersInstantiationFailure() { ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator( ++ new NegativePeriodAsyncHealthCheck(), mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void zeroPeriodTriggersInstantiationFailure() { ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void negativeInitialValueTriggersInstantiationFailure() { ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator( ++ new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void defaultAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedRateAndHealthyState() ++ throws Exception { ++ HealthCheck asyncHealthCheck = new DefaultAsyncHealthCheck(); ++ AsyncHealthCheckDecorator asyncDecorator = ++ new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); ++ ++ verify(mockExecutorService) ++ .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); ++ assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); ++ assertThat(asyncDecorator.check().isHealthy()).isTrue(); ++ } ++ ++ @Test ++ void fixedDelayAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedDelay() throws Exception { ++ HealthCheck asyncHealthCheck = new FixedDelayAsyncHealthCheck(); ++ AsyncHealthCheckDecorator asyncDecorator = ++ new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); ++ ++ verify(mockExecutorService) ++ .scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); ++ assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); ++ } ++ ++ @Test ++ void unhealthyAsyncHealthCheckTriggersSuccessfulInstantiationWithUnhealthyState() ++ throws Exception { ++ HealthCheck asyncHealthCheck = new UnhealthyAsyncHealthCheck(); ++ AsyncHealthCheckDecorator asyncDecorator = ++ new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); ++ ++ assertThat(asyncDecorator.check().isHealthy()).isFalse(); ++ } ++ ++ @SuppressWarnings("unchecked") ++ @Test ++ void tearDownTriggersCancellation() throws Exception { ++ when(mockExecutorService.scheduleAtFixedRate( ++ any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) ++ .thenReturn(mockFuture); ++ when(mockFuture.cancel(true)).thenReturn(true); ++ ++ AsyncHealthCheckDecorator asyncDecorator = ++ new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); ++ asyncDecorator.tearDown(); ++ ++ verify(mockExecutorService) ++ .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); ++ verify(mockFuture).cancel(true); ++ } ++ ++ @SuppressWarnings("unchecked") ++ @Test ++ void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { ++ HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); ++ when(mockExecutorService.scheduleAtFixedRate( ++ any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) ++ .thenReturn(mockFuture); ++ ++ AsyncHealthCheckDecorator asyncDecorator = ++ new AsyncHealthCheckDecorator( ++ new ConfigurableAsyncHealthCheck(expectedResult), mockExecutorService); ++ HealthCheck.Result initialResult = asyncDecorator.check(); ++ ++ ArgumentCaptor runnableCaptor = forClass(Runnable.class); ++ verify(mockExecutorService) ++ .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); ++ Runnable capturedRunnable = runnableCaptor.getValue(); ++ capturedRunnable.run(); ++ HealthCheck.Result actualResult = asyncDecorator.check(); ++ ++ assertThat(actualResult).isEqualTo(expectedResult); ++ assertThat(actualResult).isNotEqualTo(initialResult); ++ } ++ ++ @SuppressWarnings("unchecked") ++ @Test ++ void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { ++ Exception exception = new Exception("TestException"); ++ when(mockExecutorService.scheduleAtFixedRate( ++ any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) ++ .thenReturn(mockFuture); ++ ++ AsyncHealthCheckDecorator asyncDecorator = ++ new AsyncHealthCheckDecorator( ++ new ConfigurableAsyncHealthCheck(exception), mockExecutorService); ++ ++ ArgumentCaptor runnableCaptor = forClass(Runnable.class); ++ verify(mockExecutorService) ++ .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); ++ Runnable capturedRunnable = runnableCaptor.getValue(); ++ capturedRunnable.run(); ++ HealthCheck.Result result = asyncDecorator.check(); ++ ++ assertThat(result.isHealthy()).isFalse(); ++ assertThat(result.getError()).isEqualTo(exception); ++ } ++ ++ @Test ++ void returnUnhealthyIfPreviousResultIsExpiredBasedOnTtl() throws Exception { ++ HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInMilliseconds(); ++ AsyncHealthCheckDecorator asyncDecorator = ++ new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); ++ ++ ArgumentCaptor runnableCaptor = forClass(Runnable.class); ++ verify(mockExecutorService) ++ .scheduleAtFixedRate( ++ runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); ++ Runnable capturedRunnable = runnableCaptor.getValue(); ++ capturedRunnable.run(); ++ ++ HealthCheck.Result result = asyncDecorator.check(); ++ ++ assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); ++ } ++ ++ @Test ++ void returnUnhealthyIfPreviousResultIsExpiredBasedOnPeriod() throws Exception { ++ HealthCheck healthCheck = ++ new HealthyAsyncHealthCheckWithExpiredTtlInMillisecondsBasedOnPeriod(); ++ AsyncHealthCheckDecorator asyncDecorator = ++ new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); ++ ++ ArgumentCaptor runnableCaptor = forClass(Runnable.class); ++ verify(mockExecutorService) ++ .scheduleAtFixedRate( ++ runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); ++ Runnable capturedRunnable = runnableCaptor.getValue(); ++ capturedRunnable.run(); ++ ++ HealthCheck.Result result = asyncDecorator.check(); ++ ++ assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); ++ } ++ ++ @Test ++ void convertTtlToMillisecondsWhenCheckingExpiration() throws Exception { ++ HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInSeconds(); ++ AsyncHealthCheckDecorator asyncDecorator = ++ new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); ++ ++ ArgumentCaptor runnableCaptor = forClass(Runnable.class); ++ verify(mockExecutorService) ++ .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); ++ Runnable capturedRunnable = runnableCaptor.getValue(); ++ capturedRunnable.run(); ++ ++ HealthCheck.Result result = asyncDecorator.check(); ++ ++ assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); ++ } ++ ++ @Async(period = -1) ++ private static class NegativePeriodAsyncHealthCheck implements HealthCheck { ++ ++ @Override ++ public Result check() { ++ return null; + } ++ } + +- @Test +- void convertTtlToMillisecondsWhenCheckingExpiration() throws Exception { +- HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInSeconds(); +- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); +- +- ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), +- eq(0L), eq(1L), eq(TimeUnit.SECONDS)); +- Runnable capturedRunnable = runnableCaptor.getValue(); +- capturedRunnable.run(); +- +- HealthCheck.Result result = asyncDecorator.check(); ++ @Async(period = 0) ++ private static class ZeroPeriodAsyncHealthCheck implements HealthCheck { + +- assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); ++ @Override ++ public Result check() { ++ return null; + } ++ } + +- @Async(period = -1) +- private static class NegativePeriodAsyncHealthCheck implements HealthCheck { ++ @Async(period = 1, initialDelay = -1) ++ private static class NegativeInitialDelayAsyncHealthCheck implements HealthCheck { + +- @Override +- public Result check() { +- return null; +- } ++ @Override ++ public Result check() { ++ return null; + } ++ } + +- @Async(period = 0) +- private static class ZeroPeriodAsyncHealthCheck implements HealthCheck { ++ @Async(period = 1) ++ private static class DefaultAsyncHealthCheck implements HealthCheck { + +- @Override +- public Result check() { +- return null; +- } ++ @Override ++ public Result check() { ++ return null; + } ++ } + +- @Async(period = 1, initialDelay = -1) +- private static class NegativeInitialDelayAsyncHealthCheck implements HealthCheck { ++ @Async(period = 1, scheduleType = Async.ScheduleType.FIXED_DELAY) ++ private static class FixedDelayAsyncHealthCheck implements HealthCheck { + +- @Override +- public Result check() { +- return null; +- } ++ @Override ++ public Result check() { ++ return null; + } ++ } + +- @Async(period = 1) +- private static class DefaultAsyncHealthCheck implements HealthCheck { ++ @Async(period = 1, initialState = Async.InitialState.UNHEALTHY) ++ private static class UnhealthyAsyncHealthCheck implements HealthCheck { + +- @Override +- public Result check() { +- return null; +- } ++ @Override ++ public Result check() { ++ return null; + } ++ } + +- @Async(period = 1, scheduleType = Async.ScheduleType.FIXED_DELAY) +- private static class FixedDelayAsyncHealthCheck implements HealthCheck { ++ @Async(period = 1, initialState = Async.InitialState.UNHEALTHY) ++ private static class ConfigurableAsyncHealthCheck implements HealthCheck { ++ private final Result result; ++ private final Exception exception; + +- @Override +- public Result check() { +- return null; +- } ++ ConfigurableAsyncHealthCheck(Result result) { ++ this(result, null); + } + +- @Async(period = 1, initialState = Async.InitialState.UNHEALTHY) +- private static class UnhealthyAsyncHealthCheck implements HealthCheck { +- +- @Override +- public Result check() { +- return null; +- } ++ ConfigurableAsyncHealthCheck(Exception exception) { ++ this(null, exception); + } + +- @Async(period = 1, initialState = Async.InitialState.UNHEALTHY) +- private static class ConfigurableAsyncHealthCheck implements HealthCheck { +- private final Result result; +- private final Exception exception; +- +- ConfigurableAsyncHealthCheck(Result result) { +- this(result, null); +- } +- +- ConfigurableAsyncHealthCheck(Exception exception) { +- this(null, exception); +- } +- +- private ConfigurableAsyncHealthCheck(Result result, Exception exception) { +- this.result = result; +- this.exception = exception; +- } +- +- @Override +- public Result check() throws Exception { +- if (exception != null) { +- throw exception; +- } +- return result; +- } ++ private ConfigurableAsyncHealthCheck(Result result, Exception exception) { ++ this.result = result; ++ this.exception = exception; + } + +- @Async(period = 1000, initialState = Async.InitialState.UNHEALTHY, healthyTtl = 3000, unit = TimeUnit.MILLISECONDS) +- private static class HealthyAsyncHealthCheckWithExpiredExplicitTtlInMilliseconds implements HealthCheck { +- +- @Override +- public Result check() { +- return Result.builder().usingClock(clockWithFixedTime(CURRENT_TIME - 3001L)).healthy().build(); +- } ++ @Override ++ public Result check() throws Exception { ++ if (exception != null) { ++ throw exception; ++ } ++ return result; + } +- +- @Async(period = 1, initialState = Async.InitialState.UNHEALTHY, healthyTtl = 5, unit = TimeUnit.SECONDS) +- private static class HealthyAsyncHealthCheckWithExpiredExplicitTtlInSeconds implements HealthCheck { +- +- @Override +- public Result check() { +- return Result.builder().usingClock(clockWithFixedTime(CURRENT_TIME - 5001L)).healthy().build(); +- } ++ } ++ ++ @Async( ++ period = 1000, ++ initialState = Async.InitialState.UNHEALTHY, ++ healthyTtl = 3000, ++ unit = TimeUnit.MILLISECONDS) ++ private static class HealthyAsyncHealthCheckWithExpiredExplicitTtlInMilliseconds ++ implements HealthCheck { ++ ++ @Override ++ public Result check() { ++ return Result.builder() ++ .usingClock(clockWithFixedTime(CURRENT_TIME - 3001L)) ++ .healthy() ++ .build(); + } +- +- @Async(period = 1000, initialState = Async.InitialState.UNHEALTHY, unit = TimeUnit.MILLISECONDS) +- private static class HealthyAsyncHealthCheckWithExpiredTtlInMillisecondsBasedOnPeriod implements HealthCheck { +- +- @Override +- public Result check() { +- return Result.builder().usingClock(clockWithFixedTime(CURRENT_TIME - 2001L)).healthy().build(); +- } ++ } ++ ++ @Async( ++ period = 1, ++ initialState = Async.InitialState.UNHEALTHY, ++ healthyTtl = 5, ++ unit = TimeUnit.SECONDS) ++ private static class HealthyAsyncHealthCheckWithExpiredExplicitTtlInSeconds ++ implements HealthCheck { ++ ++ @Override ++ public Result check() { ++ return Result.builder() ++ .usingClock(clockWithFixedTime(CURRENT_TIME - 5001L)) ++ .healthy() ++ .build(); + } +- +- private static Clock clockWithFixedTime(final long time) { +- return new Clock() { +- @Override +- public long getTick() { +- return 0; +- } +- +- @Override +- public long getTime() { +- return time; +- } +- }; ++ } ++ ++ @Async(period = 1000, initialState = Async.InitialState.UNHEALTHY, unit = TimeUnit.MILLISECONDS) ++ private static class HealthyAsyncHealthCheckWithExpiredTtlInMillisecondsBasedOnPeriod ++ implements HealthCheck { ++ ++ @Override ++ public Result check() { ++ return Result.builder() ++ .usingClock(clockWithFixedTime(CURRENT_TIME - 2001L)) ++ .healthy() ++ .build(); + } +- ++ } ++ ++ private static Clock clockWithFixedTime(final long time) { ++ return new Clock() { ++ @Override ++ public long getTick() { ++ return 0; ++ } ++ ++ @Override ++ public long getTime() { ++ return time; ++ } ++ }; ++ } + } +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java +@@ -5,10 +5,10 @@ import static org.mockito.Mockito.mock; + + import org.junit.jupiter.api.Test; + +-class HealthCheckFilterTest { ++final class HealthCheckFilterTest { + +- @Test +- void theAllFilterMatchesAllHealthChecks() { +- assertThat(HealthCheckFilter.ALL.matches("", mock(HealthCheck.class))).isTrue(); +- } ++ @Test ++ void theAllFilterMatchesAllHealthChecks() { ++ assertThat(HealthCheckFilter.ALL.matches("", mock(HealthCheck.class))).isTrue(); ++ } + } +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java +@@ -1,22 +1,9 @@ + package io.dropwizard.metrics5.health; + +-import io.dropwizard.metrics5.health.annotation.Async; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +-import org.mockito.ArgumentCaptor; +- +-import java.util.Map; +-import java.util.NoSuchElementException; +-import java.util.concurrent.ExecutorService; +-import java.util.concurrent.Executors; +-import java.util.concurrent.ScheduledExecutorService; +-import java.util.concurrent.ScheduledFuture; +-import java.util.concurrent.TimeUnit; +- + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.assertj.core.api.Assertions.entry; + import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +-import static org.junit.jupiter.api.Assertions.assertThrows; + import static org.mockito.ArgumentCaptor.forClass; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; +@@ -24,206 +11,224 @@ import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +-class HealthCheckRegistryTest { +- private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); +- private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); +- private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); +- +- private final HealthCheck hc1 = mock(HealthCheck.class); +- private final HealthCheck hc2 = mock(HealthCheck.class); +- +- private final HealthCheck.Result r1 = mock(HealthCheck.Result.class); +- private final HealthCheck.Result r2 = mock(HealthCheck.Result.class); +- +- private final HealthCheck.Result ar = mock(HealthCheck.Result.class); +- private final HealthCheck ahc = new TestAsyncHealthCheck(ar); +- +- @SuppressWarnings("rawtypes") +- private final ScheduledFuture af = mock(ScheduledFuture.class); +- +- @BeforeEach +- @SuppressWarnings("unchecked") +- void setUp() { +- registry.addListener(listener); +- +- when(hc1.execute()).thenReturn(r1); +- when(hc2.execute()).thenReturn(r2); +- when(executorService.scheduleAtFixedRate(any(AsyncHealthCheckDecorator.class), eq(0L), eq(10L), eq(TimeUnit.SECONDS))) +- .thenReturn(af); +- +- registry.register("hc1", hc1); +- registry.register("hc2", hc2); +- registry.register("ahc", ahc); +- } +- +- @Test +- void asyncHealthCheckIsScheduledOnExecutor() { +- ArgumentCaptor decoratorCaptor = forClass(AsyncHealthCheckDecorator.class); +- verify(executorService).scheduleAtFixedRate(decoratorCaptor.capture(), eq(0L), eq(10L), eq(TimeUnit.SECONDS)); +- assertThat(decoratorCaptor.getValue().getHealthCheck()).isEqualTo(ahc); +- } +- +- @Test +- void asyncHealthCheckIsCanceledOnRemove() { +- registry.unregister("ahc"); +- +- verify(af).cancel(true); +- } +- +- @Test +- void registeringHealthCheckTwiceThrowsException() { +- assertThrows(IllegalArgumentException.class, () -> { +- registry.register("hc1", hc1); +- }); +- } +- +- @Test +- void registeringHealthCheckTriggersNotification() { +- verify(listener).onHealthCheckAdded("hc1", hc1); +- verify(listener).onHealthCheckAdded("hc2", hc2); +- verify(listener).onHealthCheckAdded(eq("ahc"), any(AsyncHealthCheckDecorator.class)); +- } +- +- @Test +- void removingHealthCheckTriggersNotification() { +- registry.unregister("hc1"); +- registry.unregister("hc2"); +- registry.unregister("ahc"); +- +- verify(listener).onHealthCheckRemoved("hc1", hc1); +- verify(listener).onHealthCheckRemoved("hc2", hc2); +- verify(listener).onHealthCheckRemoved(eq("ahc"), any(AsyncHealthCheckDecorator.class)); +- } +- +- @Test +- void addingListenerCatchesExistingHealthChecks() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); +- HealthCheckRegistry registry = new HealthCheckRegistry(); +- registry.register("hc1", hc1); +- registry.register("hc2", hc2); +- registry.register("ahc", ahc); +- registry.addListener(listener); +- +- verify(listener).onHealthCheckAdded("hc1", hc1); +- verify(listener).onHealthCheckAdded("hc2", hc2); +- verify(listener).onHealthCheckAdded(eq("ahc"), any(AsyncHealthCheckDecorator.class)); +- } +- +- @Test +- void removedListenerDoesNotReceiveUpdates() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); +- HealthCheckRegistry registry = new HealthCheckRegistry(); +- registry.addListener(listener); +- registry.register("hc1", hc1); +- registry.removeListener(listener); +- registry.register("hc2", hc2); +- +- verify(listener).onHealthCheckAdded("hc1", hc1); +- } +- +- @Test +- void runsRegisteredHealthChecks() { +- final Map results = registry.runHealthChecks(); +- +- assertThat(results).contains(entry("hc1", r1)); +- assertThat(results).contains(entry("hc2", r2)); +- assertThat(results).containsKey("ahc"); +- } +- +- @Test +- void runsRegisteredHealthChecksWithFilter() { +- final Map results = registry.runHealthChecks((name, healthCheck) -> "hc1".equals(name)); +- +- assertThat(results).containsOnly(entry("hc1", r1)); +- } +- +- @Test +- void runsRegisteredHealthChecksWithNonMatchingFilter() { +- final Map results = registry.runHealthChecks((name, healthCheck) -> false); +- +- assertThat(results).isEmpty(); +- } +- +- @Test +- void runsRegisteredHealthChecksInParallel() throws Exception { +- final ExecutorService executor = Executors.newFixedThreadPool(10); +- final Map results = registry.runHealthChecks(executor); +- +- executor.shutdown(); +- executor.awaitTermination(1, TimeUnit.SECONDS); +- +- assertThat(results).contains(entry("hc1", r1)); +- assertThat(results).contains(entry("hc2", r2)); +- assertThat(results).containsKey("ahc"); +- } +- +- @Test +- void runsRegisteredHealthChecksInParallelWithNonMatchingFilter() throws Exception { +- final ExecutorService executor = Executors.newFixedThreadPool(10); +- final Map results = registry.runHealthChecks(executor, (name, healthCheck) -> false); +- +- executor.shutdown(); +- executor.awaitTermination(1, TimeUnit.SECONDS); +- +- assertThat(results).isEmpty(); +- } +- +- @Test +- void runsRegisteredHealthChecksInParallelWithFilter() throws Exception { +- final ExecutorService executor = Executors.newFixedThreadPool(10); +- final Map results = registry.runHealthChecks(executor, +- (name, healthCheck) -> "hc2".equals(name)); +- +- executor.shutdown(); +- executor.awaitTermination(1, TimeUnit.SECONDS); +- +- assertThat(results).containsOnly(entry("hc2", r2)); +- } +- +- @Test +- void removesRegisteredHealthChecks() { +- registry.unregister("hc1"); +- +- final Map results = registry.runHealthChecks(); +- +- assertThat(results).doesNotContainKey("hc1"); +- assertThat(results).containsKey("hc2"); +- assertThat(results).containsKey("ahc"); +- } +- +- @Test +- void hasASetOfHealthCheckNames() { +- assertThat(registry.getNames()).containsOnly("hc1", "hc2", "ahc"); +- } ++import io.dropwizard.metrics5.health.annotation.Async; ++import java.util.Map; ++import java.util.NoSuchElementException; ++import java.util.concurrent.ExecutorService; ++import java.util.concurrent.Executors; ++import java.util.concurrent.ScheduledExecutorService; ++import java.util.concurrent.ScheduledFuture; ++import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; ++import org.mockito.ArgumentCaptor; + +- @Test +- void runsHealthChecksByName() { +- assertThat(registry.runHealthCheck("hc1")).isEqualTo(r1); +- } ++final class HealthCheckRegistryTest { ++ private final ScheduledExecutorService executorService = mock(); ++ private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); ++ private final HealthCheckRegistryListener listener = mock(); ++ ++ private final HealthCheck hc1 = mock(); ++ private final HealthCheck hc2 = mock(); ++ ++ private final HealthCheck.Result r1 = mock(); ++ private final HealthCheck.Result r2 = mock(); ++ ++ private final HealthCheck.Result ar = mock(); ++ private final HealthCheck ahc = new TestAsyncHealthCheck(ar); ++ ++ @SuppressWarnings("rawtypes") ++ private final ScheduledFuture af = mock(); ++ ++ @BeforeEach ++ @SuppressWarnings("unchecked") ++ void setUp() { ++ registry.addListener(listener); ++ ++ when(hc1.execute()).thenReturn(r1); ++ when(hc2.execute()).thenReturn(r2); ++ when(executorService.scheduleAtFixedRate( ++ any(AsyncHealthCheckDecorator.class), eq(0L), eq(10L), eq(TimeUnit.SECONDS))) ++ .thenReturn(af); ++ ++ registry.register("hc1", hc1); ++ registry.register("hc2", hc2); ++ registry.register("ahc", ahc); ++ } ++ ++ @Test ++ void asyncHealthCheckIsScheduledOnExecutor() { ++ ArgumentCaptor decoratorCaptor = ++ forClass(AsyncHealthCheckDecorator.class); ++ verify(executorService) ++ .scheduleAtFixedRate(decoratorCaptor.capture(), eq(0L), eq(10L), eq(TimeUnit.SECONDS)); ++ assertThat(decoratorCaptor.getValue().getHealthCheck()).isEqualTo(ahc); ++ } ++ ++ @Test ++ void asyncHealthCheckIsCanceledOnRemove() { ++ registry.unregister("ahc"); ++ ++ verify(af).cancel(true); ++ } ++ ++ @Test ++ void registeringHealthCheckTwiceThrowsException() { ++ assertThatThrownBy( ++ () -> { ++ registry.register("hc1", hc1); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); ++ } ++ ++ @Test ++ void registeringHealthCheckTriggersNotification() { ++ verify(listener).onHealthCheckAdded("hc1", hc1); ++ verify(listener).onHealthCheckAdded("hc2", hc2); ++ verify(listener).onHealthCheckAdded(eq("ahc"), any(AsyncHealthCheckDecorator.class)); ++ } ++ ++ @Test ++ void removingHealthCheckTriggersNotification() { ++ registry.unregister("hc1"); ++ registry.unregister("hc2"); ++ registry.unregister("ahc"); ++ ++ verify(listener).onHealthCheckRemoved("hc1", hc1); ++ verify(listener).onHealthCheckRemoved("hc2", hc2); ++ verify(listener).onHealthCheckRemoved(eq("ahc"), any(AsyncHealthCheckDecorator.class)); ++ } ++ ++ @Test ++ void addingListenerCatchesExistingHealthChecks() { ++ HealthCheckRegistryListener listener = mock(); ++ HealthCheckRegistry registry = new HealthCheckRegistry(); ++ registry.register("hc1", hc1); ++ registry.register("hc2", hc2); ++ registry.register("ahc", ahc); ++ registry.addListener(listener); ++ ++ verify(listener).onHealthCheckAdded("hc1", hc1); ++ verify(listener).onHealthCheckAdded("hc2", hc2); ++ verify(listener).onHealthCheckAdded(eq("ahc"), any(AsyncHealthCheckDecorator.class)); ++ } ++ ++ @Test ++ void removedListenerDoesNotReceiveUpdates() { ++ HealthCheckRegistryListener listener = mock(); ++ HealthCheckRegistry registry = new HealthCheckRegistry(); ++ registry.addListener(listener); ++ registry.register("hc1", hc1); ++ registry.removeListener(listener); ++ registry.register("hc2", hc2); ++ ++ verify(listener).onHealthCheckAdded("hc1", hc1); ++ } ++ ++ @Test ++ void runsRegisteredHealthChecks() { ++ final Map results = registry.runHealthChecks(); ++ ++ assertThat(results).contains(entry("hc1", r1)); ++ assertThat(results).contains(entry("hc2", r2)); ++ assertThat(results).containsKey("ahc"); ++ } ++ ++ @Test ++ void runsRegisteredHealthChecksWithFilter() { ++ final Map results = ++ registry.runHealthChecks((name, healthCheck) -> "hc1".equals(name)); ++ ++ assertThat(results).containsOnly(entry("hc1", r1)); ++ } ++ ++ @Test ++ void runsRegisteredHealthChecksWithNonMatchingFilter() { ++ final Map results = ++ registry.runHealthChecks((name, healthCheck) -> false); ++ ++ assertThat(results).isEmpty(); ++ } ++ ++ @Test ++ void runsRegisteredHealthChecksInParallel() throws Exception { ++ final ExecutorService executor = Executors.newFixedThreadPool(10); ++ final Map results = registry.runHealthChecks(executor); ++ ++ executor.shutdown(); ++ executor.awaitTermination(1, TimeUnit.SECONDS); ++ ++ assertThat(results).contains(entry("hc1", r1)); ++ assertThat(results).contains(entry("hc2", r2)); ++ assertThat(results).containsKey("ahc"); ++ } ++ ++ @Test ++ void runsRegisteredHealthChecksInParallelWithNonMatchingFilter() throws Exception { ++ final ExecutorService executor = Executors.newFixedThreadPool(10); ++ final Map results = ++ registry.runHealthChecks(executor, (name, healthCheck) -> false); ++ ++ executor.shutdown(); ++ executor.awaitTermination(1, TimeUnit.SECONDS); ++ ++ assertThat(results).isEmpty(); ++ } ++ ++ @Test ++ void runsRegisteredHealthChecksInParallelWithFilter() throws Exception { ++ final ExecutorService executor = Executors.newFixedThreadPool(10); ++ final Map results = ++ registry.runHealthChecks(executor, (name, healthCheck) -> "hc2".equals(name)); ++ ++ executor.shutdown(); ++ executor.awaitTermination(1, TimeUnit.SECONDS); ++ ++ assertThat(results).containsOnly(entry("hc2", r2)); ++ } ++ ++ @Test ++ void removesRegisteredHealthChecks() { ++ registry.unregister("hc1"); ++ ++ final Map results = registry.runHealthChecks(); ++ ++ assertThat(results).doesNotContainKey("hc1"); ++ assertThat(results).containsKey("hc2"); ++ assertThat(results).containsKey("ahc"); ++ } ++ ++ @Test ++ void hasASetOfHealthCheckNames() { ++ assertThat(registry.getNames()).containsOnly("hc1", "hc2", "ahc"); ++ } ++ ++ @Test ++ void runsHealthChecksByName() { ++ assertThat(registry.runHealthCheck("hc1")).isEqualTo(r1); ++ } ++ ++ @Test ++ void doesNotRunNonexistentHealthChecks() { ++ try { ++ registry.runHealthCheck("what"); ++ failBecauseExceptionWasNotThrown(NoSuchElementException.class); ++ } catch (NoSuchElementException e) { ++ assertThat(e.getMessage()).isEqualTo("No health check named what exists"); ++ } ++ } + +- @Test +- void doesNotRunNonexistentHealthChecks() { +- try { +- registry.runHealthCheck("what"); +- failBecauseExceptionWasNotThrown(NoSuchElementException.class); +- } catch (NoSuchElementException e) { +- assertThat(e.getMessage()) +- .isEqualTo("No health check named what exists"); +- } ++ @Async(period = 10) ++ private static class TestAsyncHealthCheck implements HealthCheck { ++ private final Result result; + ++ TestAsyncHealthCheck(Result result) { ++ this.result = result; + } + +- @Async(period = 10) +- private static class TestAsyncHealthCheck implements HealthCheck { +- private final Result result; +- +- TestAsyncHealthCheck(Result result) { +- this.result = result; +- } +- +- @Override +- public Result check() { +- return result; +- } ++ @Override ++ public Result check() { ++ return result; + } ++ } + } +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java +@@ -1,279 +1,231 @@ + package io.dropwizard.metrics5.health; + +-import io.dropwizard.metrics5.Clock; +-import org.junit.jupiter.api.Test; +- +-import java.time.ZonedDateTime; +-import java.time.format.DateTimeFormatter; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.ArgumentMatchers.anyLong; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +-class HealthCheckTest { ++import io.dropwizard.metrics5.Clock; ++import java.time.ZonedDateTime; ++import java.time.format.DateTimeFormatter; ++import org.junit.jupiter.api.Test; + +- private static final DateTimeFormatter DATE_TIME_FORMATTER = +- DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); ++final class HealthCheckTest { + +- private static class ExampleHealthCheck implements HealthCheck { +- private final HealthCheck underlying; ++ private static final DateTimeFormatter DATE_TIME_FORMATTER = ++ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + +- private ExampleHealthCheck(HealthCheck underlying) { +- this.underlying = underlying; +- } ++ private static class ExampleHealthCheck implements HealthCheck { ++ private final HealthCheck underlying; + +- @Override +- public Result check() { +- return underlying.execute(); +- } ++ private ExampleHealthCheck(HealthCheck underlying) { ++ this.underlying = underlying; + } + +- private final HealthCheck underlying = mock(HealthCheck.class); +- private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); ++ @Override ++ public Result check() { ++ return underlying.execute(); ++ } ++ } + +- @Test +- void canHaveHealthyResults() { +- final HealthCheck.Result result = HealthCheck.Result.healthy(); ++ private final HealthCheck underlying = mock(); ++ private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); + +- assertThat(result.isHealthy()) +- .isTrue(); ++ @Test ++ void canHaveHealthyResults() { ++ final HealthCheck.Result result = HealthCheck.Result.healthy(); + +- assertThat(result.getMessage()) +- .isNull(); ++ assertThat(result.isHealthy()).isTrue(); + +- assertThat(result.getError()) +- .isNull(); +- } ++ assertThat(result.getMessage()).isNull(); + +- @Test +- void canHaveHealthyResultsWithMessages() { +- final HealthCheck.Result result = HealthCheck.Result.healthy("woo"); ++ assertThat(result.getError()).isNull(); ++ } + +- assertThat(result.isHealthy()) +- .isTrue(); ++ @Test ++ void canHaveHealthyResultsWithMessages() { ++ final HealthCheck.Result result = HealthCheck.Result.healthy("woo"); + +- assertThat(result.getMessage()) +- .isEqualTo("woo"); ++ assertThat(result.isHealthy()).isTrue(); + +- assertThat(result.getError()) +- .isNull(); +- } ++ assertThat(result.getMessage()).isEqualTo("woo"); + +- @Test +- void canHaveHealthyResultsWithFormattedMessages() { +- final HealthCheck.Result result = HealthCheck.Result.healthy("foo %s", "bar"); ++ assertThat(result.getError()).isNull(); ++ } + +- assertThat(result.isHealthy()) +- .isTrue(); ++ @Test ++ void canHaveHealthyResultsWithFormattedMessages() { ++ final HealthCheck.Result result = HealthCheck.Result.healthy("foo %s", "bar"); + +- assertThat(result.getMessage()) +- .isEqualTo("foo bar"); ++ assertThat(result.isHealthy()).isTrue(); + +- assertThat(result.getError()) +- .isNull(); +- } ++ assertThat(result.getMessage()).isEqualTo("foo bar"); + +- @Test +- void canHaveUnhealthyResults() { +- final HealthCheck.Result result = HealthCheck.Result.unhealthy("bad"); ++ assertThat(result.getError()).isNull(); ++ } + +- assertThat(result.isHealthy()) +- .isFalse(); ++ @Test ++ void canHaveUnhealthyResults() { ++ final HealthCheck.Result result = HealthCheck.Result.unhealthy("bad"); + +- assertThat(result.getMessage()) +- .isEqualTo("bad"); ++ assertThat(result.isHealthy()).isFalse(); + +- assertThat(result.getError()) +- .isNull(); +- } ++ assertThat(result.getMessage()).isEqualTo("bad"); + +- @Test +- void canHaveUnhealthyResultsWithFormattedMessages() { +- final HealthCheck.Result result = HealthCheck.Result.unhealthy("foo %s %d", "bar", 123); ++ assertThat(result.getError()).isNull(); ++ } + +- assertThat(result.isHealthy()) +- .isFalse(); ++ @Test ++ void canHaveUnhealthyResultsWithFormattedMessages() { ++ final HealthCheck.Result result = HealthCheck.Result.unhealthy("foo %s %d", "bar", 123); + +- assertThat(result.getMessage()) +- .isEqualTo("foo bar 123"); ++ assertThat(result.isHealthy()).isFalse(); + +- assertThat(result.getError()) +- .isNull(); +- } ++ assertThat(result.getMessage()).isEqualTo("foo bar 123"); + +- @Test +- void canHaveUnhealthyResultsWithExceptions() { +- final RuntimeException e = mock(RuntimeException.class); +- when(e.getMessage()).thenReturn("oh noes"); ++ assertThat(result.getError()).isNull(); ++ } + +- final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); ++ @Test ++ void canHaveUnhealthyResultsWithExceptions() { ++ final RuntimeException e = mock(); ++ when(e.getMessage()).thenReturn("oh noes"); + +- assertThat(result.isHealthy()) +- .isFalse(); ++ final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); + +- assertThat(result.getMessage()) +- .isEqualTo("oh noes"); ++ assertThat(result.isHealthy()).isFalse(); + +- assertThat(result.getError()) +- .isEqualTo(e); +- } ++ assertThat(result.getMessage()).isEqualTo("oh noes"); + +- @Test +- void canHaveHealthyBuilderWithFormattedMessage() { +- final HealthCheck.Result result = HealthCheck.Result.builder() +- .healthy() +- .withMessage("There are %d %s in the %s", 42, "foos", "bar") +- .build(); ++ assertThat(result.getError()).isEqualTo(e); ++ } + +- assertThat(result.isHealthy()) +- .isTrue(); ++ @Test ++ void canHaveHealthyBuilderWithFormattedMessage() { ++ final HealthCheck.Result result = ++ HealthCheck.Result.builder() ++ .healthy() ++ .withMessage("There are %d %s in the %s", 42, "foos", "bar") ++ .build(); + +- assertThat(result.getMessage()) +- .isEqualTo("There are 42 foos in the bar"); +- } ++ assertThat(result.isHealthy()).isTrue(); + +- @Test +- void canHaveHealthyBuilderWithDetail() { +- final HealthCheck.Result result = HealthCheck.Result.builder() +- .healthy() +- .withDetail("detail", "value") +- .build(); ++ assertThat(result.getMessage()).isEqualTo("There are 42 foos in the bar"); ++ } + +- assertThat(result.isHealthy()) +- .isTrue(); ++ @Test ++ void canHaveHealthyBuilderWithDetail() { ++ final HealthCheck.Result result = ++ HealthCheck.Result.builder().healthy().withDetail("detail", "value").build(); + +- assertThat(result.getMessage()) +- .isNull(); ++ assertThat(result.isHealthy()).isTrue(); + +- assertThat(result.getError()) +- .isNull(); ++ assertThat(result.getMessage()).isNull(); + +- assertThat(result.getDetails()) +- .containsEntry("detail", "value"); +- } ++ assertThat(result.getError()).isNull(); + +- @Test +- void canHaveUnHealthyBuilderWithDetail() { +- final HealthCheck.Result result = HealthCheck.Result.builder() +- .unhealthy() +- .withDetail("detail", "value") +- .build(); ++ assertThat(result.getDetails()).containsEntry("detail", "value"); ++ } + +- assertThat(result.isHealthy()) +- .isFalse(); ++ @Test ++ void canHaveUnHealthyBuilderWithDetail() { ++ final HealthCheck.Result result = ++ HealthCheck.Result.builder().unhealthy().withDetail("detail", "value").build(); + +- assertThat(result.getMessage()) +- .isNull(); ++ assertThat(result.isHealthy()).isFalse(); + +- assertThat(result.getError()) +- .isNull(); ++ assertThat(result.getMessage()).isNull(); + +- assertThat(result.getDetails()) +- .containsEntry("detail", "value"); +- } ++ assertThat(result.getError()).isNull(); + +- @Test +- void canHaveUnHealthyBuilderWithDetailAndError() { +- final RuntimeException e = mock(RuntimeException.class); +- when(e.getMessage()).thenReturn("oh noes"); ++ assertThat(result.getDetails()).containsEntry("detail", "value"); ++ } + +- final HealthCheck.Result result = HealthCheck.Result +- .builder() +- .unhealthy(e) +- .withDetail("detail", "value") +- .build(); ++ @Test ++ void canHaveUnHealthyBuilderWithDetailAndError() { ++ final RuntimeException e = mock(); ++ when(e.getMessage()).thenReturn("oh noes"); + +- assertThat(result.isHealthy()) +- .isFalse(); ++ final HealthCheck.Result result = ++ HealthCheck.Result.builder().unhealthy(e).withDetail("detail", "value").build(); + +- assertThat(result.getMessage()) +- .isEqualTo("oh noes"); ++ assertThat(result.isHealthy()).isFalse(); + +- assertThat(result.getError()) +- .isEqualTo(e); ++ assertThat(result.getMessage()).isEqualTo("oh noes"); + +- assertThat(result.getDetails()) +- .containsEntry("detail", "value"); +- } ++ assertThat(result.getError()).isEqualTo(e); + +- @Test +- void returnsResultsWhenExecuted() { +- final HealthCheck.Result result = mock(HealthCheck.Result.class); +- when(underlying.execute()).thenReturn(result); ++ assertThat(result.getDetails()).containsEntry("detail", "value"); ++ } + +- assertThat(healthCheck.execute()) +- .isEqualTo(result); ++ @Test ++ void returnsResultsWhenExecuted() { ++ final HealthCheck.Result result = mock(); ++ when(underlying.execute()).thenReturn(result); + +- verify(result).setDuration(anyLong()); +- } ++ assertThat(healthCheck.execute()).isEqualTo(result); + +- @Test +- void wrapsExceptionsWhenExecuted() { +- final RuntimeException e = mock(RuntimeException.class); +- when(e.getMessage()).thenReturn("oh noes"); +- +- when(underlying.execute()).thenThrow(e); +- HealthCheck.Result actual = healthCheck.execute(); +- +- assertThat(actual.isHealthy()) +- .isFalse(); +- assertThat(actual.getMessage()) +- .isEqualTo("oh noes"); +- assertThat(actual.getError()) +- .isEqualTo(e); +- assertThat(actual.getDetails()) +- .isNull(); +- assertThat(actual.getDuration()) +- .isGreaterThanOrEqualTo(0); +- } ++ verify(result).setDuration(anyLong()); ++ } + +- @Test +- void canHaveUserSuppliedClockForTimestamp() { +- ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(10); +- Clock clock = clockWithFixedTime(dateTime); ++ @Test ++ void wrapsExceptionsWhenExecuted() { ++ final RuntimeException e = mock(); ++ when(e.getMessage()).thenReturn("oh noes"); + +- HealthCheck.Result result = HealthCheck.Result.builder() +- .healthy() +- .usingClock(clock) +- .build(); ++ when(underlying.execute()).thenThrow(e); ++ HealthCheck.Result actual = healthCheck.execute(); + +- assertThat(result.isHealthy()).isTrue(); ++ assertThat(actual.isHealthy()).isFalse(); ++ assertThat(actual.getMessage()).isEqualTo("oh noes"); ++ assertThat(actual.getError()).isEqualTo(e); ++ assertThat(actual.getDetails()).isNull(); ++ assertThat(actual.getDuration()).isNotNegative(); ++ } + +- assertThat(result.getTime()).isEqualTo(clock.getTime()); ++ @Test ++ void canHaveUserSuppliedClockForTimestamp() { ++ ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(10); ++ Clock clock = clockWithFixedTime(dateTime); + +- assertThat(result.getTimestamp()) +- .isEqualTo(DATE_TIME_FORMATTER.format(dateTime)); +- } ++ HealthCheck.Result result = HealthCheck.Result.builder().healthy().usingClock(clock).build(); + +- @Test +- void toStringWorksEvenForNullAttributes() { +- ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(25); +- Clock clock = clockWithFixedTime(dateTime); +- +- final HealthCheck.Result resultWithNullDetailValue = HealthCheck.Result.builder() +- .unhealthy() +- .withDetail("aNullDetail", null) +- .usingClock(clock) +- .build(); +- assertThat(resultWithNullDetailValue.toString()) +- .contains( +- "Result{isHealthy=false, duration=0, timestamp=" + DATE_TIME_FORMATTER.format(dateTime), +- ", aNullDetail=null}"); +- } ++ assertThat(result.isHealthy()).isTrue(); + +- private static Clock clockWithFixedTime(ZonedDateTime dateTime) { +- return new Clock() { +- @Override +- public long getTick() { +- return 0; +- } +- +- @Override +- public long getTime() { +- return dateTime.toInstant().toEpochMilli(); +- } +- }; +- } ++ assertThat(result.getTime()).isEqualTo(clock.getTime()); ++ ++ assertThat(result.getTimestamp()).isEqualTo(DATE_TIME_FORMATTER.format(dateTime)); ++ } ++ ++ @Test ++ void toStringWorksEvenForNullAttributes() { ++ ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(25); ++ Clock clock = clockWithFixedTime(dateTime); ++ ++ final HealthCheck.Result resultWithNullDetailValue = ++ HealthCheck.Result.builder() ++ .unhealthy() ++ .withDetail("aNullDetail", null) ++ .usingClock(clock) ++ .build(); ++ assertThat(resultWithNullDetailValue.toString()) ++ .contains( ++ "Result{isHealthy=false, duration=0, timestamp=" + DATE_TIME_FORMATTER.format(dateTime), ++ ", aNullDetail=null}"); ++ } ++ ++ private static Clock clockWithFixedTime(ZonedDateTime dateTime) { ++ return new Clock() { ++ @Override ++ public long getTick() { ++ return 0; ++ } ++ ++ @Override ++ public long getTime() { ++ return dateTime.toInstant().toEpochMilli(); ++ } ++ }; ++ } + } +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java +@@ -1,97 +1,103 @@ + package io.dropwizard.metrics5.health; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import java.util.concurrent.atomic.AtomicReference; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.junit.jupiter.api.Assertions.assertTrue; +- +-class SharedHealthCheckRegistriesTest { +- +- @BeforeEach +- void setUp() { +- SharedHealthCheckRegistries.setDefaultRegistryName(new AtomicReference<>()); +- SharedHealthCheckRegistries.clear(); +- } +- +- @Test +- void savesCreatedRegistry() { +- final HealthCheckRegistry one = SharedHealthCheckRegistries.getOrCreate("db"); +- final HealthCheckRegistry two = SharedHealthCheckRegistries.getOrCreate("db"); +- +- assertThat(one).isSameAs(two); +- } +- +- @Test +- void returnsSetOfCreatedRegistries() { +- SharedHealthCheckRegistries.getOrCreate("db"); +- +- assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); +- } +- +- @Test +- void registryCanBeRemoved() { +- final HealthCheckRegistry first = SharedHealthCheckRegistries.getOrCreate("db"); +- SharedHealthCheckRegistries.remove("db"); +- +- assertThat(SharedHealthCheckRegistries.names()).isEmpty(); +- assertThat(SharedHealthCheckRegistries.getOrCreate("db")).isNotEqualTo(first); +- } +- +- @Test +- void registryCanBeCleared() { +- SharedHealthCheckRegistries.getOrCreate("db"); +- SharedHealthCheckRegistries.getOrCreate("web"); + +- SharedHealthCheckRegistries.clear(); +- +- assertThat(SharedHealthCheckRegistries.names()).isEmpty(); +- } +- +- @Test +- void defaultRegistryIsNotSetByDefault() { +- Throwable exception = assertThrows(IllegalStateException.class, () -> { +- +- SharedHealthCheckRegistries.getDefault(); +- }); +- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); +- } +- +- @Test +- void defaultRegistryCanBeSet() { +- HealthCheckRegistry registry = SharedHealthCheckRegistries.setDefault("default"); +- +- assertThat(SharedHealthCheckRegistries.getDefault()).isEqualTo(registry); +- } +- +- @Test +- void specificRegistryCanBeSetAsDefault() { +- HealthCheckRegistry registry = new HealthCheckRegistry(); +- SharedHealthCheckRegistries.setDefault("default", registry); +- +- assertThat(SharedHealthCheckRegistries.getDefault()).isEqualTo(registry); +- } +- +- @Test +- void unableToSetDefaultRegistryTwice() { +- Throwable exception = assertThrows(IllegalStateException.class, () -> { +- +- SharedHealthCheckRegistries.setDefault("default"); +- SharedHealthCheckRegistries.setDefault("default"); +- }); +- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); +- } +- +- @Test +- void unableToSetCustomDefaultRegistryTwice() { +- Throwable exception = assertThrows(IllegalStateException.class, () -> { ++import java.util.concurrent.atomic.AtomicReference; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +- SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); +- SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); +- }); +- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); +- } ++final class SharedHealthCheckRegistriesTest { ++ ++ @BeforeEach ++ void setUp() { ++ SharedHealthCheckRegistries.setDefaultRegistryName(new AtomicReference<>()); ++ SharedHealthCheckRegistries.clear(); ++ } ++ ++ @Test ++ void savesCreatedRegistry() { ++ final HealthCheckRegistry one = SharedHealthCheckRegistries.getOrCreate("db"); ++ final HealthCheckRegistry two = SharedHealthCheckRegistries.getOrCreate("db"); ++ ++ assertThat(one).isSameAs(two); ++ } ++ ++ @Test ++ void returnsSetOfCreatedRegistries() { ++ SharedHealthCheckRegistries.getOrCreate("db"); ++ ++ assertThat(SharedHealthCheckRegistries.names()).containsExactly("db"); ++ } ++ ++ @Test ++ void registryCanBeRemoved() { ++ final HealthCheckRegistry first = SharedHealthCheckRegistries.getOrCreate("db"); ++ SharedHealthCheckRegistries.remove("db"); ++ ++ assertThat(SharedHealthCheckRegistries.names()).isEmpty(); ++ assertThat(SharedHealthCheckRegistries.getOrCreate("db")).isNotEqualTo(first); ++ } ++ ++ @Test ++ void registryCanBeCleared() { ++ SharedHealthCheckRegistries.getOrCreate("db"); ++ SharedHealthCheckRegistries.getOrCreate("web"); ++ ++ SharedHealthCheckRegistries.clear(); ++ ++ assertThat(SharedHealthCheckRegistries.names()).isEmpty(); ++ } ++ ++ @Test ++ void defaultRegistryIsNotSetByDefault() { ++ Throwable exception = ++ assertThrows( ++ IllegalStateException.class, ++ () -> { ++ SharedHealthCheckRegistries.getDefault(); ++ }); ++ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); ++ } ++ ++ @Test ++ void defaultRegistryCanBeSet() { ++ HealthCheckRegistry registry = SharedHealthCheckRegistries.setDefault("default"); ++ ++ assertThat(SharedHealthCheckRegistries.getDefault()).isEqualTo(registry); ++ } ++ ++ @Test ++ void specificRegistryCanBeSetAsDefault() { ++ HealthCheckRegistry registry = new HealthCheckRegistry(); ++ SharedHealthCheckRegistries.setDefault("default", registry); ++ ++ assertThat(SharedHealthCheckRegistries.getDefault()).isEqualTo(registry); ++ } ++ ++ @Test ++ void unableToSetDefaultRegistryTwice() { ++ Throwable exception = ++ assertThrows( ++ IllegalStateException.class, ++ () -> { ++ SharedHealthCheckRegistries.setDefault("default"); ++ SharedHealthCheckRegistries.setDefault("default"); ++ }); ++ assertThat(exception.getMessage().contains("Default health check registry is already set.")) ++ .isTrue(); ++ } ++ ++ @Test ++ void unableToSetCustomDefaultRegistryTwice() { ++ Throwable exception = ++ assertThrows( ++ IllegalStateException.class, ++ () -> { ++ SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); ++ SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); ++ }); ++ assertThat(exception.getMessage().contains("Default health check registry is already set.")) ++ .isTrue(); ++ } + } +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java +@@ -1,54 +1,48 @@ + package io.dropwizard.metrics5.health.jvm; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.health.HealthCheck; + import io.dropwizard.metrics5.jvm.ThreadDeadlockDetector; +-import org.assertj.core.api.Assertions; +-import org.junit.jupiter.api.Test; +- +-import java.util.Collections; + import java.util.Set; + import java.util.TreeSet; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-class ThreadDeadlockHealthCheckTest { +- @Test +- void isHealthyIfNoThreadsAreDeadlocked() { +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); +- final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); ++final class ThreadDeadlockHealthCheckTest { ++ @Test ++ void isHealthyIfNoThreadsAreDeadlocked() { ++ final ThreadDeadlockDetector detector = mock(); ++ final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); + +- when(detector.getDeadlockedThreads()).thenReturn(Collections.emptySet()); ++ when(detector.getDeadlockedThreads()).thenReturn(ImmutableSet.of()); + +- Assertions.assertThat(healthCheck.execute().isHealthy()) +- .isTrue(); +- } ++ assertThat(healthCheck.execute().isHealthy()).isTrue(); ++ } + +- @Test +- void isUnhealthyIfThreadsAreDeadlocked() { +- final Set threads = new TreeSet<>(); +- threads.add("one"); +- threads.add("two"); ++ @Test ++ void isUnhealthyIfThreadsAreDeadlocked() { ++ final Set threads = new TreeSet<>(); ++ threads.add("one"); ++ threads.add("two"); + +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); +- final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); ++ final ThreadDeadlockDetector detector = mock(); ++ final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); + +- when(detector.getDeadlockedThreads()).thenReturn(threads); ++ when(detector.getDeadlockedThreads()).thenReturn(threads); + +- final HealthCheck.Result result = healthCheck.execute(); ++ final HealthCheck.Result result = healthCheck.execute(); + +- assertThat(result.isHealthy()) +- .isFalse(); ++ assertThat(result.isHealthy()).isFalse(); + +- assertThat(result.getMessage()) +- .isEqualTo("[one, two]"); +- } ++ assertThat(result.getMessage()).isEqualTo("[one, two]"); ++ } + +- @Test +- void automaticallyUsesThePlatformThreadBeans() { +- final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(); +- Assertions.assertThat(healthCheck.execute().isHealthy()) +- .isTrue(); +- } ++ @Test ++ void automaticallyUsesThePlatformThreadBeans() { ++ final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(); ++ assertThat(healthCheck.execute().isHealthy()).isTrue(); ++ } + } +--- a/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java ++++ b/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java +@@ -1,6 +1,9 @@ + package io.dropwizard.metrics5.httpasyncclient; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import io.dropwizard.metrics5.MetricRegistry; ++import java.util.concurrent.TimeUnit; + import org.apache.http.config.Registry; + import org.apache.http.conn.DnsResolver; + import org.apache.http.conn.SchemePortResolver; +@@ -11,26 +14,41 @@ import org.apache.http.nio.conn.NHttpConnectionFactory; + import org.apache.http.nio.conn.SchemeIOSessionStrategy; + import org.apache.http.nio.reactor.ConnectingIOReactor; + +-import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + public class InstrumentedNClientConnManager extends PoolingNHttpClientConnectionManager { + +- public InstrumentedNClientConnManager(final ConnectingIOReactor ioreactor, final NHttpConnectionFactory connFactory, final SchemePortResolver schemePortResolver, final MetricRegistry metricRegistry, final Registry iosessionFactoryRegistry, final long timeToLive, final TimeUnit tunit, final DnsResolver dnsResolver, final String name) { +- super(ioreactor, connFactory, iosessionFactoryRegistry, schemePortResolver, dnsResolver, timeToLive, tunit); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "available-connections"), +- () -> getTotalStats().getAvailable()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "leased-connections"), +- () -> getTotalStats().getLeased()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "max-connections"), +- () -> getTotalStats().getMax()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "pending-connections"), +- () -> getTotalStats().getPending()); +- } +- ++ public InstrumentedNClientConnManager( ++ final ConnectingIOReactor ioreactor, ++ final NHttpConnectionFactory connFactory, ++ final SchemePortResolver schemePortResolver, ++ final MetricRegistry metricRegistry, ++ final Registry iosessionFactoryRegistry, ++ final long timeToLive, ++ final TimeUnit tunit, ++ final DnsResolver dnsResolver, ++ final String name) { ++ super( ++ ioreactor, ++ connFactory, ++ iosessionFactoryRegistry, ++ schemePortResolver, ++ dnsResolver, ++ timeToLive, ++ tunit); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(NHttpClientConnectionManager.class, name, "available-connections"), ++ () -> getTotalStats().getAvailable()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(NHttpClientConnectionManager.class, name, "leased-connections"), ++ () -> getTotalStats().getLeased()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(NHttpClientConnectionManager.class, name, "max-connections"), ++ () -> getTotalStats().getMax()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(NHttpClientConnectionManager.class, name, "pending-connections"), ++ () -> getTotalStats().getPending()); ++ } + } +--- a/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNHttpClientBuilder.java ++++ b/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNHttpClientBuilder.java +@@ -1,10 +1,14 @@ + package io.dropwizard.metrics5.httpasyncclient; + ++import static java.util.Objects.requireNonNull; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies; + import io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategy; ++import java.io.IOException; ++import java.util.concurrent.Future; + import org.apache.http.HttpException; + import org.apache.http.HttpRequest; + import org.apache.http.concurrent.FutureCallback; +@@ -14,107 +18,109 @@ import org.apache.http.nio.protocol.HttpAsyncRequestProducer; + import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; + import org.apache.http.protocol.HttpContext; + +-import java.io.IOException; +-import java.util.concurrent.Future; +- +-import static java.util.Objects.requireNonNull; +- + public class InstrumentedNHttpClientBuilder extends HttpAsyncClientBuilder { +- private final MetricRegistry metricRegistry; +- private final String name; +- private final HttpClientMetricNameStrategy metricNameStrategy; +- +- public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy, String name) { +- super(); +- this.metricRegistry = metricRegistry; +- this.metricNameStrategy = metricNameStrategy; +- this.name = name; +- } +- +- public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry) { +- this(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY, null); +- } +- +- public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { +- this(metricRegistry, metricNameStrategy, null); +- } +- +- public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry, String name) { +- this(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY, name); ++ private final MetricRegistry metricRegistry; ++ private final String name; ++ private final HttpClientMetricNameStrategy metricNameStrategy; ++ ++ public InstrumentedNHttpClientBuilder( ++ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy, String name) { ++ super(); ++ this.metricRegistry = metricRegistry; ++ this.metricNameStrategy = metricNameStrategy; ++ this.name = name; ++ } ++ ++ public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry) { ++ this(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY, null); ++ } ++ ++ public InstrumentedNHttpClientBuilder( ++ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { ++ this(metricRegistry, metricNameStrategy, null); ++ } ++ ++ public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry, String name) { ++ this(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY, name); ++ } ++ ++ private Timer timer(HttpRequest request) { ++ MetricName nameFor = metricNameStrategy.getNameFor(name, request); ++ return metricRegistry.timer(nameFor); ++ } ++ ++ @Override ++ public CloseableHttpAsyncClient build() { ++ final CloseableHttpAsyncClient ac = super.build(); ++ return new CloseableHttpAsyncClient() { ++ ++ @Override ++ public boolean isRunning() { ++ return ac.isRunning(); ++ } ++ ++ @Override ++ public void start() { ++ ac.start(); ++ } ++ ++ @Override ++ public Future execute( ++ HttpAsyncRequestProducer requestProducer, ++ HttpAsyncResponseConsumer responseConsumer, ++ HttpContext context, ++ FutureCallback callback) { ++ final Timer.Context timerContext; ++ try { ++ timerContext = timer(requestProducer.generateRequest()).time(); ++ } catch (IOException | HttpException ex) { ++ throw new RuntimeException(ex); ++ } ++ return ac.execute( ++ requestProducer, ++ responseConsumer, ++ context, ++ new TimingFutureCallback<>(callback, timerContext)); ++ } ++ ++ @Override ++ public void close() throws IOException { ++ ac.close(); ++ } ++ }; ++ } ++ ++ private static class TimingFutureCallback implements FutureCallback { ++ private final FutureCallback callback; ++ private final Timer.Context timerContext; ++ ++ private TimingFutureCallback(FutureCallback callback, Timer.Context timerContext) { ++ this.callback = callback; ++ this.timerContext = requireNonNull(timerContext, "timerContext"); + } + +- private Timer timer(HttpRequest request) { +- MetricName nameFor = metricNameStrategy.getNameFor(name, request); +- return metricRegistry.timer(nameFor); ++ @Override ++ public void completed(T result) { ++ timerContext.stop(); ++ if (callback != null) { ++ callback.completed(result); ++ } + } + + @Override +- public CloseableHttpAsyncClient build() { +- final CloseableHttpAsyncClient ac = super.build(); +- return new CloseableHttpAsyncClient() { +- +- @Override +- public boolean isRunning() { +- return ac.isRunning(); +- } +- +- @Override +- public void start() { +- ac.start(); +- } +- +- @Override +- public Future execute(HttpAsyncRequestProducer requestProducer, HttpAsyncResponseConsumer responseConsumer, HttpContext context, FutureCallback callback) { +- final Timer.Context timerContext; +- try { +- timerContext = timer(requestProducer.generateRequest()).time(); +- } catch (IOException | HttpException ex) { +- throw new RuntimeException(ex); +- } +- return ac.execute(requestProducer, responseConsumer, context, +- new TimingFutureCallback<>(callback, timerContext)); +- } +- +- @Override +- public void close() throws IOException { +- ac.close(); +- } +- }; ++ public void failed(Exception ex) { ++ timerContext.stop(); ++ if (callback != null) { ++ callback.failed(ex); ++ } + } + +- private static class TimingFutureCallback implements FutureCallback { +- private final FutureCallback callback; +- private final Timer.Context timerContext; +- +- private TimingFutureCallback(FutureCallback callback, +- Timer.Context timerContext) { +- this.callback = callback; +- this.timerContext = requireNonNull(timerContext, "timerContext"); +- } +- +- @Override +- public void completed(T result) { +- timerContext.stop(); +- if (callback != null) { +- callback.completed(result); +- } +- } +- +- @Override +- public void failed(Exception ex) { +- timerContext.stop(); +- if (callback != null) { +- callback.failed(ex); +- } +- } +- +- @Override +- public void cancelled() { +- timerContext.stop(); +- if (callback != null) { +- callback.cancelled(); +- } +- } ++ @Override ++ public void cancelled() { ++ timerContext.stop(); ++ if (callback != null) { ++ callback.cancelled(); ++ } + } +- ++ } + } +--- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/HttpClientTestBase.java ++++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/HttpClientTestBase.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.httpasyncclient; + ++import java.io.IOException; ++import java.net.InetSocketAddress; ++import java.net.ServerSocket; ++import java.util.concurrent.TimeUnit; + import org.apache.http.HttpHost; + import org.apache.http.impl.nio.bootstrap.HttpServer; + import org.apache.http.impl.nio.bootstrap.ServerBootstrap; +@@ -8,64 +12,59 @@ import org.apache.http.nio.reactor.ListenerEndpoint; + import org.apache.http.protocol.HttpRequestHandler; + import org.junit.jupiter.api.AfterEach; + +-import java.io.IOException; +-import java.net.InetSocketAddress; +-import java.net.ServerSocket; +-import java.util.concurrent.TimeUnit; +- + public abstract class HttpClientTestBase { + +- /** +- * {@link HttpRequestHandler} that responds with a {@code 200 OK}. +- */ +- public static final HttpRequestHandler STATUS_OK = (request, response, context) -> response.setStatusCode(200); ++ /** {@link HttpRequestHandler} that responds with a {@code 200 OK}. */ ++ public static final HttpRequestHandler STATUS_OK = ++ (request, response, context) -> response.setStatusCode(200); + +- private HttpServer server; ++ private HttpServer server; + +- /** +- * @return A free local port or {@code -1} on error. +- */ +- public static int findAvailableLocalPort() { +- try (ServerSocket socket = new ServerSocket(0)) { +- return socket.getLocalPort(); +- } catch (IOException e) { +- return -1; +- } ++ /** ++ * @return A free local port or {@code -1} on error. ++ */ ++ public static int findAvailableLocalPort() { ++ try (ServerSocket socket = new ServerSocket(0)) { ++ return socket.getLocalPort(); ++ } catch (IOException e) { ++ return -1; + } ++ } + +- /** +- * Start a local server that uses the {@code handler} to handle requests. +- *

+- * The server will be (if started) terminated in the {@link #tearDown()} {@link AfterEach} method. +- * +- * @param handler The request handler that will be used to respond to every request. +- * @return The {@link HttpHost} of the server +- * @throws IOException in case it's not possible to start the server +- * @throws InterruptedException in case the server's main thread was interrupted +- */ +- public HttpHost startServerWithGlobalRequestHandler(HttpRequestHandler handler) +- throws IOException, InterruptedException { +- // If there is an existing instance, terminate it +- tearDown(); ++ /** ++ * Start a local server that uses the {@code handler} to handle requests. ++ * ++ *

The server will be (if started) terminated in the {@link #tearDown()} {@link AfterEach} ++ * method. ++ * ++ * @param handler The request handler that will be used to respond to every request. ++ * @return The {@link HttpHost} of the server ++ * @throws IOException in case it's not possible to start the server ++ * @throws InterruptedException in case the server's main thread was interrupted ++ */ ++ public HttpHost startServerWithGlobalRequestHandler(HttpRequestHandler handler) ++ throws IOException, InterruptedException { ++ // If there is an existing instance, terminate it ++ tearDown(); + +- ServerBootstrap serverBootstrap = ServerBootstrap.bootstrap(); ++ ServerBootstrap serverBootstrap = ServerBootstrap.bootstrap(); + +- serverBootstrap.registerHandler("/*", new BasicAsyncRequestHandler(handler)); ++ serverBootstrap.registerHandler("/*", new BasicAsyncRequestHandler(handler)); + +- server = serverBootstrap.create(); +- server.start(); ++ server = serverBootstrap.create(); ++ server.start(); + +- ListenerEndpoint endpoint = server.getEndpoint(); +- endpoint.waitFor(); ++ ListenerEndpoint endpoint = server.getEndpoint(); ++ endpoint.waitFor(); + +- InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); +- return new HttpHost("localhost", address.getPort(), "http"); +- } ++ InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); ++ return new HttpHost("localhost", address.getPort(), "http"); ++ } + +- @AfterEach +- public void tearDown() { +- if (server != null) { +- server.shutdown(5, TimeUnit.SECONDS); +- } ++ @AfterEach ++ public void tearDown() { ++ if (server != null) { ++ server.shutdown(5, TimeUnit.SECONDS); + } ++ } + } +--- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java ++++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java +@@ -1,5 +1,10 @@ + package io.dropwizard.metrics5.httpasyncclient; + ++import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.ArgumentMatchers.eq; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricRegistryListener; +@@ -16,43 +21,34 @@ import org.junit.jupiter.api.extension.ExtendWith; + import org.mockito.Mock; + import org.mockito.junit.jupiter.MockitoExtension; + +-import static org.mockito.ArgumentMatchers.any; +-import static org.mockito.ArgumentMatchers.eq; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- +- + @ExtendWith(MockitoExtension.class) +-class InstrumentedHttpClientsTest extends HttpClientTestBase { +- +- private final MetricRegistry metricRegistry = new MetricRegistry(); ++final class InstrumentedHttpClientsTest extends HttpClientTestBase { + ++ private final MetricRegistry metricRegistry = new MetricRegistry(); + +- private HttpAsyncClient asyncHttpClient; +- @Mock +- private HttpClientMetricNameStrategy metricNameStrategy; +- @Mock +- private MetricRegistryListener registryListener; ++ private HttpAsyncClient asyncHttpClient; ++ @Mock private HttpClientMetricNameStrategy metricNameStrategy; ++ @Mock private MetricRegistryListener registryListener; + +- @Test +- void registersExpectedMetricsGivenNameStrategy() throws Exception { +- HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); +- final HttpGet get = new HttpGet("/q=anything"); +- final MetricName metricName = MetricName.build("some.made.up.metric.name"); ++ @Test ++ void registersExpectedMetricsGivenNameStrategy() throws Exception { ++ HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); ++ final HttpGet get = new HttpGet("/q=anything"); ++ final MetricName metricName = MetricName.build("some.made.up.metric.name"); + +- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) +- .thenReturn(metricName); ++ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); + +- asyncHttpClient.execute(host, get, null).get(); ++ asyncHttpClient.execute(host, get, null).get(); + +- verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); +- } ++ verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); ++ } + +- @BeforeEach +- void setUp() throws Exception { +- CloseableHttpAsyncClient chac = new InstrumentedNHttpClientBuilder(metricRegistry, metricNameStrategy).build(); +- chac.start(); +- asyncHttpClient = chac; +- metricRegistry.addListener(registryListener); +- } ++ @BeforeEach ++ void setUp() throws Exception { ++ CloseableHttpAsyncClient chac = ++ new InstrumentedNHttpClientBuilder(metricRegistry, metricNameStrategy).build(); ++ chac.start(); ++ asyncHttpClient = chac; ++ metricRegistry.addListener(registryListener); ++ } + } +--- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java ++++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java +@@ -1,8 +1,19 @@ + package io.dropwizard.metrics5.httpasyncclient; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; ++import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.never; ++import static org.mockito.Mockito.timeout; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; ++import java.util.concurrent.Future; ++import java.util.concurrent.TimeUnit; + import org.apache.http.HttpHost; + import org.apache.http.HttpResponse; + import org.apache.http.client.methods.HttpGet; +@@ -16,119 +27,105 @@ import org.junit.jupiter.api.extension.ExtendWith; + import org.mockito.Mock; + import org.mockito.junit.jupiter.MockitoExtension; + +-import java.util.concurrent.Future; +-import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; +-import static org.mockito.ArgumentMatchers.any; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.timeout; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- + @ExtendWith(MockitoExtension.class) + @Disabled("The tests are flaky") +-class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { ++final class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + +- private HttpAsyncClient asyncHttpClient; ++ private HttpAsyncClient asyncHttpClient; + +- @Mock +- private Timer.Context context; ++ @Mock private Timer.Context context; + +- @Mock +- private MetricRegistry metricRegistry; ++ @Mock private MetricRegistry metricRegistry; + ++ @BeforeEach ++ void setUp() throws Exception { ++ CloseableHttpAsyncClient chac = ++ new InstrumentedNHttpClientBuilder( ++ metricRegistry, (name, request) -> MetricName.build("test")) ++ .build(); ++ chac.start(); ++ asyncHttpClient = chac; + +- @BeforeEach +- void setUp() throws Exception { +- CloseableHttpAsyncClient chac = new InstrumentedNHttpClientBuilder(metricRegistry, +- (name, request) -> MetricName.build("test")).build(); +- chac.start(); +- asyncHttpClient = chac; ++ Timer timer = mock(); ++ when(timer.time()).thenReturn(context); ++ when(metricRegistry.timer(MetricName.build("test"))).thenReturn(timer); ++ } + +- Timer timer = mock(Timer.class); +- when(timer.time()).thenReturn(context); +- when(metricRegistry.timer(MetricName.build("test"))).thenReturn(timer); +- } ++ @Test ++ void timerIsStoppedCorrectly() throws Exception { ++ HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); ++ HttpGet get = new HttpGet("/?q=anything"); + +- @Test +- void timerIsStoppedCorrectly() throws Exception { +- HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); +- HttpGet get = new HttpGet("/?q=anything"); ++ // Timer hasn't been stopped prior to executing the request ++ verify(context, never()).stop(); + +- // Timer hasn't been stopped prior to executing the request +- verify(context, never()).stop(); ++ Future responseFuture = asyncHttpClient.execute(host, get, null); + +- Future responseFuture = asyncHttpClient.execute(host, get, null); ++ // Timer should still be running ++ verify(context, never()).stop(); + +- // Timer should still be running +- verify(context, never()).stop(); ++ responseFuture.get(20, TimeUnit.SECONDS); + +- responseFuture.get(20, TimeUnit.SECONDS); ++ // After the computation is complete timer must be stopped ++ // Materialzing the future and calling the future callback is not an atomic operation so ++ // we need to wait for callback to succeed ++ verify(context, timeout(200).times(1)).stop(); ++ } + +- // After the computation is complete timer must be stopped +- // Materialzing the future and calling the future callback is not an atomic operation so +- // we need to wait for callback to succeed +- verify(context, timeout(200).times(1)).stop(); +- } ++ @SuppressWarnings("unchecked") ++ @Test ++ void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { ++ HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); ++ HttpGet get = new HttpGet("/?q=something"); + +- @Test +- @SuppressWarnings("unchecked") +- void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { +- HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); +- HttpGet get = new HttpGet("/?q=something"); ++ FutureCallback futureCallback = mock(); + +- FutureCallback futureCallback = mock(FutureCallback.class); ++ // Timer hasn't been stopped prior to executing the request ++ verify(context, never()).stop(); + +- // Timer hasn't been stopped prior to executing the request +- verify(context, never()).stop(); ++ Future responseFuture = asyncHttpClient.execute(host, get, futureCallback); + +- Future responseFuture = asyncHttpClient.execute(host, get, futureCallback); ++ // Timer should still be running ++ verify(context, never()).stop(); + +- // Timer should still be running +- verify(context, never()).stop(); ++ responseFuture.get(20, TimeUnit.SECONDS); + +- responseFuture.get(20, TimeUnit.SECONDS); ++ // Callback must have been called ++ assertThat(responseFuture.isDone()).isTrue(); ++ // After the computation is complete timer must be stopped ++ // Materialzing the future and calling the future callback is not an atomic operation so ++ // we need to wait for callback to succeed ++ verify(futureCallback, timeout(200).times(1)).completed(any(HttpResponse.class)); ++ verify(context, timeout(200).times(1)).stop(); ++ } + +- // Callback must have been called +- assertThat(responseFuture.isDone()).isTrue(); +- // After the computation is complete timer must be stopped +- // Materialzing the future and calling the future callback is not an atomic operation so +- // we need to wait for callback to succeed +- verify(futureCallback, timeout(200).times(1)).completed(any(HttpResponse.class)); +- verify(context, timeout(200).times(1)).stop(); +- } ++ @SuppressWarnings("unchecked") ++ @Test ++ void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { ++ // There should be nothing listening on this port ++ HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); ++ HttpGet get = new HttpGet("/?q=something"); + +- @Test +- @SuppressWarnings("unchecked") +- void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { +- // There should be nothing listening on this port +- HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); +- HttpGet get = new HttpGet("/?q=something"); +- +- FutureCallback futureCallback = mock(FutureCallback.class); +- +- // Timer hasn't been stopped prior to executing the request +- verify(context, never()).stop(); +- +- Future responseFuture = asyncHttpClient.execute(host, get, futureCallback); +- +- // Timer should still be running +- verify(context, never()).stop(); +- +- try { +- responseFuture.get(20, TimeUnit.SECONDS); +- fail("This should fail as the client should not be able to connect"); +- } catch (Exception e) { +- // Ignore +- } +- // After the computation is complete timer must be stopped +- // Materialzing the future and calling the future callback is not an atomic operation so +- // we need to wait for callback to succeed +- verify(futureCallback, timeout(200).times(1)).failed(any(Exception.class)); +- verify(context, timeout(200).times(1)).stop(); +- } ++ FutureCallback futureCallback = mock(); ++ ++ // Timer hasn't been stopped prior to executing the request ++ verify(context, never()).stop(); + ++ Future responseFuture = asyncHttpClient.execute(host, get, futureCallback); ++ ++ // Timer should still be running ++ verify(context, never()).stop(); ++ ++ try { ++ responseFuture.get(20, TimeUnit.SECONDS); ++ fail("This should fail as the client should not be able to connect"); ++ } catch (Exception e) { ++ // Ignore ++ } ++ // After the computation is complete timer must be stopped ++ // Materialzing the future and calling the future callback is not an atomic operation so ++ // we need to wait for callback to succeed ++ verify(futureCallback, timeout(200).times(1)).failed(any(Exception.class)); ++ verify(context, timeout(200).times(1)).stop(); ++ } + } +--- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategies.java ++++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategies.java +@@ -1,61 +1,54 @@ + package io.dropwizard.metrics5.httpclient; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ ++import java.net.URI; ++import java.net.URISyntaxException; + import org.apache.http.HttpRequest; + import org.apache.http.client.HttpClient; + import org.apache.http.client.methods.HttpRequestWrapper; + import org.apache.http.client.methods.HttpUriRequest; + import org.apache.http.client.utils.URIBuilder; + +-import java.net.URI; +-import java.net.URISyntaxException; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + public class HttpClientMetricNameStrategies { + +- public static final HttpClientMetricNameStrategy METHOD_ONLY = +- (name, request) -> name(HttpClient.class, +- name, +- methodNameString(request)); +- +- public static final HttpClientMetricNameStrategy HOST_AND_METHOD = +- (name, request) -> name(HttpClient.class, +- name, +- requestURI(request).getHost(), +- methodNameString(request)); +- +- public static final HttpClientMetricNameStrategy PATH_AND_METHOD = +- (name, request) -> { +- final URIBuilder url = new URIBuilder(requestURI(request)); +- return name(HttpClient.class, +- name, +- url.getPath(), +- methodNameString(request)); +- }; +- +- public static final HttpClientMetricNameStrategy QUERYLESS_URL_AND_METHOD = +- (name, request) -> { +- try { +- final URIBuilder url = new URIBuilder(requestURI(request)); +- return name(HttpClient.class, +- name, +- url.removeQuery().build().toString(), +- methodNameString(request)); +- } catch (URISyntaxException e) { +- throw new IllegalArgumentException(e); +- } +- }; +- +- private static String methodNameString(HttpRequest request) { +- return request.getRequestLine().getMethod().toLowerCase() + "-requests"; +- } +- +- private static URI requestURI(HttpRequest request) { +- if (request instanceof HttpRequestWrapper) +- return requestURI(((HttpRequestWrapper) request).getOriginal()); +- +- return (request instanceof HttpUriRequest) ? +- ((HttpUriRequest) request).getURI() : +- URI.create(request.getRequestLine().getUri()); +- } ++ public static final HttpClientMetricNameStrategy METHOD_ONLY = ++ (name, request) -> name(HttpClient.class, name, methodNameString(request)); ++ ++ public static final HttpClientMetricNameStrategy HOST_AND_METHOD = ++ (name, request) -> ++ name(HttpClient.class, name, requestURI(request).getHost(), methodNameString(request)); ++ ++ public static final HttpClientMetricNameStrategy PATH_AND_METHOD = ++ (name, request) -> { ++ final URIBuilder url = new URIBuilder(requestURI(request)); ++ return name(HttpClient.class, name, url.getPath(), methodNameString(request)); ++ }; ++ ++ public static final HttpClientMetricNameStrategy QUERYLESS_URL_AND_METHOD = ++ (name, request) -> { ++ try { ++ final URIBuilder url = new URIBuilder(requestURI(request)); ++ return name( ++ HttpClient.class, ++ name, ++ url.removeQuery().build().toString(), ++ methodNameString(request)); ++ } catch (URISyntaxException e) { ++ throw new IllegalArgumentException(e); ++ } ++ }; ++ ++ private static String methodNameString(HttpRequest request) { ++ return request.getRequestLine().getMethod().toLowerCase() + "-requests"; ++ } ++ ++ private static URI requestURI(HttpRequest request) { ++ if (request instanceof HttpRequestWrapper) ++ return requestURI(((HttpRequestWrapper) request).getOriginal()); ++ ++ return (request instanceof HttpUriRequest) ++ ? ((HttpUriRequest) request).getURI() ++ : URI.create(request.getRequestLine().getUri()); ++ } + } +--- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategy.java ++++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategy.java +@@ -8,11 +8,9 @@ import org.apache.http.client.HttpClient; + @FunctionalInterface + public interface HttpClientMetricNameStrategy { + +- MetricName getNameFor(String name, HttpRequest request); ++ MetricName getNameFor(String name, HttpRequest request); + +- default MetricName getNameFor(String name, Exception exception) { +- return MetricRegistry.name(HttpClient.class, +- name, +- exception.getClass().getSimpleName()); +- } ++ default MetricName getNameFor(String name, Exception exception) { ++ return MetricRegistry.name(HttpClient.class, name, exception.getClass().getSimpleName()); ++ } + } +--- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java ++++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java +@@ -1,6 +1,9 @@ + package io.dropwizard.metrics5.httpclient; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import io.dropwizard.metrics5.MetricRegistry; ++import java.util.concurrent.TimeUnit; + import org.apache.http.config.Registry; + import org.apache.http.config.RegistryBuilder; + import org.apache.http.conn.DnsResolver; +@@ -17,184 +20,198 @@ import org.apache.http.impl.conn.DefaultHttpClientConnectionOperator; + import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; + import org.apache.http.impl.conn.SystemDefaultDnsResolver; + +-import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +- +-/** +- * A {@link HttpClientConnectionManager} which monitors the number of open connections. +- */ ++/** A {@link HttpClientConnectionManager} which monitors the number of open connections. */ + public class InstrumentedHttpClientConnectionManager extends PoolingHttpClientConnectionManager { + +- +- protected static Registry getDefaultRegistry() { +- return RegistryBuilder.create() +- .register("http", PlainConnectionSocketFactory.getSocketFactory()) +- .register("https", SSLConnectionSocketFactory.getSocketFactory()) +- .build(); ++ protected static Registry getDefaultRegistry() { ++ return RegistryBuilder.create() ++ .register("http", PlainConnectionSocketFactory.getSocketFactory()) ++ .register("https", SSLConnectionSocketFactory.getSocketFactory()) ++ .build(); ++ } ++ ++ private final MetricRegistry metricsRegistry; ++ private final String name; ++ ++ /** ++ * @deprecated Use {@link #builder(MetricRegistry)} instead. ++ */ ++ @Deprecated ++ public InstrumentedHttpClientConnectionManager(MetricRegistry metricRegistry) { ++ this(metricRegistry, getDefaultRegistry()); ++ } ++ ++ /** ++ * @deprecated Use {@link #builder(MetricRegistry)} instead. ++ */ ++ @Deprecated ++ public InstrumentedHttpClientConnectionManager( ++ MetricRegistry metricsRegistry, Registry socketFactoryRegistry) { ++ this(metricsRegistry, socketFactoryRegistry, -1, TimeUnit.MILLISECONDS); ++ } ++ ++ /** ++ * @deprecated Use {@link #builder(MetricRegistry)} instead. ++ */ ++ @Deprecated ++ public InstrumentedHttpClientConnectionManager( ++ MetricRegistry metricsRegistry, ++ Registry socketFactoryRegistry, ++ long connTTL, ++ TimeUnit connTTLTimeUnit) { ++ this( ++ metricsRegistry, ++ socketFactoryRegistry, ++ null, ++ null, ++ SystemDefaultDnsResolver.INSTANCE, ++ connTTL, ++ connTTLTimeUnit, ++ null); ++ } ++ ++ /** ++ * @deprecated Use {@link #builder(MetricRegistry)} instead. ++ */ ++ @Deprecated ++ public InstrumentedHttpClientConnectionManager( ++ MetricRegistry metricsRegistry, ++ Registry socketFactoryRegistry, ++ HttpConnectionFactory connFactory, ++ SchemePortResolver schemePortResolver, ++ DnsResolver dnsResolver, ++ long connTTL, ++ TimeUnit connTTLTimeUnit, ++ String name) { ++ this( ++ metricsRegistry, ++ new DefaultHttpClientConnectionOperator( ++ socketFactoryRegistry, schemePortResolver, dnsResolver), ++ connFactory, ++ connTTL, ++ connTTLTimeUnit, ++ name); ++ } ++ ++ /** ++ * @deprecated Use {@link #builder(MetricRegistry)} instead. ++ */ ++ @Deprecated ++ public InstrumentedHttpClientConnectionManager( ++ MetricRegistry metricsRegistry, ++ HttpClientConnectionOperator httpClientConnectionOperator, ++ HttpConnectionFactory connFactory, ++ long connTTL, ++ TimeUnit connTTLTimeUnit, ++ String name) { ++ super(httpClientConnectionOperator, connFactory, connTTL, connTTLTimeUnit); ++ this.metricsRegistry = metricsRegistry; ++ this.name = name; ++ ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricsRegistry.registerGauge( ++ name(HttpClientConnectionManager.class, name, "available-connections"), ++ () -> getTotalStats().getAvailable()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricsRegistry.registerGauge( ++ name(HttpClientConnectionManager.class, name, "leased-connections"), ++ () -> getTotalStats().getLeased()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricsRegistry.registerGauge( ++ name(HttpClientConnectionManager.class, name, "max-connections"), ++ () -> getTotalStats().getMax()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricsRegistry.registerGauge( ++ name(HttpClientConnectionManager.class, name, "pending-connections"), ++ () -> getTotalStats().getPending()); ++ } ++ ++ @Override ++ public void shutdown() { ++ super.shutdown(); ++ metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "available-connections")); ++ metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "leased-connections")); ++ metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "max-connections")); ++ metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "pending-connections")); ++ } ++ ++ public static Builder builder(MetricRegistry metricsRegistry) { ++ return new Builder().metricsRegistry(metricsRegistry); ++ } ++ ++ public static class Builder { ++ private MetricRegistry metricsRegistry; ++ private HttpClientConnectionOperator httpClientConnectionOperator; ++ private Registry socketFactoryRegistry = getDefaultRegistry(); ++ private HttpConnectionFactory connFactory; ++ private SchemePortResolver schemePortResolver; ++ private DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE; ++ private long connTTL = -1; ++ private TimeUnit connTTLTimeUnit = TimeUnit.MILLISECONDS; ++ private String name; ++ ++ Builder() {} ++ ++ public Builder metricsRegistry(MetricRegistry metricsRegistry) { ++ this.metricsRegistry = metricsRegistry; ++ return this; + } + +- private final MetricRegistry metricsRegistry; +- private final String name; +- +- /** +- * @deprecated Use {@link #builder(MetricRegistry)} instead. +- */ +- @Deprecated +- public InstrumentedHttpClientConnectionManager(MetricRegistry metricRegistry) { +- this(metricRegistry, getDefaultRegistry()); ++ public Builder socketFactoryRegistry(Registry socketFactoryRegistry) { ++ this.socketFactoryRegistry = socketFactoryRegistry; ++ return this; + } + +- /** +- * @deprecated Use {@link #builder(MetricRegistry)} instead. +- */ +- @Deprecated +- public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, +- Registry socketFactoryRegistry) { +- this(metricsRegistry, socketFactoryRegistry, -1, TimeUnit.MILLISECONDS); ++ public Builder connFactory( ++ HttpConnectionFactory connFactory) { ++ this.connFactory = connFactory; ++ return this; + } + +- +- /** +- * @deprecated Use {@link #builder(MetricRegistry)} instead. +- */ +- @Deprecated +- public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, +- Registry socketFactoryRegistry, +- long connTTL, +- TimeUnit connTTLTimeUnit) { +- this(metricsRegistry, socketFactoryRegistry, null, null, SystemDefaultDnsResolver.INSTANCE, connTTL, connTTLTimeUnit, null); ++ public Builder schemePortResolver(SchemePortResolver schemePortResolver) { ++ this.schemePortResolver = schemePortResolver; ++ return this; + } + +- +- /** +- * @deprecated Use {@link #builder(MetricRegistry)} instead. +- */ +- @Deprecated +- public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, +- Registry socketFactoryRegistry, +- HttpConnectionFactory +- connFactory, +- SchemePortResolver schemePortResolver, +- DnsResolver dnsResolver, +- long connTTL, +- TimeUnit connTTLTimeUnit, +- String name) { +- this(metricsRegistry, +- new DefaultHttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver), +- connFactory, +- connTTL, +- connTTLTimeUnit, +- name); ++ public Builder dnsResolver(DnsResolver dnsResolver) { ++ this.dnsResolver = dnsResolver; ++ return this; + } + +- /** +- * @deprecated Use {@link #builder(MetricRegistry)} instead. +- */ +- @Deprecated +- public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, +- HttpClientConnectionOperator httpClientConnectionOperator, +- HttpConnectionFactory +- connFactory, +- long connTTL, +- TimeUnit connTTLTimeUnit, +- String name) { +- super(httpClientConnectionOperator, connFactory, connTTL, connTTLTimeUnit); +- this.metricsRegistry = metricsRegistry; +- this.name = name; +- +- // this acquires a lock on the connection pool; remove if contention sucks +- metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "available-connections"), +- () -> getTotalStats().getAvailable()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "leased-connections"), +- () -> getTotalStats().getLeased()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "max-connections"), +- () -> getTotalStats().getMax()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "pending-connections"), +- () -> getTotalStats().getPending()); ++ public Builder connTTL(long connTTL) { ++ this.connTTL = connTTL; ++ return this; + } + +- @Override +- public void shutdown() { +- super.shutdown(); +- metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "available-connections")); +- metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "leased-connections")); +- metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "max-connections")); +- metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "pending-connections")); ++ public Builder connTTLTimeUnit(TimeUnit connTTLTimeUnit) { ++ this.connTTLTimeUnit = connTTLTimeUnit; ++ return this; + } + +- public static Builder builder(MetricRegistry metricsRegistry) { +- return new Builder().metricsRegistry(metricsRegistry); ++ public Builder httpClientConnectionOperator( ++ HttpClientConnectionOperator httpClientConnectionOperator) { ++ this.httpClientConnectionOperator = httpClientConnectionOperator; ++ return this; + } + +- public static class Builder { +- private MetricRegistry metricsRegistry; +- private HttpClientConnectionOperator httpClientConnectionOperator; +- private Registry socketFactoryRegistry = getDefaultRegistry(); +- private HttpConnectionFactory connFactory; +- private SchemePortResolver schemePortResolver; +- private DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE; +- private long connTTL = -1; +- private TimeUnit connTTLTimeUnit = TimeUnit.MILLISECONDS; +- private String name; +- +- Builder() { +- } +- +- public Builder metricsRegistry(MetricRegistry metricsRegistry) { +- this.metricsRegistry = metricsRegistry; +- return this; +- } +- +- public Builder socketFactoryRegistry(Registry socketFactoryRegistry) { +- this.socketFactoryRegistry = socketFactoryRegistry; +- return this; +- } +- +- public Builder connFactory(HttpConnectionFactory connFactory) { +- this.connFactory = connFactory; +- return this; +- } +- +- public Builder schemePortResolver(SchemePortResolver schemePortResolver) { +- this.schemePortResolver = schemePortResolver; +- return this; +- } +- +- public Builder dnsResolver(DnsResolver dnsResolver) { +- this.dnsResolver = dnsResolver; +- return this; +- } +- +- public Builder connTTL(long connTTL) { +- this.connTTL = connTTL; +- return this; +- } +- +- public Builder connTTLTimeUnit(TimeUnit connTTLTimeUnit) { +- this.connTTLTimeUnit = connTTLTimeUnit; +- return this; +- } +- +- public Builder httpClientConnectionOperator(HttpClientConnectionOperator httpClientConnectionOperator) { +- this.httpClientConnectionOperator = httpClientConnectionOperator; +- return this; +- } +- +- public Builder name(final String name) { +- this.name = name; +- return this; +- } +- +- public InstrumentedHttpClientConnectionManager build() { +- if (httpClientConnectionOperator == null) { +- httpClientConnectionOperator = new DefaultHttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver); +- } +- return new InstrumentedHttpClientConnectionManager(metricsRegistry, httpClientConnectionOperator, connFactory, connTTL, connTTLTimeUnit, name); +- } ++ public Builder name(final String name) { ++ this.name = name; ++ return this; + } + ++ public InstrumentedHttpClientConnectionManager build() { ++ if (httpClientConnectionOperator == null) { ++ httpClientConnectionOperator = ++ new DefaultHttpClientConnectionOperator( ++ socketFactoryRegistry, schemePortResolver, dnsResolver); ++ } ++ return new InstrumentedHttpClientConnectionManager( ++ metricsRegistry, ++ httpClientConnectionOperator, ++ connFactory, ++ connTTL, ++ connTTLTimeUnit, ++ name); ++ } ++ } + } +--- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClients.java ++++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClients.java +@@ -5,28 +5,28 @@ import org.apache.http.impl.client.CloseableHttpClient; + import org.apache.http.impl.client.HttpClientBuilder; + + public class InstrumentedHttpClients { +- private InstrumentedHttpClients() { +- super(); +- } ++ private InstrumentedHttpClients() { ++ super(); ++ } + +- public static CloseableHttpClient createDefault(MetricRegistry metricRegistry) { +- return createDefault(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY); +- } ++ public static CloseableHttpClient createDefault(MetricRegistry metricRegistry) { ++ return createDefault(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY); ++ } + +- public static CloseableHttpClient createDefault(MetricRegistry metricRegistry, +- HttpClientMetricNameStrategy metricNameStrategy) { +- return custom(metricRegistry, metricNameStrategy).build(); +- } ++ public static CloseableHttpClient createDefault( ++ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { ++ return custom(metricRegistry, metricNameStrategy).build(); ++ } + +- public static HttpClientBuilder custom(MetricRegistry metricRegistry) { +- return custom(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY); +- } +- +- public static HttpClientBuilder custom(MetricRegistry metricRegistry, +- HttpClientMetricNameStrategy metricNameStrategy) { +- return HttpClientBuilder.create() +- .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy)) +- .setConnectionManager(InstrumentedHttpClientConnectionManager.builder(metricRegistry).build()); +- } ++ public static HttpClientBuilder custom(MetricRegistry metricRegistry) { ++ return custom(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY); ++ } + ++ public static HttpClientBuilder custom( ++ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { ++ return HttpClientBuilder.create() ++ .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy)) ++ .setConnectionManager( ++ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build()); ++ } + } +--- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpRequestExecutor.java ++++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpRequestExecutor.java +@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.httpclient; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; ++import java.io.IOException; + import org.apache.http.HttpClientConnection; + import org.apache.http.HttpException; + import org.apache.http.HttpRequest; +@@ -10,52 +11,51 @@ import org.apache.http.HttpResponse; + import org.apache.http.protocol.HttpContext; + import org.apache.http.protocol.HttpRequestExecutor; + +-import java.io.IOException; +- + public class InstrumentedHttpRequestExecutor extends HttpRequestExecutor { +- private final MetricRegistry registry; +- private final HttpClientMetricNameStrategy metricNameStrategy; +- private final String name; +- +- public InstrumentedHttpRequestExecutor(MetricRegistry registry, +- HttpClientMetricNameStrategy metricNameStrategy) { +- this(registry, metricNameStrategy, null); +- } +- +- public InstrumentedHttpRequestExecutor(MetricRegistry registry, +- HttpClientMetricNameStrategy metricNameStrategy, +- String name) { +- this(registry, metricNameStrategy, name, HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE); ++ private final MetricRegistry registry; ++ private final HttpClientMetricNameStrategy metricNameStrategy; ++ private final String name; ++ ++ public InstrumentedHttpRequestExecutor( ++ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy) { ++ this(registry, metricNameStrategy, null); ++ } ++ ++ public InstrumentedHttpRequestExecutor( ++ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy, String name) { ++ this(registry, metricNameStrategy, name, HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE); ++ } ++ ++ public InstrumentedHttpRequestExecutor( ++ MetricRegistry registry, ++ HttpClientMetricNameStrategy metricNameStrategy, ++ String name, ++ int waitForContinue) { ++ super(waitForContinue); ++ this.registry = registry; ++ this.name = name; ++ this.metricNameStrategy = metricNameStrategy; ++ } ++ ++ @Override ++ public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context) ++ throws HttpException, IOException { ++ final Timer.Context timerContext = timer(request).time(); ++ try { ++ return super.execute(request, conn, context); ++ } catch (HttpException | IOException e) { ++ meter(e).mark(); ++ throw e; ++ } finally { ++ timerContext.stop(); + } ++ } + +- public InstrumentedHttpRequestExecutor(MetricRegistry registry, +- HttpClientMetricNameStrategy metricNameStrategy, +- String name, +- int waitForContinue) { +- super(waitForContinue); +- this.registry = registry; +- this.name = name; +- this.metricNameStrategy = metricNameStrategy; +- } +- +- @Override +- public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context) throws HttpException, IOException { +- final Timer.Context timerContext = timer(request).time(); +- try { +- return super.execute(request, conn, context); +- } catch (HttpException | IOException e) { +- meter(e).mark(); +- throw e; +- } finally { +- timerContext.stop(); +- } +- } ++ private Timer timer(HttpRequest request) { ++ return registry.timer(metricNameStrategy.getNameFor(name, request)); ++ } + +- private Timer timer(HttpRequest request) { +- return registry.timer(metricNameStrategy.getNameFor(name, request)); +- } +- +- private Meter meter(Exception e) { +- return registry.meter(metricNameStrategy.getNameFor(name, e)); +- } ++ private Meter meter(Exception e) { ++ return registry.meter(metricNameStrategy.getNameFor(name, e)); ++ } + } +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java +@@ -1,6 +1,14 @@ + package io.dropwizard.metrics5.httpclient; + ++import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.HOST_AND_METHOD; ++import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.METHOD_ONLY; ++import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.PATH_AND_METHOD; ++import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricName; ++import java.net.URI; ++import java.net.URISyntaxException; + import org.apache.http.HttpRequest; + import org.apache.http.client.methods.HttpGet; + import org.apache.http.client.methods.HttpPost; +@@ -9,103 +17,113 @@ import org.apache.http.client.methods.HttpRequestWrapper; + import org.apache.http.client.utils.URIUtils; + import org.junit.jupiter.api.Test; + +-import java.net.URI; +-import java.net.URISyntaxException; +- +-import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.HOST_AND_METHOD; +-import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.METHOD_ONLY; +-import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.PATH_AND_METHOD; +-import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; +-import static org.assertj.core.api.Assertions.assertThat; +- +-class HttpClientMetricNameStrategiesTest { +- +- @Test +- void methodOnlyWithName() { +- assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever"))) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.get-requests")); +- } +- +- @Test +- void methodOnlyWithoutName() { +- assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever"))) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.get-requests")); +- } +- +- @Test +- void hostAndMethodWithName() { +- assertThat(HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever"))) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.my.host.com.post-requests")); +- } +- +- @Test +- void hostAndMethodWithoutName() { +- assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever"))) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.my.host.com.post-requests")); +- } +- +- @Test +- void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { +- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); +- +- assertThat(HOST_AND_METHOD.getNameFor("some-service", request)) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.my.host.com.post-requests")); +- } +- +- @Test +- void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { +- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); +- +- assertThat(HOST_AND_METHOD.getNameFor(null, request)) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.my.host.com.post-requests")); +- } +- +- @Test +- void pathAndMethodWithName() { +- assertThat(PATH_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever/happens"))) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests")); +- } +- +- @Test +- void pathAndMethodWithoutName() { +- assertThat(PATH_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever/happens"))) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests")); +- } +- +- @Test +- void pathAndMethodWithNameInWrappedRequest() throws URISyntaxException { +- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); +- assertThat(PATH_AND_METHOD.getNameFor("some-service", request)) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests")); +- } +- +- @Test +- void pathAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { +- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); +- assertThat(PATH_AND_METHOD.getNameFor(null, request)) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests")); +- } +- +- @Test +- void querylessUrlAndMethodWithName() { +- assertThat(QUERYLESS_URL_AND_METHOD.getNameFor( +- "some-service", +- new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this"))) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); +- } +- +- @Test +- void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { +- HttpRequest request = rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); +- assertThat(QUERYLESS_URL_AND_METHOD.getNameFor("some-service", request)) +- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); +- } +- +- private static HttpRequest rewriteRequestURI(HttpRequest request) throws URISyntaxException { +- HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request); +- URI uri = URIUtils.rewriteURI(wrapper.getURI(), null, true); +- wrapper.setURI(uri); +- +- return wrapper; +- } ++final class HttpClientMetricNameStrategiesTest { ++ ++ @Test ++ void methodOnlyWithName() { ++ assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever"))) ++ .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.get-requests")); ++ } ++ ++ @Test ++ void methodOnlyWithoutName() { ++ assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever"))) ++ .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.get-requests")); ++ } ++ ++ @Test ++ void hostAndMethodWithName() { ++ assertThat( ++ HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever"))) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.http.client.HttpClient.some-service.my.host.com.post-requests")); ++ } ++ ++ @Test ++ void hostAndMethodWithoutName() { ++ assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever"))) ++ .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.my.host.com.post-requests")); ++ } ++ ++ @Test ++ void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { ++ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); ++ ++ assertThat(HOST_AND_METHOD.getNameFor("some-service", request)) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.http.client.HttpClient.some-service.my.host.com.post-requests")); ++ } ++ ++ @Test ++ void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { ++ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); ++ ++ assertThat(HOST_AND_METHOD.getNameFor(null, request)) ++ .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.my.host.com.post-requests")); ++ } ++ ++ @Test ++ void pathAndMethodWithName() { ++ assertThat( ++ PATH_AND_METHOD.getNameFor( ++ "some-service", new HttpPost("http://my.host.com/whatever/happens"))) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests")); ++ } ++ ++ @Test ++ void pathAndMethodWithoutName() { ++ assertThat( ++ PATH_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever/happens"))) ++ .isEqualTo( ++ MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests")); ++ } ++ ++ @Test ++ void pathAndMethodWithNameInWrappedRequest() throws URISyntaxException { ++ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); ++ assertThat(PATH_AND_METHOD.getNameFor("some-service", request)) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests")); ++ } ++ ++ @Test ++ void pathAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { ++ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); ++ assertThat(PATH_AND_METHOD.getNameFor(null, request)) ++ .isEqualTo( ++ MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests")); ++ } ++ ++ @Test ++ void querylessUrlAndMethodWithName() { ++ assertThat( ++ QUERYLESS_URL_AND_METHOD.getNameFor( ++ "some-service", new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this"))) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); ++ } ++ ++ @Test ++ void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { ++ HttpRequest request = ++ rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); ++ assertThat(QUERYLESS_URL_AND_METHOD.getNameFor("some-service", request)) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); ++ } ++ ++ private static HttpRequest rewriteRequestURI(HttpRequest request) throws URISyntaxException { ++ HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request); ++ URI uri = URIUtils.rewriteURI(wrapper.getURI(), null, true); ++ wrapper.setURI(uri); ++ ++ return wrapper; ++ } + } +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java +@@ -1,50 +1,53 @@ + package io.dropwizard.metrics5.httpclient; + +-import io.dropwizard.metrics5.MetricName; +-import io.dropwizard.metrics5.MetricRegistry; +-import org.junit.jupiter.api.Test; +-import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertTrue; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + ++import io.dropwizard.metrics5.MetricName; ++import io.dropwizard.metrics5.MetricRegistry; ++import org.junit.jupiter.api.Test; ++import org.mockito.ArgumentCaptor; + +-class InstrumentedHttpClientConnectionManagerTest { +- private final MetricRegistry metricRegistry = new MetricRegistry(); ++final class InstrumentedHttpClientConnectionManagerTest { ++ private final MetricRegistry metricRegistry = new MetricRegistry(); + +- @Test +- void shouldRemoveGauges() { +- final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); +- assertThat(metricRegistry.getGauges().entrySet().stream() ++ @Test ++ void shouldRemoveGauges() { ++ final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = ++ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); ++ assertThat( ++ metricRegistry.getGauges().entrySet().stream() + .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) +- .containsOnly(entry("org.apache.http.conn.HttpClientConnectionManager.available-connections", 0), +- entry("org.apache.http.conn.HttpClientConnectionManager.leased-connections", 0), +- entry("org.apache.http.conn.HttpClientConnectionManager.max-connections", 20), +- entry("org.apache.http.conn.HttpClientConnectionManager.pending-connections", 0)); +- +- instrumentedHttpClientConnectionManager.close(); +- assertEquals(0, metricRegistry.getGauges().size()); +- +- // should be able to create another one with the same name ("") +- InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); +- } +- +- @Test +- void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); +- +- InstrumentedHttpClientConnectionManager.builder(registry) +- .name("some-name") +- .name("some-other-name") +- .build() +- .close(); +- +- ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); +- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); +- } ++ .containsOnly( ++ entry("org.apache.http.conn.HttpClientConnectionManager.available-connections", 0), ++ entry("org.apache.http.conn.HttpClientConnectionManager.leased-connections", 0), ++ entry("org.apache.http.conn.HttpClientConnectionManager.max-connections", 20), ++ entry("org.apache.http.conn.HttpClientConnectionManager.pending-connections", 0)); ++ ++ instrumentedHttpClientConnectionManager.close(); ++ assertEquals(0, metricRegistry.getGauges().size()); ++ ++ // should be able to create another one with the same name ("") ++ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); ++ } ++ ++ @Test ++ void configurableViaBuilder() { ++ final MetricRegistry registry = mock(); ++ ++ InstrumentedHttpClientConnectionManager.builder(registry) ++ .name("some-name") ++ .name("some-other-name") ++ .build() ++ .close(); ++ ++ ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); ++ } + } +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java +@@ -1,11 +1,20 @@ + package io.dropwizard.metrics5.httpclient; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; ++import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.ArgumentMatchers.eq; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import com.sun.net.httpserver.HttpExchange; + import com.sun.net.httpserver.HttpServer; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricRegistryListener; + import io.dropwizard.metrics5.Timer; ++import java.net.InetSocketAddress; + import org.apache.http.HttpRequest; + import org.apache.http.NoHttpResponseException; + import org.apache.http.client.HttpClient; +@@ -13,66 +22,55 @@ import org.apache.http.client.methods.HttpGet; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.net.InetSocketAddress; ++final class InstrumentedHttpClientsTest { ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); ++ private final MetricRegistry metricRegistry = new MetricRegistry(); ++ private final HttpClient client = ++ InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) ++ .disableAutomaticRetries() ++ .build(); + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; +-import static org.mockito.ArgumentMatchers.any; +-import static org.mockito.ArgumentMatchers.eq; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; ++ @BeforeEach ++ void setUp() { ++ metricRegistry.addListener(registryListener); ++ } + +-class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = +- mock(MetricRegistryListener.class); +- private final MetricRegistry metricRegistry = new MetricRegistry(); +- private final HttpClient client = +- InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); ++ @Test ++ void registersExpectedMetricsGivenNameStrategy() throws Exception { ++ final HttpGet get = new HttpGet("http://example.com?q=anything"); ++ final MetricName metricName = MetricName.build("some.made.up.metric.name"); + +- @BeforeEach +- void setUp() { +- metricRegistry.addListener(registryListener); +- } +- +- @Test +- void registersExpectedMetricsGivenNameStrategy() throws Exception { +- final HttpGet get = new HttpGet("http://example.com?q=anything"); +- final MetricName metricName = MetricName.build("some.made.up.metric.name"); ++ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); + +- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) +- .thenReturn(metricName); ++ client.execute(get); + +- client.execute(get); +- +- verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); +- } ++ verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); ++ } + +- @Test +- void registersExpectedExceptionMetrics() throws Exception { +- HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); ++ @Test ++ void registersExpectedExceptionMetrics() throws Exception { ++ HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); + +- final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); +- final MetricName requestMetricName = MetricName.build("request"); +- final MetricName exceptionMetricName = MetricName.build("exception"); ++ final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); ++ final MetricName requestMetricName = MetricName.build("request"); ++ final MetricName exceptionMetricName = MetricName.build("exception"); + +- httpServer.createContext("/", HttpExchange::close); +- httpServer.start(); ++ httpServer.createContext("/", HttpExchange::close); ++ httpServer.start(); + +- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) +- .thenReturn(requestMetricName); +- when(metricNameStrategy.getNameFor(any(), any(Exception.class))) +- .thenReturn(exceptionMetricName); ++ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) ++ .thenReturn(requestMetricName); ++ when(metricNameStrategy.getNameFor(any(), any(Exception.class))) ++ .thenReturn(exceptionMetricName); + +- try { +- client.execute(get); +- fail(); +- } catch (NoHttpResponseException expected) { +- assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); +- } finally { +- httpServer.stop(0); +- } ++ try { ++ client.execute(get); ++ fail(); ++ } catch (NoHttpResponseException expected) { ++ assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); ++ } finally { ++ httpServer.stop(0); + } ++ } + } +--- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategies.java ++++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategies.java +@@ -1,48 +1,43 @@ + package io.dropwizard.metrics5.httpclient5; + +-import org.apache.hc.client5.http.classic.HttpClient; +-import org.apache.hc.core5.http.HttpRequest; +-import org.apache.hc.core5.net.URIBuilder; ++import static io.dropwizard.metrics5.MetricRegistry.name; + + import java.net.URISyntaxException; + import java.util.Locale; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; ++import org.apache.hc.client5.http.classic.HttpClient; ++import org.apache.hc.core5.http.HttpRequest; ++import org.apache.hc.core5.net.URIBuilder; + + public class HttpClientMetricNameStrategies { + +- public static final HttpClientMetricNameStrategy METHOD_ONLY = +- (name, request) -> name(HttpClient.class, +- name, +- methodNameString(request)); +- +- public static final HttpClientMetricNameStrategy HOST_AND_METHOD = +- (name, request) -> { +- try { +- return name(HttpClient.class, +- name, +- request.getUri().getHost(), +- methodNameString(request)); +- } catch (URISyntaxException e) { +- throw new IllegalArgumentException(e); +- } +- }; +- +- public static final HttpClientMetricNameStrategy QUERYLESS_URL_AND_METHOD = +- (name, request) -> { +- try { +- final URIBuilder url = new URIBuilder(request.getUri()); +- return name(HttpClient.class, +- name, +- url.removeQuery().build().toString(), +- methodNameString(request)); +- } catch (URISyntaxException e) { +- throw new IllegalArgumentException(e); +- } +- }; +- +- private static String methodNameString(HttpRequest request) { +- return request.getMethod().toLowerCase(Locale.ROOT) + "-requests"; +- } +- ++ public static final HttpClientMetricNameStrategy METHOD_ONLY = ++ (name, request) -> name(HttpClient.class, name, methodNameString(request)); ++ ++ public static final HttpClientMetricNameStrategy HOST_AND_METHOD = ++ (name, request) -> { ++ try { ++ return name( ++ HttpClient.class, name, request.getUri().getHost(), methodNameString(request)); ++ } catch (URISyntaxException e) { ++ throw new IllegalArgumentException(e); ++ } ++ }; ++ ++ public static final HttpClientMetricNameStrategy QUERYLESS_URL_AND_METHOD = ++ (name, request) -> { ++ try { ++ final URIBuilder url = new URIBuilder(request.getUri()); ++ return name( ++ HttpClient.class, ++ name, ++ url.removeQuery().build().toString(), ++ methodNameString(request)); ++ } catch (URISyntaxException e) { ++ throw new IllegalArgumentException(e); ++ } ++ }; ++ ++ private static String methodNameString(HttpRequest request) { ++ return request.getMethod().toLowerCase(Locale.ROOT) + "-requests"; ++ } + } +--- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategy.java ++++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategy.java +@@ -8,11 +8,9 @@ import org.apache.hc.core5.http.HttpRequest; + @FunctionalInterface + public interface HttpClientMetricNameStrategy { + +- MetricName getNameFor(String name, HttpRequest request); ++ MetricName getNameFor(String name, HttpRequest request); + +- default MetricName getNameFor(String name, Exception exception) { +- return MetricRegistry.name(HttpClient.class, +- name, +- exception.getClass().getSimpleName()); +- } ++ default MetricName getNameFor(String name, Exception exception) { ++ return MetricRegistry.name(HttpClient.class, name, exception.getClass().getSimpleName()); ++ } + } +--- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java ++++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java +@@ -1,5 +1,8 @@ + package io.dropwizard.metrics5.httpclient5; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static java.util.Objects.requireNonNull; ++ + import io.dropwizard.metrics5.MetricRegistry; + import org.apache.hc.client5.http.DnsResolver; + import org.apache.hc.client5.http.SchemePortResolver; +@@ -17,139 +20,135 @@ import org.apache.hc.core5.pool.PoolConcurrencyPolicy; + import org.apache.hc.core5.pool.PoolReusePolicy; + import org.apache.hc.core5.util.TimeValue; + +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static java.util.Objects.requireNonNull; +- +-/** +- * A {@link HttpClientConnectionManager} which monitors the number of open connections. +- */ ++/** A {@link HttpClientConnectionManager} which monitors the number of open connections. */ + public class InstrumentedAsyncClientConnectionManager extends PoolingAsyncClientConnectionManager { +- private static final String METRICS_PREFIX = AsyncClientConnectionManager.class.getName(); ++ private static final String METRICS_PREFIX = AsyncClientConnectionManager.class.getName(); ++ ++ protected static Registry getDefaultTlsStrategy() { ++ return RegistryBuilder.create() ++ .register(URIScheme.HTTPS.id, DefaultClientTlsStrategy.getDefault()) ++ .build(); ++ } ++ ++ private final MetricRegistry metricsRegistry; ++ private final String name; ++ ++ InstrumentedAsyncClientConnectionManager( ++ final MetricRegistry metricRegistry, ++ final String name, ++ final Lookup tlsStrategyLookup, ++ final PoolConcurrencyPolicy poolConcurrencyPolicy, ++ final PoolReusePolicy poolReusePolicy, ++ final TimeValue timeToLive, ++ final SchemePortResolver schemePortResolver, ++ final DnsResolver dnsResolver) { ++ ++ super( ++ tlsStrategyLookup, ++ poolConcurrencyPolicy, ++ poolReusePolicy, ++ timeToLive, ++ schemePortResolver, ++ dnsResolver); ++ this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); ++ this.name = name; ++ ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(METRICS_PREFIX, name, "available-connections"), () -> getTotalStats().getAvailable()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(METRICS_PREFIX, name, "leased-connections"), () -> getTotalStats().getLeased()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(METRICS_PREFIX, name, "max-connections"), () -> getTotalStats().getMax()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(METRICS_PREFIX, name, "pending-connections"), () -> getTotalStats().getPending()); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void close() { ++ close(CloseMode.GRACEFUL); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void close(CloseMode closeMode) { ++ super.close(closeMode); ++ metricsRegistry.remove(name(METRICS_PREFIX, name, "available-connections")); ++ metricsRegistry.remove(name(METRICS_PREFIX, name, "leased-connections")); ++ metricsRegistry.remove(name(METRICS_PREFIX, name, "max-connections")); ++ metricsRegistry.remove(name(METRICS_PREFIX, name, "pending-connections")); ++ } ++ ++ public static Builder builder(MetricRegistry metricsRegistry) { ++ return new Builder().metricsRegistry(metricsRegistry); ++ } ++ ++ public static class Builder { ++ private MetricRegistry metricsRegistry; ++ private String name; ++ private Lookup tlsStrategyLookup = getDefaultTlsStrategy(); ++ private SchemePortResolver schemePortResolver; ++ private DnsResolver dnsResolver; ++ private PoolConcurrencyPolicy poolConcurrencyPolicy; ++ private PoolReusePolicy poolReusePolicy; ++ private TimeValue timeToLive = TimeValue.NEG_ONE_MILLISECOND; ++ ++ Builder() {} ++ ++ public Builder metricsRegistry(MetricRegistry metricRegistry) { ++ this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); ++ return this; ++ } + +- protected static Registry getDefaultTlsStrategy() { +- return RegistryBuilder.create() +- .register(URIScheme.HTTPS.id, DefaultClientTlsStrategy.getDefault()) +- .build(); ++ public Builder name(final String name) { ++ this.name = name; ++ return this; + } + +- private final MetricRegistry metricsRegistry; +- private final String name; +- +- InstrumentedAsyncClientConnectionManager(final MetricRegistry metricRegistry, +- final String name, +- final Lookup tlsStrategyLookup, +- final PoolConcurrencyPolicy poolConcurrencyPolicy, +- final PoolReusePolicy poolReusePolicy, +- final TimeValue timeToLive, +- final SchemePortResolver schemePortResolver, +- final DnsResolver dnsResolver) { +- +- super(tlsStrategyLookup, poolConcurrencyPolicy, poolReusePolicy, timeToLive, schemePortResolver, dnsResolver); +- this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); +- this.name = name; +- +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "available-connections"), +- () -> getTotalStats().getAvailable()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "leased-connections"), +- () -> getTotalStats().getLeased()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "max-connections"), +- () -> getTotalStats().getMax()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "pending-connections"), +- () -> getTotalStats().getPending()); ++ public Builder schemePortResolver(SchemePortResolver schemePortResolver) { ++ this.schemePortResolver = schemePortResolver; ++ return this; + } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void close() { +- close(CloseMode.GRACEFUL); ++ public Builder dnsResolver(DnsResolver dnsResolver) { ++ this.dnsResolver = dnsResolver; ++ return this; + } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void close(CloseMode closeMode) { +- super.close(closeMode); +- metricsRegistry.remove(name(METRICS_PREFIX, name, "available-connections")); +- metricsRegistry.remove(name(METRICS_PREFIX, name, "leased-connections")); +- metricsRegistry.remove(name(METRICS_PREFIX, name, "max-connections")); +- metricsRegistry.remove(name(METRICS_PREFIX, name, "pending-connections")); ++ public Builder timeToLive(TimeValue timeToLive) { ++ this.timeToLive = timeToLive; ++ return this; + } + +- public static Builder builder(MetricRegistry metricsRegistry) { +- return new Builder().metricsRegistry(metricsRegistry); ++ public Builder tlsStrategyLookup(Lookup tlsStrategyLookup) { ++ this.tlsStrategyLookup = tlsStrategyLookup; ++ return this; + } + +- public static class Builder { +- private MetricRegistry metricsRegistry; +- private String name; +- private Lookup tlsStrategyLookup = getDefaultTlsStrategy(); +- private SchemePortResolver schemePortResolver; +- private DnsResolver dnsResolver; +- private PoolConcurrencyPolicy poolConcurrencyPolicy; +- private PoolReusePolicy poolReusePolicy; +- private TimeValue timeToLive = TimeValue.NEG_ONE_MILLISECOND; +- +- Builder() { +- } +- +- public Builder metricsRegistry(MetricRegistry metricRegistry) { +- this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); +- return this; +- } +- +- public Builder name(final String name) { +- this.name = name; +- return this; +- } +- +- public Builder schemePortResolver(SchemePortResolver schemePortResolver) { +- this.schemePortResolver = schemePortResolver; +- return this; +- } +- +- public Builder dnsResolver(DnsResolver dnsResolver) { +- this.dnsResolver = dnsResolver; +- return this; +- } +- +- public Builder timeToLive(TimeValue timeToLive) { +- this.timeToLive = timeToLive; +- return this; +- } +- +- public Builder tlsStrategyLookup(Lookup tlsStrategyLookup) { +- this.tlsStrategyLookup = tlsStrategyLookup; +- return this; +- } +- +- public Builder poolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) { +- this.poolConcurrencyPolicy = poolConcurrencyPolicy; +- return this; +- } +- +- public Builder poolReusePolicy(PoolReusePolicy poolReusePolicy) { +- this.poolReusePolicy = poolReusePolicy; +- return this; +- } +- +- public InstrumentedAsyncClientConnectionManager build() { +- return new InstrumentedAsyncClientConnectionManager( +- metricsRegistry, +- name, +- tlsStrategyLookup, +- poolConcurrencyPolicy, +- poolReusePolicy, +- timeToLive, +- schemePortResolver, +- dnsResolver); +- } ++ public Builder poolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) { ++ this.poolConcurrencyPolicy = poolConcurrencyPolicy; ++ return this; + } + ++ public Builder poolReusePolicy(PoolReusePolicy poolReusePolicy) { ++ this.poolReusePolicy = poolReusePolicy; ++ return this; ++ } ++ ++ public InstrumentedAsyncClientConnectionManager build() { ++ return new InstrumentedAsyncClientConnectionManager( ++ metricsRegistry, ++ name, ++ tlsStrategyLookup, ++ poolConcurrencyPolicy, ++ poolReusePolicy, ++ timeToLive, ++ schemePortResolver, ++ dnsResolver); ++ } ++ } + } +--- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncExecChainHandler.java ++++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncExecChainHandler.java +@@ -1,8 +1,11 @@ + package io.dropwizard.metrics5.httpclient5; + ++import static java.util.Objects.requireNonNull; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; ++import java.io.IOException; + import org.apache.hc.client5.http.async.AsyncExecCallback; + import org.apache.hc.client5.http.async.AsyncExecChain; + import org.apache.hc.client5.http.async.AsyncExecChainHandler; +@@ -13,87 +16,87 @@ import org.apache.hc.core5.http.HttpResponse; + import org.apache.hc.core5.http.nio.AsyncDataConsumer; + import org.apache.hc.core5.http.nio.AsyncEntityProducer; + +-import java.io.IOException; +- +-import static java.util.Objects.requireNonNull; +- + class InstrumentedAsyncExecChainHandler implements AsyncExecChainHandler { ++ private final MetricRegistry registry; ++ private final HttpClientMetricNameStrategy metricNameStrategy; ++ private final String name; ++ ++ public InstrumentedAsyncExecChainHandler( ++ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy) { ++ this(registry, metricNameStrategy, null); ++ } ++ ++ public InstrumentedAsyncExecChainHandler( ++ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy, String name) { ++ this.registry = requireNonNull(registry, "registry"); ++ this.metricNameStrategy = requireNonNull(metricNameStrategy, "metricNameStrategy"); ++ this.name = name; ++ } ++ ++ @Override ++ public void execute( ++ HttpRequest request, ++ AsyncEntityProducer entityProducer, ++ AsyncExecChain.Scope scope, ++ AsyncExecChain chain, ++ AsyncExecCallback asyncExecCallback) ++ throws HttpException, IOException { ++ final InstrumentedAsyncExecCallback instrumentedAsyncExecCallback = ++ new InstrumentedAsyncExecCallback( ++ registry, metricNameStrategy, name, asyncExecCallback, request); ++ chain.proceed(request, entityProducer, scope, instrumentedAsyncExecCallback); ++ } ++ ++ static final class InstrumentedAsyncExecCallback implements AsyncExecCallback { + private final MetricRegistry registry; + private final HttpClientMetricNameStrategy metricNameStrategy; + private final String name; +- +- public InstrumentedAsyncExecChainHandler(MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy) { +- this(registry, metricNameStrategy, null); ++ private final AsyncExecCallback delegate; ++ private final Timer.Context timerContext; ++ ++ public InstrumentedAsyncExecCallback( ++ MetricRegistry registry, ++ HttpClientMetricNameStrategy metricNameStrategy, ++ String name, ++ AsyncExecCallback delegate, ++ HttpRequest request) { ++ this.registry = registry; ++ this.metricNameStrategy = metricNameStrategy; ++ this.name = name; ++ this.delegate = delegate; ++ this.timerContext = timer(request).time(); + } + +- public InstrumentedAsyncExecChainHandler(MetricRegistry registry, +- HttpClientMetricNameStrategy metricNameStrategy, +- String name) { +- this.registry = requireNonNull(registry, "registry"); +- this.metricNameStrategy = requireNonNull(metricNameStrategy, "metricNameStrategy"); +- this.name = name; ++ @Override ++ public AsyncDataConsumer handleResponse(HttpResponse response, EntityDetails entityDetails) ++ throws HttpException, IOException { ++ return delegate.handleResponse(response, entityDetails); + } + + @Override +- public void execute(HttpRequest request, +- AsyncEntityProducer entityProducer, +- AsyncExecChain.Scope scope, +- AsyncExecChain chain, +- AsyncExecCallback asyncExecCallback) throws HttpException, IOException { +- final InstrumentedAsyncExecCallback instrumentedAsyncExecCallback = +- new InstrumentedAsyncExecCallback(registry, metricNameStrategy, name, asyncExecCallback, request); +- chain.proceed(request, entityProducer, scope, instrumentedAsyncExecCallback); +- ++ public void handleInformationResponse(HttpResponse response) throws HttpException, IOException { ++ delegate.handleInformationResponse(response); + } + +- final static class InstrumentedAsyncExecCallback implements AsyncExecCallback { +- private final MetricRegistry registry; +- private final HttpClientMetricNameStrategy metricNameStrategy; +- private final String name; +- private final AsyncExecCallback delegate; +- private final Timer.Context timerContext; +- +- public InstrumentedAsyncExecCallback(MetricRegistry registry, +- HttpClientMetricNameStrategy metricNameStrategy, +- String name, +- AsyncExecCallback delegate, +- HttpRequest request) { +- this.registry = registry; +- this.metricNameStrategy = metricNameStrategy; +- this.name = name; +- this.delegate = delegate; +- this.timerContext = timer(request).time(); +- } +- +- @Override +- public AsyncDataConsumer handleResponse(HttpResponse response, EntityDetails entityDetails) throws HttpException, IOException { +- return delegate.handleResponse(response, entityDetails); +- } +- +- @Override +- public void handleInformationResponse(HttpResponse response) throws HttpException, IOException { +- delegate.handleInformationResponse(response); +- } +- +- @Override +- public void completed() { +- delegate.completed(); +- timerContext.stop(); +- } ++ @Override ++ public void completed() { ++ delegate.completed(); ++ timerContext.stop(); ++ } + +- @Override +- public void failed(Exception cause) { +- delegate.failed(cause); +- meter(cause).mark(); +- timerContext.stop(); +- } ++ @Override ++ public void failed(Exception cause) { ++ delegate.failed(cause); ++ meter(cause).mark(); ++ timerContext.stop(); ++ } + +- private Timer timer(HttpRequest request) { +- return registry.timer(metricNameStrategy.getNameFor(name, request)); +- } ++ private Timer timer(HttpRequest request) { ++ return registry.timer(metricNameStrategy.getNameFor(name, request)); ++ } + +- private Meter meter(Exception e) { +- return registry.meter(metricNameStrategy.getNameFor(name, e)); +- } ++ private Meter meter(Exception e) { ++ return registry.meter(metricNameStrategy.getNameFor(name, e)); + } ++ } + } +--- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClients.java ++++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClients.java +@@ -1,43 +1,48 @@ + package io.dropwizard.metrics5.httpclient5; + ++import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; ++ + import io.dropwizard.metrics5.MetricRegistry; + import org.apache.hc.client5.http.impl.ChainElement; + import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; + import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder; + import org.apache.hc.client5.http.nio.AsyncClientConnectionManager; + +-import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; +- + public class InstrumentedHttpAsyncClients { +- private InstrumentedHttpAsyncClients() { +- super(); +- } +- +- public static CloseableHttpAsyncClient createDefault(MetricRegistry metricRegistry) { +- return createDefault(metricRegistry, METHOD_ONLY); +- } +- +- public static CloseableHttpAsyncClient createDefault(MetricRegistry metricRegistry, +- HttpClientMetricNameStrategy metricNameStrategy) { +- return custom(metricRegistry, metricNameStrategy).build(); +- } +- +- public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry) { +- return custom(metricRegistry, METHOD_ONLY); +- } +- +- public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry, +- HttpClientMetricNameStrategy metricNameStrategy) { +- return custom(metricRegistry, metricNameStrategy, InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build()); +- } +- +- public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry, +- HttpClientMetricNameStrategy metricNameStrategy, +- AsyncClientConnectionManager clientConnectionManager) { +- return HttpAsyncClientBuilder.create() +- .setConnectionManager(clientConnectionManager) +- .addExecInterceptorBefore(ChainElement.CONNECT.name(), "dropwizard-metrics", +- new InstrumentedAsyncExecChainHandler(metricRegistry, metricNameStrategy)); +- } +- ++ private InstrumentedHttpAsyncClients() { ++ super(); ++ } ++ ++ public static CloseableHttpAsyncClient createDefault(MetricRegistry metricRegistry) { ++ return createDefault(metricRegistry, METHOD_ONLY); ++ } ++ ++ public static CloseableHttpAsyncClient createDefault( ++ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { ++ return custom(metricRegistry, metricNameStrategy).build(); ++ } ++ ++ public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry) { ++ return custom(metricRegistry, METHOD_ONLY); ++ } ++ ++ public static HttpAsyncClientBuilder custom( ++ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { ++ return custom( ++ metricRegistry, ++ metricNameStrategy, ++ InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build()); ++ } ++ ++ public static HttpAsyncClientBuilder custom( ++ MetricRegistry metricRegistry, ++ HttpClientMetricNameStrategy metricNameStrategy, ++ AsyncClientConnectionManager clientConnectionManager) { ++ return HttpAsyncClientBuilder.create() ++ .setConnectionManager(clientConnectionManager) ++ .addExecInterceptorBefore( ++ ChainElement.CONNECT.name(), ++ "dropwizard-metrics", ++ new InstrumentedAsyncExecChainHandler(metricRegistry, metricNameStrategy)); ++ } + } +--- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java ++++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java +@@ -1,5 +1,8 @@ + package io.dropwizard.metrics5.httpclient5; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static java.util.Objects.requireNonNull; ++ + import io.dropwizard.metrics5.MetricRegistry; + import org.apache.hc.client5.http.DnsResolver; + import org.apache.hc.client5.http.SchemePortResolver; +@@ -20,156 +23,152 @@ import org.apache.hc.core5.pool.PoolConcurrencyPolicy; + import org.apache.hc.core5.pool.PoolReusePolicy; + import org.apache.hc.core5.util.TimeValue; + +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static java.util.Objects.requireNonNull; +- +-/** +- * A {@link HttpClientConnectionManager} which monitors the number of open connections. +- */ ++/** A {@link HttpClientConnectionManager} which monitors the number of open connections. */ + public class InstrumentedHttpClientConnectionManager extends PoolingHttpClientConnectionManager { +- private static final String METRICS_PREFIX = HttpClientConnectionManager.class.getName(); ++ private static final String METRICS_PREFIX = HttpClientConnectionManager.class.getName(); ++ ++ protected static Registry getDefaultRegistry() { ++ return RegistryBuilder.create() ++ .register(URIScheme.HTTP.id, PlainConnectionSocketFactory.getSocketFactory()) ++ .register(URIScheme.HTTPS.id, SSLConnectionSocketFactory.getSocketFactory()) ++ .build(); ++ } ++ ++ private final MetricRegistry metricsRegistry; ++ private final String name; ++ ++ InstrumentedHttpClientConnectionManager( ++ final MetricRegistry metricRegistry, ++ final String name, ++ final HttpClientConnectionOperator httpClientConnectionOperator, ++ final PoolConcurrencyPolicy poolConcurrencyPolicy, ++ final PoolReusePolicy poolReusePolicy, ++ final TimeValue timeToLive, ++ final HttpConnectionFactory connFactory) { ++ ++ super( ++ httpClientConnectionOperator, ++ poolConcurrencyPolicy, ++ poolReusePolicy, ++ timeToLive, ++ connFactory); ++ this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); ++ this.name = name; ++ ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(METRICS_PREFIX, name, "available-connections"), () -> getTotalStats().getAvailable()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(METRICS_PREFIX, name, "leased-connections"), () -> getTotalStats().getLeased()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(METRICS_PREFIX, name, "max-connections"), () -> getTotalStats().getMax()); ++ // this acquires a lock on the connection pool; remove if contention sucks ++ metricRegistry.registerGauge( ++ name(METRICS_PREFIX, name, "pending-connections"), () -> getTotalStats().getPending()); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void close() { ++ close(CloseMode.GRACEFUL); ++ } ++ ++ /** {@inheritDoc} */ ++ @Override ++ public void close(CloseMode closeMode) { ++ super.close(closeMode); ++ metricsRegistry.remove(name(METRICS_PREFIX, name, "available-connections")); ++ metricsRegistry.remove(name(METRICS_PREFIX, name, "leased-connections")); ++ metricsRegistry.remove(name(METRICS_PREFIX, name, "max-connections")); ++ metricsRegistry.remove(name(METRICS_PREFIX, name, "pending-connections")); ++ } ++ ++ public static Builder builder(MetricRegistry metricsRegistry) { ++ return new Builder().metricsRegistry(metricsRegistry); ++ } ++ ++ public static class Builder { ++ private MetricRegistry metricsRegistry; ++ private String name; ++ private HttpClientConnectionOperator httpClientConnectionOperator; ++ private Registry socketFactoryRegistry = getDefaultRegistry(); ++ private SchemePortResolver schemePortResolver; ++ private DnsResolver dnsResolver; ++ private PoolConcurrencyPolicy poolConcurrencyPolicy; ++ private PoolReusePolicy poolReusePolicy; ++ private TimeValue timeToLive = TimeValue.NEG_ONE_MILLISECOND; ++ private HttpConnectionFactory connFactory; ++ ++ Builder() {} ++ ++ public Builder metricsRegistry(MetricRegistry metricRegistry) { ++ this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); ++ return this; ++ } ++ ++ public Builder name(final String name) { ++ this.name = name; ++ return this; ++ } ++ ++ public Builder socketFactoryRegistry(Registry socketFactoryRegistry) { ++ this.socketFactoryRegistry = requireNonNull(socketFactoryRegistry, "socketFactoryRegistry"); ++ return this; ++ } ++ ++ public Builder connFactory(HttpConnectionFactory connFactory) { ++ this.connFactory = connFactory; ++ return this; ++ } ++ ++ public Builder schemePortResolver(SchemePortResolver schemePortResolver) { ++ this.schemePortResolver = schemePortResolver; ++ return this; ++ } + +- protected static Registry getDefaultRegistry() { +- return RegistryBuilder.create() +- .register(URIScheme.HTTP.id, PlainConnectionSocketFactory.getSocketFactory()) +- .register(URIScheme.HTTPS.id, SSLConnectionSocketFactory.getSocketFactory()) +- .build(); ++ public Builder dnsResolver(DnsResolver dnsResolver) { ++ this.dnsResolver = dnsResolver; ++ return this; + } + +- private final MetricRegistry metricsRegistry; +- private final String name; +- +- InstrumentedHttpClientConnectionManager(final MetricRegistry metricRegistry, +- final String name, +- final HttpClientConnectionOperator httpClientConnectionOperator, +- final PoolConcurrencyPolicy poolConcurrencyPolicy, +- final PoolReusePolicy poolReusePolicy, +- final TimeValue timeToLive, +- final HttpConnectionFactory connFactory) { +- +- super(httpClientConnectionOperator, poolConcurrencyPolicy, poolReusePolicy, timeToLive, connFactory); +- this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); +- this.name = name; +- +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "available-connections"), +- () -> getTotalStats().getAvailable()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "leased-connections"), +- () -> getTotalStats().getLeased()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "max-connections"), +- () -> getTotalStats().getMax()); +- // this acquires a lock on the connection pool; remove if contention sucks +- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "pending-connections"), +- () -> getTotalStats().getPending()); ++ public Builder timeToLive(TimeValue timeToLive) { ++ this.timeToLive = timeToLive; ++ return this; + } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void close() { +- close(CloseMode.GRACEFUL); ++ public Builder httpClientConnectionOperator( ++ HttpClientConnectionOperator httpClientConnectionOperator) { ++ this.httpClientConnectionOperator = httpClientConnectionOperator; ++ return this; + } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public void close(CloseMode closeMode) { +- super.close(closeMode); +- metricsRegistry.remove(name(METRICS_PREFIX, name, "available-connections")); +- metricsRegistry.remove(name(METRICS_PREFIX, name, "leased-connections")); +- metricsRegistry.remove(name(METRICS_PREFIX, name, "max-connections")); +- metricsRegistry.remove(name(METRICS_PREFIX, name, "pending-connections")); ++ public Builder poolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) { ++ this.poolConcurrencyPolicy = poolConcurrencyPolicy; ++ return this; + } + +- public static Builder builder(MetricRegistry metricsRegistry) { +- return new Builder().metricsRegistry(metricsRegistry); ++ public Builder poolReusePolicy(PoolReusePolicy poolReusePolicy) { ++ this.poolReusePolicy = poolReusePolicy; ++ return this; + } + +- public static class Builder { +- private MetricRegistry metricsRegistry; +- private String name; +- private HttpClientConnectionOperator httpClientConnectionOperator; +- private Registry socketFactoryRegistry = getDefaultRegistry(); +- private SchemePortResolver schemePortResolver; +- private DnsResolver dnsResolver; +- private PoolConcurrencyPolicy poolConcurrencyPolicy; +- private PoolReusePolicy poolReusePolicy; +- private TimeValue timeToLive = TimeValue.NEG_ONE_MILLISECOND; +- private HttpConnectionFactory connFactory; +- +- Builder() { +- } +- +- public Builder metricsRegistry(MetricRegistry metricRegistry) { +- this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); +- return this; +- } +- +- public Builder name(final String name) { +- this.name = name; +- return this; +- } +- +- public Builder socketFactoryRegistry(Registry socketFactoryRegistry) { +- this.socketFactoryRegistry = requireNonNull(socketFactoryRegistry, "socketFactoryRegistry"); +- return this; +- } +- +- public Builder connFactory(HttpConnectionFactory connFactory) { +- this.connFactory = connFactory; +- return this; +- } +- +- public Builder schemePortResolver(SchemePortResolver schemePortResolver) { +- this.schemePortResolver = schemePortResolver; +- return this; +- } +- +- public Builder dnsResolver(DnsResolver dnsResolver) { +- this.dnsResolver = dnsResolver; +- return this; +- } +- +- public Builder timeToLive(TimeValue timeToLive) { +- this.timeToLive = timeToLive; +- return this; +- } +- +- public Builder httpClientConnectionOperator(HttpClientConnectionOperator httpClientConnectionOperator) { +- this.httpClientConnectionOperator = httpClientConnectionOperator; +- return this; +- } +- +- public Builder poolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) { +- this.poolConcurrencyPolicy = poolConcurrencyPolicy; +- return this; +- } +- +- public Builder poolReusePolicy(PoolReusePolicy poolReusePolicy) { +- this.poolReusePolicy = poolReusePolicy; +- return this; +- } +- +- public InstrumentedHttpClientConnectionManager build() { +- if (httpClientConnectionOperator == null) { +- httpClientConnectionOperator = new DefaultHttpClientConnectionOperator( +- socketFactoryRegistry, +- schemePortResolver, +- dnsResolver); +- } +- +- return new InstrumentedHttpClientConnectionManager( +- metricsRegistry, +- name, +- httpClientConnectionOperator, +- poolConcurrencyPolicy, +- poolReusePolicy, +- timeToLive, +- connFactory); +- } ++ public InstrumentedHttpClientConnectionManager build() { ++ if (httpClientConnectionOperator == null) { ++ httpClientConnectionOperator = ++ new DefaultHttpClientConnectionOperator( ++ socketFactoryRegistry, schemePortResolver, dnsResolver); ++ } ++ ++ return new InstrumentedHttpClientConnectionManager( ++ metricsRegistry, ++ name, ++ httpClientConnectionOperator, ++ poolConcurrencyPolicy, ++ poolReusePolicy, ++ timeToLive, ++ connFactory); + } ++ } + } +--- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClients.java ++++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClients.java +@@ -1,34 +1,34 @@ + package io.dropwizard.metrics5.httpclient5; + ++import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; ++ + import io.dropwizard.metrics5.MetricRegistry; + import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; + import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; + +-import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; +- + public class InstrumentedHttpClients { +- private InstrumentedHttpClients() { +- super(); +- } +- +- public static CloseableHttpClient createDefault(MetricRegistry metricRegistry) { +- return createDefault(metricRegistry, METHOD_ONLY); +- } +- +- public static CloseableHttpClient createDefault(MetricRegistry metricRegistry, +- HttpClientMetricNameStrategy metricNameStrategy) { +- return custom(metricRegistry, metricNameStrategy).build(); +- } +- +- public static HttpClientBuilder custom(MetricRegistry metricRegistry) { +- return custom(metricRegistry, METHOD_ONLY); +- } +- +- public static HttpClientBuilder custom(MetricRegistry metricRegistry, +- HttpClientMetricNameStrategy metricNameStrategy) { +- return HttpClientBuilder.create() +- .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy)) +- .setConnectionManager(InstrumentedHttpClientConnectionManager.builder(metricRegistry).build()); +- } +- ++ private InstrumentedHttpClients() { ++ super(); ++ } ++ ++ public static CloseableHttpClient createDefault(MetricRegistry metricRegistry) { ++ return createDefault(metricRegistry, METHOD_ONLY); ++ } ++ ++ public static CloseableHttpClient createDefault( ++ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { ++ return custom(metricRegistry, metricNameStrategy).build(); ++ } ++ ++ public static HttpClientBuilder custom(MetricRegistry metricRegistry) { ++ return custom(metricRegistry, METHOD_ONLY); ++ } ++ ++ public static HttpClientBuilder custom( ++ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { ++ return HttpClientBuilder.create() ++ .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy)) ++ .setConnectionManager( ++ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build()); ++ } + } +--- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java ++++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java +@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.httpclient5; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; ++import java.io.IOException; + import org.apache.hc.core5.http.ClassicHttpRequest; + import org.apache.hc.core5.http.ClassicHttpResponse; + import org.apache.hc.core5.http.ConnectionReuseStrategy; +@@ -15,64 +16,66 @@ import org.apache.hc.core5.http.io.HttpResponseInformationCallback; + import org.apache.hc.core5.http.protocol.HttpContext; + import org.apache.hc.core5.util.Timeout; + +-import java.io.IOException; +- + public class InstrumentedHttpRequestExecutor extends HttpRequestExecutor { +- private final MetricRegistry registry; +- private final HttpClientMetricNameStrategy metricNameStrategy; +- private final String name; ++ private final MetricRegistry registry; ++ private final HttpClientMetricNameStrategy metricNameStrategy; ++ private final String name; + +- public InstrumentedHttpRequestExecutor(MetricRegistry registry, +- HttpClientMetricNameStrategy metricNameStrategy) { +- this(registry, metricNameStrategy, null); +- } ++ public InstrumentedHttpRequestExecutor( ++ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy) { ++ this(registry, metricNameStrategy, null); ++ } + +- public InstrumentedHttpRequestExecutor(MetricRegistry registry, +- HttpClientMetricNameStrategy metricNameStrategy, +- String name) { +- this(registry, metricNameStrategy, name, HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE); +- } ++ public InstrumentedHttpRequestExecutor( ++ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy, String name) { ++ this(registry, metricNameStrategy, name, HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE); ++ } + +- public InstrumentedHttpRequestExecutor(MetricRegistry registry, +- HttpClientMetricNameStrategy metricNameStrategy, +- String name, +- Timeout waitForContinue) { +- this(registry, metricNameStrategy, name, waitForContinue, null, null); +- } ++ public InstrumentedHttpRequestExecutor( ++ MetricRegistry registry, ++ HttpClientMetricNameStrategy metricNameStrategy, ++ String name, ++ Timeout waitForContinue) { ++ this(registry, metricNameStrategy, name, waitForContinue, null, null); ++ } + +- public InstrumentedHttpRequestExecutor(MetricRegistry registry, +- HttpClientMetricNameStrategy metricNameStrategy, +- String name, +- Timeout waitForContinue, +- ConnectionReuseStrategy connReuseStrategy, +- Http1StreamListener streamListener) { +- super(waitForContinue, connReuseStrategy, streamListener); +- this.registry = registry; +- this.name = name; +- this.metricNameStrategy = metricNameStrategy; +- } ++ public InstrumentedHttpRequestExecutor( ++ MetricRegistry registry, ++ HttpClientMetricNameStrategy metricNameStrategy, ++ String name, ++ Timeout waitForContinue, ++ ConnectionReuseStrategy connReuseStrategy, ++ Http1StreamListener streamListener) { ++ super(waitForContinue, connReuseStrategy, streamListener); ++ this.registry = registry; ++ this.name = name; ++ this.metricNameStrategy = metricNameStrategy; ++ } + +- /** +- * {@inheritDoc} +- */ +- @Override +- public ClassicHttpResponse execute(ClassicHttpRequest request, HttpClientConnection conn, HttpResponseInformationCallback informationCallback, HttpContext context) throws IOException, HttpException { +- final Timer.Context timerContext = timer(request).time(); +- try { +- return super.execute(request, conn, informationCallback, context); +- } catch (HttpException | IOException e) { +- meter(e).mark(); +- throw e; +- } finally { +- timerContext.stop(); +- } ++ /** {@inheritDoc} */ ++ @Override ++ public ClassicHttpResponse execute( ++ ClassicHttpRequest request, ++ HttpClientConnection conn, ++ HttpResponseInformationCallback informationCallback, ++ HttpContext context) ++ throws IOException, HttpException { ++ final Timer.Context timerContext = timer(request).time(); ++ try { ++ return super.execute(request, conn, informationCallback, context); ++ } catch (HttpException | IOException e) { ++ meter(e).mark(); ++ throw e; ++ } finally { ++ timerContext.stop(); + } ++ } + +- private Timer timer(HttpRequest request) { +- return registry.timer(metricNameStrategy.getNameFor(name, request)); +- } ++ private Timer timer(HttpRequest request) { ++ return registry.timer(metricNameStrategy.getNameFor(name, request)); ++ } + +- private Meter meter(Exception e) { +- return registry.meter(metricNameStrategy.getNameFor(name, e)); +- } ++ private Meter meter(Exception e) { ++ return registry.meter(metricNameStrategy.getNameFor(name, e)); ++ } + } +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java +@@ -1,6 +1,13 @@ + package io.dropwizard.metrics5.httpclient5; + ++import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.HOST_AND_METHOD; ++import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; ++import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricName; ++import java.net.URI; ++import java.net.URISyntaxException; + import org.apache.hc.client5.http.classic.methods.HttpGet; + import org.apache.hc.client5.http.classic.methods.HttpPost; + import org.apache.hc.client5.http.classic.methods.HttpPut; +@@ -9,76 +16,84 @@ import org.apache.hc.core5.http.message.HttpRequestWrapper; + import org.apache.hc.core5.net.URIBuilder; + import org.junit.jupiter.api.Test; + +-import java.net.URI; +-import java.net.URISyntaxException; +- +-import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.HOST_AND_METHOD; +-import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; +-import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; +-import static org.assertj.core.api.Assertions.assertThat; +- +-class HttpClientMetricNameStrategiesTest { +- +- @Test +- void methodOnlyWithName() { +- assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever"))) +- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.get-requests")); +- } +- +- @Test +- void methodOnlyWithoutName() { +- assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever"))) +- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.get-requests")); +- } +- +- @Test +- void hostAndMethodWithName() { +- assertThat(HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever"))) +- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.my.host.com.post-requests")); +- } +- +- @Test +- void hostAndMethodWithoutName() { +- assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever"))) +- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.my.host.com.post-requests")); +- } +- +- @Test +- void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { +- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); +- +- assertThat(HOST_AND_METHOD.getNameFor("some-service", request)) +- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.my.host.com.post-requests")); +- } +- +- @Test +- void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { +- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); +- +- assertThat(HOST_AND_METHOD.getNameFor(null, request)) +- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.my.host.com.post-requests")); +- } +- +- @Test +- void querylessUrlAndMethodWithName() { +- assertThat(QUERYLESS_URL_AND_METHOD.getNameFor( +- "some-service", +- new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this"))) +- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); +- } +- +- @Test +- void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { +- HttpRequest request = rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); +- assertThat(QUERYLESS_URL_AND_METHOD.getNameFor("some-service", request)) +- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); +- } +- +- private static HttpRequest rewriteRequestURI(HttpRequest request) throws URISyntaxException { +- URI uri = new URIBuilder(request.getUri()).setFragment(null).build(); +- HttpRequestWrapper wrapper = new HttpRequestWrapper(request); +- wrapper.setUri(uri); +- +- return wrapper; +- } ++final class HttpClientMetricNameStrategiesTest { ++ ++ @Test ++ void methodOnlyWithName() { ++ assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever"))) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.hc.client5.http.classic.HttpClient.some-service.get-requests")); ++ } ++ ++ @Test ++ void methodOnlyWithoutName() { ++ assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever"))) ++ .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.get-requests")); ++ } ++ ++ @Test ++ void hostAndMethodWithName() { ++ assertThat( ++ HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever"))) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.hc.client5.http.classic.HttpClient.some-service.my.host.com.post-requests")); ++ } ++ ++ @Test ++ void hostAndMethodWithoutName() { ++ assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever"))) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.hc.client5.http.classic.HttpClient.my.host.com.post-requests")); ++ } ++ ++ @Test ++ void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { ++ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); ++ ++ assertThat(HOST_AND_METHOD.getNameFor("some-service", request)) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.hc.client5.http.classic.HttpClient.some-service.my.host.com.post-requests")); ++ } ++ ++ @Test ++ void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { ++ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); ++ ++ assertThat(HOST_AND_METHOD.getNameFor(null, request)) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.hc.client5.http.classic.HttpClient.my.host.com.post-requests")); ++ } ++ ++ @Test ++ void querylessUrlAndMethodWithName() { ++ assertThat( ++ QUERYLESS_URL_AND_METHOD.getNameFor( ++ "some-service", new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this"))) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); ++ } ++ ++ @Test ++ void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { ++ HttpRequest request = ++ rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); ++ assertThat(QUERYLESS_URL_AND_METHOD.getNameFor("some-service", request)) ++ .isEqualTo( ++ MetricName.build( ++ "org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); ++ } ++ ++ private static HttpRequest rewriteRequestURI(HttpRequest request) throws URISyntaxException { ++ URI uri = new URIBuilder(request.getUri()).setFragment(null).build(); ++ HttpRequestWrapper wrapper = new HttpRequestWrapper(request); ++ wrapper.setUri(uri); ++ ++ return wrapper; ++ } + } +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java +@@ -1,49 +1,60 @@ + package io.dropwizard.metrics5.httpclient5; + +-import io.dropwizard.metrics5.MetricName; +-import io.dropwizard.metrics5.MetricRegistry; +-import org.junit.jupiter.api.Test; +-import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertTrue; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; ++ ++import io.dropwizard.metrics5.MetricName; ++import io.dropwizard.metrics5.MetricRegistry; ++import org.junit.jupiter.api.Test; ++import org.mockito.ArgumentCaptor; + +-class InstrumentedAsyncClientConnectionManagerTest { +- private final MetricRegistry metricRegistry = new MetricRegistry(); ++final class InstrumentedAsyncClientConnectionManagerTest { ++ private final MetricRegistry metricRegistry = new MetricRegistry(); + +- @Test +- void shouldRemoveGauges() { +- final InstrumentedAsyncClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build(); +- assertThat(metricRegistry.getGauges().entrySet().stream() ++ @Test ++ void shouldRemoveGauges() { ++ final InstrumentedAsyncClientConnectionManager instrumentedHttpClientConnectionManager = ++ InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build(); ++ assertThat( ++ metricRegistry.getGauges().entrySet().stream() + .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) +- .containsOnly(entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.available-connections", 0), +- entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.leased-connections", 0), +- entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.max-connections", 25), +- entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.pending-connections", 0)); +- +- instrumentedHttpClientConnectionManager.close(); +- assertEquals(0, metricRegistry.getGauges().size()); +- +- // should be able to create another one with the same name ("") +- InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); +- } +- +- @Test +- void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); +- +- InstrumentedAsyncClientConnectionManager.builder(registry) +- .name("some-name") +- .name("some-other-name") +- .build() +- .close(); +- +- ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); +- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); +- } ++ .containsOnly( ++ entry( ++ "org.apache.hc.client5.http.nio.AsyncClientConnectionManager.available-connections", ++ 0), ++ entry( ++ "org.apache.hc.client5.http.nio.AsyncClientConnectionManager.leased-connections", ++ 0), ++ entry( ++ "org.apache.hc.client5.http.nio.AsyncClientConnectionManager.max-connections", 25), ++ entry( ++ "org.apache.hc.client5.http.nio.AsyncClientConnectionManager.pending-connections", ++ 0)); ++ ++ instrumentedHttpClientConnectionManager.close(); ++ assertEquals(0, metricRegistry.getGauges().size()); ++ ++ // should be able to create another one with the same name ("") ++ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); ++ } ++ ++ @Test ++ void configurableViaBuilder() { ++ final MetricRegistry registry = mock(); ++ ++ InstrumentedAsyncClientConnectionManager.builder(registry) ++ .name("some-name") ++ .name("some-other-name") ++ .build() ++ .close(); ++ ++ ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); ++ } + } +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java +@@ -1,11 +1,28 @@ + package io.dropwizard.metrics5.httpclient5; + ++import static java.nio.charset.StandardCharsets.US_ASCII; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; ++import static org.awaitility.Awaitility.await; ++import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.ArgumentMatchers.eq; ++import static org.mockito.Mockito.atLeastOnce; ++import static org.mockito.Mockito.spy; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import com.sun.net.httpserver.HttpExchange; + import com.sun.net.httpserver.HttpServer; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricRegistryListener; + import io.dropwizard.metrics5.Timer; ++import java.io.IOException; ++import java.net.InetSocketAddress; ++import java.util.concurrent.CountDownLatch; ++import java.util.concurrent.ExecutionException; ++import java.util.concurrent.Future; ++import java.util.concurrent.TimeUnit; + import org.apache.hc.client5.http.async.methods.SimpleHttpRequest; + import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; + import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder; +@@ -21,182 +38,191 @@ import org.junit.jupiter.api.extension.ExtendWith; + import org.mockito.Mock; + import org.mockito.junit.jupiter.MockitoExtension; + +-import java.io.IOException; +-import java.net.InetSocketAddress; +-import java.nio.charset.StandardCharsets; +-import java.util.concurrent.CountDownLatch; +-import java.util.concurrent.ExecutionException; +-import java.util.concurrent.Future; +-import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.awaitility.Awaitility.await; +-import static org.junit.jupiter.api.Assertions.fail; +-import static org.mockito.ArgumentMatchers.any; +-import static org.mockito.ArgumentMatchers.eq; +-import static org.mockito.Mockito.atLeastOnce; +-import static org.mockito.Mockito.spy; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- + @ExtendWith(MockitoExtension.class) +-class InstrumentedHttpAsyncClientsTest { +- +- @Mock +- private HttpClientMetricNameStrategy metricNameStrategy; +- @Mock +- private MetricRegistryListener registryListener; +- private HttpServer httpServer; +- private MetricRegistry metricRegistry; +- private CloseableHttpAsyncClient client; +- +- @BeforeEach +- void setUp() throws IOException { +- httpServer = HttpServer.create(new InetSocketAddress(0), 0); +- +- metricRegistry = new MetricRegistry(); +- metricRegistry.addListener(registryListener); ++final class InstrumentedHttpAsyncClientsTest { ++ ++ @Mock private HttpClientMetricNameStrategy metricNameStrategy; ++ @Mock private MetricRegistryListener registryListener; ++ private HttpServer httpServer; ++ private MetricRegistry metricRegistry; ++ private CloseableHttpAsyncClient client; ++ ++ @BeforeEach ++ void setUp() throws IOException { ++ httpServer = HttpServer.create(new InetSocketAddress(0), 0); ++ ++ metricRegistry = new MetricRegistry(); ++ metricRegistry.addListener(registryListener); ++ } ++ ++ @AfterEach ++ void tearDown() throws IOException { ++ if (client != null) { ++ client.close(); + } +- +- @AfterEach +- void tearDown() throws IOException { +- if (client != null) { +- client.close(); +- } +- if (httpServer != null) { +- httpServer.stop(0); +- } ++ if (httpServer != null) { ++ httpServer.stop(0); + } +- +- @Test +- void registersExpectedMetricsGivenNameStrategy() throws Exception { +- client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); +- client.start(); +- +- final SimpleHttpRequest request = SimpleRequestBuilder +- .get("http://localhost:" + httpServer.getAddress().getPort() + "/") +- .build(); +- final MetricName metricName = MetricName.build("some.made.up.metric.name"); +- +- httpServer.createContext("/", exchange -> { +- exchange.sendResponseHeaders(200, 0L); +- exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); +- exchange.close(); ++ } ++ ++ @Test ++ void registersExpectedMetricsGivenNameStrategy() throws Exception { ++ client = ++ InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy) ++ .disableAutomaticRetries() ++ .build(); ++ client.start(); ++ ++ final SimpleHttpRequest request = ++ SimpleRequestBuilder.get("http://localhost:" + httpServer.getAddress().getPort() + "/") ++ .build(); ++ final MetricName metricName = MetricName.build("some.made.up.metric.name"); ++ ++ httpServer.createContext( ++ "/", ++ exchange -> { ++ exchange.sendResponseHeaders(200, 0L); ++ exchange.setStreams(null, null); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); ++ exchange.close(); + }); +- httpServer.start(); ++ httpServer.start(); + +- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); ++ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); + +- final Future responseFuture = client.execute(request, new FutureCallback() { +- @Override +- public void completed(SimpleHttpResponse result) { ++ final Future responseFuture = ++ client.execute( ++ request, ++ new FutureCallback() { ++ @Override ++ public void completed(SimpleHttpResponse result) { + assertThat(result.getBodyText()).isEqualTo("TEST"); +- } ++ } + +- @Override +- public void failed(Exception ex) { ++ @Override ++ public void failed(Exception ex) { + fail(); +- } ++ } + +- @Override +- public void cancelled() { ++ @Override ++ public void cancelled() { + fail(); +- } +- }); +- responseFuture.get(1L, TimeUnit.SECONDS); +- +- verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); +- } +- +- @Test +- void registersExpectedExceptionMetrics() throws Exception { +- client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); +- client.start(); +- +- final CountDownLatch countDownLatch = new CountDownLatch(1); +- final SimpleHttpRequest request = SimpleRequestBuilder +- .get("http://localhost:" + httpServer.getAddress().getPort() + "/") +- .build(); +- final MetricName requestMetricName = MetricName.build("request"); +- final MetricName exceptionMetricName = MetricName.build("exception"); +- +- httpServer.createContext("/", HttpExchange::close); +- httpServer.start(); +- +- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) +- .thenReturn(requestMetricName); +- when(metricNameStrategy.getNameFor(any(), any(Exception.class))) +- .thenReturn(exceptionMetricName); +- +- try { +- final Future responseFuture = client.execute(request, new FutureCallback() { ++ } ++ }); ++ responseFuture.get(1L, TimeUnit.SECONDS); ++ ++ verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); ++ } ++ ++ @Test ++ void registersExpectedExceptionMetrics() throws Exception { ++ client = ++ InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy) ++ .disableAutomaticRetries() ++ .build(); ++ client.start(); ++ ++ final CountDownLatch countDownLatch = new CountDownLatch(1); ++ final SimpleHttpRequest request = ++ SimpleRequestBuilder.get("http://localhost:" + httpServer.getAddress().getPort() + "/") ++ .build(); ++ final MetricName requestMetricName = MetricName.build("request"); ++ final MetricName exceptionMetricName = MetricName.build("exception"); ++ ++ httpServer.createContext("/", HttpExchange::close); ++ httpServer.start(); ++ ++ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) ++ .thenReturn(requestMetricName); ++ when(metricNameStrategy.getNameFor(any(), any(Exception.class))) ++ .thenReturn(exceptionMetricName); ++ ++ try { ++ final Future responseFuture = ++ client.execute( ++ request, ++ new FutureCallback() { + @Override + public void completed(SimpleHttpResponse result) { +- fail(); ++ fail(); + } + + @Override + public void failed(Exception ex) { +- countDownLatch.countDown(); ++ countDownLatch.countDown(); + } + + @Override + public void cancelled() { +- fail(); ++ fail(); + } +- }); +- countDownLatch.await(5, TimeUnit.SECONDS); +- responseFuture.get(5, TimeUnit.SECONDS); +- +- fail(); +- } catch (ExecutionException e) { +- assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class); +- await().atMost(5, TimeUnit.SECONDS) +- .untilAsserted(() -> assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception"))); +- } ++ }); ++ countDownLatch.await(5, TimeUnit.SECONDS); ++ responseFuture.get(5, TimeUnit.SECONDS); ++ ++ fail(); ++ } catch (ExecutionException e) { ++ assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class); ++ await() ++ .atMost(5, TimeUnit.SECONDS) ++ .untilAsserted( ++ () -> ++ assertThat(metricRegistry.getMeters()) ++ .containsKey(MetricName.build("exception"))); + } ++ } ++ ++ @Test ++ void usesCustomClientConnectionManager() throws Exception { ++ try (PoolingAsyncClientConnectionManager clientConnectionManager = ++ spy(new PoolingAsyncClientConnectionManager())) { ++ client = ++ InstrumentedHttpAsyncClients.custom( ++ metricRegistry, metricNameStrategy, clientConnectionManager) ++ .disableAutomaticRetries() ++ .build(); ++ client.start(); ++ ++ final SimpleHttpRequest request = ++ SimpleRequestBuilder.get("http://localhost:" + httpServer.getAddress().getPort() + "/") ++ .build(); ++ final MetricName metricName = MetricName.build("some.made.up.metric.name"); ++ ++ httpServer.createContext( ++ "/", ++ exchange -> { ++ exchange.sendResponseHeaders(200, 0L); ++ exchange.setStreams(null, null); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); ++ exchange.close(); ++ }); ++ httpServer.start(); + +- @Test +- void usesCustomClientConnectionManager() throws Exception { +- try (PoolingAsyncClientConnectionManager clientConnectionManager = spy(new PoolingAsyncClientConnectionManager())) { +- client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy, clientConnectionManager).disableAutomaticRetries().build(); +- client.start(); +- +- final SimpleHttpRequest request = SimpleRequestBuilder +- .get("http://localhost:" + httpServer.getAddress().getPort() + "/") +- .build(); +- final MetricName metricName = MetricName.build("some.made.up.metric.name"); +- +- httpServer.createContext("/", exchange -> { +- exchange.sendResponseHeaders(200, 0L); +- exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); +- exchange.close(); +- }); +- httpServer.start(); +- +- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); ++ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); + +- final Future responseFuture = client.execute(request, new FutureCallback() { ++ final Future responseFuture = ++ client.execute( ++ request, ++ new FutureCallback() { + @Override + public void completed(SimpleHttpResponse result) { +- assertThat(result.getCode()).isEqualTo(200); ++ assertThat(result.getCode()).isEqualTo(200); + } + + @Override + public void failed(Exception ex) { +- fail(); ++ fail(); + } + + @Override + public void cancelled() { +- fail(); ++ fail(); + } +- }); +- responseFuture.get(1L, TimeUnit.SECONDS); ++ }); ++ responseFuture.get(1L, TimeUnit.SECONDS); + +- verify(clientConnectionManager, atLeastOnce()).connect(any(), any(), any(), any(), any(), any()); +- } ++ verify(clientConnectionManager, atLeastOnce()) ++ .connect(any(), any(), any(), any(), any(), any()); + } ++ } + } +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java +@@ -1,49 +1,58 @@ + package io.dropwizard.metrics5.httpclient5; + +-import io.dropwizard.metrics5.MetricName; +-import io.dropwizard.metrics5.MetricRegistry; +-import org.junit.jupiter.api.Test; +-import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertTrue; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; ++ ++import io.dropwizard.metrics5.MetricName; ++import io.dropwizard.metrics5.MetricRegistry; ++import org.junit.jupiter.api.Test; ++import org.mockito.ArgumentCaptor; + +-class InstrumentedHttpClientConnectionManagerTest { +- private final MetricRegistry metricRegistry = new MetricRegistry(); ++final class InstrumentedHttpClientConnectionManagerTest { ++ private final MetricRegistry metricRegistry = new MetricRegistry(); + +- @Test +- void shouldRemoveGauges() { +- final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); +- assertThat(metricRegistry.getGauges().entrySet().stream() ++ @Test ++ void shouldRemoveGauges() { ++ final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = ++ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); ++ assertThat( ++ metricRegistry.getGauges().entrySet().stream() + .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) +- .containsOnly(entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.available-connections", 0), +- entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.leased-connections", 0), +- entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.max-connections", 25), +- entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.pending-connections", 0)); +- +- instrumentedHttpClientConnectionManager.close(); +- assertEquals(0, metricRegistry.getGauges().size()); +- +- // should be able to create another one with the same name ("") +- InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); +- } +- +- @Test +- void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); +- +- InstrumentedHttpClientConnectionManager.builder(registry) +- .name("some-name") +- .name("some-other-name") +- .build() +- .close(); +- +- ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); +- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); +- } ++ .containsOnly( ++ entry( ++ "org.apache.hc.client5.http.io.HttpClientConnectionManager.available-connections", ++ 0), ++ entry( ++ "org.apache.hc.client5.http.io.HttpClientConnectionManager.leased-connections", 0), ++ entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.max-connections", 25), ++ entry( ++ "org.apache.hc.client5.http.io.HttpClientConnectionManager.pending-connections", ++ 0)); ++ ++ instrumentedHttpClientConnectionManager.close(); ++ assertEquals(0, metricRegistry.getGauges().size()); ++ ++ // should be able to create another one with the same name ("") ++ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); ++ } ++ ++ @Test ++ void configurableViaBuilder() { ++ final MetricRegistry registry = mock(); ++ ++ InstrumentedHttpClientConnectionManager.builder(registry) ++ .name("some-name") ++ .name("some-other-name") ++ .build() ++ .close(); ++ ++ ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); ++ } + } +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java +@@ -1,11 +1,20 @@ + package io.dropwizard.metrics5.httpclient5; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; ++import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.ArgumentMatchers.eq; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import com.sun.net.httpserver.HttpExchange; + import com.sun.net.httpserver.HttpServer; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricRegistryListener; + import io.dropwizard.metrics5.Timer; ++import java.net.InetSocketAddress; + import org.apache.hc.client5.http.classic.HttpClient; + import org.apache.hc.client5.http.classic.methods.HttpGet; + import org.apache.hc.core5.http.HttpRequest; +@@ -13,66 +22,55 @@ import org.apache.hc.core5.http.NoHttpResponseException; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.net.InetSocketAddress; ++final class InstrumentedHttpClientsTest { ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); ++ private final MetricRegistry metricRegistry = new MetricRegistry(); ++ private final HttpClient client = ++ InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) ++ .disableAutomaticRetries() ++ .build(); + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; +-import static org.mockito.ArgumentMatchers.any; +-import static org.mockito.ArgumentMatchers.eq; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; ++ @BeforeEach ++ void setUp() { ++ metricRegistry.addListener(registryListener); ++ } + +-class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = +- mock(MetricRegistryListener.class); +- private final MetricRegistry metricRegistry = new MetricRegistry(); +- private final HttpClient client = +- InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); ++ @Test ++ void registersExpectedMetricsGivenNameStrategy() throws Exception { ++ final HttpGet get = new HttpGet("http://example.com?q=anything"); ++ final MetricName metricName = MetricName.build("some.made.up.metric.name"); + +- @BeforeEach +- void setUp() { +- metricRegistry.addListener(registryListener); +- } +- +- @Test +- void registersExpectedMetricsGivenNameStrategy() throws Exception { +- final HttpGet get = new HttpGet("http://example.com?q=anything"); +- final MetricName metricName = MetricName.build("some.made.up.metric.name"); ++ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); + +- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) +- .thenReturn(metricName); ++ client.execute(get); + +- client.execute(get); +- +- verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); +- } ++ verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); ++ } + +- @Test +- void registersExpectedExceptionMetrics() throws Exception { +- HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); ++ @Test ++ void registersExpectedExceptionMetrics() throws Exception { ++ HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); + +- final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); +- final MetricName requestMetricName = MetricName.build("request"); +- final MetricName exceptionMetricName = MetricName.build("exception"); ++ final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); ++ final MetricName requestMetricName = MetricName.build("request"); ++ final MetricName exceptionMetricName = MetricName.build("exception"); + +- httpServer.createContext("/", HttpExchange::close); +- httpServer.start(); ++ httpServer.createContext("/", HttpExchange::close); ++ httpServer.start(); + +- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) +- .thenReturn(requestMetricName); +- when(metricNameStrategy.getNameFor(any(), any(Exception.class))) +- .thenReturn(exceptionMetricName); ++ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) ++ .thenReturn(requestMetricName); ++ when(metricNameStrategy.getNameFor(any(), any(Exception.class))) ++ .thenReturn(exceptionMetricName); + +- try { +- client.execute(get); +- fail(); +- } catch (NoHttpResponseException expected) { +- assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); +- } finally { +- httpServer.stop(0); +- } ++ try { ++ client.execute(get); ++ fail(); ++ } catch (NoHttpResponseException expected) { ++ assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); ++ } finally { ++ httpServer.stop(0); + } ++ } + } +--- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/GarbageFreeScheduledReporter.java ++++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/GarbageFreeScheduledReporter.java +@@ -11,7 +11,6 @@ import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricRegistryListener; + import io.dropwizard.metrics5.ScheduledReporter; + import io.dropwizard.metrics5.Timer; +- + import java.util.Set; + import java.util.SortedMap; + import java.util.concurrent.ConcurrentSkipListMap; +@@ -20,135 +19,149 @@ import java.util.concurrent.TimeUnit; + + abstract class GarbageFreeScheduledReporter extends ScheduledReporter { + +- private final MetricRegistry registry; +- private final RegistryMirror mirror; ++ private final MetricRegistry registry; ++ private final RegistryMirror mirror; ++ ++ protected GarbageFreeScheduledReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes) { ++ super( ++ registry, ++ name, ++ filter, ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes); ++ this.registry = registry; ++ this.mirror = new RegistryMirror(filter); ++ registry.addListener(mirror); ++ } ++ ++ @Override ++ public void stop() { ++ try { ++ super.stop(); ++ } finally { ++ registry.removeListener(mirror); ++ } ++ } ++ ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report() { ++ synchronized (this) { ++ report( ++ mirror.gauges(), ++ mirror.counters(), ++ mirror.histograms(), ++ mirror.meters(), ++ mirror.timers()); ++ } ++ } ++ ++ @SuppressWarnings("rawtypes") // because of signature (for Gauge) in ScheduledReporter#report(..) ++ private static class RegistryMirror implements MetricRegistryListener { ++ ++ private final MetricFilter filter; ++ private final ConcurrentSkipListMap> gauges = ++ new ConcurrentSkipListMap<>(); ++ private final ConcurrentSkipListMap counters = ++ new ConcurrentSkipListMap<>(); ++ private final ConcurrentSkipListMap histograms = ++ new ConcurrentSkipListMap<>(); ++ private final ConcurrentSkipListMap meters = new ConcurrentSkipListMap<>(); ++ private final ConcurrentSkipListMap timers = new ConcurrentSkipListMap<>(); ++ ++ RegistryMirror(MetricFilter filter) { ++ this.filter = filter; ++ } ++ ++ SortedMap> gauges() { ++ return gauges; ++ } ++ ++ SortedMap counters() { ++ return counters; ++ } ++ ++ SortedMap histograms() { ++ return histograms; ++ } ++ ++ SortedMap meters() { ++ return meters; ++ } ++ ++ SortedMap timers() { ++ return timers; ++ } ++ ++ @Override ++ public void onGaugeAdded(MetricName name, Gauge gauge) { ++ if (filter.matches(name, gauge)) { ++ gauges.put(name, gauge); ++ } ++ } ++ ++ @Override ++ public void onGaugeRemoved(MetricName name) { ++ gauges.remove(name); ++ } + +- protected GarbageFreeScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, +- TimeUnit durationUnit, ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop, +- Set disabledMetricAttributes) { +- super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, disabledMetricAttributes); +- this.registry = registry; +- this.mirror = new RegistryMirror(filter); +- registry.addListener(mirror); ++ @Override ++ public void onCounterAdded(MetricName name, Counter counter) { ++ if (filter.matches(name, counter)) { ++ counters.put(name, counter); ++ } + } + + @Override +- public void stop() { +- try { +- super.stop(); +- } finally { +- registry.removeListener(mirror); +- } ++ public void onCounterRemoved(MetricName name) { ++ counters.remove(name); + } + + @Override +- @SuppressWarnings("rawtypes") +- public void report() { +- synchronized (this) { +- report(mirror.gauges(), +- mirror.counters(), +- mirror.histograms(), +- mirror.meters(), +- mirror.timers()); +- } +- } +- +- @SuppressWarnings("rawtypes") // because of signature (for Gauge) in ScheduledReporter#report(..) +- private static class RegistryMirror implements MetricRegistryListener { +- +- private final MetricFilter filter; +- private final ConcurrentSkipListMap> gauges = new ConcurrentSkipListMap<>(); +- private final ConcurrentSkipListMap counters = new ConcurrentSkipListMap<>(); +- private final ConcurrentSkipListMap histograms = new ConcurrentSkipListMap<>(); +- private final ConcurrentSkipListMap meters = new ConcurrentSkipListMap<>(); +- private final ConcurrentSkipListMap timers = new ConcurrentSkipListMap<>(); +- +- RegistryMirror(MetricFilter filter) { +- this.filter = filter; +- } +- +- SortedMap> gauges() { +- return gauges; +- } +- +- SortedMap counters() { +- return counters; +- } +- +- SortedMap histograms() { +- return histograms; +- } +- +- SortedMap meters() { +- return meters; +- } +- +- SortedMap timers() { +- return timers; +- } +- +- +- @Override +- public void onGaugeAdded(MetricName name, Gauge gauge) { +- if (filter.matches(name, gauge)) { +- gauges.put(name, gauge); +- } +- } +- +- @Override +- public void onGaugeRemoved(MetricName name) { +- gauges.remove(name); +- } +- +- @Override +- public void onCounterAdded(MetricName name, Counter counter) { +- if (filter.matches(name, counter)) { +- counters.put(name, counter); +- } +- } +- +- @Override +- public void onCounterRemoved(MetricName name) { +- counters.remove(name); +- } +- +- @Override +- public void onHistogramAdded(MetricName name, Histogram histogram) { +- if (filter.matches(name, histogram)) { +- histograms.put(name, histogram); +- } +- } +- +- @Override +- public void onHistogramRemoved(MetricName name) { +- histograms.remove(name); +- } +- +- @Override +- public void onMeterAdded(MetricName name, Meter meter) { +- if (filter.matches(name, meter)) { +- meters.put(name, meter); +- } +- } +- +- @Override +- public void onMeterRemoved(MetricName name) { +- meters.remove(name); +- } +- +- @Override +- public void onTimerAdded(MetricName name, Timer timer) { +- if (filter.matches(name, timer)) { +- timers.put(name, timer); +- } +- } +- +- @Override +- public void onTimerRemoved(MetricName name) { +- timers.remove(name); +- } ++ public void onHistogramAdded(MetricName name, Histogram histogram) { ++ if (filter.matches(name, histogram)) { ++ histograms.put(name, histogram); ++ } ++ } + ++ @Override ++ public void onHistogramRemoved(MetricName name) { ++ histograms.remove(name); ++ } ++ ++ @Override ++ public void onMeterAdded(MetricName name, Meter meter) { ++ if (filter.matches(name, meter)) { ++ meters.put(name, meter); ++ } + } + ++ @Override ++ public void onMeterRemoved(MetricName name) { ++ meters.remove(name); ++ } ++ ++ @Override ++ public void onTimerAdded(MetricName name, Timer timer) { ++ if (filter.matches(name, timer)) { ++ timers.put(name, timer); ++ } ++ } ++ ++ @Override ++ public void onTimerRemoved(MetricName name) { ++ timers.remove(name); ++ } ++ } + } +--- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilder.java ++++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilder.java +@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.influxdb; + + import io.dropwizard.metrics5.MetricAttribute; + import io.dropwizard.metrics5.MetricName; +- + import java.util.Map; + import java.util.Set; + import java.util.WeakHashMap; +@@ -29,136 +28,135 @@ import java.util.WeakHashMap; + */ + class InfluxDbLineBuilder { + +- private final StringBuilder str = new StringBuilder(); +- private boolean firstField; +- +- private final Set disabledMetricAttributes; +- private final MetricName prefix; +- private final Map encodedNameCache = new WeakHashMap<>(); +- +- InfluxDbLineBuilder(Set disabledMetricAttributes, MetricName prefix) { +- this.disabledMetricAttributes = disabledMetricAttributes; +- this.prefix = prefix != null ? prefix : MetricName.empty(); +- } +- +- InfluxDbLineBuilder writeMeasurement(MetricName name) { +- str.setLength(0); +- str.append(encodedNameCache.computeIfAbsent(name, this::writeMeasurementNoCache)); +- str.append(' '); +- firstField = true; +- return this; +- } +- +- private String writeMeasurementNoCache(MetricName name) { +- StringBuilder sb = new StringBuilder(); +- +- MetricName prefixedName = prefix.append(name); +- appendName(prefixedName.getKey(), sb); +- // InfluxDB Performance and Setup Tips: +- // Sort tags by key before sending them to the database. +- // The sort should match the results from the Go bytes.Compare function. +- // ... tags are already sorted in MetricName +- for (Map.Entry tag : prefixedName.getTags().entrySet()) { +- sb.append(','); +- appendName(tag.getKey(), sb); +- sb.append('='); +- appendName(tag.getValue(), sb); +- } +- return sb.toString(); +- } +- +- InfluxDbLineBuilder writeField(MetricAttribute key) { +- if (!firstField) { +- str.append(','); +- } +- str.append(key.getCode()).append('='); +- firstField = false; +- return this; +- } +- +- InfluxDbLineBuilder writeField(String key) { +- if (!firstField) { +- str.append(','); +- } +- appendName(key, str); +- str.append('='); +- firstField = false; +- return this; +- } +- +- InfluxDbLineBuilder writeFieldValue(double value) { +- str.append(value); +- return this; +- } +- +- InfluxDbLineBuilder writeFieldValue(long value) { +- str.append(value).append('i'); +- return this; +- } +- +- InfluxDbLineBuilder writeFieldValue(String value) { +- str.append('"'); +- appendString(value, str); +- str.append('"'); +- return this; +- } +- +- InfluxDbLineBuilder writeFieldValue(boolean value) { +- str.append(value ? 't' : 'f'); +- return this; +- } +- +- InfluxDbLineBuilder writeTimestampMillis(long utcMillis) { +- str.append(' ').append(utcMillis).append("000000\n"); +- return this; +- } +- +- InfluxDbLineBuilder writeFieldIfEnabled(MetricAttribute key, double value) { +- if (!disabledMetricAttributes.contains(key)) { +- writeField(key); +- writeFieldValue(value); +- } +- return this; +- } +- +- InfluxDbLineBuilder writeFieldIfEnabled(MetricAttribute key, long value) { +- if (!disabledMetricAttributes.contains(key)) { +- writeField(key); +- writeFieldValue(value); +- } +- return this; +- } +- +- boolean hasValues() { +- return !firstField; +- } +- +- StringBuilder get() { +- return str; +- } +- +- private static void appendName(CharSequence field, StringBuilder dst) { +- int len = field.length(); +- for (int i = 0; i < len; i++) { +- char ch = field.charAt(i); +- if (ch == ',' || ch == '=' || ch == ' ') { +- // escape +- dst.append('\\'); +- } +- dst.append(ch); +- } +- } +- +- private static void appendString(CharSequence field, StringBuilder dst) { +- int len = field.length(); +- for (int i = 0; i < len; i++) { +- char ch = field.charAt(i); +- if (ch == '"') { +- // escape +- dst.append('\\'); +- } +- dst.append(ch); +- } +- } +- ++ private final StringBuilder str = new StringBuilder(); ++ private boolean firstField; ++ ++ private final Set disabledMetricAttributes; ++ private final MetricName prefix; ++ private final Map encodedNameCache = new WeakHashMap<>(); ++ ++ InfluxDbLineBuilder(Set disabledMetricAttributes, MetricName prefix) { ++ this.disabledMetricAttributes = disabledMetricAttributes; ++ this.prefix = prefix != null ? prefix : MetricName.empty(); ++ } ++ ++ InfluxDbLineBuilder writeMeasurement(MetricName name) { ++ str.setLength(0); ++ str.append(encodedNameCache.computeIfAbsent(name, this::writeMeasurementNoCache)); ++ str.append(' '); ++ firstField = true; ++ return this; ++ } ++ ++ private String writeMeasurementNoCache(MetricName name) { ++ StringBuilder sb = new StringBuilder(); ++ ++ MetricName prefixedName = prefix.append(name); ++ appendName(prefixedName.getKey(), sb); ++ // InfluxDB Performance and Setup Tips: ++ // Sort tags by key before sending them to the database. ++ // The sort should match the results from the Go bytes.Compare function. ++ // ... tags are already sorted in MetricName ++ for (Map.Entry tag : prefixedName.getTags().entrySet()) { ++ sb.append(','); ++ appendName(tag.getKey(), sb); ++ sb.append('='); ++ appendName(tag.getValue(), sb); ++ } ++ return sb.toString(); ++ } ++ ++ InfluxDbLineBuilder writeField(MetricAttribute key) { ++ if (!firstField) { ++ str.append(','); ++ } ++ str.append(key.getCode()).append('='); ++ firstField = false; ++ return this; ++ } ++ ++ InfluxDbLineBuilder writeField(String key) { ++ if (!firstField) { ++ str.append(','); ++ } ++ appendName(key, str); ++ str.append('='); ++ firstField = false; ++ return this; ++ } ++ ++ InfluxDbLineBuilder writeFieldValue(double value) { ++ str.append(value); ++ return this; ++ } ++ ++ InfluxDbLineBuilder writeFieldValue(long value) { ++ str.append(value).append('i'); ++ return this; ++ } ++ ++ InfluxDbLineBuilder writeFieldValue(String value) { ++ str.append('"'); ++ appendString(value, str); ++ str.append('"'); ++ return this; ++ } ++ ++ InfluxDbLineBuilder writeFieldValue(boolean value) { ++ str.append(value ? 't' : 'f'); ++ return this; ++ } ++ ++ InfluxDbLineBuilder writeTimestampMillis(long utcMillis) { ++ str.append(' ').append(utcMillis).append("000000\n"); ++ return this; ++ } ++ ++ InfluxDbLineBuilder writeFieldIfEnabled(MetricAttribute key, double value) { ++ if (!disabledMetricAttributes.contains(key)) { ++ writeField(key); ++ writeFieldValue(value); ++ } ++ return this; ++ } ++ ++ InfluxDbLineBuilder writeFieldIfEnabled(MetricAttribute key, long value) { ++ if (!disabledMetricAttributes.contains(key)) { ++ writeField(key); ++ writeFieldValue(value); ++ } ++ return this; ++ } ++ ++ boolean hasValues() { ++ return !firstField; ++ } ++ ++ StringBuilder get() { ++ return str; ++ } ++ ++ private static void appendName(CharSequence field, StringBuilder dst) { ++ int len = field.length(); ++ for (int i = 0; i < len; i++) { ++ char ch = field.charAt(i); ++ if (ch == ',' || ch == '=' || ch == ' ') { ++ // escape ++ dst.append('\\'); ++ } ++ dst.append(ch); ++ } ++ } ++ ++ private static void appendString(CharSequence field, StringBuilder dst) { ++ int len = field.length(); ++ for (int i = 0; i < len; i++) { ++ char ch = field.charAt(i); ++ if (ch == '"') { ++ // escape ++ dst.append('\\'); ++ } ++ dst.append(ch); ++ } ++ } + } +--- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java ++++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java +@@ -1,5 +1,8 @@ + package io.dropwizard.metrics5.influxdb; + ++import static io.dropwizard.metrics5.MetricAttribute.*; ++ ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -7,369 +10,393 @@ import io.dropwizard.metrics5.Histogram; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.Metered; + import io.dropwizard.metrics5.MetricAttribute; +-import io.dropwizard.metrics5.MetricName; +- +-import java.util.Map; +- +-import static io.dropwizard.metrics5.MetricAttribute.*; +- + import io.dropwizard.metrics5.MetricFilter; ++import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +- + import java.io.IOException; +-import java.util.Collections; ++import java.util.Map; + import java.util.Set; + import java.util.SortedMap; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; +- + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + + /** + * A reporter which publishes metric values to InfluxDB. +- *

+- * Metrics are reported according to the +- * InfluxDB Line Protocol. +- * Brief line protocol syntax as follows: ++ * ++ *

Metrics are reported according to the InfluxDB ++ * Line Protocol. Brief line protocol syntax as follows: ++ * + *

+  * measurement(,tag_key=tag_val)* field_key=field_val(,field_key_n=field_value_n)* (nanoseconds-timestamp)?
+  * 
++ * + *

+- *

+- * This InfluxDB reporter is "garbage free" in steady state. +- * This means objects and buffers are reused and no temporary objects are allocated as much as possible. ++ * ++ *

This InfluxDB reporter is "garbage free" in steady state. This means objects and buffers are ++ * reused and no temporary objects are allocated as much as possible. + */ + public class InfluxDbReporter extends GarbageFreeScheduledReporter { + ++ /** ++ * Returns a new Builder for {@link InfluxDbReporter}. ++ * ++ * @param registry the registry to report ++ * @return a Builder instance for a {@link InfluxDbReporter} ++ */ ++ public static Builder forRegistry(MetricRegistry registry) { ++ return new Builder(registry); ++ } ++ ++ /** ++ * A builder for {@link InfluxDbReporter} instances. Defaults to not using a prefix, using the ++ * default clock, converting rates to events/second, converting durations to milliseconds, and not ++ * filtering metrics. ++ */ ++ public static class Builder { ++ ++ private final MetricRegistry registry; ++ private Clock clock; ++ private MetricName prefix; ++ private TimeUnit rateUnit; ++ private TimeUnit durationUnit; ++ private MetricFilter filter; ++ private ScheduledExecutorService executor; ++ private boolean shutdownExecutorOnStop; ++ private Set disabledMetricAttributes; ++ ++ private Builder(MetricRegistry registry) { ++ this.registry = registry; ++ this.clock = Clock.defaultClock(); ++ this.prefix = null; ++ this.rateUnit = TimeUnit.SECONDS; ++ this.durationUnit = TimeUnit.MILLISECONDS; ++ this.filter = MetricFilter.ALL; ++ this.executor = null; ++ this.shutdownExecutorOnStop = true; ++ this.disabledMetricAttributes = ImmutableSet.of(); ++ } ++ + /** +- * Returns a new Builder for {@link InfluxDbReporter}. ++ * Specifies whether or not, the executor (used for reporting) will be stopped with same time ++ * with reporter. Default value is true. Setting this parameter to false, has the sense in ++ * combining with providing external managed executor via {@link ++ * #scheduleOn(ScheduledExecutorService)}. + * +- * @param registry the registry to report +- * @return a Builder instance for a {@link InfluxDbReporter} ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ * @return {@code this} + */ +- public static Builder forRegistry(MetricRegistry registry) { +- return new Builder(registry); ++ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { ++ this.shutdownExecutorOnStop = shutdownExecutorOnStop; ++ return this; + } + + /** +- * A builder for {@link InfluxDbReporter} instances. Defaults to not using a prefix, using the +- * default clock, converting rates to events/second, converting durations to milliseconds, and +- * not filtering metrics. ++ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. ++ * Null value leads to executor will be auto created on start. ++ * ++ * @param executor the executor to use while scheduling reporting of metrics. ++ * @return {@code this} + */ +- public static class Builder { +- +- private final MetricRegistry registry; +- private Clock clock; +- private MetricName prefix; +- private TimeUnit rateUnit; +- private TimeUnit durationUnit; +- private MetricFilter filter; +- private ScheduledExecutorService executor; +- private boolean shutdownExecutorOnStop; +- private Set disabledMetricAttributes; +- +- private Builder(MetricRegistry registry) { +- this.registry = registry; +- this.clock = Clock.defaultClock(); +- this.prefix = null; +- this.rateUnit = TimeUnit.SECONDS; +- this.durationUnit = TimeUnit.MILLISECONDS; +- this.filter = MetricFilter.ALL; +- this.executor = null; +- this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); +- } +- +- /** +- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. +- * Default value is true. +- * Setting this parameter to false, has the sense in combining with providing external managed executor via +- * {@link #scheduleOn(ScheduledExecutorService)}. +- * +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- * @return {@code this} +- */ +- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { +- this.shutdownExecutorOnStop = shutdownExecutorOnStop; +- return this; +- } +- +- /** +- * Specifies the executor to use while scheduling reporting of metrics. +- * Default value is null. +- * Null value leads to executor will be auto created on start. +- * +- * @param executor the executor to use while scheduling reporting of metrics. +- * @return {@code this} +- */ +- public Builder scheduleOn(ScheduledExecutorService executor) { +- this.executor = executor; +- return this; +- } +- +- /** +- * Use the given {@link Clock} instance for the time. +- * +- * @param clock a {@link Clock} instance +- * @return {@code this} +- */ +- public Builder withClock(Clock clock) { +- this.clock = clock; +- return this; +- } +- +- /** +- * Prefix all metric names with the given name. +- * +- * @param prefix the prefix for all metric names +- * @return {@code this} +- */ +- public Builder prefixedWith(MetricName prefix) { +- this.prefix = prefix; +- return this; +- } +- +- /** +- * Convert rates to the given time unit. +- * +- * @param rateUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertRatesTo(TimeUnit rateUnit) { +- this.rateUnit = rateUnit; +- return this; +- } +- +- /** +- * Convert durations to the given time unit. +- * +- * @param durationUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertDurationsTo(TimeUnit durationUnit) { +- this.durationUnit = durationUnit; +- return this; +- } +- +- /** +- * Only report metrics which match the given filter. +- * +- * @param filter a {@link MetricFilter} +- * @return {@code this} +- */ +- public Builder filter(MetricFilter filter) { +- this.filter = filter; +- return this; +- } +- +- /** +- * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). +- * +- * @param disabledMetricAttributes the disabled metric attributes +- * @return {@code this} +- */ +- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { +- this.disabledMetricAttributes = disabledMetricAttributes; +- return this; +- } +- +- /** +- * Builds a InfluxDbReporter with the given properties, sending metrics using the +- * given InfluxDbSender. +- * +- * @param sender the InfluxDbSender +- * @return the InfluxDbReporter +- */ +- public InfluxDbReporter build(InfluxDbSender sender) { +- return new InfluxDbReporter(registry, sender, clock, prefix, rateUnit, durationUnit, filter, executor, +- shutdownExecutorOnStop, disabledMetricAttributes); +- } ++ public Builder scheduleOn(ScheduledExecutorService executor) { ++ this.executor = executor; ++ return this; + } + +- private static final Logger LOGGER = LoggerFactory.getLogger(InfluxDbReporter.class); +- private static final String VALUE = "value"; +- +- private final Clock clock; +- private final InfluxDbSender sender; +- private final InfluxDbLineBuilder builder; +- + /** +- * Creates a new InfluxDbReporter instance. ++ * Use the given {@link Clock} instance for the time. + * +- * @param registry the MetricRegistry containing the metrics this reporter will report +- * @param sender the InfluxDbSender which is responsible for sending metrics to a influxdb +- * server via a transport protocol +- * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default +- * @param prefix the prefix of all metric names (may be null) +- * @param rateUnit the time unit of in which rates will be converted +- * @param durationUnit the time unit of in which durations will be converted +- * @param filter the filter for which metrics to report +- * @param executor the executor to use while scheduling reporting of metrics (may be null). +- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter +- * @param disabledMetricAttributes the disable metric attributes ++ * @param clock a {@link Clock} instance ++ * @return {@code this} + */ +- public InfluxDbReporter(MetricRegistry registry, InfluxDbSender sender, Clock clock, MetricName prefix, +- TimeUnit rateUnit, TimeUnit durationUnit, MetricFilter filter, ScheduledExecutorService executor, +- boolean shutdownExecutorOnStop, Set disabledMetricAttributes) { +- super(registry, "influxdb-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, +- disabledMetricAttributes); +- this.sender = sender; +- this.clock = clock; +- this.builder = new InfluxDbLineBuilder(disabledMetricAttributes, prefix); ++ public Builder withClock(Clock clock) { ++ this.clock = clock; ++ return this; + } + +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap> gauges, +- SortedMap counters, +- SortedMap histograms, +- SortedMap meters, +- SortedMap timers) { +- +- final long timestamp = clock.getTime(); +- +- try { +- sender.connect(); +- +- for (Map.Entry> entry : gauges.entrySet()) { +- reportGauge(entry.getKey(), entry.getValue(), timestamp); +- } +- +- for (Map.Entry entry : counters.entrySet()) { +- reportCounter(entry.getKey(), entry.getValue(), timestamp); +- } +- +- for (Map.Entry entry : histograms.entrySet()) { +- reportHistogram(entry.getKey(), entry.getValue(), timestamp); +- } +- +- for (Map.Entry entry : meters.entrySet()) { +- reportMetered(entry.getKey(), entry.getValue(), timestamp); +- } +- +- for (Map.Entry entry : timers.entrySet()) { +- reportTimer(entry.getKey(), entry.getValue(), timestamp); +- } +- sender.flush(); +- } catch (IOException e) { +- LOGGER.warn("Unable to report to InfluxDb", sender, e); +- } finally { +- try { +- sender.disconnect(); +- } catch (IOException e) { +- LOGGER.warn("Error disconnecting InfluxDb", sender, e); +- } +- } ++ /** ++ * Prefix all metric names with the given name. ++ * ++ * @param prefix the prefix for all metric names ++ * @return {@code this} ++ */ ++ public Builder prefixedWith(MetricName prefix) { ++ this.prefix = prefix; ++ return this; + } + +- @Override +- public void stop() { +- try { +- super.stop(); +- } finally { +- try { +- sender.close(); +- } catch (IOException e) { +- LOGGER.debug("Error disconnecting from InfluxDb", e); +- } +- } ++ /** ++ * Convert rates to the given time unit. ++ * ++ * @param rateUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertRatesTo(TimeUnit rateUnit) { ++ this.rateUnit = rateUnit; ++ return this; + } + +- private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { +- final Snapshot snapshot = timer.getSnapshot(); +- builder.writeMeasurement(name) +- .writeFieldIfEnabled(MAX, convertDuration(snapshot.getMax())) +- .writeFieldIfEnabled(MEAN, convertDuration(snapshot.getMean())) +- .writeFieldIfEnabled(MIN, convertDuration(snapshot.getMin())) +- .writeFieldIfEnabled(STDDEV, convertDuration(snapshot.getStdDev())) +- .writeFieldIfEnabled(P50, convertDuration(snapshot.getMedian())) +- .writeFieldIfEnabled(P75, convertDuration(snapshot.get75thPercentile())) +- .writeFieldIfEnabled(P95, convertDuration(snapshot.get95thPercentile())) +- .writeFieldIfEnabled(P98, convertDuration(snapshot.get98thPercentile())) +- .writeFieldIfEnabled(P99, convertDuration(snapshot.get99thPercentile())) +- .writeFieldIfEnabled(P999, convertDuration(snapshot.get999thPercentile())); +- writeMeteredFieldsIfEnabled(timer) +- .writeTimestampMillis(timestamp); +- +- reportLine(); ++ /** ++ * Convert durations to the given time unit. ++ * ++ * @param durationUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertDurationsTo(TimeUnit durationUnit) { ++ this.durationUnit = durationUnit; ++ return this; + } + +- +- private void reportHistogram(MetricName name, Histogram histogram, long timestamp) throws IOException { +- final Snapshot snapshot = histogram.getSnapshot(); +- builder.writeMeasurement(name) +- .writeFieldIfEnabled(COUNT, histogram.getCount()) +- .writeFieldIfEnabled(SUM, histogram.getSum()) +- .writeFieldIfEnabled(MAX, snapshot.getMax()) +- .writeFieldIfEnabled(MEAN, snapshot.getMean()) +- .writeFieldIfEnabled(MIN, snapshot.getMin()) +- .writeFieldIfEnabled(STDDEV, snapshot.getStdDev()) +- .writeFieldIfEnabled(P50, snapshot.getMedian()) +- .writeFieldIfEnabled(P75, snapshot.get75thPercentile()) +- .writeFieldIfEnabled(P95, snapshot.get95thPercentile()) +- .writeFieldIfEnabled(P98, snapshot.get98thPercentile()) +- .writeFieldIfEnabled(P99, snapshot.get99thPercentile()) +- .writeFieldIfEnabled(P999, snapshot.get999thPercentile()) +- .writeTimestampMillis(timestamp); +- +- reportLine(); ++ /** ++ * Only report metrics which match the given filter. ++ * ++ * @param filter a {@link MetricFilter} ++ * @return {@code this} ++ */ ++ public Builder filter(MetricFilter filter) { ++ this.filter = filter; ++ return this; + } + +- +- private void reportMetered(MetricName name, Metered meter, long timestamp) throws IOException { +- builder.writeMeasurement(name); +- writeMeteredFieldsIfEnabled(meter) +- .writeTimestampMillis(timestamp); +- +- reportLine(); ++ /** ++ * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). ++ * ++ * @param disabledMetricAttributes the disabled metric attributes ++ * @return {@code this} ++ */ ++ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { ++ this.disabledMetricAttributes = disabledMetricAttributes; ++ return this; + } + +- private InfluxDbLineBuilder writeMeteredFieldsIfEnabled(Metered meter) { +- return builder.writeFieldIfEnabled(COUNT, meter.getCount()) +- .writeFieldIfEnabled(SUM, meter.getSum()) +- .writeFieldIfEnabled(M1_RATE, convertRate(meter.getOneMinuteRate())) +- .writeFieldIfEnabled(M5_RATE, convertRate(meter.getFiveMinuteRate())) +- .writeFieldIfEnabled(M15_RATE, convertRate(meter.getFifteenMinuteRate())) +- .writeFieldIfEnabled(MEAN_RATE, convertRate(meter.getMeanRate())); ++ /** ++ * Builds a InfluxDbReporter with the given properties, sending metrics using the given ++ * InfluxDbSender. ++ * ++ * @param sender the InfluxDbSender ++ * @return the InfluxDbReporter ++ */ ++ public InfluxDbReporter build(InfluxDbSender sender) { ++ return new InfluxDbReporter( ++ registry, ++ sender, ++ clock, ++ prefix, ++ rateUnit, ++ durationUnit, ++ filter, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes); + } +- +- private void reportCounter(MetricName name, Counter counter, long timestamp) throws IOException { +- builder.writeMeasurement(name) +- .writeFieldIfEnabled(COUNT, counter.getCount()) +- .writeTimestampMillis(timestamp); +- +- reportLine(); ++ } ++ ++ private static final Logger LOG = LoggerFactory.getLogger(InfluxDbReporter.class); ++ private static final String VALUE = "value"; ++ ++ private final Clock clock; ++ private final InfluxDbSender sender; ++ private final InfluxDbLineBuilder builder; ++ ++ /** ++ * Creates a new InfluxDbReporter instance. ++ * ++ * @param registry the MetricRegistry containing the metrics this reporter will report ++ * @param sender the InfluxDbSender which is responsible for sending metrics to a influxdb server ++ * via a transport protocol ++ * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default ++ * @param prefix the prefix of all metric names (may be null) ++ * @param rateUnit the time unit of in which rates will be converted ++ * @param durationUnit the time unit of in which durations will be converted ++ * @param filter the filter for which metrics to report ++ * @param executor the executor to use while scheduling reporting of metrics (may be null). ++ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this ++ * reporter ++ * @param disabledMetricAttributes the disable metric attributes ++ */ ++ public InfluxDbReporter( ++ MetricRegistry registry, ++ InfluxDbSender sender, ++ Clock clock, ++ MetricName prefix, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ MetricFilter filter, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes) { ++ super( ++ registry, ++ "influxdb-reporter", ++ filter, ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes); ++ this.sender = sender; ++ this.clock = clock; ++ this.builder = new InfluxDbLineBuilder(disabledMetricAttributes, prefix); ++ } ++ ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap> gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ ++ final long timestamp = clock.getTime(); ++ ++ try { ++ sender.connect(); ++ ++ for (Map.Entry> entry : gauges.entrySet()) { ++ reportGauge(entry.getKey(), entry.getValue(), timestamp); ++ } ++ ++ for (Map.Entry entry : counters.entrySet()) { ++ reportCounter(entry.getKey(), entry.getValue(), timestamp); ++ } ++ ++ for (Map.Entry entry : histograms.entrySet()) { ++ reportHistogram(entry.getKey(), entry.getValue(), timestamp); ++ } ++ ++ for (Map.Entry entry : meters.entrySet()) { ++ reportMetered(entry.getKey(), entry.getValue(), timestamp); ++ } ++ ++ for (Map.Entry entry : timers.entrySet()) { ++ reportTimer(entry.getKey(), entry.getValue(), timestamp); ++ } ++ sender.flush(); ++ } catch (IOException e) { ++ LOG.warn("Unable to report to InfluxDb", sender, e); ++ } finally { ++ try { ++ sender.disconnect(); ++ } catch (IOException e) { ++ LOG.warn("Error disconnecting InfluxDb", sender, e); ++ } + } +- +- private void reportGauge(MetricName name, Gauge gauge, long timestamp) throws IOException { +- builder.writeMeasurement(name); +- final Object value = gauge.getValue(); +- if (value != null) { +- builder.writeField(VALUE); +- if (value instanceof Number) { +- final Number number = (Number) value; +- if (number instanceof Long || number instanceof Integer || number instanceof Short || +- number instanceof Byte) { +- builder.writeFieldValue(number.longValue()); +- } else { +- builder.writeFieldValue(number.doubleValue()); +- } +- } else if (value instanceof Boolean) { +- builder.writeFieldValue(((Boolean) value)); +- } else { +- builder.writeFieldValue(value.toString()); +- } ++ } ++ ++ @Override ++ public void stop() { ++ try { ++ super.stop(); ++ } finally { ++ try { ++ sender.close(); ++ } catch (IOException e) { ++ LOG.debug("Error disconnecting from InfluxDb", e); ++ } ++ } ++ } ++ ++ private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { ++ final Snapshot snapshot = timer.getSnapshot(); ++ builder ++ .writeMeasurement(name) ++ .writeFieldIfEnabled(MAX, convertDuration(snapshot.getMax())) ++ .writeFieldIfEnabled(MEAN, convertDuration(snapshot.getMean())) ++ .writeFieldIfEnabled(MIN, convertDuration(snapshot.getMin())) ++ .writeFieldIfEnabled(STDDEV, convertDuration(snapshot.getStdDev())) ++ .writeFieldIfEnabled(P50, convertDuration(snapshot.getMedian())) ++ .writeFieldIfEnabled(P75, convertDuration(snapshot.get75thPercentile())) ++ .writeFieldIfEnabled(P95, convertDuration(snapshot.get95thPercentile())) ++ .writeFieldIfEnabled(P98, convertDuration(snapshot.get98thPercentile())) ++ .writeFieldIfEnabled(P99, convertDuration(snapshot.get99thPercentile())) ++ .writeFieldIfEnabled(P999, convertDuration(snapshot.get999thPercentile())); ++ writeMeteredFieldsIfEnabled(timer).writeTimestampMillis(timestamp); ++ ++ reportLine(); ++ } ++ ++ private void reportHistogram(MetricName name, Histogram histogram, long timestamp) ++ throws IOException { ++ final Snapshot snapshot = histogram.getSnapshot(); ++ builder ++ .writeMeasurement(name) ++ .writeFieldIfEnabled(COUNT, histogram.getCount()) ++ .writeFieldIfEnabled(SUM, histogram.getSum()) ++ .writeFieldIfEnabled(MAX, snapshot.getMax()) ++ .writeFieldIfEnabled(MEAN, snapshot.getMean()) ++ .writeFieldIfEnabled(MIN, snapshot.getMin()) ++ .writeFieldIfEnabled(STDDEV, snapshot.getStdDev()) ++ .writeFieldIfEnabled(P50, snapshot.getMedian()) ++ .writeFieldIfEnabled(P75, snapshot.get75thPercentile()) ++ .writeFieldIfEnabled(P95, snapshot.get95thPercentile()) ++ .writeFieldIfEnabled(P98, snapshot.get98thPercentile()) ++ .writeFieldIfEnabled(P99, snapshot.get99thPercentile()) ++ .writeFieldIfEnabled(P999, snapshot.get999thPercentile()) ++ .writeTimestampMillis(timestamp); ++ ++ reportLine(); ++ } ++ ++ private void reportMetered(MetricName name, Metered meter, long timestamp) throws IOException { ++ builder.writeMeasurement(name); ++ writeMeteredFieldsIfEnabled(meter).writeTimestampMillis(timestamp); ++ ++ reportLine(); ++ } ++ ++ private InfluxDbLineBuilder writeMeteredFieldsIfEnabled(Metered meter) { ++ return builder ++ .writeFieldIfEnabled(COUNT, meter.getCount()) ++ .writeFieldIfEnabled(SUM, meter.getSum()) ++ .writeFieldIfEnabled(M1_RATE, convertRate(meter.getOneMinuteRate())) ++ .writeFieldIfEnabled(M5_RATE, convertRate(meter.getFiveMinuteRate())) ++ .writeFieldIfEnabled(M15_RATE, convertRate(meter.getFifteenMinuteRate())) ++ .writeFieldIfEnabled(MEAN_RATE, convertRate(meter.getMeanRate())); ++ } ++ ++ private void reportCounter(MetricName name, Counter counter, long timestamp) throws IOException { ++ builder ++ .writeMeasurement(name) ++ .writeFieldIfEnabled(COUNT, counter.getCount()) ++ .writeTimestampMillis(timestamp); ++ ++ reportLine(); ++ } ++ ++ private void reportGauge(MetricName name, Gauge gauge, long timestamp) throws IOException { ++ builder.writeMeasurement(name); ++ final Object value = gauge.getValue(); ++ if (value != null) { ++ builder.writeField(VALUE); ++ if (value instanceof Number) { ++ final Number number = (Number) value; ++ if (number instanceof Long ++ || number instanceof Integer ++ || number instanceof Short ++ || number instanceof Byte) { ++ builder.writeFieldValue(number.longValue()); ++ } else { ++ builder.writeFieldValue(number.doubleValue()); + } +- builder.writeTimestampMillis(timestamp); +- reportLine(); ++ } else if (value instanceof Boolean) { ++ builder.writeFieldValue(((Boolean) value)); ++ } else { ++ builder.writeFieldValue(value.toString()); ++ } + } ++ builder.writeTimestampMillis(timestamp); ++ reportLine(); ++ } + +- private void reportLine() throws IOException { +- if (builder.hasValues()) { +- sender.send(builder.get()); +- } ++ private void reportLine() throws IOException { ++ if (builder.hasValues()) { ++ sender.send(builder.get()); + } ++ } + } +--- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbSender.java ++++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbSender.java +@@ -5,43 +5,40 @@ import java.io.IOException; + + public interface InfluxDbSender extends Closeable { + +- /** +- * Connects to the server. +- * +- * @throws IllegalStateException if the client is already connected +- * @throws IOException if there is an error connecting +- */ +- void connect() throws IllegalStateException, IOException; ++ /** ++ * Connects to the server. ++ * ++ * @throws IllegalStateException if the client is already connected ++ * @throws IOException if there is an error connecting ++ */ ++ void connect() throws IllegalStateException, IOException; + +- /** +- * Sends the given measurement to the server. +- *

+- * NOTE: The caller may modify the measurement buffer after this call. +- * The implementation of this method MUST NOT keep any reference to the buffer after this call. +- *

+- * +- * @param measurement a single measurement line, +- * according to the InfluxDb line protocol including a trailing newline. +- * @throws IOException if there was an error sending the metric +- */ +- void send(StringBuilder measurement) throws IOException; ++ /** ++ * Sends the given measurement to the server. ++ * ++ *

NOTE: The caller may modify the measurement buffer after this call. The ++ * implementation of this method MUST NOT keep any reference to the buffer after this call. ++ * ++ * @param measurement a single measurement line, according to the InfluxDb line protocol including ++ * a trailing newline. ++ * @throws IOException if there was an error sending the metric ++ */ ++ void send(StringBuilder measurement) throws IOException; + +- /** +- * Flushes buffer, if applicable +- * +- * @throws IOException if there was an error during flushing metrics to the server +- */ +- void flush() throws IOException; ++ /** ++ * Flushes buffer, if applicable ++ * ++ * @throws IOException if there was an error during flushing metrics to the server ++ */ ++ void flush() throws IOException; + +- /** +- * Disconnects from the server. +- * +- * @throws IOException if there is an error disconnecting +- */ +- void disconnect() throws IOException; ++ /** ++ * Disconnects from the server. ++ * ++ * @throws IOException if there is an error disconnecting ++ */ ++ void disconnect() throws IOException; + +- /** +- * Returns true if ready to send data +- */ +- boolean isConnected(); ++ /** Returns true if ready to send data */ ++ boolean isConnected(); + } +--- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java ++++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.influxdb; + ++import static java.util.Objects.requireNonNull; ++ + import java.io.IOException; + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; +@@ -9,139 +11,137 @@ import java.nio.charset.Charset; + import java.nio.charset.CharsetEncoder; + import java.nio.charset.CoderResult; + import java.nio.charset.CodingErrorAction; +-import java.util.Objects; + + public class InfluxDbUdpSender implements InfluxDbSender { + +- private final InetSocketAddress address; +- private int mtu = 1500; +- +- private DatagramChannel datagramChannel; +- private ByteBuffer byteBuf; +- private CharBuffer charBuf; +- +- private final CharsetEncoder encoder = Charset.forName("UTF-8") +- .newEncoder() +- .onMalformedInput(CodingErrorAction.REPLACE) +- .onUnmappableCharacter(CodingErrorAction.REPLACE); +- +- /** +- * Creates a new client which sends data to given address using UDP +- * +- * @param hostname The hostname of the InfluxDb server +- * @param port The port of the InfluxDb server +- */ +- public InfluxDbUdpSender(String hostname, int port) { +- this(new InetSocketAddress(hostname, port)); ++ private final InetSocketAddress address; ++ private int mtu = 1500; ++ ++ private DatagramChannel datagramChannel; ++ private ByteBuffer byteBuf; ++ private CharBuffer charBuf; ++ ++ private final CharsetEncoder encoder = ++ Charset.forName("UTF-8") ++ .newEncoder() ++ .onMalformedInput(CodingErrorAction.REPLACE) ++ .onUnmappableCharacter(CodingErrorAction.REPLACE); ++ ++ /** ++ * Creates a new client which sends data to given address using UDP ++ * ++ * @param hostname The hostname of the InfluxDb server ++ * @param port The port of the InfluxDb server ++ */ ++ public InfluxDbUdpSender(String hostname, int port) { ++ this(new InetSocketAddress(hostname, port)); ++ } ++ ++ /** ++ * Creates a new client which sends data to given address using UDP ++ * ++ * @param address the address of the InfluxDb server ++ */ ++ public InfluxDbUdpSender(InetSocketAddress address) { ++ this.address = requireNonNull(address); ++ charBuf = CharBuffer.allocate(mtu * 2); ++ byteBuf = ByteBuffer.allocate(mtu * 2); ++ } ++ ++ // for testing ++ void setMTU(int mtu) { ++ this.mtu = mtu; ++ } ++ ++ // for testing ++ void setDatagramChannel(DatagramChannel datagramChannel) { ++ this.datagramChannel = datagramChannel; ++ } ++ ++ @Override ++ public void connect() throws IllegalStateException, IOException { ++ if (datagramChannel == null) { ++ datagramChannel = DatagramChannel.open(); + } +- +- /** +- * Creates a new client which sends data to given address using UDP +- * +- * @param address the address of the InfluxDb server +- */ +- public InfluxDbUdpSender(InetSocketAddress address) { +- this.address = Objects.requireNonNull(address); +- charBuf = CharBuffer.allocate(mtu * 2); +- byteBuf = ByteBuffer.allocate(mtu * 2); ++ byteBuf.clear(); ++ } ++ ++ @Override ++ public boolean isConnected() { ++ return datagramChannel != null; ++ } ++ ++ @Override ++ public void disconnect() throws IOException { ++ // ignore, keep the datagram channel open ++ } ++ ++ @Override ++ public void close() throws IOException { ++ try { ++ datagramChannel.close(); ++ } finally { ++ datagramChannel = null; + } +- +- // for testing +- void setMTU(int mtu) { +- this.mtu = mtu; +- } +- +- // for testing +- void setDatagramChannel(DatagramChannel datagramChannel) { +- this.datagramChannel = datagramChannel; +- } +- +- @Override +- public void connect() throws IllegalStateException, IOException { +- if (datagramChannel == null) { +- datagramChannel = DatagramChannel.open(); +- } ++ } ++ ++ @Override ++ public void send(StringBuilder str) throws IOException { ++ int len = byteBuf.position(); ++ encode(str); ++ int len2 = byteBuf.position(); ++ if (len2 >= mtu) { ++ if (len == 0) { ++ // send current buffer (one single measurement exceeds the MTU) ++ sendBuffer(); + byteBuf.clear(); ++ } else { ++ // send previous buffer ++ byteBuf.position(len); ++ sendBuffer(); ++ byteBuf.limit(len2); ++ byteBuf.compact(); ++ } + } ++ } + +- @Override +- public boolean isConnected() { +- return datagramChannel != null; ++ @Override ++ public void flush() throws IOException { ++ if (byteBuf.position() > 0) { ++ sendBuffer(); ++ byteBuf.clear(); + } +- +- @Override +- public void disconnect() throws IOException { +- // ignore, keep the datagram channel open ++ } ++ ++ private void sendBuffer() throws IOException { ++ byteBuf.flip(); ++ datagramChannel.send(byteBuf, address); ++ } ++ ++ private void encode(StringBuilder str) { ++ // copy chars ++ if (charBuf.capacity() < str.length()) { ++ charBuf = CharBuffer.allocate(str.length()); ++ } else { ++ charBuf.clear(); + } ++ str.getChars(0, str.length(), charBuf.array(), charBuf.arrayOffset()); ++ charBuf.limit(str.length()); + +- @Override +- public void close() throws IOException { +- try { +- datagramChannel.close(); +- } finally { +- datagramChannel = null; +- } +- } ++ // encode chars ++ encoder.reset(); + +- @Override +- public void send(StringBuilder str) throws IOException { +- int len = byteBuf.position(); +- encode(str); +- int len2 = byteBuf.position(); +- if (len2 >= mtu) { +- if (len == 0) { +- // send current buffer (one single measurement exceeds the MTU) +- sendBuffer(); +- byteBuf.clear(); +- } else { +- // send previous buffer +- byteBuf.position(len); +- sendBuffer(); +- byteBuf.limit(len2); +- byteBuf.compact(); +- } +- } +- } +- +- @Override +- public void flush() throws IOException { +- if (byteBuf.position() > 0) { +- sendBuffer(); +- byteBuf.clear(); +- } +- } +- +- private void sendBuffer() throws IOException { ++ for (; ; ) { ++ CoderResult result = encoder.encode(charBuf, byteBuf, true); ++ if (result.isOverflow()) { ++ // grow the buffer ++ ByteBuffer byteBuf2 = ByteBuffer.allocate(byteBuf.capacity() * 2); + byteBuf.flip(); +- datagramChannel.send(byteBuf, address); ++ byteBuf2.put(byteBuf); ++ byteBuf = byteBuf2; ++ } else { // underflow, i.e. done ++ break; ++ } + } +- +- private void encode(StringBuilder str) { +- // copy chars +- if (charBuf.capacity() < str.length()) { +- charBuf = CharBuffer.allocate(str.length()); +- } else { +- charBuf.clear(); +- } +- str.getChars(0, str.length(), charBuf.array(), charBuf.arrayOffset()); +- charBuf.limit(str.length()); +- +- // encode chars +- encoder.reset(); +- +- for (; ; ) { +- CoderResult result = encoder.encode(charBuf, byteBuf, true); +- if (result.isOverflow()) { +- // grow the buffer +- ByteBuffer byteBuf2 = ByteBuffer.allocate(byteBuf.capacity() * 2); +- byteBuf.flip(); +- byteBuf2.put(byteBuf); +- byteBuf = byteBuf2; +- } else { // underflow, i.e. done +- break; +- } +- } +- } +- +- ++ } + } +--- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java ++++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java +@@ -1,17 +1,17 @@ + package io.dropwizard.metrics5.influxdb; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricAttribute; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class InfluxDbLineBuilderAssumptionsTest { ++final class InfluxDbLineBuilderAssumptionsTest { + +- @Test +- void ensureMetricAttributeCodesAreSafeFieldKeys() { +- for (MetricAttribute ma : MetricAttribute.values()) { +- String code = ma.getCode(); +- assertThat(code).doesNotContainPattern("[,= ]"); +- } ++ @Test ++ void ensureMetricAttributeCodesAreSafeFieldKeys() { ++ for (MetricAttribute ma : MetricAttribute.values()) { ++ String code = ma.getCode(); ++ assertThat(code).doesNotContainPattern("[,= ]"); + } ++ } + } +--- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java ++++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java +@@ -1,5 +1,17 @@ + package io.dropwizard.metrics5.influxdb; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.doAnswer; ++import static org.mockito.Mockito.doThrow; ++import static org.mockito.Mockito.inOrder; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.times; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.verifyNoMoreInteractions; ++import static org.mockito.Mockito.when; ++ ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -11,458 +23,397 @@ import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import org.mockito.InOrder; +- + import java.io.IOException; + import java.net.UnknownHostException; + import java.util.ArrayList; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Set; + import java.util.SortedMap; + import java.util.TreeMap; + import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; ++import org.mockito.InOrder; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.ArgumentMatchers.any; +-import static org.mockito.Mockito.doAnswer; +-import static org.mockito.Mockito.doThrow; +-import static org.mockito.Mockito.inOrder; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.times; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.verifyNoMoreInteractions; +-import static org.mockito.Mockito.when; +- +-class InfluxDbReporterTest { +- private static final MetricName GAUGE = MetricName.build("gauge"); +- private static final MetricName METER = MetricName.build("meter"); +- private static final MetricName COUNTER = MetricName.build("counter"); +- +- private final long timestamp = 1000198; +- private final Clock clock = mock(Clock.class); +- private final InfluxDbSender sender = mock(InfluxDbSender.class); +- private final List send = new ArrayList<>(); +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final InfluxDbReporter reporter = InfluxDbReporter.forRegistry(registry) ++final class InfluxDbReporterTest { ++ private static final MetricName GAUGE = MetricName.build("gauge"); ++ private static final MetricName METER = MetricName.build("meter"); ++ private static final MetricName COUNTER = MetricName.build("counter"); ++ ++ private final long timestamp = 1000198; ++ private final Clock clock = mock(); ++ private final InfluxDbSender sender = mock(); ++ private final List send = new ArrayList<>(); ++ private final MetricRegistry registry = mock(); ++ private final InfluxDbReporter reporter = ++ InfluxDbReporter.forRegistry(registry) ++ .withClock(clock) ++ .prefixedWith(new MetricName("prefix", map("foo", "bar"))) ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(ImmutableSet.of()) ++ .build(sender); ++ ++ private final InfluxDbReporter minuteRateReporter = ++ InfluxDbReporter.forRegistry(registry) ++ .withClock(clock) ++ .prefixedWith(new MetricName("prefix", map("foo", "bar"))) ++ .convertRatesTo(TimeUnit.MINUTES) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(ImmutableSet.of()) ++ .build(sender); ++ ++ @BeforeEach ++ void setUp() throws IOException { ++ when(clock.getTime()).thenReturn(timestamp * 1000); ++ send.clear(); ++ doAnswer(invocation -> send.add(invocation.getArgument(0).toString())) ++ .when(sender) ++ .send(any(StringBuilder.class)); ++ } ++ ++ @Test ++ void reportsStringGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge("value")), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=\"value\" 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsByteGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge((byte) 1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsShortGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge((short) 1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsIntegerGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsLongGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(1L)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsFloatGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(1.5f)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1.5 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsDoubleGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(1.1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1.1 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsBooleanGaugeValues() throws Exception { ++ reporter.report(map(GAUGE, gauge(true)), map(), map(), map(), map()); ++ ++ reporter.report(map(GAUGE, gauge(false)), map(), map(), map(), map()); ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ ++ assertThat(send).element(0).isEqualTo("prefix.gauge,foo=bar value=t 1000198000000000\n"); ++ assertThat(send).element(1).isEqualTo("prefix.gauge,foo=bar value=f 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsCounters() throws Exception { ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(100L); ++ ++ reporter.report(map(), map(COUNTER, counter), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send).first().isEqualTo("prefix.counter,foo=bar count=100i 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsHistograms() throws Exception { ++ final Histogram histogram = mock(); ++ when(histogram.getCount()).thenReturn(1L); ++ when(histogram.getSum()).thenReturn(12L); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(2L); ++ when(snapshot.getMean()).thenReturn(3.0); ++ when(snapshot.getMin()).thenReturn(4L); ++ when(snapshot.getStdDev()).thenReturn(5.0); ++ when(snapshot.getMedian()).thenReturn(6.0); ++ when(snapshot.get75thPercentile()).thenReturn(7.0); ++ when(snapshot.get95thPercentile()).thenReturn(8.0); ++ when(snapshot.get98thPercentile()).thenReturn(9.0); ++ when(snapshot.get99thPercentile()).thenReturn(10.0); ++ when(snapshot.get999thPercentile()).thenReturn(11.0); ++ ++ when(histogram.getSnapshot()).thenReturn(snapshot); ++ ++ reporter.report(map(), map(), map(MetricName.build("histogram"), histogram), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send) ++ .first() ++ .isEqualTo( ++ "prefix.histogram,foo=bar count=1i,sum=12i,max=2i,mean=3.0,min=4i,stddev=5.0,p50=6.0,p75=7.0,p95=8.0,p98=9.0,p99=10.0,p999=11.0 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsMeters() throws Exception { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(6L); ++ when(meter.getOneMinuteRate()).thenReturn(2.0); ++ when(meter.getFiveMinuteRate()).thenReturn(3.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(4.0); ++ when(meter.getMeanRate()).thenReturn(5.0); ++ ++ reporter.report(map(), map(), map(), map(METER, meter), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send) ++ .first() ++ .isEqualTo( ++ "prefix.meter,foo=bar count=1i,sum=6i,m1_rate=2.0,m5_rate=3.0,m15_rate=4.0,mean_rate=5.0 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsMetersInMinutes() throws Exception { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(6L); ++ when(meter.getOneMinuteRate()).thenReturn(2.0); ++ when(meter.getFiveMinuteRate()).thenReturn(3.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(4.0); ++ when(meter.getMeanRate()).thenReturn(5.0); ++ ++ minuteRateReporter.report( ++ this.map(), this.map(), this.map(), this.map(METER, meter), this.map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send) ++ .first() ++ .isEqualTo( ++ "prefix.meter,foo=bar count=1i,sum=6i,m1_rate=120.0,m5_rate=180.0,m15_rate=240.0,mean_rate=300.0 1000198000000000\n"); ++ } ++ ++ @Test ++ void reportsTimers() throws Exception { ++ final Timer timer = mock(); ++ when(timer.getCount()).thenReturn(1L); ++ when(timer.getSum()).thenReturn(6L); ++ when(timer.getMeanRate()).thenReturn(2.0); ++ when(timer.getOneMinuteRate()).thenReturn(3.0); ++ when(timer.getFiveMinuteRate()).thenReturn(4.0); ++ when(timer.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); ++ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); ++ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ++ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); ++ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); ++ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); ++ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); ++ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); ++ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); ++ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); ++ ++ when(timer.getSnapshot()).thenReturn(snapshot); ++ ++ reporter.report(map(), map(), map(), map(), map(MetricName.build("timer"), timer)); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ assertThat(send) ++ .first() ++ .isEqualTo( ++ "prefix.timer,foo=bar max=100.0,mean=200.0,min=300.0,stddev=400.0,p50=500.0,p75=600.0,p95=700.0,p98=800.0,p99=900.0,p999=1000.0,count=1i,sum=6i,m1_rate=3.0,m5_rate=4.0,m15_rate=5.0,mean_rate=2.0 1000198000000000\n"); ++ ++ reporter.close(); ++ } ++ ++ @Test ++ void disconnectsIfSenderIsUnavailable() throws Exception { ++ doThrow(new UnknownHostException("UNKNOWN-HOST")).when(sender).connect(); ++ reporter.report(map(GAUGE, gauge(1)), map(), map(), map(), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ } ++ ++ @Test ++ void closesConnectionOnReporterStop() throws Exception { ++ reporter.stop(); ++ ++ verify(sender).close(); ++ } ++ ++ @Test ++ void disabledMetricsAttribute() throws Exception { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(6L); ++ when(meter.getOneMinuteRate()).thenReturn(2.0); ++ when(meter.getFiveMinuteRate()).thenReturn(3.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(4.0); ++ when(meter.getMeanRate()).thenReturn(5.0); ++ ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(11L); ++ ++ Set disabledMetricAttributes = ++ EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE); ++ InfluxDbReporter reporterWithdisabledMetricAttributes = ++ InfluxDbReporter.forRegistry(registry) + .withClock(clock) +- .prefixedWith(new MetricName("prefix", map("foo", "bar"))) ++ .prefixedWith(MetricName.build("prefix")) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(disabledMetricAttributes) + .build(sender); +- +- private final InfluxDbReporter minuteRateReporter = InfluxDbReporter +- .forRegistry(registry) +- .withClock(clock) +- .prefixedWith(new MetricName("prefix", map("foo", "bar"))) +- .convertRatesTo(TimeUnit.MINUTES) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) +- .build(sender); +- +- @BeforeEach +- void setUp() throws IOException { +- when(clock.getTime()).thenReturn(timestamp * 1000); +- send.clear(); +- doAnswer(invocation -> send.add(invocation.getArgument(0).toString())) +- .when(sender).send(any(StringBuilder.class)); +- } +- +- @Test +- void reportsStringGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge("value")), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=\"value\" 1000198000000000\n"); +- } +- +- @Test +- void reportsByteGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge((byte) 1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); +- } +- +- @Test +- void reportsShortGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge((short) 1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); +- } +- +- @Test +- void reportsIntegerGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); +- } +- +- @Test +- void reportsLongGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(1L)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); +- } +- +- @Test +- void reportsFloatGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(1.5f)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1.5 1000198000000000\n"); +- } +- +- @Test +- void reportsDoubleGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(1.1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1.1 1000198000000000\n"); +- } +- +- @Test +- void reportsBooleanGaugeValues() throws Exception { +- reporter.report(map(GAUGE, gauge(true)), +- map(), +- map(), +- map(), +- map()); +- +- reporter.report(map(GAUGE, gauge(false)), +- map(), +- map(), +- map(), +- map()); +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- +- assertThat(send).element(0).isEqualTo("prefix.gauge,foo=bar value=t 1000198000000000\n"); +- assertThat(send).element(1).isEqualTo("prefix.gauge,foo=bar value=f 1000198000000000\n"); +- } +- +- @Test +- void reportsCounters() throws Exception { +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(100L); +- +- reporter.report(map(), +- map(COUNTER, counter), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.counter,foo=bar count=100i 1000198000000000\n"); +- } +- +- @Test +- void reportsHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); +- when(histogram.getCount()).thenReturn(1L); +- when(histogram.getSum()).thenReturn(12L); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(2L); +- when(snapshot.getMean()).thenReturn(3.0); +- when(snapshot.getMin()).thenReturn(4L); +- when(snapshot.getStdDev()).thenReturn(5.0); +- when(snapshot.getMedian()).thenReturn(6.0); +- when(snapshot.get75thPercentile()).thenReturn(7.0); +- when(snapshot.get95thPercentile()).thenReturn(8.0); +- when(snapshot.get98thPercentile()).thenReturn(9.0); +- when(snapshot.get99thPercentile()).thenReturn(10.0); +- when(snapshot.get999thPercentile()).thenReturn(11.0); +- +- when(histogram.getSnapshot()).thenReturn(snapshot); +- +- reporter.report(map(), +- map(), +- map(MetricName.build("histogram"), histogram), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.histogram,foo=bar count=1i,sum=12i,max=2i,mean=3.0,min=4i,stddev=5.0,p50=6.0,p75=7.0,p95=8.0,p98=9.0,p99=10.0,p999=11.0 1000198000000000\n"); +- +- } +- +- @Test +- void reportsMeters() throws Exception { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(6L); +- when(meter.getOneMinuteRate()).thenReturn(2.0); +- when(meter.getFiveMinuteRate()).thenReturn(3.0); +- when(meter.getFifteenMinuteRate()).thenReturn(4.0); +- when(meter.getMeanRate()).thenReturn(5.0); +- +- reporter.report(map(), +- map(), +- map(), +- map(METER, meter), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.meter,foo=bar count=1i,sum=6i,m1_rate=2.0,m5_rate=3.0,m15_rate=4.0,mean_rate=5.0 1000198000000000\n"); +- } +- +- @Test +- void reportsMetersInMinutes() throws Exception { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(6L); +- when(meter.getOneMinuteRate()).thenReturn(2.0); +- when(meter.getFiveMinuteRate()).thenReturn(3.0); +- when(meter.getFifteenMinuteRate()).thenReturn(4.0); +- when(meter.getMeanRate()).thenReturn(5.0); +- +- minuteRateReporter.report(this.map(), +- this.map(), +- this.map(), +- this.map(METER, meter), +- this.map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.meter,foo=bar count=1i,sum=6i,m1_rate=120.0,m5_rate=180.0,m15_rate=240.0,mean_rate=300.0 1000198000000000\n"); +- } +- +- @Test +- void reportsTimers() throws Exception { +- final Timer timer = mock(Timer.class); +- when(timer.getCount()).thenReturn(1L); +- when(timer.getSum()).thenReturn(6L); +- when(timer.getMeanRate()).thenReturn(2.0); +- when(timer.getOneMinuteRate()).thenReturn(3.0); +- when(timer.getFiveMinuteRate()).thenReturn(4.0); +- when(timer.getFifteenMinuteRate()).thenReturn(5.0); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); +- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); +- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); +- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); +- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); +- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); +- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); +- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); +- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS +- .toNanos(1000)); +- +- when(timer.getSnapshot()).thenReturn(snapshot); +- +- reporter.report(map(), +- map(), +- map(), +- map(), +- map(MetricName.build("timer"), timer)); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- assertThat(send).first().isEqualTo("prefix.timer,foo=bar max=100.0,mean=200.0,min=300.0,stddev=400.0,p50=500.0,p75=600.0,p95=700.0,p98=800.0,p99=900.0,p999=1000.0,count=1i,sum=6i,m1_rate=3.0,m5_rate=4.0,m15_rate=5.0,mean_rate=2.0 1000198000000000\n"); +- +- reporter.close(); +- } +- +- @Test +- void disconnectsIfSenderIsUnavailable() throws Exception { +- doThrow(new UnknownHostException("UNKNOWN-HOST")).when(sender).connect(); +- reporter.report(map(GAUGE, gauge(1)), +- map(), +- map(), +- map(), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender).disconnect(); +- +- +- verifyNoMoreInteractions(sender); +- } +- +- @Test +- void closesConnectionOnReporterStop() throws Exception { +- reporter.stop(); +- +- verify(sender).close(); +- } +- +- @Test +- void disabledMetricsAttribute() throws Exception { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(6L); +- when(meter.getOneMinuteRate()).thenReturn(2.0); +- when(meter.getFiveMinuteRate()).thenReturn(3.0); +- when(meter.getFifteenMinuteRate()).thenReturn(4.0); +- when(meter.getMeanRate()).thenReturn(5.0); +- +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(11L); +- +- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE); +- InfluxDbReporter reporterWithdisabledMetricAttributes = InfluxDbReporter.forRegistry(registry) +- .withClock(clock) +- .prefixedWith(MetricName.build("prefix")) +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(disabledMetricAttributes) +- .build(sender); +- reporterWithdisabledMetricAttributes.report(map(), +- map(COUNTER, counter), +- map(), +- map(METER, meter), +- map()); +- +- final InOrder inOrder = inOrder(sender); +- inOrder.verify(sender).connect(); +- inOrder.verify(sender, times(2)).send(anySb()); +- inOrder.verify(sender).flush(); +- inOrder.verify(sender).disconnect(); +- +- verifyNoMoreInteractions(sender); +- +- assertThat(send).element(0).isEqualTo("prefix.counter count=11i 1000198000000000\n"); +- assertThat(send).element(1).isEqualTo("prefix.meter count=1i,sum=6i,m1_rate=2.0,mean_rate=5.0 1000198000000000\n"); +- } +- +- private SortedMap map() { +- return new TreeMap<>(); +- } +- +- private SortedMap map(K key, V value) { +- final SortedMap map = new TreeMap<>(); +- map.put(key, value); +- return map; +- } +- +- private Gauge gauge(T value) { +- return () -> value; +- } +- +- private StringBuilder anySb() { +- return any(StringBuilder.class); +- } ++ reporterWithdisabledMetricAttributes.report( ++ map(), map(COUNTER, counter), map(), map(METER, meter), map()); ++ ++ final InOrder inOrder = inOrder(sender); ++ inOrder.verify(sender).connect(); ++ inOrder.verify(sender, times(2)).send(anySb()); ++ inOrder.verify(sender).flush(); ++ inOrder.verify(sender).disconnect(); ++ ++ verifyNoMoreInteractions(sender); ++ ++ assertThat(send).element(0).isEqualTo("prefix.counter count=11i 1000198000000000\n"); ++ assertThat(send) ++ .element(1) ++ .isEqualTo("prefix.meter count=1i,sum=6i,m1_rate=2.0,mean_rate=5.0 1000198000000000\n"); ++ } ++ ++ private SortedMap map() { ++ return new TreeMap<>(); ++ } ++ ++ private SortedMap map(K key, V value) { ++ final SortedMap map = new TreeMap<>(); ++ map.put(key, value); ++ return map; ++ } ++ ++ private Gauge gauge(T value) { ++ return () -> value; ++ } ++ ++ private StringBuilder anySb() { ++ return any(StringBuilder.class); ++ } + } +--- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java ++++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java +@@ -1,83 +1,84 @@ + package io.dropwizard.metrics5.influxdb; + +-import java.io.IOException; +- +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import org.mockito.Mockito; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.any; ++import static org.mockito.Mockito.doAnswer; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.times; ++import static org.mockito.Mockito.verify; + ++import java.io.IOException; + import java.net.SocketAddress; + import java.nio.ByteBuffer; + import java.nio.channels.DatagramChannel; + import java.util.ArrayList; + import java.util.List; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-import static org.mockito.Mockito.doAnswer; +-import static org.mockito.Mockito.any; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.times; +- +-class InfluxDbUdpTest { +- +- private final String host = "example.com"; +- private final int port = 1234; +- +- private InfluxDbUdpSender influxdbUdp; +- private final DatagramChannel datagramChannel = Mockito.mock(DatagramChannel.class); +- private final List sent = new ArrayList<>(); +- +- @BeforeEach +- void setUp() throws IOException { +- sent.clear(); +- doAnswer(invocation -> { +- sent.add(toBytes(invocation.getArgument(0))); +- return 0; +- }).when(datagramChannel).send(any(ByteBuffer.class), any(SocketAddress.class)); +- influxdbUdp = new InfluxDbUdpSender(host, port); +- influxdbUdp.setDatagramChannel(datagramChannel); +- } +- +- @Test +- void writesValue() throws Exception { +- influxdbUdp.send(new StringBuilder("räksmörgås value=123 456000000000\n")); +- influxdbUdp.flush(); +- +- verify(datagramChannel).send(any(), any()); +- +- assertThat(sent).first().isEqualTo("räksmörgås value=123 456000000000\n".getBytes("UTF-8")); +- } +- +- @Test +- void batchesValues() throws Exception { +- influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); +- influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); +- influxdbUdp.flush(); +- +- verify(datagramChannel).send(any(), any()); +- +- assertThat(sent).first().isEqualTo( +- "name1 value=111 456000000000\nname2 value=222 456000000000\n".getBytes("UTF-8")); +- } +- +- @Test +- void respectsMTU() throws Exception { +- influxdbUdp.setMTU(40); +- influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); +- influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); +- influxdbUdp.flush(); +- +- verify(datagramChannel, times(2)).send(any(), any()); +- +- assertThat(sent).element(0).isEqualTo("name1 value=111 456000000000\n".getBytes("UTF-8")); +- assertThat(sent).element(1).isEqualTo("name2 value=222 456000000000\n".getBytes("UTF-8")); +- } +- +- private byte[] toBytes(ByteBuffer buf) { +- byte[] bytes = new byte[buf.remaining()]; +- buf.get(bytes); +- return bytes; +- } +-} +\ No newline at end of file ++final class InfluxDbUdpTest { ++ ++ private final String host = "example.com"; ++ private final int port = 1234; ++ ++ private InfluxDbUdpSender influxdbUdp; ++ private final DatagramChannel datagramChannel = mock(); ++ private final List sent = new ArrayList<>(); ++ ++ @BeforeEach ++ void setUp() throws IOException { ++ sent.clear(); ++ doAnswer( ++ invocation -> { ++ sent.add(toBytes(invocation.getArgument(0))); ++ return 0; ++ }) ++ .when(datagramChannel) ++ .send(any(ByteBuffer.class), any(SocketAddress.class)); ++ influxdbUdp = new InfluxDbUdpSender(host, port); ++ influxdbUdp.setDatagramChannel(datagramChannel); ++ } ++ ++ @Test ++ void writesValue() throws Exception { ++ influxdbUdp.send(new StringBuilder("räksmörgås value=123 456000000000\n")); ++ influxdbUdp.flush(); ++ ++ verify(datagramChannel).send(any(), any()); ++ ++ assertThat(sent).first().isEqualTo("räksmörgås value=123 456000000000\n".getBytes("UTF-8")); ++ } ++ ++ @Test ++ void batchesValues() throws Exception { ++ influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); ++ influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); ++ influxdbUdp.flush(); ++ ++ verify(datagramChannel).send(any(), any()); ++ ++ assertThat(sent) ++ .first() ++ .isEqualTo( ++ "name1 value=111 456000000000\nname2 value=222 456000000000\n".getBytes("UTF-8")); ++ } ++ ++ @Test ++ void respectsMTU() throws Exception { ++ influxdbUdp.setMTU(40); ++ influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); ++ influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); ++ influxdbUdp.flush(); ++ ++ verify(datagramChannel, times(2)).send(any(), any()); ++ ++ assertThat(sent).element(0).isEqualTo("name1 value=111 456000000000\n".getBytes("UTF-8")); ++ assertThat(sent).element(1).isEqualTo("name2 value=222 456000000000\n".getBytes("UTF-8")); ++ } ++ ++ private byte[] toBytes(ByteBuffer buf) { ++ byte[] bytes = new byte[buf.remaining()]; ++ buf.get(bytes); ++ return bytes; ++ } ++} +--- a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java ++++ b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java +@@ -1,5 +1,8 @@ + package io.dropwizard.metrics5.servlet; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -14,205 +17,197 @@ import jakarta.servlet.ServletRequest; + import jakarta.servlet.ServletResponse; + import jakarta.servlet.http.HttpServletResponse; + import jakarta.servlet.http.HttpServletResponseWrapper; +- + import java.io.IOException; + import java.util.Map; + import java.util.Map.Entry; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; + +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + /** + * {@link Filter} implementation which captures request information and a breakdown of the response + * codes being returned. + */ + public abstract class AbstractInstrumentedFilter implements Filter { +- static final String METRIC_PREFIX = "name-prefix"; +- +- private final String otherMetricName; +- private final Map meterNamesByStatusCode; +- private final String registryAttribute; +- +- // initialized after call of init method +- private ConcurrentMap metersByStatusCode; +- private Meter otherMeter; +- private Meter timeoutsMeter; +- private Meter errorsMeter; +- private Counter activeRequests; +- private Timer requestTimer; +- +- +- /** +- * Creates a new instance of the filter. +- * +- * @param registryAttribute the attribute used to look up the metrics registry in the +- * servlet context +- * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are +- * interested in. +- * @param otherMetricName The name used for the catch-all meter. +- */ +- protected AbstractInstrumentedFilter(String registryAttribute, +- Map meterNamesByStatusCode, +- String otherMetricName) { +- this.registryAttribute = registryAttribute; +- this.otherMetricName = otherMetricName; +- this.meterNamesByStatusCode = meterNamesByStatusCode; ++ static final String METRIC_PREFIX = "name-prefix"; ++ ++ private final String otherMetricName; ++ private final Map meterNamesByStatusCode; ++ private final String registryAttribute; ++ ++ // initialized after call of init method ++ private ConcurrentMap metersByStatusCode; ++ private Meter otherMeter; ++ private Meter timeoutsMeter; ++ private Meter errorsMeter; ++ private Counter activeRequests; ++ private Timer requestTimer; ++ ++ /** ++ * Creates a new instance of the filter. ++ * ++ * @param registryAttribute the attribute used to look up the metrics registry in the servlet ++ * context ++ * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are ++ * interested in. ++ * @param otherMetricName The name used for the catch-all meter. ++ */ ++ protected AbstractInstrumentedFilter( ++ String registryAttribute, ++ Map meterNamesByStatusCode, ++ String otherMetricName) { ++ this.registryAttribute = registryAttribute; ++ this.otherMetricName = otherMetricName; ++ this.meterNamesByStatusCode = meterNamesByStatusCode; ++ } ++ ++ @Override ++ public void init(FilterConfig filterConfig) throws ServletException { ++ final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); ++ ++ String metricName = filterConfig.getInitParameter(METRIC_PREFIX); ++ if (Strings.isNullOrEmpty(metricName)) { ++ metricName = getClass().getName(); + } + +- @Override +- public void init(FilterConfig filterConfig) throws ServletException { +- final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); +- +- String metricName = filterConfig.getInitParameter(METRIC_PREFIX); +- if (metricName == null || metricName.isEmpty()) { +- metricName = getClass().getName(); +- } +- +- this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); +- for (Entry entry : meterNamesByStatusCode.entrySet()) { +- metersByStatusCode.put(entry.getKey(), +- metricsRegistry.meter(name(metricName, entry.getValue()))); +- } +- this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); +- this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); +- this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); +- this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); +- this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); +- ++ this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); ++ for (Entry entry : meterNamesByStatusCode.entrySet()) { ++ metersByStatusCode.put( ++ entry.getKey(), metricsRegistry.meter(name(metricName, entry.getValue()))); + } +- +- private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { +- final MetricRegistry metricsRegistry; +- +- final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); +- if (o instanceof MetricRegistry) { +- metricsRegistry = (MetricRegistry) o; ++ this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); ++ this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); ++ this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); ++ this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); ++ this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); ++ } ++ ++ private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { ++ final MetricRegistry metricsRegistry; ++ ++ final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); ++ if (o instanceof MetricRegistry) { ++ metricsRegistry = (MetricRegistry) o; ++ } else { ++ metricsRegistry = new MetricRegistry(); ++ } ++ return metricsRegistry; ++ } ++ ++ @Override ++ public void destroy() {} ++ ++ @Override ++ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) ++ throws IOException, ServletException { ++ final StatusExposingServletResponse wrappedResponse = ++ new StatusExposingServletResponse((HttpServletResponse) response); ++ activeRequests.inc(); ++ final Timer.Context context = requestTimer.time(); ++ boolean error = false; ++ try { ++ chain.doFilter(request, wrappedResponse); ++ } catch (IOException | RuntimeException | ServletException e) { ++ error = true; ++ throw e; ++ } finally { ++ if (!error && request.isAsyncStarted()) { ++ request.getAsyncContext().addListener(new AsyncResultListener(context)); ++ } else { ++ context.stop(); ++ activeRequests.dec(); ++ if (error) { ++ errorsMeter.mark(); + } else { +- metricsRegistry = new MetricRegistry(); ++ markMeterForStatusCode(wrappedResponse.getStatus()); + } +- return metricsRegistry; ++ } ++ } ++ } ++ ++ private void markMeterForStatusCode(int status) { ++ final Meter metric = metersByStatusCode.get(status); ++ if (metric != null) { ++ metric.mark(); ++ } else { ++ otherMeter.mark(); + } ++ } + +- @Override +- public void destroy() { ++ private static class StatusExposingServletResponse extends HttpServletResponseWrapper { ++ // The Servlet spec says: calling setStatus is optional, if no status is set, the default is ++ // 200. ++ private int httpStatus = 200; + ++ public StatusExposingServletResponse(HttpServletResponse response) { ++ super(response); + } + + @Override +- public void doFilter(ServletRequest request, +- ServletResponse response, +- FilterChain chain) throws IOException, ServletException { +- final StatusExposingServletResponse wrappedResponse = +- new StatusExposingServletResponse((HttpServletResponse) response); +- activeRequests.inc(); +- final Timer.Context context = requestTimer.time(); +- boolean error = false; +- try { +- chain.doFilter(request, wrappedResponse); +- } catch (IOException | RuntimeException | ServletException e) { +- error = true; +- throw e; +- } finally { +- if (!error && request.isAsyncStarted()) { +- request.getAsyncContext().addListener(new AsyncResultListener(context)); +- } else { +- context.stop(); +- activeRequests.dec(); +- if (error) { +- errorsMeter.mark(); +- } else { +- markMeterForStatusCode(wrappedResponse.getStatus()); +- } +- } +- } ++ public void sendError(int sc) throws IOException { ++ httpStatus = sc; ++ super.sendError(sc); + } + +- private void markMeterForStatusCode(int status) { +- final Meter metric = metersByStatusCode.get(status); +- if (metric != null) { +- metric.mark(); +- } else { +- otherMeter.mark(); +- } ++ @Override ++ public void sendError(int sc, String msg) throws IOException { ++ httpStatus = sc; ++ super.sendError(sc, msg); + } + +- private static class StatusExposingServletResponse extends HttpServletResponseWrapper { +- // The Servlet spec says: calling setStatus is optional, if no status is set, the default is 200. +- private int httpStatus = 200; +- +- public StatusExposingServletResponse(HttpServletResponse response) { +- super(response); +- } +- +- @Override +- public void sendError(int sc) throws IOException { +- httpStatus = sc; +- super.sendError(sc); +- } +- +- @Override +- public void sendError(int sc, String msg) throws IOException { +- httpStatus = sc; +- super.sendError(sc, msg); +- } +- +- @Override +- public void setStatus(int sc) { +- httpStatus = sc; +- super.setStatus(sc); +- } +- +- @Override +- @SuppressWarnings("deprecation") +- public void setStatus(int sc, String sm) { +- httpStatus = sc; +- super.setStatus(sc, sm); +- } ++ @Override ++ public void setStatus(int sc) { ++ httpStatus = sc; ++ super.setStatus(sc); ++ } + +- @Override +- public int getStatus() { +- return httpStatus; +- } ++ @Override ++ @SuppressWarnings("deprecation") ++ public void setStatus(int sc, String sm) { ++ httpStatus = sc; ++ super.setStatus(sc, sm); + } + +- private class AsyncResultListener implements AsyncListener { +- private Timer.Context context; +- private boolean done = false; ++ @Override ++ public int getStatus() { ++ return httpStatus; ++ } ++ } + +- public AsyncResultListener(Timer.Context context) { +- this.context = context; +- } ++ private class AsyncResultListener implements AsyncListener { ++ private Timer.Context context; ++ private boolean done = false; + +- @Override +- public void onComplete(AsyncEvent event) throws IOException { +- if (!done) { +- HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); +- context.stop(); +- activeRequests.dec(); +- markMeterForStatusCode(suppliedResponse.getStatus()); +- } +- } +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException { +- context.stop(); +- activeRequests.dec(); +- timeoutsMeter.mark(); +- done = true; +- } ++ public AsyncResultListener(Timer.Context context) { ++ this.context = context; ++ } + +- @Override +- public void onError(AsyncEvent event) throws IOException { +- context.stop(); +- activeRequests.dec(); +- errorsMeter.mark(); +- done = true; +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException { ++ if (!done) { ++ HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); ++ context.stop(); ++ activeRequests.dec(); ++ markMeterForStatusCode(suppliedResponse.getStatus()); ++ } ++ } + +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException { ++ context.stop(); ++ activeRequests.dec(); ++ timeoutsMeter.mark(); ++ done = true; ++ } + +- } ++ @Override ++ public void onError(AsyncEvent event) throws IOException { ++ context.stop(); ++ activeRequests.dec(); ++ errorsMeter.mark(); ++ done = true; + } ++ ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException {} ++ } + } +--- a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilter.java ++++ b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilter.java +@@ -4,8 +4,13 @@ import java.util.HashMap; + import java.util.Map; + + /** +- * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response codes +- * to capture information about.

Use it in your servlet.xml like this:

++ * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response ++ * codes to capture information about. ++ * ++ *

Use it in your servlet.xml like this: ++ * ++ *

++ * + *

{@code
+  * 
+  *     instrumentedFilter
+@@ -18,31 +23,29 @@ import java.util.Map;
+  * }
+ */ + public class InstrumentedFilter extends AbstractInstrumentedFilter { +- public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; ++ public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; + +- private static final String NAME_PREFIX = "responseCodes."; +- private static final int OK = 200; +- private static final int CREATED = 201; +- private static final int NO_CONTENT = 204; +- private static final int BAD_REQUEST = 400; +- private static final int NOT_FOUND = 404; +- private static final int SERVER_ERROR = 500; ++ private static final String NAME_PREFIX = "responseCodes."; ++ private static final int OK = 200; ++ private static final int CREATED = 201; ++ private static final int NO_CONTENT = 204; ++ private static final int BAD_REQUEST = 400; ++ private static final int NOT_FOUND = 404; ++ private static final int SERVER_ERROR = 500; + +- /** +- * Creates a new instance of the filter. +- */ +- public InstrumentedFilter() { +- super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); +- } ++ /** Creates a new instance of the filter. */ ++ public InstrumentedFilter() { ++ super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); ++ } + +- private static Map createMeterNamesByStatusCode() { +- final Map meterNamesByStatusCode = new HashMap<>(6); +- meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); +- meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); +- meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); +- meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); +- meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); +- meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); +- return meterNamesByStatusCode; +- } ++ private static Map createMeterNamesByStatusCode() { ++ final Map meterNamesByStatusCode = new HashMap<>(6); ++ meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); ++ meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); ++ meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); ++ meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); ++ meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); ++ meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); ++ return meterNamesByStatusCode; ++ } + } +--- a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListener.java ++++ b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListener.java +@@ -10,17 +10,17 @@ import jakarta.servlet.ServletContextListener; + * application. + */ + public abstract class InstrumentedFilterContextListener implements ServletContextListener { +- /** +- * @return the {@link MetricRegistry} to inject into the servlet context. +- */ +- protected abstract MetricRegistry getMetricRegistry(); ++ /** ++ * @return the {@link MetricRegistry} to inject into the servlet context. ++ */ ++ protected abstract MetricRegistry getMetricRegistry(); + +- @Override +- public void contextInitialized(ServletContextEvent sce) { +- sce.getServletContext().setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); +- } ++ @Override ++ public void contextInitialized(ServletContextEvent sce) { ++ sce.getServletContext() ++ .setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); ++ } + +- @Override +- public void contextDestroyed(ServletContextEvent sce) { +- } ++ @Override ++ public void contextDestroyed(ServletContextEvent sce) {} + } +--- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +@@ -1,32 +1,34 @@ + package io.dropwizard.metrics5.servlet; + ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.MetricRegistry; + import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletContextEvent; + import org.junit.jupiter.api.Test; + +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- +-class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final InstrumentedFilterContextListener listener = new InstrumentedFilterContextListener() { ++final class InstrumentedFilterContextListenerTest { ++ private final MetricRegistry registry = mock(); ++ private final InstrumentedFilterContextListener listener = ++ new InstrumentedFilterContextListener() { + @Override + protected MetricRegistry getMetricRegistry() { +- return registry; ++ return registry; + } +- }; ++ }; + +- @Test +- void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ @Test ++ void injectsTheMetricRegistryIntoTheServletContext() { ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); +- when(event.getServletContext()).thenReturn(context); ++ final ServletContextEvent event = mock(); ++ when(event.getServletContext()).thenReturn(context); + +- listener.contextInitialized(event); ++ listener.contextInitialized(event); + +- verify(context).setAttribute("io.dropwizard.metrics5.servlet.InstrumentedFilter.registry", registry); +- } ++ verify(context) ++ .setAttribute("io.dropwizard.metrics5.servlet.InstrumentedFilter.registry", registry); ++ } + } +--- a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java ++++ b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java +@@ -1,5 +1,8 @@ + package io.dropwizard.metrics5.servlet6; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -14,198 +17,190 @@ import jakarta.servlet.ServletRequest; + import jakarta.servlet.ServletResponse; + import jakarta.servlet.http.HttpServletResponse; + import jakarta.servlet.http.HttpServletResponseWrapper; +- + import java.io.IOException; + import java.util.Map; + import java.util.Map.Entry; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; + +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + /** + * {@link Filter} implementation which captures request information and a breakdown of the response + * codes being returned. + */ + public abstract class AbstractInstrumentedFilter implements Filter { +- static final String METRIC_PREFIX = "name-prefix"; +- +- private final String otherMetricName; +- private final Map meterNamesByStatusCode; +- private final String registryAttribute; +- +- // initialized after call of init method +- private ConcurrentMap metersByStatusCode; +- private Meter otherMeter; +- private Meter timeoutsMeter; +- private Meter errorsMeter; +- private Counter activeRequests; +- private Timer requestTimer; +- +- +- /** +- * Creates a new instance of the filter. +- * +- * @param registryAttribute the attribute used to look up the metrics registry in the +- * servlet context +- * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are +- * interested in. +- * @param otherMetricName The name used for the catch-all meter. +- */ +- protected AbstractInstrumentedFilter(String registryAttribute, +- Map meterNamesByStatusCode, +- String otherMetricName) { +- this.registryAttribute = registryAttribute; +- this.otherMetricName = otherMetricName; +- this.meterNamesByStatusCode = meterNamesByStatusCode; ++ static final String METRIC_PREFIX = "name-prefix"; ++ ++ private final String otherMetricName; ++ private final Map meterNamesByStatusCode; ++ private final String registryAttribute; ++ ++ // initialized after call of init method ++ private ConcurrentMap metersByStatusCode; ++ private Meter otherMeter; ++ private Meter timeoutsMeter; ++ private Meter errorsMeter; ++ private Counter activeRequests; ++ private Timer requestTimer; ++ ++ /** ++ * Creates a new instance of the filter. ++ * ++ * @param registryAttribute the attribute used to look up the metrics registry in the servlet ++ * context ++ * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are ++ * interested in. ++ * @param otherMetricName The name used for the catch-all meter. ++ */ ++ protected AbstractInstrumentedFilter( ++ String registryAttribute, ++ Map meterNamesByStatusCode, ++ String otherMetricName) { ++ this.registryAttribute = registryAttribute; ++ this.otherMetricName = otherMetricName; ++ this.meterNamesByStatusCode = meterNamesByStatusCode; ++ } ++ ++ @Override ++ public void init(FilterConfig filterConfig) throws ServletException { ++ final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); ++ ++ String metricName = filterConfig.getInitParameter(METRIC_PREFIX); ++ if (Strings.isNullOrEmpty(metricName)) { ++ metricName = getClass().getName(); + } + +- @Override +- public void init(FilterConfig filterConfig) throws ServletException { +- final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); +- +- String metricName = filterConfig.getInitParameter(METRIC_PREFIX); +- if (metricName == null || metricName.isEmpty()) { +- metricName = getClass().getName(); +- } +- +- this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); +- for (Entry entry : meterNamesByStatusCode.entrySet()) { +- metersByStatusCode.put(entry.getKey(), +- metricsRegistry.meter(name(metricName, entry.getValue()))); +- } +- this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); +- this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); +- this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); +- this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); +- this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); +- ++ this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); ++ for (Entry entry : meterNamesByStatusCode.entrySet()) { ++ metersByStatusCode.put( ++ entry.getKey(), metricsRegistry.meter(name(metricName, entry.getValue()))); + } +- +- private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { +- final MetricRegistry metricsRegistry; +- +- final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); +- if (o instanceof MetricRegistry) { +- metricsRegistry = (MetricRegistry) o; ++ this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); ++ this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); ++ this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); ++ this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); ++ this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); ++ } ++ ++ private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { ++ final MetricRegistry metricsRegistry; ++ ++ final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); ++ if (o instanceof MetricRegistry) { ++ metricsRegistry = (MetricRegistry) o; ++ } else { ++ metricsRegistry = new MetricRegistry(); ++ } ++ return metricsRegistry; ++ } ++ ++ @Override ++ public void destroy() {} ++ ++ @Override ++ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) ++ throws IOException, ServletException { ++ final StatusExposingServletResponse wrappedResponse = ++ new StatusExposingServletResponse((HttpServletResponse) response); ++ activeRequests.inc(); ++ final Timer.Context context = requestTimer.time(); ++ boolean error = false; ++ try { ++ chain.doFilter(request, wrappedResponse); ++ } catch (IOException | RuntimeException | ServletException e) { ++ error = true; ++ throw e; ++ } finally { ++ if (!error && request.isAsyncStarted()) { ++ request.getAsyncContext().addListener(new AsyncResultListener(context)); ++ } else { ++ context.stop(); ++ activeRequests.dec(); ++ if (error) { ++ errorsMeter.mark(); + } else { +- metricsRegistry = new MetricRegistry(); ++ markMeterForStatusCode(wrappedResponse.getStatus()); + } +- return metricsRegistry; ++ } ++ } ++ } ++ ++ private void markMeterForStatusCode(int status) { ++ final Meter metric = metersByStatusCode.get(status); ++ if (metric != null) { ++ metric.mark(); ++ } else { ++ otherMeter.mark(); + } ++ } + +- @Override +- public void destroy() { ++ private static class StatusExposingServletResponse extends HttpServletResponseWrapper { ++ // The Servlet spec says: calling setStatus is optional, if no status is set, the default is ++ // 200. ++ private int httpStatus = 200; + ++ public StatusExposingServletResponse(HttpServletResponse response) { ++ super(response); + } + + @Override +- public void doFilter(ServletRequest request, +- ServletResponse response, +- FilterChain chain) throws IOException, ServletException { +- final StatusExposingServletResponse wrappedResponse = +- new StatusExposingServletResponse((HttpServletResponse) response); +- activeRequests.inc(); +- final Timer.Context context = requestTimer.time(); +- boolean error = false; +- try { +- chain.doFilter(request, wrappedResponse); +- } catch (IOException | RuntimeException | ServletException e) { +- error = true; +- throw e; +- } finally { +- if (!error && request.isAsyncStarted()) { +- request.getAsyncContext().addListener(new AsyncResultListener(context)); +- } else { +- context.stop(); +- activeRequests.dec(); +- if (error) { +- errorsMeter.mark(); +- } else { +- markMeterForStatusCode(wrappedResponse.getStatus()); +- } +- } +- } ++ public void sendError(int sc) throws IOException { ++ httpStatus = sc; ++ super.sendError(sc); + } + +- private void markMeterForStatusCode(int status) { +- final Meter metric = metersByStatusCode.get(status); +- if (metric != null) { +- metric.mark(); +- } else { +- otherMeter.mark(); +- } ++ @Override ++ public void sendError(int sc, String msg) throws IOException { ++ httpStatus = sc; ++ super.sendError(sc, msg); + } + +- private static class StatusExposingServletResponse extends HttpServletResponseWrapper { +- // The Servlet spec says: calling setStatus is optional, if no status is set, the default is 200. +- private int httpStatus = 200; +- +- public StatusExposingServletResponse(HttpServletResponse response) { +- super(response); +- } +- +- @Override +- public void sendError(int sc) throws IOException { +- httpStatus = sc; +- super.sendError(sc); +- } +- +- @Override +- public void sendError(int sc, String msg) throws IOException { +- httpStatus = sc; +- super.sendError(sc, msg); +- } +- +- @Override +- public void setStatus(int sc) { +- httpStatus = sc; +- super.setStatus(sc); +- } +- +- @Override +- public int getStatus() { +- return httpStatus; +- } ++ @Override ++ public void setStatus(int sc) { ++ httpStatus = sc; ++ super.setStatus(sc); + } + +- private class AsyncResultListener implements AsyncListener { +- private final Timer.Context context; +- private boolean done = false; +- +- public AsyncResultListener(Timer.Context context) { +- this.context = context; +- } ++ @Override ++ public int getStatus() { ++ return httpStatus; ++ } ++ } + +- @Override +- public void onComplete(AsyncEvent event) throws IOException { +- if (!done) { +- HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); +- context.stop(); +- activeRequests.dec(); +- markMeterForStatusCode(suppliedResponse.getStatus()); +- } +- } ++ private class AsyncResultListener implements AsyncListener { ++ private final Timer.Context context; ++ private boolean done = false; + +- @Override +- public void onTimeout(AsyncEvent event) throws IOException { +- context.stop(); +- activeRequests.dec(); +- timeoutsMeter.mark(); +- done = true; +- } ++ public AsyncResultListener(Timer.Context context) { ++ this.context = context; ++ } + +- @Override +- public void onError(AsyncEvent event) throws IOException { +- context.stop(); +- activeRequests.dec(); +- errorsMeter.mark(); +- done = true; +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException { ++ if (!done) { ++ HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); ++ context.stop(); ++ activeRequests.dec(); ++ markMeterForStatusCode(suppliedResponse.getStatus()); ++ } ++ } + +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException { ++ context.stop(); ++ activeRequests.dec(); ++ timeoutsMeter.mark(); ++ done = true; ++ } + +- } ++ @Override ++ public void onError(AsyncEvent event) throws IOException { ++ context.stop(); ++ activeRequests.dec(); ++ errorsMeter.mark(); ++ done = true; + } ++ ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException {} ++ } + } +--- a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/InstrumentedFilter.java ++++ b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/InstrumentedFilter.java +@@ -4,8 +4,13 @@ import java.util.HashMap; + import java.util.Map; + + /** +- * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response codes +- * to capture information about.

Use it in your servlet.xml like this:

++ * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response ++ * codes to capture information about. ++ * ++ *

Use it in your servlet.xml like this: ++ * ++ *

++ * + *

{@code
+  * 
+  *     instrumentedFilter
+@@ -18,31 +23,29 @@ import java.util.Map;
+  * }
+ */ + public class InstrumentedFilter extends AbstractInstrumentedFilter { +- public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; ++ public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; + +- private static final String NAME_PREFIX = "responseCodes."; +- private static final int OK = 200; +- private static final int CREATED = 201; +- private static final int NO_CONTENT = 204; +- private static final int BAD_REQUEST = 400; +- private static final int NOT_FOUND = 404; +- private static final int SERVER_ERROR = 500; ++ private static final String NAME_PREFIX = "responseCodes."; ++ private static final int OK = 200; ++ private static final int CREATED = 201; ++ private static final int NO_CONTENT = 204; ++ private static final int BAD_REQUEST = 400; ++ private static final int NOT_FOUND = 404; ++ private static final int SERVER_ERROR = 500; + +- /** +- * Creates a new instance of the filter. +- */ +- public InstrumentedFilter() { +- super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); +- } ++ /** Creates a new instance of the filter. */ ++ public InstrumentedFilter() { ++ super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); ++ } + +- private static Map createMeterNamesByStatusCode() { +- final Map meterNamesByStatusCode = new HashMap<>(6); +- meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); +- meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); +- meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); +- meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); +- meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); +- meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); +- return meterNamesByStatusCode; +- } ++ private static Map createMeterNamesByStatusCode() { ++ final Map meterNamesByStatusCode = new HashMap<>(6); ++ meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); ++ meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); ++ meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); ++ meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); ++ meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); ++ meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); ++ return meterNamesByStatusCode; ++ } + } +--- a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListener.java ++++ b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListener.java +@@ -10,17 +10,17 @@ import jakarta.servlet.ServletContextListener; + * application. + */ + public abstract class InstrumentedFilterContextListener implements ServletContextListener { +- /** +- * @return the {@link MetricRegistry} to inject into the servlet context. +- */ +- protected abstract MetricRegistry getMetricRegistry(); ++ /** ++ * @return the {@link MetricRegistry} to inject into the servlet context. ++ */ ++ protected abstract MetricRegistry getMetricRegistry(); + +- @Override +- public void contextInitialized(ServletContextEvent sce) { +- sce.getServletContext().setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); +- } ++ @Override ++ public void contextInitialized(ServletContextEvent sce) { ++ sce.getServletContext() ++ .setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); ++ } + +- @Override +- public void contextDestroyed(ServletContextEvent sce) { +- } ++ @Override ++ public void contextDestroyed(ServletContextEvent sce) {} + } +--- a/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java ++++ b/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java +@@ -1,32 +1,34 @@ + package io.dropwizard.metrics5.servlet6; + ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.MetricRegistry; + import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletContextEvent; + import org.junit.jupiter.api.Test; + +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- +-class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final InstrumentedFilterContextListener listener = new InstrumentedFilterContextListener() { ++final class InstrumentedFilterContextListenerTest { ++ private final MetricRegistry registry = mock(); ++ private final InstrumentedFilterContextListener listener = ++ new InstrumentedFilterContextListener() { + @Override + protected MetricRegistry getMetricRegistry() { +- return registry; ++ return registry; + } +- }; ++ }; + +- @Test +- void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ @Test ++ void injectsTheMetricRegistryIntoTheServletContext() { ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); +- when(event.getServletContext()).thenReturn(context); ++ final ServletContextEvent event = mock(); ++ when(event.getServletContext()).thenReturn(context); + +- listener.contextInitialized(event); ++ listener.contextInitialized(event); + +- verify(context).setAttribute("io.dropwizard.metrics5.servlet6.InstrumentedFilter.registry", registry); +- } ++ verify(context) ++ .setAttribute("io.dropwizard.metrics5.servlet6.InstrumentedFilter.registry", registry); ++ } + } +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/AdminServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/AdminServlet.java +@@ -6,185 +6,205 @@ import jakarta.servlet.ServletException; + import jakarta.servlet.http.HttpServlet; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; +- + import java.io.IOException; + import java.io.PrintWriter; + import java.text.MessageFormat; + + public class AdminServlet extends HttpServlet { +- public static final String DEFAULT_HEALTHCHECK_URI = "/healthcheck"; +- public static final String DEFAULT_METRICS_URI = "/metrics"; +- public static final String DEFAULT_PING_URI = "/ping"; +- public static final String DEFAULT_THREADS_URI = "/threads"; +- public static final String DEFAULT_CPU_PROFILE_URI = "/pprof"; +- +- public static final String METRICS_ENABLED_PARAM_KEY = "metrics-enabled"; +- public static final String METRICS_URI_PARAM_KEY = "metrics-uri"; +- public static final String PING_ENABLED_PARAM_KEY = "ping-enabled"; +- public static final String PING_URI_PARAM_KEY = "ping-uri"; +- public static final String THREADS_ENABLED_PARAM_KEY = "threads-enabled"; +- public static final String THREADS_URI_PARAM_KEY = "threads-uri"; +- public static final String HEALTHCHECK_ENABLED_PARAM_KEY = "healthcheck-enabled"; +- public static final String HEALTHCHECK_URI_PARAM_KEY = "healthcheck-uri"; +- public static final String SERVICE_NAME_PARAM_KEY = "service-name"; +- public static final String CPU_PROFILE_ENABLED_PARAM_KEY = "cpu-profile-enabled"; +- public static final String CPU_PROFILE_URI_PARAM_KEY = "cpu-profile-uri"; +- +- private static final String BASE_TEMPLATE = +- "%n" + +- "%n" + +- "%n" + +- " Metrics{10}%n" + +- "%n" + +- "%n" + +- "

Operational Menu{10}

%n" + +- "
    %n" + +- "%s" + +- "
%n" + +- "%n" + +- ""; +- private static final String METRICS_LINK = "
  • Metrics
  • %n"; +- private static final String PING_LINK = "
  • Ping
  • %n" ; +- private static final String THREADS_LINK = "
  • Threads
  • %n" ; +- private static final String HEALTHCHECK_LINK = "
  • Healthcheck
  • %n" ; +- private static final String CPU_PROFILE_LINK = "
  • CPU Profile
  • %n" + +- "
  • CPU Contention
  • %n"; +- +- +- private static final String CONTENT_TYPE = "text/html"; +- private static final long serialVersionUID = -2850794040708785318L; +- +- private transient HealthCheckServlet healthCheckServlet; +- private transient MetricsServlet metricsServlet; +- private transient PingServlet pingServlet; +- private transient ThreadDumpServlet threadDumpServlet; +- private transient CpuProfileServlet cpuProfileServlet; +- private transient boolean metricsEnabled; +- private transient String metricsUri; +- private transient boolean pingEnabled; +- private transient String pingUri; +- private transient boolean threadsEnabled; +- private transient String threadsUri; +- private transient boolean healthcheckEnabled; +- private transient String healthcheckUri; +- private transient boolean cpuProfileEnabled; +- private transient String cpuProfileUri; +- private transient String serviceName; +- private transient String pageContentTemplate; +- +- @Override +- public void init(ServletConfig config) throws ServletException { +- super.init(config); +- +- final ServletContext context = config.getServletContext(); +- final StringBuilder servletLinks = new StringBuilder(); +- +- this.metricsEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(METRICS_ENABLED_PARAM_KEY), "true")); +- if (this.metricsEnabled) { +- servletLinks.append(METRICS_LINK); +- } +- this.metricsServlet = new MetricsServlet(); +- metricsServlet.init(config); +- +- this.pingEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(PING_ENABLED_PARAM_KEY), "true")); +- if (this.pingEnabled) { +- servletLinks.append(PING_LINK); +- } +- this.pingServlet = new PingServlet(); +- pingServlet.init(config); +- +- this.threadsEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(THREADS_ENABLED_PARAM_KEY), "true")); +- if (this.threadsEnabled) { +- servletLinks.append(THREADS_LINK); +- } +- this.threadDumpServlet = new ThreadDumpServlet(); +- threadDumpServlet.init(config); +- +- this.healthcheckEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(HEALTHCHECK_ENABLED_PARAM_KEY), "true")); +- if (this.healthcheckEnabled) { +- servletLinks.append(HEALTHCHECK_LINK); +- } +- this.healthCheckServlet = new HealthCheckServlet(); +- healthCheckServlet.init(config); +- +- this.cpuProfileEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(CPU_PROFILE_ENABLED_PARAM_KEY), "true")); +- if (this.cpuProfileEnabled) { +- servletLinks.append(CPU_PROFILE_LINK); +- } +- this.cpuProfileServlet = new CpuProfileServlet(); +- cpuProfileServlet.init(config); +- +- pageContentTemplate = String.format(BASE_TEMPLATE, String.format(servletLinks.toString())); +- +- this.metricsUri = getParam(context.getInitParameter(METRICS_URI_PARAM_KEY), DEFAULT_METRICS_URI); +- this.pingUri = getParam(context.getInitParameter(PING_URI_PARAM_KEY), DEFAULT_PING_URI); +- this.threadsUri = getParam(context.getInitParameter(THREADS_URI_PARAM_KEY), DEFAULT_THREADS_URI); +- this.healthcheckUri = getParam(context.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI); +- this.cpuProfileUri = getParam(context.getInitParameter(CPU_PROFILE_URI_PARAM_KEY), DEFAULT_CPU_PROFILE_URI); +- this.serviceName = getParam(context.getInitParameter(SERVICE_NAME_PARAM_KEY), null); ++ public static final String DEFAULT_HEALTHCHECK_URI = "/healthcheck"; ++ public static final String DEFAULT_METRICS_URI = "/metrics"; ++ public static final String DEFAULT_PING_URI = "/ping"; ++ public static final String DEFAULT_THREADS_URI = "/threads"; ++ public static final String DEFAULT_CPU_PROFILE_URI = "/pprof"; ++ ++ public static final String METRICS_ENABLED_PARAM_KEY = "metrics-enabled"; ++ public static final String METRICS_URI_PARAM_KEY = "metrics-uri"; ++ public static final String PING_ENABLED_PARAM_KEY = "ping-enabled"; ++ public static final String PING_URI_PARAM_KEY = "ping-uri"; ++ public static final String THREADS_ENABLED_PARAM_KEY = "threads-enabled"; ++ public static final String THREADS_URI_PARAM_KEY = "threads-uri"; ++ public static final String HEALTHCHECK_ENABLED_PARAM_KEY = "healthcheck-enabled"; ++ public static final String HEALTHCHECK_URI_PARAM_KEY = "healthcheck-uri"; ++ public static final String SERVICE_NAME_PARAM_KEY = "service-name"; ++ public static final String CPU_PROFILE_ENABLED_PARAM_KEY = "cpu-profile-enabled"; ++ public static final String CPU_PROFILE_URI_PARAM_KEY = "cpu-profile-uri"; ++ ++ private static final String BASE_TEMPLATE = ++ "%n" ++ + "%n" ++ + "%n" ++ + " Metrics{10}%n" ++ + "%n" ++ + "%n" ++ + "

    Operational Menu{10}

    %n" ++ + "
      %n" ++ + "%s" ++ + "
    %n" ++ + "%n" ++ + ""; ++ private static final String METRICS_LINK = ++ "
  • Metrics
  • %n"; ++ private static final String PING_LINK = "
  • Ping
  • %n"; ++ private static final String THREADS_LINK = "
  • Threads
  • %n"; ++ private static final String HEALTHCHECK_LINK = ++ "
  • Healthcheck
  • %n"; ++ private static final String CPU_PROFILE_LINK = ++ "
  • CPU Profile
  • %n" ++ + "
  • CPU Contention
  • %n"; ++ ++ private static final String CONTENT_TYPE = "text/html"; ++ private static final long serialVersionUID = -2850794040708785318L; ++ ++ private transient HealthCheckServlet healthCheckServlet; ++ private transient MetricsServlet metricsServlet; ++ private transient PingServlet pingServlet; ++ private transient ThreadDumpServlet threadDumpServlet; ++ private transient CpuProfileServlet cpuProfileServlet; ++ private transient boolean metricsEnabled; ++ private transient String metricsUri; ++ private transient boolean pingEnabled; ++ private transient String pingUri; ++ private transient boolean threadsEnabled; ++ private transient String threadsUri; ++ private transient boolean healthcheckEnabled; ++ private transient String healthcheckUri; ++ private transient boolean cpuProfileEnabled; ++ private transient String cpuProfileUri; ++ private transient String serviceName; ++ private transient String pageContentTemplate; ++ ++ @Override ++ public void init(ServletConfig config) throws ServletException { ++ super.init(config); ++ ++ final ServletContext context = config.getServletContext(); ++ final StringBuilder servletLinks = new StringBuilder(); ++ ++ this.metricsEnabled = ++ Boolean.parseBoolean(getParam(context.getInitParameter(METRICS_ENABLED_PARAM_KEY), "true")); ++ if (this.metricsEnabled) { ++ servletLinks.append(METRICS_LINK); + } ++ this.metricsServlet = new MetricsServlet(); ++ metricsServlet.init(config); + +- @Override +- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { +- final String path = req.getContextPath() + req.getServletPath(); +- +- resp.setStatus(HttpServletResponse.SC_OK); +- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); +- resp.setContentType(CONTENT_TYPE); +- try (PrintWriter writer = resp.getWriter()) { +- writer.println(MessageFormat.format(pageContentTemplate, path, metricsUri, path, pingUri, path, +- threadsUri, path, healthcheckUri, path, cpuProfileUri, +- serviceName == null ? "" : " (" + serviceName + ")")); +- } ++ this.pingEnabled = ++ Boolean.parseBoolean(getParam(context.getInitParameter(PING_ENABLED_PARAM_KEY), "true")); ++ if (this.pingEnabled) { ++ servletLinks.append(PING_LINK); + } ++ this.pingServlet = new PingServlet(); ++ pingServlet.init(config); + +- @Override +- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { +- final String uri = req.getPathInfo(); +- if (uri == null || uri.equals("/")) { +- super.service(req, resp); +- } else if (uri.equals(healthcheckUri)) { +- if (healthcheckEnabled) { +- healthCheckServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else if (uri.startsWith(metricsUri)) { +- if (metricsEnabled) { +- metricsServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else if (uri.equals(pingUri)) { +- if (pingEnabled) { +- pingServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else if (uri.equals(threadsUri)) { +- if (threadsEnabled) { +- threadDumpServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else if (uri.equals(cpuProfileUri)) { +- if (cpuProfileEnabled) { +- cpuProfileServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } ++ this.threadsEnabled = ++ Boolean.parseBoolean(getParam(context.getInitParameter(THREADS_ENABLED_PARAM_KEY), "true")); ++ if (this.threadsEnabled) { ++ servletLinks.append(THREADS_LINK); + } +- +- private static String getParam(String initParam, String defaultValue) { +- return initParam == null ? defaultValue : initParam; ++ this.threadDumpServlet = new ThreadDumpServlet(); ++ threadDumpServlet.init(config); ++ ++ this.healthcheckEnabled = ++ Boolean.parseBoolean( ++ getParam(context.getInitParameter(HEALTHCHECK_ENABLED_PARAM_KEY), "true")); ++ if (this.healthcheckEnabled) { ++ servletLinks.append(HEALTHCHECK_LINK); ++ } ++ this.healthCheckServlet = new HealthCheckServlet(); ++ healthCheckServlet.init(config); ++ ++ this.cpuProfileEnabled = ++ Boolean.parseBoolean( ++ getParam(context.getInitParameter(CPU_PROFILE_ENABLED_PARAM_KEY), "true")); ++ if (this.cpuProfileEnabled) { ++ servletLinks.append(CPU_PROFILE_LINK); + } ++ this.cpuProfileServlet = new CpuProfileServlet(); ++ cpuProfileServlet.init(config); ++ ++ pageContentTemplate = String.format(BASE_TEMPLATE, String.format(servletLinks.toString())); ++ ++ this.metricsUri = ++ getParam(context.getInitParameter(METRICS_URI_PARAM_KEY), DEFAULT_METRICS_URI); ++ this.pingUri = getParam(context.getInitParameter(PING_URI_PARAM_KEY), DEFAULT_PING_URI); ++ this.threadsUri = ++ getParam(context.getInitParameter(THREADS_URI_PARAM_KEY), DEFAULT_THREADS_URI); ++ this.healthcheckUri = ++ getParam(context.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI); ++ this.cpuProfileUri = ++ getParam(context.getInitParameter(CPU_PROFILE_URI_PARAM_KEY), DEFAULT_CPU_PROFILE_URI); ++ this.serviceName = getParam(context.getInitParameter(SERVICE_NAME_PARAM_KEY), null); ++ } ++ ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ final String path = req.getContextPath() + req.getServletPath(); ++ ++ resp.setStatus(HttpServletResponse.SC_OK); ++ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); ++ resp.setContentType(CONTENT_TYPE); ++ try (PrintWriter writer = resp.getWriter()) { ++ writer.println( ++ MessageFormat.format( ++ pageContentTemplate, ++ path, ++ metricsUri, ++ path, ++ pingUri, ++ path, ++ threadsUri, ++ path, ++ healthcheckUri, ++ path, ++ cpuProfileUri, ++ serviceName == null ? "" : " (" + serviceName + ")")); ++ } ++ } ++ ++ @Override ++ protected void service(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ final String uri = req.getPathInfo(); ++ if (uri == null || uri.equals("/")) { ++ super.service(req, resp); ++ } else if (uri.equals(healthcheckUri)) { ++ if (healthcheckEnabled) { ++ healthCheckServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else if (uri.startsWith(metricsUri)) { ++ if (metricsEnabled) { ++ metricsServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else if (uri.equals(pingUri)) { ++ if (pingEnabled) { ++ pingServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else if (uri.equals(threadsUri)) { ++ if (threadsEnabled) { ++ threadDumpServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else if (uri.equals(cpuProfileUri)) { ++ if (cpuProfileEnabled) { ++ cpuProfileServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } ++ ++ private static String getParam(String initParam, String defaultValue) { ++ return initParam == null ? defaultValue : initParam; ++ } + } +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java +@@ -5,7 +5,6 @@ import jakarta.servlet.ServletException; + import jakarta.servlet.http.HttpServlet; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; +- + import java.io.IOException; + import java.io.OutputStream; + import java.time.Duration; +@@ -13,67 +12,68 @@ import java.util.concurrent.locks.Lock; + import java.util.concurrent.locks.ReentrantLock; + + /** +- * An HTTP servlets which outputs a pprof parseable response. ++ * An HTTP servlets which outputs a pprof ++ * parseable response. + */ + public class CpuProfileServlet extends HttpServlet { +- private static final long serialVersionUID = -668666696530287501L; +- private static final String CONTENT_TYPE = "pprof/raw"; +- private static final String CACHE_CONTROL = "Cache-Control"; +- private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; +- private final Lock lock = new ReentrantLock(); ++ private static final long serialVersionUID = -668666696530287501L; ++ private static final String CONTENT_TYPE = "pprof/raw"; ++ private static final String CACHE_CONTROL = "Cache-Control"; ++ private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; ++ private final Lock lock = new ReentrantLock(); + +- @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { + +- int duration = 10; +- if (req.getParameter("duration") != null) { +- try { +- duration = Integer.parseInt(req.getParameter("duration")); +- } catch (NumberFormatException e) { +- duration = 10; +- } +- } ++ int duration = 10; ++ if (req.getParameter("duration") != null) { ++ try { ++ duration = Integer.parseInt(req.getParameter("duration")); ++ } catch (NumberFormatException e) { ++ duration = 10; ++ } ++ } + +- int frequency = 100; +- if (req.getParameter("frequency") != null) { +- try { +- frequency = Integer.parseInt(req.getParameter("frequency")); +- frequency = Math.min(Math.max(frequency, 1), 1000); +- } catch (NumberFormatException e) { +- frequency = 100; +- } +- } ++ int frequency = 100; ++ if (req.getParameter("frequency") != null) { ++ try { ++ frequency = Integer.parseInt(req.getParameter("frequency")); ++ frequency = Math.min(Math.max(frequency, 1), 1000); ++ } catch (NumberFormatException e) { ++ frequency = 100; ++ } ++ } + +- final Thread.State state; +- if ("blocked".equalsIgnoreCase(req.getParameter("state"))) { +- state = Thread.State.BLOCKED; +- } else { +- state = Thread.State.RUNNABLE; +- } ++ final Thread.State state; ++ if ("blocked".equalsIgnoreCase(req.getParameter("state"))) { ++ state = Thread.State.BLOCKED; ++ } else { ++ state = Thread.State.RUNNABLE; ++ } + +- resp.setStatus(HttpServletResponse.SC_OK); +- resp.setHeader(CACHE_CONTROL, NO_CACHE); +- resp.setContentType(CONTENT_TYPE); +- try (OutputStream output = resp.getOutputStream()) { +- doProfile(output, duration, frequency, state); +- } ++ resp.setStatus(HttpServletResponse.SC_OK); ++ resp.setHeader(CACHE_CONTROL, NO_CACHE); ++ resp.setContentType(CONTENT_TYPE); ++ try (OutputStream output = resp.getOutputStream()) { ++ doProfile(output, duration, frequency, state); + } ++ } + +- protected void doProfile(OutputStream out, int duration, int frequency, Thread.State state) throws IOException { +- if (lock.tryLock()) { +- try { +- CpuProfile profile = CpuProfile.record(Duration.ofSeconds(duration), +- frequency, state); +- if (profile == null) { +- throw new RuntimeException("could not create CpuProfile"); +- } +- profile.writeGoogleProfile(out); +- return; +- } finally { +- lock.unlock(); +- } ++ protected void doProfile(OutputStream out, int duration, int frequency, Thread.State state) ++ throws IOException { ++ if (lock.tryLock()) { ++ try { ++ CpuProfile profile = CpuProfile.record(Duration.ofSeconds(duration), frequency, state); ++ if (profile == null) { ++ throw new RuntimeException("could not create CpuProfile"); + } +- throw new RuntimeException("Only one profile request may be active at a time"); ++ profile.writeGoogleProfile(out); ++ return; ++ } finally { ++ lock.unlock(); ++ } + } ++ throw new RuntimeException("Only one profile request may be active at a time"); ++ } + } +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java +@@ -1,11 +1,11 @@ + package io.dropwizard.metrics5.servlets; + ++import com.fasterxml.jackson.databind.ObjectMapper; ++import com.fasterxml.jackson.databind.ObjectWriter; + import io.dropwizard.metrics5.health.HealthCheck; + import io.dropwizard.metrics5.health.HealthCheckFilter; + import io.dropwizard.metrics5.health.HealthCheckRegistry; + import io.dropwizard.metrics5.json.HealthCheckModule; +-import com.fasterxml.jackson.databind.ObjectMapper; +-import com.fasterxml.jackson.databind.ObjectWriter; + import jakarta.servlet.ServletConfig; + import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletContextEvent; +@@ -14,7 +14,6 @@ import jakarta.servlet.ServletException; + import jakarta.servlet.http.HttpServlet; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; +- + import java.io.IOException; + import java.io.OutputStream; + import java.util.Map; +@@ -22,175 +21,179 @@ import java.util.SortedMap; + import java.util.concurrent.ExecutorService; + + public class HealthCheckServlet extends HttpServlet { +- public static abstract class ContextListener implements ServletContextListener { +- /** +- * @return the {@link HealthCheckRegistry} to inject into the servlet context. +- */ +- protected abstract HealthCheckRegistry getHealthCheckRegistry(); +- +- /** +- * @return the {@link ExecutorService} to inject into the servlet context, or {@code null} +- * if the health checks should be run in the servlet worker thread. +- */ +- protected ExecutorService getExecutorService() { +- // don't use a thread pool by default +- return null; +- } +- +- /** +- * @return the {@link HealthCheckFilter} that shall be used to filter health checks, +- * or {@link HealthCheckFilter#ALL} if the default should be used. +- */ +- protected HealthCheckFilter getHealthCheckFilter() { +- return HealthCheckFilter.ALL; +- } +- +- /** +- * @return the {@link ObjectMapper} that shall be used to render health checks, +- * or {@code null} if the default object mapper should be used. +- */ +- protected ObjectMapper getObjectMapper() { +- // don't use an object mapper by default +- return null; +- } +- +- @Override +- public void contextInitialized(ServletContextEvent event) { +- final ServletContext context = event.getServletContext(); +- context.setAttribute(HEALTH_CHECK_REGISTRY, getHealthCheckRegistry()); +- context.setAttribute(HEALTH_CHECK_EXECUTOR, getExecutorService()); +- context.setAttribute(HEALTH_CHECK_MAPPER, getObjectMapper()); +- } +- +- @Override +- public void contextDestroyed(ServletContextEvent event) { +- // no-op +- } +- } +- +- public static final String HEALTH_CHECK_REGISTRY = HealthCheckServlet.class.getCanonicalName() + ".registry"; +- public static final String HEALTH_CHECK_EXECUTOR = HealthCheckServlet.class.getCanonicalName() + ".executor"; +- public static final String HEALTH_CHECK_FILTER = HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter"; +- public static final String HEALTH_CHECK_MAPPER = HealthCheckServlet.class.getCanonicalName() + ".mapper"; +- public static final String HEALTH_CHECK_HTTP_STATUS_INDICATOR = HealthCheckServlet.class.getCanonicalName() + ".httpStatusIndicator"; +- +- private static final long serialVersionUID = -8432996484889177321L; +- private static final String CONTENT_TYPE = "application/json"; +- private static final String HTTP_STATUS_INDICATOR_PARAM = "httpStatusIndicator"; +- +- private transient HealthCheckRegistry registry; +- private transient ExecutorService executorService; +- private transient HealthCheckFilter filter; +- private transient ObjectMapper mapper; +- private transient boolean httpStatusIndicator; +- +- public HealthCheckServlet() { +- } +- +- public HealthCheckServlet(HealthCheckRegistry registry) { +- this.registry = registry; ++ public abstract static class ContextListener implements ServletContextListener { ++ /** ++ * @return the {@link HealthCheckRegistry} to inject into the servlet context. ++ */ ++ protected abstract HealthCheckRegistry getHealthCheckRegistry(); ++ ++ /** ++ * @return the {@link ExecutorService} to inject into the servlet context, or {@code null} if ++ * the health checks should be run in the servlet worker thread. ++ */ ++ protected ExecutorService getExecutorService() { ++ // don't use a thread pool by default ++ return null; + } + +- @Override +- public void init(ServletConfig config) throws ServletException { +- super.init(config); +- +- final ServletContext context = config.getServletContext(); +- if (null == registry) { +- final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); +- if (registryAttr instanceof HealthCheckRegistry) { +- this.registry = (HealthCheckRegistry) registryAttr; +- } else { +- throw new ServletException("Couldn't find a HealthCheckRegistry instance."); +- } +- } +- +- final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR); +- if (executorAttr instanceof ExecutorService) { +- this.executorService = (ExecutorService) executorAttr; +- } +- +- +- final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER); +- if (filterAttr instanceof HealthCheckFilter) { +- filter = (HealthCheckFilter) filterAttr; +- } +- if (filter == null) { +- filter = HealthCheckFilter.ALL; +- } +- +- final Object mapperAttr = context.getAttribute(HEALTH_CHECK_MAPPER); +- if (mapperAttr instanceof ObjectMapper) { +- this.mapper = (ObjectMapper) mapperAttr; +- } else { +- this.mapper = new ObjectMapper(); +- } +- this.mapper.registerModule(new HealthCheckModule()); +- +- final Object httpStatusIndicatorAttr = context.getAttribute(HEALTH_CHECK_HTTP_STATUS_INDICATOR); +- if (httpStatusIndicatorAttr instanceof Boolean) { +- this.httpStatusIndicator = (Boolean) httpStatusIndicatorAttr; +- } else { +- this.httpStatusIndicator = true; +- } ++ /** ++ * @return the {@link HealthCheckFilter} that shall be used to filter health checks, or {@link ++ * HealthCheckFilter#ALL} if the default should be used. ++ */ ++ protected HealthCheckFilter getHealthCheckFilter() { ++ return HealthCheckFilter.ALL; ++ } ++ ++ /** ++ * @return the {@link ObjectMapper} that shall be used to render health checks, or {@code null} ++ * if the default object mapper should be used. ++ */ ++ protected ObjectMapper getObjectMapper() { ++ // don't use an object mapper by default ++ return null; + } + + @Override +- public void destroy() { +- super.destroy(); +- registry.shutdown(); ++ public void contextInitialized(ServletContextEvent event) { ++ final ServletContext context = event.getServletContext(); ++ context.setAttribute(HEALTH_CHECK_REGISTRY, getHealthCheckRegistry()); ++ context.setAttribute(HEALTH_CHECK_EXECUTOR, getExecutorService()); ++ context.setAttribute(HEALTH_CHECK_MAPPER, getObjectMapper()); + } + + @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { +- final SortedMap results = runHealthChecks(); +- resp.setContentType(CONTENT_TYPE); +- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); +- if (results.isEmpty()) { +- resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); +- } else { +- final String reqParameter = req.getParameter(HTTP_STATUS_INDICATOR_PARAM); +- final boolean httpStatusIndicatorParam = Boolean.parseBoolean(reqParameter); +- final boolean useHttpStatusForHealthCheck = reqParameter == null ? httpStatusIndicator : httpStatusIndicatorParam; +- if (!useHttpStatusForHealthCheck || isAllHealthy(results)) { +- resp.setStatus(HttpServletResponse.SC_OK); +- } else { +- resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); +- } +- } +- +- try (OutputStream output = resp.getOutputStream()) { +- getWriter(req).writeValue(output, results); +- } +- } +- +- private ObjectWriter getWriter(HttpServletRequest request) { +- final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); +- if (prettyPrint) { +- return mapper.writerWithDefaultPrettyPrinter(); +- } +- return mapper.writer(); +- } +- +- private SortedMap runHealthChecks() { +- if (executorService == null) { +- return registry.runHealthChecks(filter); +- } +- return registry.runHealthChecks(executorService, filter); +- } +- +- private static boolean isAllHealthy(Map results) { +- for (HealthCheck.Result result : results.values()) { +- if (!result.isHealthy()) { +- return false; +- } +- } +- return true; +- } +- +- // visible for testing +- ObjectMapper getMapper() { +- return mapper; ++ public void contextDestroyed(ServletContextEvent event) { ++ // no-op ++ } ++ } ++ ++ public static final String HEALTH_CHECK_REGISTRY = ++ HealthCheckServlet.class.getCanonicalName() + ".registry"; ++ public static final String HEALTH_CHECK_EXECUTOR = ++ HealthCheckServlet.class.getCanonicalName() + ".executor"; ++ public static final String HEALTH_CHECK_FILTER = ++ HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter"; ++ public static final String HEALTH_CHECK_MAPPER = ++ HealthCheckServlet.class.getCanonicalName() + ".mapper"; ++ public static final String HEALTH_CHECK_HTTP_STATUS_INDICATOR = ++ HealthCheckServlet.class.getCanonicalName() + ".httpStatusIndicator"; ++ ++ private static final long serialVersionUID = -8432996484889177321L; ++ private static final String CONTENT_TYPE = "application/json"; ++ private static final String HTTP_STATUS_INDICATOR_PARAM = "httpStatusIndicator"; ++ ++ private transient HealthCheckRegistry registry; ++ private transient ExecutorService executorService; ++ private transient HealthCheckFilter filter; ++ private transient ObjectMapper mapper; ++ private transient boolean httpStatusIndicator; ++ ++ public HealthCheckServlet() {} ++ ++ public HealthCheckServlet(HealthCheckRegistry registry) { ++ this.registry = registry; ++ } ++ ++ @Override ++ public void init(ServletConfig config) throws ServletException { ++ super.init(config); ++ ++ final ServletContext context = config.getServletContext(); ++ if (registry == null) { ++ final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); ++ if (registryAttr instanceof HealthCheckRegistry) { ++ this.registry = (HealthCheckRegistry) registryAttr; ++ } else { ++ throw new ServletException("Couldn't find a HealthCheckRegistry instance."); ++ } ++ } ++ ++ final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR); ++ if (executorAttr instanceof ExecutorService) { ++ this.executorService = (ExecutorService) executorAttr; ++ } ++ ++ final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER); ++ if (filterAttr instanceof HealthCheckFilter) { ++ filter = (HealthCheckFilter) filterAttr; ++ } ++ if (filter == null) { ++ filter = HealthCheckFilter.ALL; + } ++ ++ final Object mapperAttr = context.getAttribute(HEALTH_CHECK_MAPPER); ++ if (mapperAttr instanceof ObjectMapper) { ++ this.mapper = (ObjectMapper) mapperAttr; ++ } else { ++ this.mapper = new ObjectMapper(); ++ } ++ this.mapper.registerModule(new HealthCheckModule()); ++ ++ final Object httpStatusIndicatorAttr = context.getAttribute(HEALTH_CHECK_HTTP_STATUS_INDICATOR); ++ if (httpStatusIndicatorAttr instanceof Boolean) { ++ this.httpStatusIndicator = (Boolean) httpStatusIndicatorAttr; ++ } else { ++ this.httpStatusIndicator = true; ++ } ++ } ++ ++ @Override ++ public void destroy() { ++ super.destroy(); ++ registry.shutdown(); ++ } ++ ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ final SortedMap results = runHealthChecks(); ++ resp.setContentType(CONTENT_TYPE); ++ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); ++ if (results.isEmpty()) { ++ resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); ++ } else { ++ final String reqParameter = req.getParameter(HTTP_STATUS_INDICATOR_PARAM); ++ final boolean httpStatusIndicatorParam = Boolean.parseBoolean(reqParameter); ++ final boolean useHttpStatusForHealthCheck = ++ reqParameter == null ? httpStatusIndicator : httpStatusIndicatorParam; ++ if (!useHttpStatusForHealthCheck || isAllHealthy(results)) { ++ resp.setStatus(HttpServletResponse.SC_OK); ++ } else { ++ resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ++ } ++ } ++ ++ try (OutputStream output = resp.getOutputStream()) { ++ getWriter(req).writeValue(output, results); ++ } ++ } ++ ++ private ObjectWriter getWriter(HttpServletRequest request) { ++ final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); ++ if (prettyPrint) { ++ return mapper.writerWithDefaultPrettyPrinter(); ++ } ++ return mapper.writer(); ++ } ++ ++ private SortedMap runHealthChecks() { ++ if (executorService == null) { ++ return registry.runHealthChecks(filter); ++ } ++ return registry.runHealthChecks(executorService, filter); ++ } ++ ++ private static boolean isAllHealthy(Map results) { ++ for (HealthCheck.Result result : results.values()) { ++ if (!result.isHealthy()) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ // visible for testing ++ ObjectMapper getMapper() { ++ return mapper; ++ } + } +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +@@ -1,11 +1,11 @@ + package io.dropwizard.metrics5.servlets; + +-import io.dropwizard.metrics5.MetricFilter; +-import io.dropwizard.metrics5.MetricRegistry; +-import io.dropwizard.metrics5.json.MetricsModule; + import com.fasterxml.jackson.databind.ObjectMapper; + import com.fasterxml.jackson.databind.ObjectWriter; + import com.fasterxml.jackson.databind.util.JSONPObject; ++import io.dropwizard.metrics5.MetricFilter; ++import io.dropwizard.metrics5.MetricRegistry; ++import io.dropwizard.metrics5.json.MetricsModule; + import jakarta.servlet.ServletConfig; + import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletContextEvent; +@@ -14,7 +14,6 @@ import jakarta.servlet.ServletException; + import jakarta.servlet.http.HttpServlet; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; +- + import java.io.IOException; + import java.io.OutputStream; + import java.util.Locale; +@@ -24,176 +23,177 @@ import java.util.concurrent.TimeUnit; + * A servlet which returns the metrics in a given registry as an {@code application/json} response. + */ + public class MetricsServlet extends HttpServlet { ++ /** ++ * An abstract {@link ServletContextListener} which allows you to programmatically inject the ++ * {@link MetricRegistry}, rate and duration units, and allowed origin for {@link MetricsServlet}. ++ */ ++ public abstract static class ContextListener implements ServletContextListener { + /** +- * An abstract {@link ServletContextListener} which allows you to programmatically inject the +- * {@link MetricRegistry}, rate and duration units, and allowed origin for +- * {@link MetricsServlet}. ++ * @return the {@link MetricRegistry} to inject into the servlet context. + */ +- public static abstract class ContextListener implements ServletContextListener { +- /** +- * @return the {@link MetricRegistry} to inject into the servlet context. +- */ +- protected abstract MetricRegistry getMetricRegistry(); +- +- /** +- * @return the {@link TimeUnit} to which rates should be converted, or {@code null} if the +- * default should be used. +- */ +- protected TimeUnit getRateUnit() { +- // use the default +- return null; +- } +- +- /** +- * @return the {@link TimeUnit} to which durations should be converted, or {@code null} if +- * the default should be used. +- */ +- protected TimeUnit getDurationUnit() { +- // use the default +- return null; +- } +- +- /** +- * @return the {@code Access-Control-Allow-Origin} header value, if any. +- */ +- protected String getAllowedOrigin() { +- // use the default +- return null; +- } +- +- /** +- * Returns the name of the parameter used to specify the jsonp callback, if any. +- */ +- protected String getJsonpCallbackParameter() { +- return null; +- } +- +- /** +- * Returns the {@link MetricFilter} that shall be used to filter metrics, or {@link MetricFilter#ALL} if +- * the default should be used. +- */ +- protected MetricFilter getMetricFilter() { +- // use the default +- return MetricFilter.ALL; +- } +- +- @Override +- public void contextInitialized(ServletContextEvent event) { +- final ServletContext context = event.getServletContext(); +- context.setAttribute(METRICS_REGISTRY, getMetricRegistry()); +- context.setAttribute(METRIC_FILTER, getMetricFilter()); +- if (getDurationUnit() != null) { +- context.setInitParameter(MetricsServlet.DURATION_UNIT, getDurationUnit().toString()); +- } +- if (getRateUnit() != null) { +- context.setInitParameter(MetricsServlet.RATE_UNIT, getRateUnit().toString()); +- } +- if (getAllowedOrigin() != null) { +- context.setInitParameter(MetricsServlet.ALLOWED_ORIGIN, getAllowedOrigin()); +- } +- if (getJsonpCallbackParameter() != null) { +- context.setAttribute(CALLBACK_PARAM, getJsonpCallbackParameter()); +- } +- } +- +- @Override +- public void contextDestroyed(ServletContextEvent event) { +- // no-op +- } +- } +- +- public static final String RATE_UNIT = MetricsServlet.class.getCanonicalName() + ".rateUnit"; +- public static final String DURATION_UNIT = MetricsServlet.class.getCanonicalName() + ".durationUnit"; +- public static final String SHOW_SAMPLES = MetricsServlet.class.getCanonicalName() + ".showSamples"; +- public static final String METRICS_REGISTRY = MetricsServlet.class.getCanonicalName() + ".registry"; +- public static final String ALLOWED_ORIGIN = MetricsServlet.class.getCanonicalName() + ".allowedOrigin"; +- public static final String METRIC_FILTER = MetricsServlet.class.getCanonicalName() + ".metricFilter"; +- public static final String CALLBACK_PARAM = MetricsServlet.class.getCanonicalName() + ".jsonpCallback"; ++ protected abstract MetricRegistry getMetricRegistry(); + +- private static final long serialVersionUID = 1049773947734939602L; +- private static final String CONTENT_TYPE = "application/json"; ++ /** ++ * @return the {@link TimeUnit} to which rates should be converted, or {@code null} if the ++ * default should be used. ++ */ ++ protected TimeUnit getRateUnit() { ++ // use the default ++ return null; ++ } + +- protected String allowedOrigin; +- protected String jsonpParamName; +- protected transient MetricRegistry registry; +- protected transient ObjectMapper mapper; ++ /** ++ * @return the {@link TimeUnit} to which durations should be converted, or {@code null} if the ++ * default should be used. ++ */ ++ protected TimeUnit getDurationUnit() { ++ // use the default ++ return null; ++ } + +- public MetricsServlet() { ++ /** ++ * @return the {@code Access-Control-Allow-Origin} header value, if any. ++ */ ++ protected String getAllowedOrigin() { ++ // use the default ++ return null; + } + +- public MetricsServlet(MetricRegistry registry) { +- this.registry = registry; ++ /** Returns the name of the parameter used to specify the jsonp callback, if any. */ ++ protected String getJsonpCallbackParameter() { ++ return null; + } + +- @Override +- public void init(ServletConfig config) throws ServletException { +- super.init(config); +- +- final ServletContext context = config.getServletContext(); +- if (null == registry) { +- final Object registryAttr = context.getAttribute(METRICS_REGISTRY); +- if (registryAttr instanceof MetricRegistry) { +- this.registry = (MetricRegistry) registryAttr; +- } else { +- throw new ServletException("Couldn't find a MetricRegistry instance."); +- } +- } +- this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); +- this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); +- +- setupMetricsModule(context); ++ /** ++ * Returns the {@link MetricFilter} that shall be used to filter metrics, or {@link ++ * MetricFilter#ALL} if the default should be used. ++ */ ++ protected MetricFilter getMetricFilter() { ++ // use the default ++ return MetricFilter.ALL; + } + +- protected void setupMetricsModule(ServletContext context) { +- final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), +- TimeUnit.SECONDS); +- final TimeUnit durationUnit = parseTimeUnit(context.getInitParameter(DURATION_UNIT), +- TimeUnit.SECONDS); +- final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES)); +- MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER); +- if (filter == null) { +- filter = MetricFilter.ALL; +- } +- +- this.mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit, +- durationUnit, +- showSamples, +- filter)); ++ @Override ++ public void contextInitialized(ServletContextEvent event) { ++ final ServletContext context = event.getServletContext(); ++ context.setAttribute(METRICS_REGISTRY, getMetricRegistry()); ++ context.setAttribute(METRIC_FILTER, getMetricFilter()); ++ if (getDurationUnit() != null) { ++ context.setInitParameter(MetricsServlet.DURATION_UNIT, getDurationUnit().toString()); ++ } ++ if (getRateUnit() != null) { ++ context.setInitParameter(MetricsServlet.RATE_UNIT, getRateUnit().toString()); ++ } ++ if (getAllowedOrigin() != null) { ++ context.setInitParameter(MetricsServlet.ALLOWED_ORIGIN, getAllowedOrigin()); ++ } ++ if (getJsonpCallbackParameter() != null) { ++ context.setAttribute(CALLBACK_PARAM, getJsonpCallbackParameter()); ++ } + } + + @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { +- resp.setContentType(CONTENT_TYPE); +- if (allowedOrigin != null) { +- resp.setHeader("Access-Control-Allow-Origin", allowedOrigin); +- } +- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); +- resp.setStatus(HttpServletResponse.SC_OK); +- +- try (OutputStream output = resp.getOutputStream()) { +- if (jsonpParamName != null && req.getParameter(jsonpParamName) != null) { +- getWriter(req).writeValue(output, new JSONPObject(req.getParameter(jsonpParamName), registry)); +- } else { +- getWriter(req).writeValue(output, registry); +- } +- } ++ public void contextDestroyed(ServletContextEvent event) { ++ // no-op ++ } ++ } ++ ++ public static final String RATE_UNIT = MetricsServlet.class.getCanonicalName() + ".rateUnit"; ++ public static final String DURATION_UNIT = ++ MetricsServlet.class.getCanonicalName() + ".durationUnit"; ++ public static final String SHOW_SAMPLES = ++ MetricsServlet.class.getCanonicalName() + ".showSamples"; ++ public static final String METRICS_REGISTRY = ++ MetricsServlet.class.getCanonicalName() + ".registry"; ++ public static final String ALLOWED_ORIGIN = ++ MetricsServlet.class.getCanonicalName() + ".allowedOrigin"; ++ public static final String METRIC_FILTER = ++ MetricsServlet.class.getCanonicalName() + ".metricFilter"; ++ public static final String CALLBACK_PARAM = ++ MetricsServlet.class.getCanonicalName() + ".jsonpCallback"; ++ ++ private static final long serialVersionUID = 1049773947734939602L; ++ private static final String CONTENT_TYPE = "application/json"; ++ ++ protected String allowedOrigin; ++ protected String jsonpParamName; ++ protected transient MetricRegistry registry; ++ protected transient ObjectMapper mapper; ++ ++ public MetricsServlet() {} ++ ++ public MetricsServlet(MetricRegistry registry) { ++ this.registry = registry; ++ } ++ ++ @Override ++ public void init(ServletConfig config) throws ServletException { ++ super.init(config); ++ ++ final ServletContext context = config.getServletContext(); ++ if (registry == null) { ++ final Object registryAttr = context.getAttribute(METRICS_REGISTRY); ++ if (registryAttr instanceof MetricRegistry) { ++ this.registry = (MetricRegistry) registryAttr; ++ } else { ++ throw new ServletException("Couldn't find a MetricRegistry instance."); ++ } ++ } ++ this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); ++ this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); ++ ++ setupMetricsModule(context); ++ } ++ ++ protected void setupMetricsModule(ServletContext context) { ++ final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), TimeUnit.SECONDS); ++ final TimeUnit durationUnit = ++ parseTimeUnit(context.getInitParameter(DURATION_UNIT), TimeUnit.SECONDS); ++ final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES)); ++ MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER); ++ if (filter == null) { ++ filter = MetricFilter.ALL; + } + +- protected ObjectWriter getWriter(HttpServletRequest request) { +- final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); +- if (prettyPrint) { +- return mapper.writerWithDefaultPrettyPrinter(); +- } +- return mapper.writer(); ++ this.mapper = ++ new ObjectMapper() ++ .registerModule(new MetricsModule(rateUnit, durationUnit, showSamples, filter)); ++ } ++ ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ resp.setContentType(CONTENT_TYPE); ++ if (allowedOrigin != null) { ++ resp.setHeader("Access-Control-Allow-Origin", allowedOrigin); ++ } ++ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); ++ resp.setStatus(HttpServletResponse.SC_OK); ++ ++ try (OutputStream output = resp.getOutputStream()) { ++ if (jsonpParamName != null && req.getParameter(jsonpParamName) != null) { ++ getWriter(req) ++ .writeValue(output, new JSONPObject(req.getParameter(jsonpParamName), registry)); ++ } else { ++ getWriter(req).writeValue(output, registry); ++ } + } ++ } + +- @SuppressWarnings("IdentityConversion") +- protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { +- try { +- return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); +- } catch (IllegalArgumentException e) { +- return defaultValue; +- } ++ protected ObjectWriter getWriter(HttpServletRequest request) { ++ final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); ++ if (prettyPrint) { ++ return mapper.writerWithDefaultPrettyPrinter(); ++ } ++ return mapper.writer(); ++ } ++ ++ @SuppressWarnings("IdentityConversion") ++ protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { ++ try { ++ return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); ++ } catch (IllegalArgumentException e) { ++ return defaultValue; + } ++ } + } +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/PingServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/PingServlet.java +@@ -4,28 +4,25 @@ import jakarta.servlet.ServletException; + import jakarta.servlet.http.HttpServlet; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; +- + import java.io.IOException; + import java.io.PrintWriter; + +-/** +- * An HTTP servlets which outputs a {@code text/plain} {@code "pong"} response. +- */ ++/** An HTTP servlets which outputs a {@code text/plain} {@code "pong"} response. */ + public class PingServlet extends HttpServlet { +- private static final long serialVersionUID = 3772654177231086757L; +- private static final String CONTENT_TYPE = "text/plain"; +- private static final String CONTENT = "pong"; +- private static final String CACHE_CONTROL = "Cache-Control"; +- private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; ++ private static final long serialVersionUID = 3772654177231086757L; ++ private static final String CONTENT_TYPE = "text/plain"; ++ private static final String CONTENT = "pong"; ++ private static final String CACHE_CONTROL = "Cache-Control"; ++ private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; + +- @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { +- resp.setStatus(HttpServletResponse.SC_OK); +- resp.setHeader(CACHE_CONTROL, NO_CACHE); +- resp.setContentType(CONTENT_TYPE); +- try (PrintWriter writer = resp.getWriter()) { +- writer.println(CONTENT); +- } ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ resp.setStatus(HttpServletResponse.SC_OK); ++ resp.setHeader(CACHE_CONTROL, NO_CACHE); ++ resp.setContentType(CONTENT_TYPE); ++ try (PrintWriter writer = resp.getWriter()) { ++ writer.println(CONTENT); + } ++ } + } +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/ThreadDumpServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/ThreadDumpServlet.java +@@ -5,51 +5,50 @@ import jakarta.servlet.ServletException; + import jakarta.servlet.http.HttpServlet; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; +- + import java.io.IOException; + import java.io.OutputStream; + import java.lang.management.ManagementFactory; + + /** +- * An HTTP servlets which outputs a {@code text/plain} dump of all threads in +- * the VM. Only responds to {@code GET} requests. ++ * An HTTP servlets which outputs a {@code text/plain} dump of all threads in the VM. Only responds ++ * to {@code GET} requests. + */ + public class ThreadDumpServlet extends HttpServlet { + +- private static final long serialVersionUID = -2690343532336103046L; +- private static final String CONTENT_TYPE = "text/plain"; ++ private static final long serialVersionUID = -2690343532336103046L; ++ private static final String CONTENT_TYPE = "text/plain"; + +- private transient ThreadDump threadDump; ++ private transient ThreadDump threadDump; + +- @Override +- public void init() throws ServletException { +- try { +- // Some PaaS like Google App Engine blacklist java.lang.managament +- this.threadDump = new ThreadDump(ManagementFactory.getThreadMXBean()); +- } catch (NoClassDefFoundError ncdfe) { +- this.threadDump = null; // we won't be able to provide thread dump +- } ++ @Override ++ public void init() throws ServletException { ++ try { ++ // Some PaaS like Google App Engine blacklist java.lang.managament ++ this.threadDump = new ThreadDump(ManagementFactory.getThreadMXBean()); ++ } catch (NoClassDefFoundError ncdfe) { ++ this.threadDump = null; // we won't be able to provide thread dump + } +- +- @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { +- final boolean includeMonitors = getParam(req.getParameter("monitors"), true); +- final boolean includeSynchronizers = getParam(req.getParameter("synchronizers"), true); +- +- resp.setStatus(HttpServletResponse.SC_OK); +- resp.setContentType(CONTENT_TYPE); +- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); +- if (threadDump == null) { +- resp.getWriter().println("Sorry your runtime environment does not allow to dump threads."); +- return; +- } +- try (OutputStream output = resp.getOutputStream()) { +- threadDump.dump(includeMonitors, includeSynchronizers, output); +- } ++ } ++ ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ final boolean includeMonitors = getParam(req.getParameter("monitors"), true); ++ final boolean includeSynchronizers = getParam(req.getParameter("synchronizers"), true); ++ ++ resp.setStatus(HttpServletResponse.SC_OK); ++ resp.setContentType(CONTENT_TYPE); ++ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); ++ if (threadDump == null) { ++ resp.getWriter().println("Sorry your runtime environment does not allow to dump threads."); ++ return; + } +- +- private static Boolean getParam(String initParam, boolean defaultValue) { +- return initParam == null ? defaultValue : Boolean.parseBoolean(initParam); ++ try (OutputStream output = resp.getOutputStream()) { ++ threadDump.dump(includeMonitors, includeSynchronizers, output); + } ++ } ++ ++ private static Boolean getParam(String initParam, boolean defaultValue) { ++ return initParam == null ? defaultValue : Boolean.parseBoolean(initParam); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java +@@ -6,24 +6,24 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + + public abstract class AbstractServletTest { +- private final ServletTester tester = new ServletTester(); +- protected final HttpTester.Request request = HttpTester.newRequest(); +- protected HttpTester.Response response; ++ private final ServletTester tester = new ServletTester(); ++ protected final HttpTester.Request request = HttpTester.newRequest(); ++ protected HttpTester.Response response; + +- @BeforeEach +- public void setUpTester() throws Exception { +- setUp(tester); +- tester.start(); +- } ++ @BeforeEach ++ public void setUpTester() throws Exception { ++ setUp(tester); ++ tester.start(); ++ } + +- protected abstract void setUp(ServletTester tester); ++ protected abstract void setUp(ServletTester tester); + +- @AfterEach +- public void tearDownTester() throws Exception { +- tester.stop(); +- } ++ @AfterEach ++ public void tearDownTester() throws Exception { ++ tester.stop(); ++ } + +- protected void processRequest() throws Exception { +- this.response = HttpTester.parseResponse(tester.getResponses(request.generate())); +- } ++ protected void processRequest() throws Exception { ++ this.response = HttpTester.parseResponse(tester.getResponses(request.generate())); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java +@@ -1,60 +1,60 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.health.HealthCheckRegistry; +-import static org.assertj.core.api.Assertions.assertThat; + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class AdminServletExclusionTest extends AbstractServletTest { +- private final MetricRegistry registry = new MetricRegistry(); +- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); +- +- @Override +- protected void setUp(ServletTester tester) { +- tester.setContextPath("/context"); +- +- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); +- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); +- tester.setInitParameter("threads-enabled", "false"); +- tester.setInitParameter("cpu-profile-enabled", "false"); +- tester.addServlet(AdminServlet.class, "/admin"); +- } +- +- @BeforeEach +- void setUp() { +- request.setMethod("GET"); +- request.setURI("/context/admin"); +- request.setVersion("HTTP/1.0"); +- } +- +- @Test +- void returnsA200() throws Exception { +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.getContent()) +- .isEqualTo(String.format( +- "%n" + +- "%n" + +- "%n" + +- " Metrics%n" + +- "%n" + +- "%n" + +- "

    Operational Menu

    %n" + +- " %n" + +- "%n" + +- "%n" +- )); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("text/html;charset=UTF-8"); +- } ++final class AdminServletExclusionTest extends AbstractServletTest { ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.setContextPath("/context"); ++ ++ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); ++ tester.setAttribute( ++ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); ++ tester.setInitParameter("threads-enabled", "false"); ++ tester.setInitParameter("cpu-profile-enabled", "false"); ++ tester.addServlet(AdminServlet.class, "/admin"); ++ } ++ ++ @BeforeEach ++ void setUp() { ++ request.setMethod("GET"); ++ request.setURI("/context/admin"); ++ request.setVersion("HTTP/1.0"); ++ } ++ ++ @Test ++ void returnsA200() throws Exception { ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "%n" ++ + "%n" ++ + "%n" ++ + " Metrics%n" ++ + "%n" ++ + "%n" ++ + "

    Operational Menu

    %n" ++ + " %n" ++ + "%n" ++ + "%n")); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.health.HealthCheckRegistry; + import org.eclipse.jetty.http.HttpHeader; +@@ -7,56 +9,53 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class AdminServletTest extends AbstractServletTest { +- private final MetricRegistry registry = new MetricRegistry(); +- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); +- +- @Override +- protected void setUp(ServletTester tester) { +- tester.setContextPath("/context"); +- +- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); +- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); +- tester.addServlet(AdminServlet.class, "/admin"); +- } +- +- @BeforeEach +- void setUp() { +- request.setMethod("GET"); +- request.setURI("/context/admin"); +- request.setVersion("HTTP/1.0"); +- } +- +- @Test +- void returnsA200() throws Exception { +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.getContent()) +- .isEqualTo(String.format( +- "%n" + +- "%n" + +- "%n" + +- " Metrics%n" + +- "%n" + +- "%n" + +- "

    Operational Menu

    %n" + +- " %n" + +- "%n" + +- "%n" +- )); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("text/html;charset=UTF-8"); +- } ++final class AdminServletTest extends AbstractServletTest { ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.setContextPath("/context"); ++ ++ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); ++ tester.setAttribute( ++ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); ++ tester.addServlet(AdminServlet.class, "/admin"); ++ } ++ ++ @BeforeEach ++ void setUp() { ++ request.setMethod("GET"); ++ request.setURI("/context/admin"); ++ request.setVersion("HTTP/1.0"); ++ } ++ ++ @Test ++ void returnsA200() throws Exception { ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "%n" ++ + "%n" ++ + "%n" ++ + " Metrics%n" ++ + "%n" ++ + "%n" ++ + "

    Operational Menu

    %n" ++ + " %n" ++ + "%n" ++ + "%n")); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +@@ -1,66 +1,66 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.health.HealthCheckRegistry; +-import static org.assertj.core.api.Assertions.assertThat; + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class AdminServletUriTest extends AbstractServletTest { +- private final MetricRegistry registry = new MetricRegistry(); +- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); ++final class AdminServletUriTest extends AbstractServletTest { ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + +- @Override +- protected void setUp(ServletTester tester) { +- tester.setContextPath("/context"); ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.setContextPath("/context"); + +- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); +- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); +- tester.setInitParameter("metrics-uri", "/metrics-test"); +- tester.setInitParameter("ping-uri", "/ping-test"); +- tester.setInitParameter("threads-uri", "/threads-test"); +- tester.setInitParameter("healthcheck-uri", "/healthcheck-test"); +- tester.setInitParameter("cpu-profile-uri", "/pprof-test"); +- tester.addServlet(AdminServlet.class, "/admin"); +- } ++ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); ++ tester.setAttribute( ++ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); ++ tester.setInitParameter("metrics-uri", "/metrics-test"); ++ tester.setInitParameter("ping-uri", "/ping-test"); ++ tester.setInitParameter("threads-uri", "/threads-test"); ++ tester.setInitParameter("healthcheck-uri", "/healthcheck-test"); ++ tester.setInitParameter("cpu-profile-uri", "/pprof-test"); ++ tester.addServlet(AdminServlet.class, "/admin"); ++ } + +- @BeforeEach +- void setUp() { +- request.setMethod("GET"); +- request.setURI("/context/admin"); +- request.setVersion("HTTP/1.0"); +- } ++ @BeforeEach ++ void setUp() { ++ request.setMethod("GET"); ++ request.setURI("/context/admin"); ++ request.setVersion("HTTP/1.0"); ++ } + +- @Test +- void returnsA200() throws Exception { +- processRequest(); ++ @Test ++ void returnsA200() throws Exception { ++ processRequest(); + +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.getContent()) +- .isEqualTo(String.format( +- "%n" + +- "%n" + +- "%n" + +- " Metrics%n" + +- "%n" + +- "%n" + +- "

    Operational Menu

    %n" + +- " %n" + +- "%n" + +- "%n" +- )); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("text/html;charset=UTF-8"); +- } ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "%n" ++ + "%n" ++ + "%n" ++ + " Metrics%n" ++ + "%n" ++ + "%n" ++ + "

    Operational Menu

    %n" ++ + " %n" ++ + "%n" ++ + "%n")); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +@@ -1,44 +1,41 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class CpuProfileServletTest extends AbstractServletTest { +- +- @Override +- protected void setUp(ServletTester tester) { +- tester.addServlet(CpuProfileServlet.class, "/pprof"); +- } +- +- @BeforeEach +- void setUp() throws Exception { +- request.setMethod("GET"); +- request.setURI("/pprof?duration=1"); +- request.setVersion("HTTP/1.0"); +- +- processRequest(); +- } +- +- @Test +- void returns200OK() { +- assertThat(response.getStatus()) +- .isEqualTo(200); +- } +- +- @Test +- void returnsPprofRaw() { +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("pprof/raw"); +- } +- +- @Test +- void returnsUncacheable() { +- assertThat(response.get(HttpHeader.CACHE_CONTROL)) +- .isEqualTo("must-revalidate,no-cache,no-store"); +- +- } ++final class CpuProfileServletTest extends AbstractServletTest { ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.addServlet(CpuProfileServlet.class, "/pprof"); ++ } ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ request.setMethod("GET"); ++ request.setURI("/pprof?duration=1"); ++ request.setVersion("HTTP/1.0"); ++ ++ processRequest(); ++ } ++ ++ @Test ++ void returns200OK() { ++ assertThat(response.getStatus()).isEqualTo(200); ++ } ++ ++ @Test ++ void returnsPprofRaw() { ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("pprof/raw"); ++ } ++ ++ @Test ++ void returnsUncacheable() { ++ assertThat(response.get(HttpHeader.CACHE_CONTROL)) ++ .isEqualTo("must-revalidate,no-cache,no-store"); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +@@ -1,5 +1,12 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.never; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import com.fasterxml.jackson.databind.ObjectMapper; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.health.HealthCheck; +@@ -8,251 +15,255 @@ import io.dropwizard.metrics5.health.HealthCheckRegistry; + import jakarta.servlet.ServletConfig; + import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletException; +-import org.eclipse.jetty.http.HttpHeader; +-import org.eclipse.jetty.servlet.ServletTester; +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- + import java.time.ZonedDateTime; + import java.time.format.DateTimeFormatter; + import java.util.concurrent.Callable; + import java.util.concurrent.ExecutorService; + import java.util.concurrent.Executors; ++import org.eclipse.jetty.http.HttpHeader; ++import org.eclipse.jetty.servlet.ServletTester; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- +-class HealthCheckServletTest extends AbstractServletTest { ++final class HealthCheckServletTest extends AbstractServletTest { + +- private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); ++ private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); + +- private static final DateTimeFormatter DATE_TIME_FORMATTER = +- DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); ++ private static final DateTimeFormatter DATE_TIME_FORMATTER = ++ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + +- private static final String EXPECTED_TIMESTAMP = DATE_TIME_FORMATTER.format(FIXED_TIME); ++ private static final String EXPECTED_TIMESTAMP = DATE_TIME_FORMATTER.format(FIXED_TIME); + +- private static final Clock FIXED_CLOCK = new Clock() { ++ private static final Clock FIXED_CLOCK = ++ new Clock() { + @Override + public long getTick() { +- return 0L; ++ return 0L; + } + + @Override + public long getTime() { +- return FIXED_TIME.toInstant().toEpochMilli(); ++ return FIXED_TIME.toInstant().toEpochMilli(); + } +- }; +- +- private final HealthCheckRegistry registry = new HealthCheckRegistry(); +- private final ExecutorService threadPool = Executors.newCachedThreadPool(); +- private final ObjectMapper mapper = new ObjectMapper(); +- +- @Override +- protected void setUp(ServletTester tester) { +- tester.addServlet(HealthCheckServlet.class, "/healthchecks"); +- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", registry); +- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".executor", threadPool); +- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".mapper", mapper); +- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter", +- (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); +- } +- +- @BeforeEach +- void setUp() { +- request.setMethod("GET"); +- request.setURI("/healthchecks"); +- request.setVersion("HTTP/1.0"); +- } +- +- @AfterEach +- void tearDown() { +- threadPool.shutdown(); +- } +- +- @Test +- void returns501IfNoHealthChecksAreRegistered() throws Exception { +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(501); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()).isEqualTo("{}"); +- } +- +- @Test +- void returnsA200IfAllHealthChecksAreHealthy() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()) +- .isEqualTo("{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + +- EXPECTED_TIMESTAMP + +- "\"}}"); +- } +- +- @Test +- void returnsASubsetOfHealthChecksIfFiltered() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); +- registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()) +- .isEqualTo("{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + +- EXPECTED_TIMESTAMP + +- "\"}}"); +- } +- +- @Test +- void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); +- registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(500); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()).contains( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", +- ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); +- } +- +- @Test +- void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); +- registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); +- request.setURI("/healthchecks?httpStatusIndicator=false"); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()).contains( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", +- ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); +- } +- +- @Test +- void optionallyPrettyPrintsTheJson() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); +- +- request.setURI("/healthchecks?pretty=true"); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()) +- .isEqualTo(String.format("{%n" + +- " \"fun\" : {%n" + +- " \"healthy\" : true,%n" + +- " \"message\" : \"foo bar 123\",%n" + +- " \"duration\" : 0,%n" + +- " \"timestamp\" : \"" + EXPECTED_TIMESTAMP + "\"" + +- "%n }%n}")); +- } +- +- private static HealthCheck.Result healthyResultWithMessage(String message) { +- return HealthCheck.Result.builder() +- .healthy() +- .withMessage(message) +- .usingClock(FIXED_CLOCK) +- .build(); +- } +- +- private static HealthCheck.Result unhealthyResultWithMessage(String message) { +- return HealthCheck.Result.builder() +- .unhealthy() +- .withMessage(message) +- .usingClock(FIXED_CLOCK) +- .build(); +- } +- +- @Test +- void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); +- healthCheckServlet.init(servletConfig); +- +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); +- } +- +- @Test +- void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) +- .thenReturn(healthCheckRegistry); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); +- +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); +- } +- +- @Test +- void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { +- assertThrows(ServletException.class, () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) +- .thenReturn("IRELLEVANT_STRING"); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); +- }); ++ }; ++ ++ private final HealthCheckRegistry registry = new HealthCheckRegistry(); ++ private final ExecutorService threadPool = Executors.newCachedThreadPool(); ++ private final ObjectMapper mapper = new ObjectMapper(); ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.addServlet(HealthCheckServlet.class, "/healthchecks"); ++ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", registry); ++ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".executor", threadPool); ++ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".mapper", mapper); ++ tester.setAttribute( ++ HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter", ++ (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); ++ } ++ ++ @BeforeEach ++ void setUp() { ++ request.setMethod("GET"); ++ request.setURI("/healthchecks"); ++ request.setVersion("HTTP/1.0"); ++ } ++ ++ @AfterEach ++ void tearDown() { ++ threadPool.shutdown(); ++ } ++ ++ @Test ++ void returns501IfNoHealthChecksAreRegistered() throws Exception { ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(501); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()).isEqualTo("{}"); ++ } ++ ++ @Test ++ void returnsA200IfAllHealthChecksAreHealthy() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); ++ } ++ ++ @Test ++ void returnsASubsetOfHealthChecksIfFiltered() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); ++ registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); ++ } ++ ++ @Test ++ void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); ++ registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(500); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .contains( ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" ++ + EXPECTED_TIMESTAMP ++ + "\"}", ++ ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" ++ + EXPECTED_TIMESTAMP ++ + "\"}}"); ++ } ++ ++ @Test ++ void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); ++ registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); ++ request.setURI("/healthchecks?httpStatusIndicator=false"); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .contains( ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" ++ + EXPECTED_TIMESTAMP ++ + "\"}", ++ ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" ++ + EXPECTED_TIMESTAMP ++ + "\"}}"); ++ } ++ ++ @Test ++ void optionallyPrettyPrintsTheJson() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); ++ ++ request.setURI("/healthchecks?pretty=true"); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", ++ EXPECTED_TIMESTAMP)); ++ } ++ ++ private static HealthCheck.Result healthyResultWithMessage(String message) { ++ return HealthCheck.Result.builder() ++ .healthy() ++ .withMessage(message) ++ .usingClock(FIXED_CLOCK) ++ .build(); ++ } ++ ++ private static HealthCheck.Result unhealthyResultWithMessage(String message) { ++ return HealthCheck.Result.builder() ++ .unhealthy() ++ .withMessage(message) ++ .usingClock(FIXED_CLOCK) ++ .build(); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); ++ healthCheckServlet.init(servletConfig); ++ ++ verify(servletConfig).getServletContext(); ++ verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn(healthCheckRegistry); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() ++ throws Exception { ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); ++ } ++ ++ @Test ++ void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() ++ throws Exception { ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn(registry); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_MAPPER)) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ ++ assertThat(healthCheckServlet.getMapper()).isNotNull().isInstanceOf(ObjectMapper.class); ++ } ++ ++ static class TestHealthCheck implements HealthCheck { ++ private final Callable check; ++ ++ public TestHealthCheck(Callable check) { ++ this.check = check; + } + +- @Test +- void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)).thenReturn(registry); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_MAPPER)).thenReturn("IRELLEVANT_STRING"); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); +- +- assertThat(healthCheckServlet.getMapper()) +- .isNotNull() +- .isInstanceOf(ObjectMapper.class); ++ @Override ++ public Result check() throws Exception { ++ return check.call(); + } + +- static class TestHealthCheck implements HealthCheck { +- private final Callable check; +- +- public TestHealthCheck(Callable check) { +- this.check = check; +- } +- +- @Override +- public Result check() throws Exception { +- return check.call(); +- } +- +- @Override +- public Clock clock() { +- return FIXED_CLOCK; +- } ++ @Override ++ public Clock clock() { ++ return FIXED_CLOCK; + } ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Gauge; +@@ -7,166 +11,163 @@ import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; ++import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-class MetricsServletContextListenerTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); +- private final MetricRegistry registry = new MetricRegistry(); +- private final String allowedOrigin = "some.other.origin"; +- +- @Override +- protected void setUp(ServletTester tester) { +- tester.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry); +- tester.addServlet(MetricsServlet.class, "/metrics"); +- tester.getContext().addEventListener(new MetricsServlet.ContextListener() { +- @Override +- protected MetricRegistry getMetricRegistry() { ++final class MetricsServletContextListenerTest extends AbstractServletTest { ++ private final Clock clock = mock(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final String allowedOrigin = "some.other.origin"; ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry); ++ tester.addServlet(MetricsServlet.class, "/metrics"); ++ tester ++ .getContext() ++ .addEventListener( ++ new MetricsServlet.ContextListener() { ++ @Override ++ protected MetricRegistry getMetricRegistry() { + return registry; +- } ++ } + +- @Override +- protected TimeUnit getDurationUnit() { ++ @Override ++ protected TimeUnit getDurationUnit() { + return TimeUnit.MILLISECONDS; +- } ++ } + +- @Override +- protected TimeUnit getRateUnit() { ++ @Override ++ protected TimeUnit getRateUnit() { + return TimeUnit.MINUTES; +- } ++ } + +- @Override +- protected String getAllowedOrigin() { ++ @Override ++ protected String getAllowedOrigin() { + return allowedOrigin; +- } +- }); +- } +- +- @BeforeEach +- void setUp() { +- // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves +- // will call getTick again several times and always get the same value (the last specified here) +- when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); +- +- registry.register(MetricName.build("g1"), (Gauge) () -> 100L); +- registry.counter("c").inc(); +- registry.histogram("h").update(1); +- registry.register(MetricName.build("m"), new Meter(clock)).mark(); +- registry.register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) +- .update(1, TimeUnit.SECONDS); +- +- request.setMethod("GET"); +- request.setURI("/metrics"); +- request.setVersion("HTTP/1.0"); +- } +- +- @Test +- void returnsA200() throws Exception { +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo(allowedOrigin); +- assertThat(response.getContent()) +- .isEqualTo("{" + +- "\"version\":\"5.0.0\"," + +- "\"gauges\":{" + +- "\"g1\":{\"value\":100}" + +- "}," + +- "\"counters\":{" + +- "\"c\":{\"count\":1}" + +- "}," + +- "\"histograms\":{" + +- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + +- "}," + +- "\"meters\":{" + +- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":2.0E8,\"units\":\"events/minute\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1000.0,\"mean\":1000.0,\"min\":1000.0,\"p50\":1000.0,\"p75\":1000.0,\"p95\":1000.0,\"p98\":1000.0,\"p99\":1000.0,\"p999\":1000.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":6.0E8,\"duration_units\":\"milliseconds\",\"rate_units\":\"calls/minute\"}" + +- "}" + +- "}"); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void optionallyPrettyPrintsTheJson() throws Exception { +- request.setURI("/metrics?pretty=true"); +- +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo(allowedOrigin); +- assertThat(response.getContent()) +- .isEqualTo(String.format("{%n" + +- " \"version\" : \"5.0.0\",%n" + +- " \"gauges\" : {%n" + +- " \"g1\" : {%n" + +- " \"value\" : 100%n" + +- " }%n" + +- " },%n" + +- " \"counters\" : {%n" + +- " \"c\" : {%n" + +- " \"count\" : 1%n" + +- " }%n" + +- " },%n" + +- " \"histograms\" : {%n" + +- " \"h\" : {%n" + +- " \"count\" : 1,%n" + +- " \"max\" : 1,%n" + +- " \"mean\" : 1.0,%n" + +- " \"min\" : 1,%n" + +- " \"p50\" : 1.0,%n" + +- " \"p75\" : 1.0,%n" + +- " \"p95\" : 1.0,%n" + +- " \"p98\" : 1.0,%n" + +- " \"p99\" : 1.0,%n" + +- " \"p999\" : 1.0,%n" + +- " \"stddev\" : 0.0%n" + +- " }%n" + +- " },%n" + +- " \"meters\" : {%n" + +- " \"m\" : {%n" + +- " \"count\" : 1,%n" + +- " \"m15_rate\" : 0.0,%n" + +- " \"m1_rate\" : 0.0,%n" + +- " \"m5_rate\" : 0.0,%n" + +- " \"mean_rate\" : 2.0E8,%n" + +- " \"units\" : \"events/minute\"%n" + +- " }%n" + +- " },%n" + +- " \"timers\" : {%n" + +- " \"t\" : {%n" + +- " \"count\" : 1,%n" + +- " \"max\" : 1000.0,%n" + +- " \"mean\" : 1000.0,%n" + +- " \"min\" : 1000.0,%n" + +- " \"p50\" : 1000.0,%n" + +- " \"p75\" : 1000.0,%n" + +- " \"p95\" : 1000.0,%n" + +- " \"p98\" : 1000.0,%n" + +- " \"p99\" : 1000.0,%n" + +- " \"p999\" : 1000.0,%n" + +- " \"stddev\" : 0.0,%n" + +- " \"m15_rate\" : 0.0,%n" + +- " \"m1_rate\" : 0.0,%n" + +- " \"m5_rate\" : 0.0,%n" + +- " \"mean_rate\" : 6.0E8,%n" + +- " \"duration_units\" : \"milliseconds\",%n" + +- " \"rate_units\" : \"calls/minute\"%n" + +- " }%n" + +- " }%n" + +- "}")); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } ++ } ++ }); ++ } ++ ++ @BeforeEach ++ void setUp() { ++ // provide ticks for the setup (calls getTick 6 times). The serialization in the tests ++ // themselves ++ // will call getTick again several times and always get the same value (the last specified here) ++ when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); ++ ++ registry.register(MetricName.build("g1"), (Gauge) () -> 100L); ++ registry.counter("c").inc(); ++ registry.histogram("h").update(1); ++ registry.register(MetricName.build("m"), new Meter(clock)).mark(); ++ registry ++ .register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) ++ .update(1, TimeUnit.SECONDS); ++ ++ request.setMethod("GET"); ++ request.setURI("/metrics"); ++ request.setVersion("HTTP/1.0"); ++ } ++ ++ @Test ++ void returnsA200() throws Exception { ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo(allowedOrigin); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{" ++ + "\"version\":\"5.0.0\"," ++ + "\"gauges\":{" ++ + "\"g1\":{\"value\":100}" ++ + "}," ++ + "\"counters\":{" ++ + "\"c\":{\"count\":1}" ++ + "}," ++ + "\"histograms\":{" ++ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" ++ + "}," ++ + "\"meters\":{" ++ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":2.0E8,\"units\":\"events/minute\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1000.0,\"mean\":1000.0,\"min\":1000.0,\"p50\":1000.0,\"p75\":1000.0,\"p95\":1000.0,\"p98\":1000.0,\"p99\":1000.0,\"p999\":1000.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":6.0E8,\"duration_units\":\"milliseconds\",\"rate_units\":\"calls/minute\"}" ++ + "}" ++ + "}"); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void optionallyPrettyPrintsTheJson() throws Exception { ++ request.setURI("/metrics?pretty=true"); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo(allowedOrigin); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "{%n" ++ + " \"version\" : \"5.0.0\",%n" ++ + " \"gauges\" : {%n" ++ + " \"g1\" : {%n" ++ + " \"value\" : 100%n" ++ + " }%n" ++ + " },%n" ++ + " \"counters\" : {%n" ++ + " \"c\" : {%n" ++ + " \"count\" : 1%n" ++ + " }%n" ++ + " },%n" ++ + " \"histograms\" : {%n" ++ + " \"h\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"max\" : 1,%n" ++ + " \"mean\" : 1.0,%n" ++ + " \"min\" : 1,%n" ++ + " \"p50\" : 1.0,%n" ++ + " \"p75\" : 1.0,%n" ++ + " \"p95\" : 1.0,%n" ++ + " \"p98\" : 1.0,%n" ++ + " \"p99\" : 1.0,%n" ++ + " \"p999\" : 1.0,%n" ++ + " \"stddev\" : 0.0%n" ++ + " }%n" ++ + " },%n" ++ + " \"meters\" : {%n" ++ + " \"m\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"m15_rate\" : 0.0,%n" ++ + " \"m1_rate\" : 0.0,%n" ++ + " \"m5_rate\" : 0.0,%n" ++ + " \"mean_rate\" : 2.0E8,%n" ++ + " \"units\" : \"events/minute\"%n" ++ + " }%n" ++ + " },%n" ++ + " \"timers\" : {%n" ++ + " \"t\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"max\" : 1000.0,%n" ++ + " \"mean\" : 1000.0,%n" ++ + " \"min\" : 1000.0,%n" ++ + " \"p50\" : 1000.0,%n" ++ + " \"p75\" : 1000.0,%n" ++ + " \"p95\" : 1000.0,%n" ++ + " \"p98\" : 1000.0,%n" ++ + " \"p99\" : 1000.0,%n" ++ + " \"p999\" : 1000.0,%n" ++ + " \"stddev\" : 0.0,%n" ++ + " \"m15_rate\" : 0.0,%n" ++ + " \"m1_rate\" : 0.0,%n" ++ + " \"m5_rate\" : 0.0,%n" ++ + " \"mean_rate\" : 6.0E8,%n" ++ + " \"duration_units\" : \"milliseconds\",%n" ++ + " \"rate_units\" : \"calls/minute\"%n" ++ + " }%n" ++ + " }%n" ++ + "}")); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +@@ -1,5 +1,12 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.never; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Gauge; +@@ -10,258 +17,238 @@ import io.dropwizard.metrics5.Timer; + import jakarta.servlet.ServletConfig; + import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletException; ++import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.mockito.ArgumentMatchers.eq; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- +-class MetricsServletTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); +- private final MetricRegistry registry = new MetricRegistry(); +- private ServletTester tester; +- +- @Override +- protected void setUp(ServletTester tester) { +- this.tester = tester; +- tester.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry); +- tester.addServlet(MetricsServlet.class, "/metrics"); +- tester.getContext().setInitParameter(MetricsServlet.class.getCanonicalName() + ".allowedOrigin", "*"); +- } +- +- @BeforeEach +- void setUp() { +- // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves +- // will call getTick again several times and always get the same value (the last specified here) +- when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); +- +- registry.register(MetricName.build("g1"), (Gauge) () -> 100L); +- registry.counter("c").inc(); +- registry.histogram("h").update(1); +- registry.register(MetricName.build("m"), new Meter(clock)).mark(); +- registry.register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) +- .update(1, TimeUnit.SECONDS); +- +- request.setMethod("GET"); +- request.setURI("/metrics"); +- request.setVersion("HTTP/1.0"); +- } +- +- @Test +- void returnsA200() throws Exception { +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo("*"); +- assertThat(response.getContent()) +- .isEqualTo("{" + +- "\"version\":\"5.0.0\"," + +- "\"gauges\":{" + +- "\"g1\":{\"value\":100}" + +- "}," + +- "\"counters\":{" + +- "\"c\":{\"count\":1}" + +- "}," + +- "\"histograms\":{" + +- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + +- "}," + +- "\"meters\":{" + +- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + +- "}" + +- "}"); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void returnsJsonWhenJsonpInitParamNotSet() throws Exception { +- String callbackParamName = "callbackParam"; +- String callbackParamVal = "callbackParamVal"; +- request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo("*"); +- assertThat(response.getContent()) +- .isEqualTo("{" + +- "\"version\":\"5.0.0\"," + +- "\"gauges\":{" + +- "\"g1\":{\"value\":100}" + +- "}," + +- "\"counters\":{" + +- "\"c\":{\"count\":1}" + +- "}," + +- "\"histograms\":{" + +- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + +- "}," + +- "\"meters\":{" + +- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + +- "}" + +- "}"); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void returnsJsonpWhenInitParamSet() throws Exception { +- String callbackParamName = "callbackParam"; +- String callbackParamVal = "callbackParamVal"; +- request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); +- tester.getContext().setInitParameter(MetricsServlet.class.getCanonicalName() + ".jsonpCallback", callbackParamName); +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo("*"); +- assertThat(response.getContent()) +- .isEqualTo(callbackParamVal + "({" + +- "\"version\":\"5.0.0\"," + +- "\"gauges\":{" + +- "\"g1\":{\"value\":100}" + +- "}," + +- "\"counters\":{" + +- "\"c\":{\"count\":1}" + +- "}," + +- "\"histograms\":{" + +- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + +- "}," + +- "\"meters\":{" + +- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + +- "}" + +- "})"); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void optionallyPrettyPrintsTheJson() throws Exception { +- request.setURI("/metrics?pretty=true"); +- +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo("*"); +- assertThat(response.getContent()) +- .isEqualTo(String.format("{%n" + +- " \"version\" : \"5.0.0\",%n" + +- " \"gauges\" : {%n" + +- " \"g1\" : {%n" + +- " \"value\" : 100%n" + +- " }%n" + +- " },%n" + +- " \"counters\" : {%n" + +- " \"c\" : {%n" + +- " \"count\" : 1%n" + +- " }%n" + +- " },%n" + +- " \"histograms\" : {%n" + +- " \"h\" : {%n" + +- " \"count\" : 1,%n" + +- " \"max\" : 1,%n" + +- " \"mean\" : 1.0,%n" + +- " \"min\" : 1,%n" + +- " \"p50\" : 1.0,%n" + +- " \"p75\" : 1.0,%n" + +- " \"p95\" : 1.0,%n" + +- " \"p98\" : 1.0,%n" + +- " \"p99\" : 1.0,%n" + +- " \"p999\" : 1.0,%n" + +- " \"stddev\" : 0.0%n" + +- " }%n" + +- " },%n" + +- " \"meters\" : {%n" + +- " \"m\" : {%n" + +- " \"count\" : 1,%n" + +- " \"m15_rate\" : 0.0,%n" + +- " \"m1_rate\" : 0.0,%n" + +- " \"m5_rate\" : 0.0,%n" + +- " \"mean_rate\" : 3333333.3333333335,%n" + +- " \"units\" : \"events/second\"%n" + +- " }%n" + +- " },%n" + +- " \"timers\" : {%n" + +- " \"t\" : {%n" + +- " \"count\" : 1,%n" + +- " \"max\" : 1.0,%n" + +- " \"mean\" : 1.0,%n" + +- " \"min\" : 1.0,%n" + +- " \"p50\" : 1.0,%n" + +- " \"p75\" : 1.0,%n" + +- " \"p95\" : 1.0,%n" + +- " \"p98\" : 1.0,%n" + +- " \"p99\" : 1.0,%n" + +- " \"p999\" : 1.0,%n" + +- " \"stddev\" : 0.0,%n" + +- " \"m15_rate\" : 0.0,%n" + +- " \"m1_rate\" : 0.0,%n" + +- " \"m5_rate\" : 0.0,%n" + +- " \"mean_rate\" : 1.0E7,%n" + +- " \"duration_units\" : \"seconds\",%n" + +- " \"rate_units\" : \"calls/second\"%n" + +- " }%n" + +- " }%n" + +- "}")); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- +- final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); +- metricsServlet.init(servletConfig); +- +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); +- } +- +- @Test +- void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn(metricRegistry); +- +- final MetricsServlet metricsServlet = new MetricsServlet(null); +- metricsServlet.init(servletConfig); +- +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); +- } +- +- @Test +- void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { +- assertThrows(ServletException.class, () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn("IRELLEVANT_STRING"); +- +- final MetricsServlet metricsServlet = new MetricsServlet(null); +- metricsServlet.init(servletConfig); +- }); +- } ++final class MetricsServletTest extends AbstractServletTest { ++ private final Clock clock = mock(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private ServletTester tester; ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ this.tester = tester; ++ tester.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry); ++ tester.addServlet(MetricsServlet.class, "/metrics"); ++ tester ++ .getContext() ++ .setInitParameter(MetricsServlet.class.getCanonicalName() + ".allowedOrigin", "*"); ++ } ++ ++ @BeforeEach ++ void setUp() { ++ // provide ticks for the setup (calls getTick 6 times). The serialization in the tests ++ // themselves ++ // will call getTick again several times and always get the same value (the last specified here) ++ when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); ++ ++ registry.register(MetricName.build("g1"), (Gauge) () -> 100L); ++ registry.counter("c").inc(); ++ registry.histogram("h").update(1); ++ registry.register(MetricName.build("m"), new Meter(clock)).mark(); ++ registry ++ .register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) ++ .update(1, TimeUnit.SECONDS); ++ ++ request.setMethod("GET"); ++ request.setURI("/metrics"); ++ request.setVersion("HTTP/1.0"); ++ } ++ ++ @Test ++ void returnsA200() throws Exception { ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{" ++ + "\"version\":\"5.0.0\"," ++ + "\"gauges\":{" ++ + "\"g1\":{\"value\":100}" ++ + "}," ++ + "\"counters\":{" ++ + "\"c\":{\"count\":1}" ++ + "}," ++ + "\"histograms\":{" ++ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" ++ + "}," ++ + "\"meters\":{" ++ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" ++ + "}" ++ + "}"); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void returnsJsonWhenJsonpInitParamNotSet() throws Exception { ++ String callbackParamName = "callbackParam"; ++ String callbackParamVal = "callbackParamVal"; ++ request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{" ++ + "\"version\":\"5.0.0\"," ++ + "\"gauges\":{" ++ + "\"g1\":{\"value\":100}" ++ + "}," ++ + "\"counters\":{" ++ + "\"c\":{\"count\":1}" ++ + "}," ++ + "\"histograms\":{" ++ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" ++ + "}," ++ + "\"meters\":{" ++ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" ++ + "}" ++ + "}"); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void returnsJsonpWhenInitParamSet() throws Exception { ++ String callbackParamName = "callbackParam"; ++ String callbackParamVal = "callbackParamVal"; ++ request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); ++ tester ++ .getContext() ++ .setInitParameter( ++ MetricsServlet.class.getCanonicalName() + ".jsonpCallback", callbackParamName); ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", ++ callbackParamVal); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void optionallyPrettyPrintsTheJson() throws Exception { ++ request.setURI("/metrics?pretty=true"); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "{%n" ++ + " \"version\" : \"5.0.0\",%n" ++ + " \"gauges\" : {%n" ++ + " \"g1\" : {%n" ++ + " \"value\" : 100%n" ++ + " }%n" ++ + " },%n" ++ + " \"counters\" : {%n" ++ + " \"c\" : {%n" ++ + " \"count\" : 1%n" ++ + " }%n" ++ + " },%n" ++ + " \"histograms\" : {%n" ++ + " \"h\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"max\" : 1,%n" ++ + " \"mean\" : 1.0,%n" ++ + " \"min\" : 1,%n" ++ + " \"p50\" : 1.0,%n" ++ + " \"p75\" : 1.0,%n" ++ + " \"p95\" : 1.0,%n" ++ + " \"p98\" : 1.0,%n" ++ + " \"p99\" : 1.0,%n" ++ + " \"p999\" : 1.0,%n" ++ + " \"stddev\" : 0.0%n" ++ + " }%n" ++ + " },%n" ++ + " \"meters\" : {%n" ++ + " \"m\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"m15_rate\" : 0.0,%n" ++ + " \"m1_rate\" : 0.0,%n" ++ + " \"m5_rate\" : 0.0,%n" ++ + " \"mean_rate\" : 3333333.3333333335,%n" ++ + " \"units\" : \"events/second\"%n" ++ + " }%n" ++ + " },%n" ++ + " \"timers\" : {%n" ++ + " \"t\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"max\" : 1.0,%n" ++ + " \"mean\" : 1.0,%n" ++ + " \"min\" : 1.0,%n" ++ + " \"p50\" : 1.0,%n" ++ + " \"p75\" : 1.0,%n" ++ + " \"p95\" : 1.0,%n" ++ + " \"p98\" : 1.0,%n" ++ + " \"p99\" : 1.0,%n" ++ + " \"p999\" : 1.0,%n" ++ + " \"stddev\" : 0.0,%n" ++ + " \"m15_rate\" : 0.0,%n" ++ + " \"m1_rate\" : 0.0,%n" ++ + " \"m5_rate\" : 0.0,%n" ++ + " \"mean_rate\" : 1.0E7,%n" ++ + " \"duration_units\" : \"seconds\",%n" ++ + " \"rate_units\" : \"calls/second\"%n" ++ + " }%n" ++ + " }%n" ++ + "}")); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ ++ final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); ++ metricsServlet.init(servletConfig); ++ ++ verify(servletConfig).getServletContext(); ++ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); ++ ++ final MetricsServlet metricsServlet = new MetricsServlet(null); ++ metricsServlet.init(servletConfig); ++ ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() ++ throws Exception { ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final MetricsServlet metricsServlet = new MetricsServlet(null); ++ metricsServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +@@ -1,49 +1,45 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class PingServletTest extends AbstractServletTest { +- @Override +- protected void setUp(ServletTester tester) { +- tester.addServlet(PingServlet.class, "/ping"); +- } +- +- @BeforeEach +- void setUp() throws Exception { +- request.setMethod("GET"); +- request.setURI("/ping"); +- request.setVersion("HTTP/1.0"); +- +- processRequest(); +- } +- +- @Test +- void returns200OK() { +- assertThat(response.getStatus()) +- .isEqualTo(200); +- } +- +- @Test +- void returnsPong() { +- assertThat(response.getContent()) +- .isEqualTo(String.format("pong%n")); +- } +- +- @Test +- void returnsTextPlain() { +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("text/plain;charset=ISO-8859-1"); +- } +- +- @Test +- void returnsUncacheable() { +- assertThat(response.get(HttpHeader.CACHE_CONTROL)) +- .isEqualTo("must-revalidate,no-cache,no-store"); +- +- } ++final class PingServletTest extends AbstractServletTest { ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.addServlet(PingServlet.class, "/ping"); ++ } ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ request.setMethod("GET"); ++ request.setURI("/ping"); ++ request.setVersion("HTTP/1.0"); ++ ++ processRequest(); ++ } ++ ++ @Test ++ void returns200OK() { ++ assertThat(response.getStatus()).isEqualTo(200); ++ } ++ ++ @Test ++ void returnsPong() { ++ assertThat(response.getContent()).isEqualTo(String.format("pong%n")); ++ } ++ ++ @Test ++ void returnsTextPlain() { ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/plain;charset=ISO-8859-1"); ++ } ++ ++ @Test ++ void returnsUncacheable() { ++ assertThat(response.get(HttpHeader.CACHE_CONTROL)) ++ .isEqualTo("must-revalidate,no-cache,no-store"); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +@@ -1,49 +1,45 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class ThreadDumpServletTest extends AbstractServletTest { +- @Override +- protected void setUp(ServletTester tester) { +- tester.addServlet(ThreadDumpServlet.class, "/threads"); +- } +- +- @BeforeEach +- void setUp() throws Exception { +- request.setMethod("GET"); +- request.setURI("/threads"); +- request.setVersion("HTTP/1.0"); +- +- processRequest(); +- } +- +- @Test +- void returns200OK() { +- assertThat(response.getStatus()) +- .isEqualTo(200); +- } +- +- @Test +- void returnsAThreadDump() { +- assertThat(response.getContent()) +- .contains("Finalizer"); +- } +- +- @Test +- void returnsTextPlain() { +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("text/plain"); +- } +- +- @Test +- void returnsUncacheable() { +- assertThat(response.get(HttpHeader.CACHE_CONTROL)) +- .isEqualTo("must-revalidate,no-cache,no-store"); +- +- } ++final class ThreadDumpServletTest extends AbstractServletTest { ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.addServlet(ThreadDumpServlet.class, "/threads"); ++ } ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ request.setMethod("GET"); ++ request.setURI("/threads"); ++ request.setVersion("HTTP/1.0"); ++ ++ processRequest(); ++ } ++ ++ @Test ++ void returns200OK() { ++ assertThat(response.getStatus()).isEqualTo(200); ++ } ++ ++ @Test ++ void returnsAThreadDump() { ++ assertThat(response.getContent()).contains("Finalizer"); ++ } ++ ++ @Test ++ void returnsTextPlain() { ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/plain"); ++ } ++ ++ @Test ++ void returnsUncacheable() { ++ assertThat(response.get(HttpHeader.CACHE_CONTROL)) ++ .isEqualTo("must-revalidate,no-cache,no-store"); ++ } + } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/experiments/ExampleServer.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/experiments/ExampleServer.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.servlets.experiments; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricRegistry; +@@ -18,43 +20,48 @@ import org.eclipse.jetty.servlet.ServletContextHandler; + import org.eclipse.jetty.servlet.ServletHolder; + import org.eclipse.jetty.util.thread.ThreadPool; + +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + public class ExampleServer { +- private static final MetricRegistry REGISTRY = new MetricRegistry(); +- private static final Counter COUNTER_1 = REGISTRY.counter(name(ExampleServer.class, "wah", "doody")); +- private static final Counter COUNTER_2 = REGISTRY.counter(name(ExampleServer.class, "woo")); ++ private static final MetricRegistry REGISTRY = new MetricRegistry(); ++ private static final Counter COUNTER_1 = ++ REGISTRY.counter(name(ExampleServer.class, "wah", "doody")); ++ private static final Counter COUNTER_2 = REGISTRY.counter(name(ExampleServer.class, "woo")); + +- static { +- REGISTRY.register(name(ExampleServer.class, "boo"), (Gauge) () -> { +- throw new RuntimeException("asplode!"); +- }); +- } ++ static { ++ REGISTRY.register( ++ name(ExampleServer.class, "boo"), ++ (Gauge) ++ () -> { ++ throw new RuntimeException("asplode!"); ++ }); ++ } + +- public static void main(String[] args) throws Exception { +- COUNTER_1.inc(); +- COUNTER_2.inc(); ++ public static void main(String[] args) throws Exception { ++ COUNTER_1.inc(); ++ COUNTER_2.inc(); + +- final ThreadPool threadPool = new InstrumentedQueuedThreadPool(REGISTRY); +- final Server server = new Server(threadPool); ++ final ThreadPool threadPool = new InstrumentedQueuedThreadPool(REGISTRY); ++ final Server server = new Server(threadPool); + +- final Connector connector = new ServerConnector(server, new InstrumentedConnectionFactory( ++ final Connector connector = ++ new ServerConnector( ++ server, ++ new InstrumentedConnectionFactory( + new HttpConnectionFactory(), REGISTRY.timer("http.connection"))); +- server.addConnector(connector); ++ server.addConnector(connector); + +- final ServletContextHandler context = new ServletContextHandler(); +- context.setContextPath("/initial"); +- context.setAttribute(MetricsServlet.METRICS_REGISTRY, REGISTRY); +- context.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, new HealthCheckRegistry()); ++ final ServletContextHandler context = new ServletContextHandler(); ++ context.setContextPath("/initial"); ++ context.setAttribute(MetricsServlet.METRICS_REGISTRY, REGISTRY); ++ context.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, new HealthCheckRegistry()); + +- final ServletHolder holder = new ServletHolder(new AdminServlet()); +- context.addServlet(holder, "/dingo/*"); ++ final ServletHolder holder = new ServletHolder(new AdminServlet()); ++ context.addServlet(holder, "/dingo/*"); + +- final InstrumentedHandler handler = new InstrumentedHandler(REGISTRY); +- handler.setHandler(context); +- server.setHandler(handler); ++ final InstrumentedHandler handler = new InstrumentedHandler(REGISTRY); ++ handler.setHandler(context); ++ server.setHandler(handler); + +- server.start(); +- server.join(); +- } ++ server.start(); ++ server.join(); ++ } + } +--- a/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java ++++ b/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java +@@ -1,27 +1,26 @@ + package io.dropwizard.metrics5.jcache; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricSet; + import io.dropwizard.metrics5.jvm.JmxAttributeGauge; +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; +- +-import javax.cache.management.CacheStatisticsMXBean; +-import javax.management.MalformedObjectNameException; +-import javax.management.ObjectInstance; +-import javax.management.ObjectName; + import java.lang.management.ManagementFactory; + import java.lang.reflect.Method; + import java.util.ArrayList; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Locale; + import java.util.Map; + import java.util.Set; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; ++import javax.cache.management.CacheStatisticsMXBean; ++import javax.management.MalformedObjectNameException; ++import javax.management.ObjectInstance; ++import javax.management.ObjectName; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + + /** + * Gauge set retrieving JCache JMX attributes +@@ -31,54 +30,55 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + */ + public class JCacheGaugeSet implements MetricSet { + +- private static final String M_BEAN_COORDINATES = "javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"; +- +- private static final Logger LOGGER = LoggerFactory.getLogger(JCacheGaugeSet.class); ++ private static final String M_BEAN_COORDINATES = ++ "javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"; + +- @Override +- public Map getMetrics() { +- Set cacheBeans = getCacheBeans(); +- List availableStatsNames = retrieveStatsNames(); ++ private static final Logger LOG = LoggerFactory.getLogger(JCacheGaugeSet.class); + +- Map gauges = new HashMap<>(cacheBeans.size() * availableStatsNames.size()); ++ @Override ++ public Map getMetrics() { ++ Set cacheBeans = getCacheBeans(); ++ List availableStatsNames = retrieveStatsNames(); + +- for (ObjectInstance cacheBean : cacheBeans) { +- ObjectName objectName = cacheBean.getObjectName(); +- String cacheName = objectName.getKeyProperty("Cache"); ++ Map gauges = new HashMap<>(cacheBeans.size() * availableStatsNames.size()); + +- for (String statsName : availableStatsNames) { +- JmxAttributeGauge jmxAttributeGauge = new JmxAttributeGauge(objectName, statsName); +- gauges.put(name(cacheName, toSpinalCase(statsName)), jmxAttributeGauge); +- } +- } ++ for (ObjectInstance cacheBean : cacheBeans) { ++ ObjectName objectName = cacheBean.getObjectName(); ++ String cacheName = objectName.getKeyProperty("Cache"); + +- return Collections.unmodifiableMap(gauges); ++ for (String statsName : availableStatsNames) { ++ JmxAttributeGauge jmxAttributeGauge = new JmxAttributeGauge(objectName, statsName); ++ gauges.put(name(cacheName, toSpinalCase(statsName)), jmxAttributeGauge); ++ } + } + +- private Set getCacheBeans() { +- try { +- return ManagementFactory.getPlatformMBeanServer().queryMBeans(ObjectName.getInstance(M_BEAN_COORDINATES), null); +- } catch (MalformedObjectNameException e) { +- LOGGER.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); +- throw new RuntimeException(e); +- } +- } ++ return unmodifiableMap(gauges); ++ } + +- private List retrieveStatsNames() { +- Method[] methods = CacheStatisticsMXBean.class.getDeclaredMethods(); +- List availableStatsNames = new ArrayList<>(methods.length); +- +- for (Method method : methods) { +- String methodName = method.getName(); +- if (methodName.startsWith("get")) { +- availableStatsNames.add(methodName.substring(3)); +- } +- } +- return availableStatsNames; ++ private Set getCacheBeans() { ++ try { ++ return ManagementFactory.getPlatformMBeanServer() ++ .queryMBeans(ObjectName.getInstance(M_BEAN_COORDINATES), null); ++ } catch (MalformedObjectNameException e) { ++ LOG.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); ++ throw new RuntimeException(e); + } ++ } ++ ++ private List retrieveStatsNames() { ++ Method[] methods = CacheStatisticsMXBean.class.getDeclaredMethods(); ++ List availableStatsNames = new ArrayList<>(methods.length); + +- private static String toSpinalCase(String camelCase) { +- return camelCase.replaceAll("(.)(\\p{Upper})", "$1-$2").toLowerCase(Locale.US); ++ for (Method method : methods) { ++ String methodName = method.getName(); ++ if (methodName.startsWith("get")) { ++ availableStatsNames.add(methodName.substring(3)); ++ } + } ++ return availableStatsNames; ++ } + ++ private static String toSpinalCase(String camelCase) { ++ return camelCase.replaceAll("(.)(\\p{Upper})", "$1-$2").toLowerCase(Locale.US); ++ } + } +--- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java ++++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java +@@ -1,88 +1,83 @@ ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jcache.JCacheGaugeSet; +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- + import javax.cache.Cache; + import javax.cache.CacheManager; + import javax.cache.Caching; + import javax.cache.spi.CachingProvider; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class JCacheGaugeSetTest { ++final class JCacheGaugeSetTest { + +- private MetricRegistry registry; +- private Cache myCache; +- private Cache myOtherCache; +- private CacheManager cacheManager; ++ private MetricRegistry registry; ++ private Cache myCache; ++ private Cache myOtherCache; ++ private CacheManager cacheManager; + +- @BeforeEach +- void setUp() throws Exception { ++ @BeforeEach ++ void setUp() throws Exception { + +- CachingProvider provider = Caching.getCachingProvider(); +- cacheManager = provider.getCacheManager( +- getClass().getResource("ehcache.xml").toURI(), +- getClass().getClassLoader()); ++ CachingProvider provider = Caching.getCachingProvider(); ++ cacheManager = ++ provider.getCacheManager( ++ getClass().getResource("ehcache.xml").toURI(), getClass().getClassLoader()); + +- myCache = cacheManager.getCache("myCache"); +- myOtherCache = cacheManager.getCache("myOtherCache"); ++ myCache = cacheManager.getCache("myCache"); ++ myOtherCache = cacheManager.getCache("myOtherCache"); + +- registry = new MetricRegistry(); +- registry.register(MetricName.build("jcache.statistics"), new JCacheGaugeSet()); +- } ++ registry = new MetricRegistry(); ++ registry.register(MetricName.build("jcache.statistics"), new JCacheGaugeSet()); ++ } + +- @Test +- void measuresGauges() throws Exception { ++ @Test ++ void measuresGauges() throws Exception { + +- myOtherCache.get("woo"); +- assertThat(registry.getGauges().get(MetricName.build("jcache.statistics.myOtherCache.cache-misses")) ++ myOtherCache.get("woo"); ++ assertThat( ++ registry ++ .getGauges() ++ .get(MetricName.build("jcache.statistics.myOtherCache.cache-misses")) + .getValue()) +- .isEqualTo(1L); +- +- myCache.get("woo"); +- MetricName myCache = MetricName.build("jcache.statistics.myCache"); +- assertThat(registry.getGauges().get(myCache.resolve("cache-misses")).getValue()) +- .isEqualTo(1L); +- assertThat(registry.getGauges().get(myCache.resolve("cache-hits")).getValue()) +- .isEqualTo(0L); +- assertThat(registry.getGauges().get(myCache.resolve("cache-gets")).getValue()) +- .isEqualTo(1L); +- +- this.myCache.put("woo", "whee"); +- this.myCache.get("woo"); +- assertThat(registry.getGauges().get(myCache.resolve("cache-puts")).getValue()) +- .isEqualTo(1L); +- assertThat(registry.getGauges().get(myCache.resolve("cache-hits")).getValue()) +- .isEqualTo(1L); +- assertThat(registry.getGauges().get(myCache.resolve("cache-hit-percentage")).getValue()) +- .isEqualTo(50.0f); +- assertThat(registry.getGauges().get(myCache.resolve("cache-miss-percentage")).getValue()) +- .isEqualTo(50.0f); +- assertThat(registry.getGauges().get(myCache.resolve("cache-gets")).getValue()) +- .isEqualTo(2L); +- +- // cache size being 1, eviction occurs after this line +- this.myCache.put("woo2", "whoza"); +- assertThat(registry.getGauges().get(myCache.resolve("cache-evictions")).getValue()) +- .isEqualTo(1L); +- +- this.myCache.remove("woo2"); +- assertThat((Float) registry.getGauges().get(myCache.resolve("average-get-time")).getValue()) +- .isGreaterThan(0.0f); +- assertThat((Float) registry.getGauges().get(myCache.resolve("average-put-time")).getValue()) +- .isGreaterThan(0.0f); +- assertThat((Float) registry.getGauges().get(myCache.resolve("average-remove-time")).getValue()) +- .isGreaterThan(0.0f); +- +- } +- +- @AfterEach +- void tearDown() throws Exception { +- cacheManager.destroyCache("myCache"); +- cacheManager.destroyCache("myOtherCache"); +- cacheManager.close(); +- } ++ .isEqualTo(1L); ++ ++ myCache.get("woo"); ++ MetricName myCache = MetricName.build("jcache.statistics.myCache"); ++ assertThat(registry.getGauges().get(myCache.resolve("cache-misses")).getValue()).isEqualTo(1L); ++ assertThat(registry.getGauges().get(myCache.resolve("cache-hits")).getValue()).isEqualTo(0L); ++ assertThat(registry.getGauges().get(myCache.resolve("cache-gets")).getValue()).isEqualTo(1L); ++ ++ this.myCache.put("woo", "whee"); ++ this.myCache.get("woo"); ++ assertThat(registry.getGauges().get(myCache.resolve("cache-puts")).getValue()).isEqualTo(1L); ++ assertThat(registry.getGauges().get(myCache.resolve("cache-hits")).getValue()).isEqualTo(1L); ++ assertThat(registry.getGauges().get(myCache.resolve("cache-hit-percentage")).getValue()) ++ .isEqualTo(50.0f); ++ assertThat(registry.getGauges().get(myCache.resolve("cache-miss-percentage")).getValue()) ++ .isEqualTo(50.0f); ++ assertThat(registry.getGauges().get(myCache.resolve("cache-gets")).getValue()).isEqualTo(2L); ++ ++ // cache size being 1, eviction occurs after this line ++ this.myCache.put("woo2", "whoza"); ++ assertThat(registry.getGauges().get(myCache.resolve("cache-evictions")).getValue()) ++ .isEqualTo(1L); ++ ++ this.myCache.remove("woo2"); ++ assertThat((Float) registry.getGauges().get(myCache.resolve("average-get-time")).getValue()) ++ .isPositive(); ++ assertThat((Float) registry.getGauges().get(myCache.resolve("average-put-time")).getValue()) ++ .isPositive(); ++ assertThat((Float) registry.getGauges().get(myCache.resolve("average-remove-time")).getValue()) ++ .isPositive(); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ cacheManager.destroyCache("myCache"); ++ cacheManager.destroyCache("myOtherCache"); ++ cacheManager.close(); ++ } + } +--- a/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTrimReadTest.java ++++ b/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTrimReadTest.java +@@ -1,5 +1,8 @@ + package io.dropwizard.metrics5; + ++import java.util.Arrays; ++import java.util.concurrent.TimeUnit; ++import java.util.concurrent.atomic.AtomicLong; + import org.openjdk.jcstress.annotations.Actor; + import org.openjdk.jcstress.annotations.Expect; + import org.openjdk.jcstress.annotations.JCStressTest; +@@ -7,61 +10,59 @@ import org.openjdk.jcstress.annotations.Outcome; + import org.openjdk.jcstress.annotations.State; + import org.openjdk.jcstress.infra.results.L_Result; + +-import java.util.Arrays; +-import java.util.concurrent.TimeUnit; +-import java.util.concurrent.atomic.AtomicLong; +- + @JCStressTest + @Outcome( + id = "\\[240, 241, 242, 243, 244, 245, 246, 247, 248, 249\\]", + expect = Expect.ACCEPTABLE, +- desc = "Actor1 made read before Actor2 even started" +- ) ++ desc = "Actor1 made read before Actor2 even started") + @Outcome( + id = "\\[243, 244, 245, 246, 247, 248, 249\\]", + expect = Expect.ACCEPTABLE, +- desc = "Actor2 made trim before Actor1 even started" +- ) ++ desc = "Actor2 made trim before Actor1 even started") + @Outcome( + id = "\\[244, 245, 246, 247, 248, 249\\]", + expect = Expect.ACCEPTABLE, +- desc = "Actor1 made trim, then Actor2 started trim and made startIndex change, " + +- "before Actor1 concurrent read." +- ) ++ desc = ++ "Actor1 made trim, then Actor2 started trim and made startIndex change, " ++ + "before Actor1 concurrent read.") + @Outcome( + id = "\\[243, 244, 245, 246, 247, 248\\]", + expect = Expect.ACCEPTABLE, +- desc = "Actor1 made trim, then Actor2 started trim, but not finished startIndex change, before Actor1 concurrent read." +- ) ++ desc = ++ "Actor1 made trim, then Actor2 started trim, but not finished startIndex change, before Actor1 concurrent read.") + @State + public class SlidingTimeWindowArrayReservoirTrimReadTest { +- private final AtomicLong ticks = new AtomicLong(0); +- private final SlidingTimeWindowArrayReservoir reservoir; ++ private final AtomicLong ticks = new AtomicLong(0); ++ private final SlidingTimeWindowArrayReservoir reservoir; + +- public SlidingTimeWindowArrayReservoirTrimReadTest() { +- reservoir = new SlidingTimeWindowArrayReservoir(10, TimeUnit.NANOSECONDS, new Clock() { +- @Override +- public long getTick() { ++ public SlidingTimeWindowArrayReservoirTrimReadTest() { ++ reservoir = ++ new SlidingTimeWindowArrayReservoir( ++ 10, ++ TimeUnit.NANOSECONDS, ++ new Clock() { ++ @Override ++ public long getTick() { + return ticks.get(); +- } +- }); ++ } ++ }); + +- for (int i = 0; i < 250; i++) { +- ticks.set(i); +- reservoir.update(i); +- } ++ for (int i = 0; i < 250; i++) { ++ ticks.set(i); ++ reservoir.update(i); + } ++ } + +- @Actor +- public void actor1(L_Result r) { +- Snapshot snapshot = reservoir.getSnapshot(); +- String stringValues = Arrays.toString(snapshot.getValues()); +- r.r1 = stringValues; +- } ++ @Actor ++ public void actor1(L_Result r) { ++ Snapshot snapshot = reservoir.getSnapshot(); ++ String stringValues = Arrays.toString(snapshot.getValues()); ++ r.r1 = stringValues; ++ } + +- @Actor +- public void actor2() { +- ticks.set(253); +- reservoir.trim(); +- } +-} +\ No newline at end of file ++ @Actor ++ public void actor2() { ++ ticks.set(253); ++ reservoir.trim(); ++ } ++} +--- a/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirWriteReadAllocate.java ++++ b/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirWriteReadAllocate.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5; + ++import java.util.Arrays; ++import java.util.concurrent.TimeUnit; + import org.openjdk.jcstress.annotations.Actor; + import org.openjdk.jcstress.annotations.Arbiter; + import org.openjdk.jcstress.annotations.Expect; +@@ -8,38 +10,36 @@ import org.openjdk.jcstress.annotations.Outcome; + import org.openjdk.jcstress.annotations.State; + import org.openjdk.jcstress.infra.results.L_Result; + +-import java.util.Arrays; +-import java.util.concurrent.TimeUnit; +- + @JCStressTest + @Outcome(id = "\\[1023, 1029, 1034\\]", expect = Expect.ACCEPTABLE) + @State + public class SlidingTimeWindowArrayReservoirWriteReadAllocate { + +- private final SlidingTimeWindowArrayReservoir reservoir; +- +- public SlidingTimeWindowArrayReservoirWriteReadAllocate() { +- reservoir = new SlidingTimeWindowArrayReservoir(500, TimeUnit.SECONDS); +- for (int i = 0; i < 1024; i++) { +- reservoir.update(i); +- } +- } +- +- @Actor +- public void actor1() { +- reservoir.update(1029L); +- } +- +- @Actor +- public void actor2() { +- reservoir.update(1034L); +- } ++ private final SlidingTimeWindowArrayReservoir reservoir; + +- @Arbiter +- public void arbiter(L_Result r) { +- Snapshot snapshot = reservoir.getSnapshot(); +- long[] values = snapshot.getValues(); +- String stringValues = Arrays.toString(Arrays.copyOfRange(values, values.length - 3, values.length)); +- r.r1 = stringValues; ++ public SlidingTimeWindowArrayReservoirWriteReadAllocate() { ++ reservoir = new SlidingTimeWindowArrayReservoir(500, TimeUnit.SECONDS); ++ for (int i = 0; i < 1024; i++) { ++ reservoir.update(i); + } +-} +\ No newline at end of file ++ } ++ ++ @Actor ++ public void actor1() { ++ reservoir.update(1029L); ++ } ++ ++ @Actor ++ public void actor2() { ++ reservoir.update(1034L); ++ } ++ ++ @Arbiter ++ public void arbiter(L_Result r) { ++ Snapshot snapshot = reservoir.getSnapshot(); ++ long[] values = snapshot.getValues(); ++ String stringValues = ++ Arrays.toString(Arrays.copyOfRange(values, values.length - 3, values.length)); ++ r.r1 = stringValues; ++ } ++} +--- a/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirWriteReadTest.java ++++ b/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirWriteReadTest.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5; + ++import java.util.Arrays; ++import java.util.concurrent.TimeUnit; + import org.openjdk.jcstress.annotations.Actor; + import org.openjdk.jcstress.annotations.Expect; + import org.openjdk.jcstress.annotations.JCStressTest; +@@ -7,9 +9,6 @@ import org.openjdk.jcstress.annotations.Outcome; + import org.openjdk.jcstress.annotations.State; + import org.openjdk.jcstress.infra.results.L_Result; + +-import java.util.Arrays; +-import java.util.concurrent.TimeUnit; +- + @JCStressTest + @Outcome(id = "\\[\\]", expect = Expect.ACCEPTABLE) + @Outcome(id = "\\[31\\]", expect = Expect.ACCEPTABLE) +@@ -19,27 +18,26 @@ import java.util.concurrent.TimeUnit; + @State + public class SlidingTimeWindowArrayReservoirWriteReadTest { + +- private final SlidingTimeWindowArrayReservoir reservoir; +- +- public SlidingTimeWindowArrayReservoirWriteReadTest() { +- reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.SECONDS); +- } +- +- @Actor +- public void actor1() { +- reservoir.update(31L); +- } +- +- @Actor +- public void actor2() { +- reservoir.update(15L); +- } +- +- @Actor +- public void actor3(L_Result r) { +- Snapshot snapshot = reservoir.getSnapshot(); +- String stringValues = Arrays.toString(snapshot.getValues()); +- r.r1 = stringValues; +- } +- +-} +\ No newline at end of file ++ private final SlidingTimeWindowArrayReservoir reservoir; ++ ++ public SlidingTimeWindowArrayReservoirWriteReadTest() { ++ reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.SECONDS); ++ } ++ ++ @Actor ++ public void actor1() { ++ reservoir.update(31L); ++ } ++ ++ @Actor ++ public void actor2() { ++ reservoir.update(15L); ++ } ++ ++ @Actor ++ public void actor3(L_Result r) { ++ Snapshot snapshot = reservoir.getSnapshot(); ++ String stringValues = Arrays.toString(snapshot.getValues()); ++ r.r1 = stringValues; ++ } ++} +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedSqlLogger.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedSqlLogger.java +@@ -4,45 +4,45 @@ import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jdbi3.strategies.SmartNameStrategy; + import io.dropwizard.metrics5.jdbi3.strategies.StatementNameStrategy; +-import org.jdbi.v3.core.statement.SqlLogger; +-import org.jdbi.v3.core.statement.StatementContext; +- + import java.sql.SQLException; + import java.time.temporal.ChronoUnit; + import java.util.concurrent.TimeUnit; ++import org.jdbi.v3.core.statement.SqlLogger; ++import org.jdbi.v3.core.statement.StatementContext; + + /** +- * A {@link SqlLogger} implementation for JDBI which uses the SQL objects' class names and +- * method names for nanosecond-precision timers. ++ * A {@link SqlLogger} implementation for JDBI which uses the SQL objects' class names and method ++ * names for nanosecond-precision timers. + */ + public class InstrumentedSqlLogger implements SqlLogger { +- private final MetricRegistry registry; +- private final StatementNameStrategy statementNameStrategy; +- +- public InstrumentedSqlLogger(MetricRegistry registry) { +- this(registry, new SmartNameStrategy()); +- } +- +- public InstrumentedSqlLogger(MetricRegistry registry, StatementNameStrategy statementNameStrategy) { +- this.registry = registry; +- this.statementNameStrategy = statementNameStrategy; +- } +- +- @Override +- public void logAfterExecution(StatementContext context) { +- log(context); +- } +- +- @Override +- public void logException(StatementContext context, SQLException ex) { +- log(context); +- } +- +- private void log(StatementContext context) { +- MetricName statementName = statementNameStrategy.getStatementName(context); +- if (statementName != null) { +- final long elapsed = context.getElapsedTime(ChronoUnit.NANOS); +- registry.timer(statementName).update(elapsed, TimeUnit.NANOSECONDS); +- } ++ private final MetricRegistry registry; ++ private final StatementNameStrategy statementNameStrategy; ++ ++ public InstrumentedSqlLogger(MetricRegistry registry) { ++ this(registry, new SmartNameStrategy()); ++ } ++ ++ public InstrumentedSqlLogger( ++ MetricRegistry registry, StatementNameStrategy statementNameStrategy) { ++ this.registry = registry; ++ this.statementNameStrategy = statementNameStrategy; ++ } ++ ++ @Override ++ public void logAfterExecution(StatementContext context) { ++ log(context); ++ } ++ ++ @Override ++ public void logException(StatementContext context, SQLException ex) { ++ log(context); ++ } ++ ++ private void log(StatementContext context) { ++ MetricName statementName = statementNameStrategy.getStatementName(context); ++ if (statementName != null) { ++ final long elapsed = context.getElapsedTime(ChronoUnit.NANOS); ++ registry.timer(statementName).update(elapsed, TimeUnit.NANOSECONDS); + } ++ } + } +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java +@@ -4,39 +4,39 @@ import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jdbi3.strategies.SmartNameStrategy; + import io.dropwizard.metrics5.jdbi3.strategies.StatementNameStrategy; ++import java.util.concurrent.TimeUnit; + import org.jdbi.v3.core.statement.SqlLogger; + import org.jdbi.v3.core.statement.StatementContext; + import org.jdbi.v3.core.statement.TimingCollector; + +-import java.util.concurrent.TimeUnit; +- + /** + * A {@link TimingCollector} implementation for JDBI which uses the SQL objects' class names and + * method names for millisecond-precision timers. + * +- * @deprecated Use {@link InstrumentedSqlLogger} and {@link org.jdbi.v3.core.Jdbi#setSqlLogger(SqlLogger)} instead. ++ * @deprecated Use {@link InstrumentedSqlLogger} and {@link ++ * org.jdbi.v3.core.Jdbi#setSqlLogger(SqlLogger)} instead. + */ + @Deprecated + public class InstrumentedTimingCollector implements TimingCollector { + +- private final MetricRegistry registry; +- private final StatementNameStrategy statementNameStrategy; ++ private final MetricRegistry registry; ++ private final StatementNameStrategy statementNameStrategy; + +- public InstrumentedTimingCollector(MetricRegistry registry) { +- this(registry, new SmartNameStrategy()); +- } ++ public InstrumentedTimingCollector(MetricRegistry registry) { ++ this(registry, new SmartNameStrategy()); ++ } + +- public InstrumentedTimingCollector(MetricRegistry registry, +- StatementNameStrategy statementNameStrategy) { +- this.registry = registry; +- this.statementNameStrategy = statementNameStrategy; +- } ++ public InstrumentedTimingCollector( ++ MetricRegistry registry, StatementNameStrategy statementNameStrategy) { ++ this.registry = registry; ++ this.statementNameStrategy = statementNameStrategy; ++ } + +- @Override +- public void collect(long elapsedTime, StatementContext ctx) { +- MetricName statementName = statementNameStrategy.getStatementName(ctx); +- if (statementName != null) { +- registry.timer(statementName).update(elapsedTime, TimeUnit.NANOSECONDS); +- } ++ @Override ++ public void collect(long elapsedTime, StatementContext ctx) { ++ MetricName statementName = statementNameStrategy.getStatementName(ctx); ++ if (statementName != null) { ++ registry.timer(statementName).update(elapsedTime, TimeUnit.NANOSECONDS); + } ++ } + } +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategy.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategy.java +@@ -1,12 +1,9 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + +-/** +- * Collects metrics by respective SQLObject methods. +- */ ++/** Collects metrics by respective SQLObject methods. */ + public class BasicSqlNameStrategy extends DelegatingStatementNameStrategy { + +- public BasicSqlNameStrategy() { +- super(DefaultNameStrategy.CHECK_EMPTY, +- DefaultNameStrategy.SQL_OBJECT); +- } ++ public BasicSqlNameStrategy() { ++ super(DefaultNameStrategy.CHECK_EMPTY, DefaultNameStrategy.SQL_OBJECT); ++ } + } +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java +@@ -1,60 +1,52 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.jdbi.v3.core.extension.ExtensionMethod; + import org.jdbi.v3.core.statement.StatementContext; + +-/** +- * Default strategies which build a basis of more complex strategies +- */ ++/** Default strategies which build a basis of more complex strategies */ + public enum DefaultNameStrategy implements StatementNameStrategy { + +- /** +- * If no SQL in the context, returns `sql.empty`, otherwise falls through +- */ +- CHECK_EMPTY { +- @Override +- public MetricName getStatementName(StatementContext statementContext) { +- final String rawSql = statementContext.getRawSql(); +- return rawSql == null || rawSql.isEmpty() ? MetricName.build("sql.empty") : null; +- } +- }, +- +- /** +- * If there is an SQL object attached to the context, returns the name package, +- * the class and the method on which SQL is declared. If not SQL object is attached, +- * falls through +- */ +- SQL_OBJECT { +- @Override +- public MetricName getStatementName(StatementContext statementContext) { +- ExtensionMethod extensionMethod = statementContext.getExtensionMethod(); +- if (extensionMethod != null) { +- return MetricRegistry.name(extensionMethod.getType(), extensionMethod.getMethod().getName()); +- } +- return null; +- } +- }, ++ /** If no SQL in the context, returns `sql.empty`, otherwise falls through */ ++ CHECK_EMPTY { ++ @Override ++ public MetricName getStatementName(StatementContext statementContext) { ++ final String rawSql = statementContext.getRawSql(); ++ return Strings.isNullOrEmpty(rawSql) ? MetricName.build("sql.empty") : null; ++ } ++ }, + +- /** +- * Returns a raw SQL in the context (even if it's not exist) +- */ +- NAIVE_NAME { +- @Override +- public MetricName getStatementName(StatementContext statementContext) { +- return MetricName.build(statementContext.getRawSql()); +- } +- }, ++ /** ++ * If there is an SQL object attached to the context, returns the name package, the class and the ++ * method on which SQL is declared. If not SQL object is attached, falls through ++ */ ++ SQL_OBJECT { ++ @Override ++ public MetricName getStatementName(StatementContext statementContext) { ++ ExtensionMethod extensionMethod = statementContext.getExtensionMethod(); ++ if (extensionMethod != null) { ++ return MetricRegistry.name( ++ extensionMethod.getType(), extensionMethod.getMethod().getName()); ++ } ++ return null; ++ } ++ }, + +- /** +- * Returns the `sql.raw` constant +- */ +- CONSTANT_SQL_RAW { +- @Override +- public MetricName getStatementName(StatementContext statementContext) { +- return MetricName.build("sql.raw"); +- } ++ /** Returns a raw SQL in the context (even if it's not exist) */ ++ NAIVE_NAME { ++ @Override ++ public MetricName getStatementName(StatementContext statementContext) { ++ return MetricName.build(statementContext.getRawSql()); + } ++ }, + ++ /** Returns the `sql.raw` constant */ ++ CONSTANT_SQL_RAW { ++ @Override ++ public MetricName getStatementName(StatementContext statementContext) { ++ return MetricName.build("sql.raw"); ++ } ++ } + } +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DelegatingStatementNameStrategy.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DelegatingStatementNameStrategy.java +@@ -1,33 +1,30 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + + import io.dropwizard.metrics5.MetricName; +-import org.jdbi.v3.core.statement.StatementContext; +- + import java.util.Arrays; + import java.util.List; ++import org.jdbi.v3.core.statement.StatementContext; + + public abstract class DelegatingStatementNameStrategy implements StatementNameStrategy { + +- /** +- * Unknown SQL. +- */ +- private static final MetricName UNKNOWN_SQL = MetricName.build("sql.unknown"); ++ /** Unknown SQL. */ ++ private static final MetricName UNKNOWN_SQL = MetricName.build("sql.unknown"); + +- private final List strategies; ++ private final List strategies; + +- protected DelegatingStatementNameStrategy(StatementNameStrategy... strategies) { +- this.strategies = Arrays.asList(strategies); +- } +- +- @Override +- public MetricName getStatementName(StatementContext statementContext) { +- for (StatementNameStrategy strategy : strategies) { +- final MetricName statementName = strategy.getStatementName(statementContext); +- if (statementName != null) { +- return statementName; +- } +- } ++ protected DelegatingStatementNameStrategy(StatementNameStrategy... strategies) { ++ this.strategies = Arrays.asList(strategies); ++ } + +- return UNKNOWN_SQL; ++ @Override ++ public MetricName getStatementName(StatementContext statementContext) { ++ for (StatementNameStrategy strategy : strategies) { ++ final MetricName statementName = strategy.getStatementName(statementContext); ++ if (statementName != null) { ++ return statementName; ++ } + } ++ ++ return UNKNOWN_SQL; ++ } + } +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategy.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategy.java +@@ -1,12 +1,9 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + +-/** +- * Very simple strategy, can be used with any JDBI loader to build basic statistics. +- */ ++/** Very simple strategy, can be used with any JDBI loader to build basic statistics. */ + public class NaiveNameStrategy extends DelegatingStatementNameStrategy { + +- public NaiveNameStrategy() { +- super(DefaultNameStrategy.CHECK_EMPTY, +- DefaultNameStrategy.NAIVE_NAME); +- } ++ public NaiveNameStrategy() { ++ super(DefaultNameStrategy.CHECK_EMPTY, DefaultNameStrategy.NAIVE_NAME); ++ } + } +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategy.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategy.java +@@ -5,9 +5,10 @@ package io.dropwizard.metrics5.jdbi3.strategies; + */ + public class SmartNameStrategy extends DelegatingStatementNameStrategy { + +- public SmartNameStrategy() { +- super(DefaultNameStrategy.CHECK_EMPTY, +- DefaultNameStrategy.SQL_OBJECT, +- DefaultNameStrategy.CONSTANT_SQL_RAW); +- } ++ public SmartNameStrategy() { ++ super( ++ DefaultNameStrategy.CHECK_EMPTY, ++ DefaultNameStrategy.SQL_OBJECT, ++ DefaultNameStrategy.CONSTANT_SQL_RAW); ++ } + } +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/StatementNameStrategy.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/StatementNameStrategy.java +@@ -3,11 +3,9 @@ package io.dropwizard.metrics5.jdbi3.strategies; + import io.dropwizard.metrics5.MetricName; + import org.jdbi.v3.core.statement.StatementContext; + +-/** +- * Interface for strategies to statement contexts to metric names. +- */ ++/** Interface for strategies to statement contexts to metric names. */ + @FunctionalInterface + public interface StatementNameStrategy { + +- MetricName getStatementName(StatementContext statementContext); ++ MetricName getStatementName(StatementContext statementContext); + } +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategy.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategy.java +@@ -3,46 +3,44 @@ package io.dropwizard.metrics5.jdbi3.strategies; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.annotation.Timed; ++import java.lang.reflect.Method; + import org.jdbi.v3.core.extension.ExtensionMethod; + import org.jdbi.v3.core.statement.StatementContext; + +-import java.lang.reflect.Method; +- +-/** +- * Takes into account the {@link Timed} annotation on extension methods +- */ ++/** Takes into account the {@link Timed} annotation on extension methods */ + public class TimedAnnotationNameStrategy implements StatementNameStrategy { + +- @Override +- public MetricName getStatementName(StatementContext statementContext) { +- final ExtensionMethod extensionMethod = statementContext.getExtensionMethod(); +- if (extensionMethod == null) { +- return null; +- } ++ @Override ++ public MetricName getStatementName(StatementContext statementContext) { ++ final ExtensionMethod extensionMethod = statementContext.getExtensionMethod(); ++ if (extensionMethod == null) { ++ return null; ++ } + +- final Class clazz = extensionMethod.getType(); +- final Timed classTimed = clazz.getAnnotation(Timed.class); +- final Method method = extensionMethod.getMethod(); +- final Timed methodTimed = method.getAnnotation(Timed.class); ++ final Class clazz = extensionMethod.getType(); ++ final Timed classTimed = clazz.getAnnotation(Timed.class); ++ final Method method = extensionMethod.getMethod(); ++ final Timed methodTimed = method.getAnnotation(Timed.class); + +- // If the method is timed, figure out the name +- if (methodTimed != null) { +- String methodName = methodTimed.name().isEmpty() ? method.getName() : methodTimed.name(); +- if (methodTimed.absolute()) { +- return MetricName.build(methodName); +- } else { +- // We need to check if the class has a custom timer name +- return classTimed == null || classTimed.name().isEmpty() ? +- MetricRegistry.name(clazz, methodName) : +- MetricRegistry.name(classTimed.name(), methodName); +- } +- } else if (classTimed != null) { +- // Maybe the class is timed? +- return classTimed.name().isEmpty() ? MetricRegistry.name(clazz, method.getName()) : +- MetricRegistry.name(classTimed.name(), method.getName()); +- } else { +- // No timers neither on the method or the class +- return null; +- } ++ // If the method is timed, figure out the name ++ if (methodTimed != null) { ++ String methodName = methodTimed.name().isEmpty() ? method.getName() : methodTimed.name(); ++ if (methodTimed.absolute()) { ++ return MetricName.build(methodName); ++ } else { ++ // We need to check if the class has a custom timer name ++ return classTimed == null || classTimed.name().isEmpty() ++ ? MetricRegistry.name(clazz, methodName) ++ : MetricRegistry.name(classTimed.name(), methodName); ++ } ++ } else if (classTimed != null) { ++ // Maybe the class is timed? ++ return classTimed.name().isEmpty() ++ ? MetricRegistry.name(clazz, method.getName()) ++ : MetricRegistry.name(classTimed.name(), method.getName()); ++ } else { ++ // No timers neither on the method or the class ++ return null; + } ++ } + } +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/AbstractStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/AbstractStrategyTest.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.jdbi.v3.core.statement.StatementContext; +@@ -10,22 +12,19 @@ import org.mockito.junit.jupiter.MockitoExtension; + import org.mockito.junit.jupiter.MockitoSettings; + import org.mockito.quality.Strictness; + +-import static org.mockito.Mockito.when; +- + @ExtendWith(MockitoExtension.class) + @MockitoSettings(strictness = Strictness.LENIENT) + class AbstractStrategyTest { + +- MetricRegistry registry = new MetricRegistry(); +- @Mock +- StatementContext ctx; ++ MetricRegistry registry = new MetricRegistry(); ++ @Mock StatementContext ctx; + +- @BeforeEach +- void setUp() throws Exception { +- when(ctx.getRawSql()).thenReturn("SELECT 1"); +- } ++ @BeforeEach ++ void setUp() throws Exception { ++ when(ctx.getRawSql()).thenReturn("SELECT 1"); ++ } + +- long getTimerMaxValue(MetricName name) { +- return registry.timer(name).getSnapshot().getMax(); +- } ++ long getTimerMaxValue(MetricName name) { ++ return registry.timer(name).getSnapshot().getMax(); ++ } + } +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java +@@ -1,24 +1,24 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + +-import io.dropwizard.metrics5.MetricName; +-import org.jdbi.v3.core.extension.ExtensionMethod; +-import org.junit.jupiter.api.Test; +- + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.when; + +-class BasicSqlNameStrategyTest extends AbstractStrategyTest { ++import io.dropwizard.metrics5.MetricName; ++import org.jdbi.v3.core.extension.ExtensionMethod; ++import org.junit.jupiter.api.Test; ++ ++final class BasicSqlNameStrategyTest extends AbstractStrategyTest { + +- private final BasicSqlNameStrategy basicSqlNameStrategy = new BasicSqlNameStrategy(); ++ private final BasicSqlNameStrategy basicSqlNameStrategy = new BasicSqlNameStrategy(); + +- @Test +- void producesMethodNameAsMetric() throws Exception { +- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); +- MetricName name = basicSqlNameStrategy.getStatementName(ctx); +- assertThat(name).isEqualTo(name(getClass(), "someMethod")); +- } ++ @Test ++ void producesMethodNameAsMetric() throws Exception { ++ when(ctx.getExtensionMethod()) ++ .thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); ++ MetricName name = basicSqlNameStrategy.getStatementName(ctx); ++ assertThat(name).isEqualTo(name(getClass(), "someMethod")); ++ } + +- public void someMethod() { +- } ++ public void someMethod() {} + } +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java +@@ -1,61 +1,59 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + ++import static org.mockito.Mockito.*; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.jdbi3.InstrumentedSqlLogger; +-import io.dropwizard.metrics5.jdbi3.strategies.StatementNameStrategy; +-import org.jdbi.v3.core.statement.StatementContext; +-import org.junit.jupiter.api.Test; +- + import java.sql.SQLException; + import java.time.temporal.ChronoUnit; + import java.util.concurrent.TimeUnit; ++import org.jdbi.v3.core.statement.StatementContext; ++import org.junit.jupiter.api.Test; + +-import static org.mockito.Mockito.*; +- +-class InstrumentedSqlLoggerTest { +- @Test +- void logsExecutionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); +- final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); ++final class InstrumentedSqlLoggerTest { ++ @Test ++ void logsExecutionTime() { ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); ++ final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); + +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); + +- final MetricName statementName = MetricName.build("my-fake-name"); +- final long fakeElapsed = 1234L; ++ final MetricName statementName = MetricName.build("my-fake-name"); ++ final long fakeElapsed = 1234L; + +- when(mockNameStrategy.getStatementName(mockContext)).thenReturn(statementName); +- when(mockRegistry.timer(statementName)).thenReturn(mockTimer); ++ when(mockNameStrategy.getStatementName(mockContext)).thenReturn(statementName); ++ when(mockRegistry.timer(statementName)).thenReturn(mockTimer); + +- when(mockContext.getElapsedTime(ChronoUnit.NANOS)).thenReturn(fakeElapsed); ++ when(mockContext.getElapsedTime(ChronoUnit.NANOS)).thenReturn(fakeElapsed); + +- logger.logAfterExecution(mockContext); ++ logger.logAfterExecution(mockContext); + +- verify(mockTimer).update(fakeElapsed, TimeUnit.NANOSECONDS); +- } ++ verify(mockTimer).update(fakeElapsed, TimeUnit.NANOSECONDS); ++ } + +- @Test +- void logsExceptionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); +- final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); ++ @Test ++ void logsExceptionTime() { ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); ++ final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); + +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); + +- final MetricName statementName = MetricName.build("my-fake-name"); +- final long fakeElapsed = 1234L; ++ final MetricName statementName = MetricName.build("my-fake-name"); ++ final long fakeElapsed = 1234L; + +- when(mockNameStrategy.getStatementName(mockContext)).thenReturn(statementName); +- when(mockRegistry.timer(statementName)).thenReturn(mockTimer); ++ when(mockNameStrategy.getStatementName(mockContext)).thenReturn(statementName); ++ when(mockRegistry.timer(statementName)).thenReturn(mockTimer); + +- when(mockContext.getElapsedTime(ChronoUnit.NANOS)).thenReturn(fakeElapsed); ++ when(mockContext.getElapsedTime(ChronoUnit.NANOS)).thenReturn(fakeElapsed); + +- logger.logException(mockContext, new SQLException()); ++ logger.logException(mockContext, new SQLException()); + +- verify(mockTimer).update(fakeElapsed, TimeUnit.NANOSECONDS); +- } ++ verify(mockTimer).update(fakeElapsed, TimeUnit.NANOSECONDS); ++ } + } +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java +@@ -1,18 +1,17 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + +-import io.dropwizard.metrics5.MetricName; +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + +-class NaiveNameStrategyTest extends AbstractStrategyTest { ++import io.dropwizard.metrics5.MetricName; ++import org.junit.jupiter.api.Test; + +- private final NaiveNameStrategy naiveNameStrategy = new NaiveNameStrategy(); ++final class NaiveNameStrategyTest extends AbstractStrategyTest { + +- @Test +- void producesSqlRawMetrics() throws Exception { +- MetricName name = naiveNameStrategy.getStatementName(ctx); +- assertThat(name.getKey()).isEqualToIgnoringCase("SELECT 1"); +- } ++ private final NaiveNameStrategy naiveNameStrategy = new NaiveNameStrategy(); + ++ @Test ++ void producesSqlRawMetrics() throws Exception { ++ MetricName name = naiveNameStrategy.getStatementName(ctx); ++ assertThat(name.getKey()).isEqualToIgnoringCase("SELECT 1"); ++ } + } +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java +@@ -1,73 +1,71 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.reset; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.jdbi3.InstrumentedTimingCollector; ++import java.util.concurrent.TimeUnit; + import org.jdbi.v3.core.extension.ExtensionMethod; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.reset; +-import static org.mockito.Mockito.when; +- +-class SmartNameStrategyTest extends AbstractStrategyTest { ++final class SmartNameStrategyTest extends AbstractStrategyTest { + +- private final StatementNameStrategy smartNameStrategy = new SmartNameStrategy(); +- private InstrumentedTimingCollector collector; ++ private final StatementNameStrategy smartNameStrategy = new SmartNameStrategy(); ++ private InstrumentedTimingCollector collector; + +- @BeforeEach +- @Override +- public void setUp() throws Exception { +- super.setUp(); +- collector = new InstrumentedTimingCollector(registry, smartNameStrategy); +- } ++ @BeforeEach ++ @Override ++ public void setUp() throws Exception { ++ super.setUp(); ++ collector = new InstrumentedTimingCollector(registry, smartNameStrategy); ++ } + +- @Test +- void updatesTimerForSqlObjects() throws Exception { +- when(ctx.getExtensionMethod()).thenReturn( +- new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); ++ @Test ++ void updatesTimerForSqlObjects() throws Exception { ++ when(ctx.getExtensionMethod()) ++ .thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); + +- collector.collect(TimeUnit.SECONDS.toNanos(1), ctx); ++ collector.collect(TimeUnit.SECONDS.toNanos(1), ctx); + +- MetricName name = smartNameStrategy.getStatementName(ctx); +- assertThat(name).isEqualTo(name(getClass(), "someMethod")); +- assertThat(getTimerMaxValue(name)).isEqualTo(1000000000); +- } ++ MetricName name = smartNameStrategy.getStatementName(ctx); ++ assertThat(name).isEqualTo(name(getClass(), "someMethod")); ++ assertThat(getTimerMaxValue(name)).isEqualTo(1000000000); ++ } + +- @Test +- void updatesTimerForRawSql() throws Exception { +- collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); ++ @Test ++ void updatesTimerForRawSql() throws Exception { ++ collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); + +- MetricName name = smartNameStrategy.getStatementName(ctx); +- assertThat(name).isEqualTo(name("sql", "raw")); +- assertThat(getTimerMaxValue(name)).isEqualTo(2000000000); +- } ++ MetricName name = smartNameStrategy.getStatementName(ctx); ++ assertThat(name).isEqualTo(name("sql", "raw")); ++ assertThat(getTimerMaxValue(name)).isEqualTo(2000000000); ++ } + +- @Test +- void updatesTimerForNoRawSql() throws Exception { +- reset(ctx); ++ @Test ++ void updatesTimerForNoRawSql() throws Exception { ++ reset(ctx); + +- collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); ++ collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); + +- MetricName name = smartNameStrategy.getStatementName(ctx); +- assertThat(name).isEqualTo(name("sql", "empty")); +- assertThat(getTimerMaxValue(name)).isEqualTo(2000000000); +- } ++ MetricName name = smartNameStrategy.getStatementName(ctx); ++ assertThat(name).isEqualTo(name("sql", "empty")); ++ assertThat(getTimerMaxValue(name)).isEqualTo(2000000000); ++ } + +- @Test +- void updatesTimerForContextClass() throws Exception { +- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(getClass(), +- getClass().getMethod("someMethod"))); +- collector.collect(TimeUnit.SECONDS.toNanos(3), ctx); ++ @Test ++ void updatesTimerForContextClass() throws Exception { ++ when(ctx.getExtensionMethod()) ++ .thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); ++ collector.collect(TimeUnit.SECONDS.toNanos(3), ctx); + +- MetricName name = smartNameStrategy.getStatementName(ctx); +- assertThat(name).isEqualTo(name(getClass(), "someMethod")); +- assertThat(getTimerMaxValue(name)).isEqualTo(3000000000L); +- } ++ MetricName name = smartNameStrategy.getStatementName(ctx); ++ assertThat(name).isEqualTo(name(getClass(), "someMethod")); ++ assertThat(getTimerMaxValue(name)).isEqualTo(3000000000L); ++ } + +- public void someMethod() { +- } ++ public void someMethod() {} + } +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java +@@ -1,89 +1,104 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.annotation.Timed; + import org.jdbi.v3.core.extension.ExtensionMethod; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.when; +- +-class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { +- +- private final TimedAnnotationNameStrategy timedAnnotationNameStrategy = new TimedAnnotationNameStrategy(); +- +- public interface Foo { +- +- @Timed +- void update(); +- +- @Timed(name = "custom-update") +- void customUpdate(); ++final class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + +- @Timed(name = "absolute-update", absolute = true) +- void absoluteUpdate(); +- } ++ private final TimedAnnotationNameStrategy timedAnnotationNameStrategy = ++ new TimedAnnotationNameStrategy(); + ++ public interface Foo { + + @Timed +- public interface Bar { +- +- void update(); +- } +- +- @Timed(name = "custom-bar") +- public interface CustomBar { +- +- @Timed(name = "find-by-id") +- int find(String name); +- } +- +- public interface Dummy { +- +- void show(); +- } +- +- @Test +- void testAnnotationOnMethod() throws Exception { +- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("update"))); +- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +- .isEqualTo(MetricName.build("io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.update")); +- } +- +- @Test +- void testAnnotationOnMethodWithCustomName() throws Exception { +- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("customUpdate"))); +- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +- .isEqualTo(MetricName.build("io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.custom-update")); +- } +- +- @Test +- void testAnnotationOnMethodWithCustomAbsoluteName() throws Exception { +- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("absoluteUpdate"))); +- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isEqualTo(MetricName.build("absolute-update")); +- } +- +- @Test +- void testAnnotationOnClass() throws Exception { +- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Bar.class, Bar.class.getMethod("update"))); +- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +- .isEqualTo(MetricName.build("io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Bar.update")); +- } +- +- @Test +- void testAnnotationOnMethodAndClassWithCustomNames() throws Exception { +- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(CustomBar.class, CustomBar.class.getMethod("find", String.class))); +- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isEqualTo(MetricName.build("custom-bar.find-by-id")); +- } +- +- @Test +- void testNoAnnotations() throws Exception { +- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Dummy.class, Dummy.class.getMethod("show"))); +- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); +- } +- +- @Test +- void testNoMethod() { +- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); +- } +-} +\ No newline at end of file ++ void update(); ++ ++ @Timed(name = "custom-update") ++ void customUpdate(); ++ ++ @Timed(name = "absolute-update", absolute = true) ++ void absoluteUpdate(); ++ } ++ ++ @Timed ++ public interface Bar { ++ ++ void update(); ++ } ++ ++ @Timed(name = "custom-bar") ++ public interface CustomBar { ++ ++ @Timed(name = "find-by-id") ++ int find(String name); ++ } ++ ++ public interface Dummy { ++ ++ void show(); ++ } ++ ++ @Test ++ void annotationOnMethod() throws Exception { ++ when(ctx.getExtensionMethod()) ++ .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("update"))); ++ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) ++ .isEqualTo( ++ MetricName.build( ++ "io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.update")); ++ } ++ ++ @Test ++ void annotationOnMethodWithCustomName() throws Exception { ++ when(ctx.getExtensionMethod()) ++ .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("customUpdate"))); ++ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) ++ .isEqualTo( ++ MetricName.build( ++ "io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.custom-update")); ++ } ++ ++ @Test ++ void annotationOnMethodWithCustomAbsoluteName() throws Exception { ++ when(ctx.getExtensionMethod()) ++ .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("absoluteUpdate"))); ++ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) ++ .isEqualTo(MetricName.build("absolute-update")); ++ } ++ ++ @Test ++ void annotationOnClass() throws Exception { ++ when(ctx.getExtensionMethod()) ++ .thenReturn(new ExtensionMethod(Bar.class, Bar.class.getMethod("update"))); ++ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) ++ .isEqualTo( ++ MetricName.build( ++ "io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Bar.update")); ++ } ++ ++ @Test ++ void annotationOnMethodAndClassWithCustomNames() throws Exception { ++ when(ctx.getExtensionMethod()) ++ .thenReturn( ++ new ExtensionMethod(CustomBar.class, CustomBar.class.getMethod("find", String.class))); ++ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) ++ .isEqualTo(MetricName.build("custom-bar.find-by-id")); ++ } ++ ++ @Test ++ void noAnnotations() throws Exception { ++ when(ctx.getExtensionMethod()) ++ .thenReturn(new ExtensionMethod(Dummy.class, Dummy.class.getMethod("show"))); ++ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); ++ } ++ ++ @Test ++ void noMethod() { ++ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); ++ } ++} +--- a/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java +@@ -1,5 +1,13 @@ + package io.dropwizard.metrics5.jersey2; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; ++ ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Meter; +@@ -12,541 +20,589 @@ import io.dropwizard.metrics5.annotation.Metered; + import io.dropwizard.metrics5.annotation.ResponseMetered; + import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; + import io.dropwizard.metrics5.annotation.Timed; +-import org.glassfish.jersey.server.ContainerResponse; +-import org.glassfish.jersey.server.model.ModelProcessor; +-import org.glassfish.jersey.server.model.Resource; +-import org.glassfish.jersey.server.model.ResourceMethod; +-import org.glassfish.jersey.server.model.ResourceModel; +-import org.glassfish.jersey.server.monitoring.ApplicationEvent; +-import org.glassfish.jersey.server.monitoring.ApplicationEventListener; +-import org.glassfish.jersey.server.monitoring.RequestEvent; +-import org.glassfish.jersey.server.monitoring.RequestEventListener; +- +-import javax.ws.rs.core.Configuration; +-import javax.ws.rs.ext.Provider; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; ++import java.util.EnumSet; + import java.util.List; + import java.util.Map; + import java.util.Set; +-import java.util.EnumSet; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; + import java.util.concurrent.TimeUnit; + import java.util.function.Supplier; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import javax.ws.rs.core.Configuration; ++import javax.ws.rs.ext.Provider; ++import org.glassfish.jersey.server.ContainerResponse; ++import org.glassfish.jersey.server.model.ModelProcessor; ++import org.glassfish.jersey.server.model.Resource; ++import org.glassfish.jersey.server.model.ResourceMethod; ++import org.glassfish.jersey.server.model.ResourceModel; ++import org.glassfish.jersey.server.monitoring.ApplicationEvent; ++import org.glassfish.jersey.server.monitoring.ApplicationEventListener; ++import org.glassfish.jersey.server.monitoring.RequestEvent; ++import org.glassfish.jersey.server.monitoring.RequestEventListener; + + /** +- * An application event listener that listens for Jersey application initialization to +- * be finished, then creates a map of resource method that have metrics annotations. +- *

    +- * Finally, it listens for method start events, and returns a {@link RequestEventListener} +- * that updates the relevant metric for suitably annotated methods when it gets the +- * request events indicating that the method is about to be invoked, or just got done +- * being invoked. ++ * An application event listener that listens for Jersey application initialization to be finished, ++ * then creates a map of resource method that have metrics annotations. ++ * ++ *

    Finally, it listens for method start events, and returns a {@link RequestEventListener} that ++ * updates the relevant metric for suitably annotated methods when it gets the request events ++ * indicating that the method is about to be invoked, or just got done being invoked. + */ + @Provider +-public class InstrumentedResourceMethodApplicationListener implements ApplicationEventListener, ModelProcessor { +- +- private static final String[] REQUEST_FILTERING = {"request", "filtering"}; +- private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; +- private static final String TOTAL = "total"; +- +- private final MetricRegistry metrics; +- private final ConcurrentMap timers = new ConcurrentHashMap<>(); +- private final ConcurrentMap meters = new ConcurrentHashMap<>(); +- private final ConcurrentMap exceptionMeters = new ConcurrentHashMap<>(); +- private final ConcurrentMap responseMeters = new ConcurrentHashMap<>(); +- +- private final Clock clock; +- private final boolean trackFilters; +- private final Supplier reservoirSupplier; +- +- /** +- * Construct an application event listener using the given metrics registry. +- *

    +- * When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} +- * should be added to a Jersey {@code ResourceConfig} as a singleton. +- * +- * @param metrics a {@link MetricRegistry} +- */ +- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { +- this(metrics, Clock.defaultClock(), false); +- } +- +- /** +- * Constructs a custom application listener. +- * +- * @param metrics the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- */ +- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, +- final boolean trackFilters) { +- this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); +- } +- +- /** +- * Constructs a custom application listener. +- * +- * @param metrics the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. +- */ +- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, +- final boolean trackFilters, +- final Supplier reservoirSupplier) { +- this.metrics = metrics; +- this.clock = clock; +- this.trackFilters = trackFilters; +- this.reservoirSupplier = reservoirSupplier; +- } +- +- /** +- * A private class to maintain the metric for a method annotated with the +- * {@link ExceptionMetered} annotation, which needs to maintain both a meter +- * and a cause for which the meter should be updated. +- */ +- private static class ExceptionMeterMetric { +- public final Meter meter; +- public final Class cause; +- +- public ExceptionMeterMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final ExceptionMetered exceptionMetered) { +- final MetricName name = chooseName(exceptionMetered.name(), +- exceptionMetered.absolute(), method, ExceptionMetered.DEFAULT_NAME_SUFFIX); +- this.meter = registry.meter(name); +- this.cause = exceptionMetered.cause(); +- } ++public class InstrumentedResourceMethodApplicationListener ++ implements ApplicationEventListener, ModelProcessor { ++ ++ private static final String[] REQUEST_FILTERING = {"request", "filtering"}; ++ private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; ++ private static final String TOTAL = "total"; ++ ++ private final MetricRegistry metrics; ++ private final ConcurrentMap timers = new ConcurrentHashMap<>(); ++ private final ConcurrentMap meters = new ConcurrentHashMap<>(); ++ private final ConcurrentMap exceptionMeters = ++ new ConcurrentHashMap<>(); ++ private final ConcurrentMap responseMeters = ++ new ConcurrentHashMap<>(); ++ ++ private final Clock clock; ++ private final boolean trackFilters; ++ private final Supplier reservoirSupplier; ++ ++ /** ++ * Construct an application event listener using the given metrics registry. ++ * ++ *

    When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} ++ * should be added to a Jersey {@code ResourceConfig} as a singleton. ++ * ++ * @param metrics a {@link MetricRegistry} ++ */ ++ public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { ++ this(metrics, Clock.defaultClock(), false); ++ } ++ ++ /** ++ * Constructs a custom application listener. ++ * ++ * @param metrics the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be ++ * tracked ++ */ ++ public InstrumentedResourceMethodApplicationListener( ++ final MetricRegistry metrics, final Clock clock, final boolean trackFilters) { ++ this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); ++ } ++ ++ /** ++ * Constructs a custom application listener. ++ * ++ * @param metrics the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be ++ * tracked ++ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. ++ */ ++ public InstrumentedResourceMethodApplicationListener( ++ final MetricRegistry metrics, ++ final Clock clock, ++ final boolean trackFilters, ++ final Supplier reservoirSupplier) { ++ this.metrics = metrics; ++ this.clock = clock; ++ this.trackFilters = trackFilters; ++ this.reservoirSupplier = reservoirSupplier; ++ } ++ ++ /** ++ * A private class to maintain the metric for a method annotated with the {@link ExceptionMetered} ++ * annotation, which needs to maintain both a meter and a cause for which the meter should be ++ * updated. ++ */ ++ private static class ExceptionMeterMetric { ++ public final Meter meter; ++ public final Class cause; ++ ++ public ExceptionMeterMetric( ++ final MetricRegistry registry, ++ final ResourceMethod method, ++ final ExceptionMetered exceptionMetered) { ++ final MetricName name = ++ chooseName( ++ exceptionMetered.name(), ++ exceptionMetered.absolute(), ++ method, ++ ExceptionMetered.DEFAULT_NAME_SUFFIX); ++ this.meter = registry.meter(name); ++ this.cause = exceptionMetered.cause(); + } +- +- /** +- * A private class to maintain the metrics for a method annotated with the +- * {@link ResponseMetered} annotation, which needs to maintain meters for +- * different response codes +- */ +- private static class ResponseMeterMetric { +- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); +- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); +- private final MetricName metricName; +- private final List meters; +- private final Map responseCodeMeters; +- private final MetricRegistry metricRegistry; +- private final ResponseMeteredLevel level; +- +- public ResponseMeterMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final ResponseMetered responseMetered) { +- this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); +- this.level = responseMetered.level(); +- this.meters = COARSE_METER_LEVELS.contains(level) ? +- Collections.unmodifiableList(Arrays.asList( +- registry.meter(metricName.resolve("1xx-responses")), // 1xx +- registry.meter(metricName.resolve("2xx-responses")), // 2xx +- registry.meter(metricName.resolve("3xx-responses")), // 3xx +- registry.meter(metricName.resolve("4xx-responses")), // 4xx +- registry.meter(metricName.resolve("5xx-responses")) // 5xx +- )) : Collections.emptyList(); +- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : Collections.emptyMap(); +- this.metricRegistry = registry; +- } +- +- public void mark(int statusCode) { +- if (DETAILED_METER_LEVELS.contains(level)) { +- getResponseCodeMeter(statusCode).mark(); +- } +- +- if (COARSE_METER_LEVELS.contains(level)) { +- final int responseStatus = statusCode / 100; +- if (responseStatus >= 1 && responseStatus <= 5) { +- meters.get(responseStatus - 1).mark(); +- } +- } +- } +- +- private Meter getResponseCodeMeter(int statusCode) { +- return responseCodeMeters +- .computeIfAbsent(statusCode, sc -> metricRegistry +- .meter(metricName.resolve(String.format("%d-responses", sc)))); +- } ++ } ++ ++ /** ++ * A private class to maintain the metrics for a method annotated with the {@link ResponseMetered} ++ * annotation, which needs to maintain meters for different response codes ++ */ ++ private static class ResponseMeterMetric { ++ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); ++ private static final Set DETAILED_METER_LEVELS = ++ EnumSet.of(DETAILED, ALL); ++ private final MetricName metricName; ++ private final List meters; ++ private final Map responseCodeMeters; ++ private final MetricRegistry metricRegistry; ++ private final ResponseMeteredLevel level; ++ ++ public ResponseMeterMetric( ++ final MetricRegistry registry, ++ final ResourceMethod method, ++ final ResponseMetered responseMetered) { ++ this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); ++ this.level = responseMetered.level(); ++ this.meters = ++ COARSE_METER_LEVELS.contains(level) ++ ? unmodifiableList( ++ Arrays.asList( ++ registry.meter(metricName.resolve("1xx-responses")), // 1xx ++ registry.meter(metricName.resolve("2xx-responses")), // 2xx ++ registry.meter(metricName.resolve("3xx-responses")), // 3xx ++ registry.meter(metricName.resolve("4xx-responses")), // 4xx ++ registry.meter(metricName.resolve("5xx-responses")) // 5xx ++ )) ++ : ImmutableList.of(); ++ this.responseCodeMeters = ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); ++ this.metricRegistry = registry; + } + +- private static class TimerRequestEventListener implements RequestEventListener { ++ public void mark(int statusCode) { ++ if (DETAILED_METER_LEVELS.contains(level)) { ++ getResponseCodeMeter(statusCode).mark(); ++ } + +- private final ConcurrentMap timers; +- private final Clock clock; +- private final long start; +- private Timer.Context resourceMethodStartContext; +- private Timer.Context requestMatchedContext; +- private Timer.Context responseFiltersStartContext; +- +- public TimerRequestEventListener(final ConcurrentMap timers, final Clock clock) { +- this.timers = timers; +- this.clock = clock; +- start = clock.getTick(); +- } +- +- @Override +- public void onEvent(RequestEvent event) { +- switch (event.getType()) { +- case RESOURCE_METHOD_START: +- resourceMethodStartContext = context(event); +- break; +- case REQUEST_MATCHED: +- requestMatchedContext = context(event); +- break; +- case RESP_FILTERS_START: +- responseFiltersStartContext = context(event); +- break; +- case RESOURCE_METHOD_FINISHED: +- if (resourceMethodStartContext != null) { +- resourceMethodStartContext.close(); +- } +- break; +- case REQUEST_FILTERED: +- if (requestMatchedContext != null) { +- requestMatchedContext.close(); +- } +- break; +- case RESP_FILTERS_FINISHED: +- if (responseFiltersStartContext != null) { +- responseFiltersStartContext.close(); +- } +- break; +- case FINISHED: +- if (requestMatchedContext != null && responseFiltersStartContext != null) { +- final Timer timer = timer(event); +- if (timer != null) { +- timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); +- } +- } +- break; +- default: +- break; +- } +- } +- +- private Timer timer(RequestEvent event) { +- final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); +- if (resourceMethod == null) { +- return null; +- } +- return timers.get(new EventTypeAndMethod(event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); +- } +- +- private Timer.Context context(RequestEvent event) { +- final Timer timer = timer(event); +- return timer != null ? timer.time() : null; ++ if (COARSE_METER_LEVELS.contains(level)) { ++ final int responseStatus = statusCode / 100; ++ if (responseStatus >= 1 && responseStatus <= 5) { ++ meters.get(responseStatus - 1).mark(); + } ++ } + } + +- private static class MeterRequestEventListener implements RequestEventListener { +- private final ConcurrentMap meters; +- +- public MeterRequestEventListener(final ConcurrentMap meters) { +- this.meters = meters; +- } +- +- @Override +- public void onEvent(RequestEvent event) { +- if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { +- final Meter meter = this.meters.get(event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); +- if (meter != null) { +- meter.mark(); +- } +- } +- } ++ private Meter getResponseCodeMeter(int statusCode) { ++ return responseCodeMeters.computeIfAbsent( ++ statusCode, ++ sc -> metricRegistry.meter(metricName.resolve(String.format("%d-responses", sc)))); + } ++ } + +- private static class ExceptionMeterRequestEventListener implements RequestEventListener { +- private final ConcurrentMap exceptionMeters; ++ private static class TimerRequestEventListener implements RequestEventListener { + +- public ExceptionMeterRequestEventListener(final ConcurrentMap exceptionMeters) { +- this.exceptionMeters = exceptionMeters; +- } ++ private final ConcurrentMap timers; ++ private final Clock clock; ++ private final long start; ++ private Timer.Context resourceMethodStartContext; ++ private Timer.Context requestMatchedContext; ++ private Timer.Context responseFiltersStartContext; ++ ++ public TimerRequestEventListener( ++ final ConcurrentMap timers, final Clock clock) { ++ this.timers = timers; ++ this.clock = clock; ++ start = clock.getTick(); ++ } + +- @Override +- public void onEvent(RequestEvent event) { +- if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { +- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); +- final ExceptionMeterMetric metric = (method != null) ? +- this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) : null; +- +- if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) || +- (event.getException().getCause() != null && +- metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { +- metric.meter.mark(); +- } +- } ++ @Override ++ public void onEvent(RequestEvent event) { ++ switch (event.getType()) { ++ case RESOURCE_METHOD_START: ++ resourceMethodStartContext = context(event); ++ break; ++ case REQUEST_MATCHED: ++ requestMatchedContext = context(event); ++ break; ++ case RESP_FILTERS_START: ++ responseFiltersStartContext = context(event); ++ break; ++ case RESOURCE_METHOD_FINISHED: ++ if (resourceMethodStartContext != null) { ++ resourceMethodStartContext.close(); ++ } ++ break; ++ case REQUEST_FILTERED: ++ if (requestMatchedContext != null) { ++ requestMatchedContext.close(); ++ } ++ break; ++ case RESP_FILTERS_FINISHED: ++ if (responseFiltersStartContext != null) { ++ responseFiltersStartContext.close(); ++ } ++ break; ++ case FINISHED: ++ if (requestMatchedContext != null && responseFiltersStartContext != null) { ++ final Timer timer = timer(event); ++ if (timer != null) { ++ timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); + } +- } ++ } ++ break; ++ default: ++ break; ++ } + } + +- private static class ResponseMeterRequestEventListener implements RequestEventListener { +- private final ConcurrentMap responseMeters; +- +- public ResponseMeterRequestEventListener(final ConcurrentMap responseMeters) { +- this.responseMeters = responseMeters; +- } +- +- @Override +- public void onEvent(RequestEvent event) { +- if (event.getType() == RequestEvent.Type.FINISHED) { +- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); +- final ResponseMeterMetric metric = (method != null) ? +- this.responseMeters.get(method.getInvocable().getDefinitionMethod()) : null; +- +- if (metric != null) { +- ContainerResponse containerResponse = event.getContainerResponse(); +- if (containerResponse == null && event.getException() != null) { +- metric.mark(500); +- } else if (containerResponse != null) { +- metric.mark(containerResponse.getStatus()); +- } +- } +- } +- } ++ private Timer timer(RequestEvent event) { ++ final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); ++ if (resourceMethod == null) { ++ return null; ++ } ++ return timers.get( ++ new EventTypeAndMethod( ++ event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); + } + +- private static class ChainedRequestEventListener implements RequestEventListener { +- private final RequestEventListener[] listeners; ++ private Timer.Context context(RequestEvent event) { ++ final Timer timer = timer(event); ++ return timer != null ? timer.time() : null; ++ } ++ } + +- private ChainedRequestEventListener(final RequestEventListener... listeners) { +- this.listeners = listeners; +- } ++ private static class MeterRequestEventListener implements RequestEventListener { ++ private final ConcurrentMap meters; + +- @Override +- public void onEvent(final RequestEvent event) { +- for (RequestEventListener listener : listeners) { +- listener.onEvent(event); +- } +- } ++ public MeterRequestEventListener(final ConcurrentMap meters) { ++ this.meters = meters; + } + + @Override +- public void onEvent(ApplicationEvent event) { +- if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { +- registerMetricsForModel(event.getResourceModel()); +- } ++ public void onEvent(RequestEvent event) { ++ if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { ++ final Meter meter = ++ this.meters.get( ++ event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); ++ if (meter != null) { ++ meter.mark(); ++ } ++ } + } ++ } + +- @Override +- public ResourceModel processResourceModel(ResourceModel resourceModel, Configuration configuration) { +- return resourceModel; ++ private static class ExceptionMeterRequestEventListener implements RequestEventListener { ++ private final ConcurrentMap exceptionMeters; ++ ++ public ExceptionMeterRequestEventListener( ++ final ConcurrentMap exceptionMeters) { ++ this.exceptionMeters = exceptionMeters; + } + + @Override +- public ResourceModel processSubResource(ResourceModel subResourceModel, Configuration configuration) { +- registerMetricsForModel(subResourceModel); +- return subResourceModel; ++ public void onEvent(RequestEvent event) { ++ if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { ++ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); ++ final ExceptionMeterMetric metric = ++ (method != null) ++ ? this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) ++ : null; ++ ++ if (metric != null) { ++ if (metric.cause.isInstance(event.getException()) ++ || (event.getException().getCause() != null ++ && metric.cause.isInstance(event.getException().getCause()))) { ++ metric.meter.mark(); ++ } ++ } ++ } + } ++ } + +- private void registerMetricsForModel(ResourceModel resourceModel) { +- for (final Resource resource : resourceModel.getResources()) { +- +- final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); +- final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); +- final ExceptionMetered classLevelExceptionMetered = getClassLevelAnnotation(resource, ExceptionMetered.class); +- final ResponseMetered classLevelResponseMetered = getClassLevelAnnotation(resource, ResponseMetered.class); +- +- for (final ResourceMethod method : resource.getAllMethods()) { +- registerTimedAnnotations(method, classLevelTimed); +- registerMeteredAnnotations(method, classLevelMetered); +- registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); +- registerResponseMeteredAnnotations(method, classLevelResponseMetered); +- } +- +- for (final Resource childResource : resource.getChildResources()) { ++ private static class ResponseMeterRequestEventListener implements RequestEventListener { ++ private final ConcurrentMap responseMeters; + +- final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); +- final Metered classLevelMeteredChild = getClassLevelAnnotation(childResource, Metered.class); +- final ExceptionMetered classLevelExceptionMeteredChild = getClassLevelAnnotation(childResource, ExceptionMetered.class); +- final ResponseMetered classLevelResponseMeteredChild = getClassLevelAnnotation(childResource, ResponseMetered.class); +- +- for (final ResourceMethod method : childResource.getAllMethods()) { +- registerTimedAnnotations(method, classLevelTimedChild); +- registerMeteredAnnotations(method, classLevelMeteredChild); +- registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); +- registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); +- } +- } +- } ++ public ResponseMeterRequestEventListener( ++ final ConcurrentMap responseMeters) { ++ this.responseMeters = responseMeters; + } + + @Override +- public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ public void onEvent(RequestEvent event) { ++ if (event.getType() == RequestEvent.Type.FINISHED) { ++ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); ++ final ResponseMeterMetric metric = ++ (method != null) ++ ? this.responseMeters.get(method.getInvocable().getDefinitionMethod()) ++ : null; ++ ++ if (metric != null) { ++ ContainerResponse containerResponse = event.getContainerResponse(); ++ if (containerResponse == null && event.getException() != null) { ++ metric.mark(500); ++ } else if (containerResponse != null) { ++ metric.mark(containerResponse.getStatus()); ++ } ++ } ++ } + } ++ } + +- private T getClassLevelAnnotation(final Resource resource, final Class annotationClazz) { +- T annotation = null; ++ private static class ChainedRequestEventListener implements RequestEventListener { ++ private final RequestEventListener[] listeners; + +- for (final Class clazz : resource.getHandlerClasses()) { +- annotation = clazz.getAnnotation(annotationClazz); +- +- if (annotation != null) { +- break; +- } +- } +- return annotation; ++ private ChainedRequestEventListener(final RequestEventListener... listeners) { ++ this.listeners = listeners; + } + +- private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); +- if (classLevelTimed != null) { +- registerTimers(method, definitionMethod, classLevelTimed); +- return; +- } +- +- final Timed annotation = definitionMethod.getAnnotation(Timed.class); +- if (annotation != null) { +- registerTimers(method, definitionMethod, annotation); +- } ++ @Override ++ public void onEvent(final RequestEvent event) { ++ for (RequestEventListener listener : listeners) { ++ listener.onEvent(event); ++ } + } ++ } + +- private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { +- timers.putIfAbsent(EventTypeAndMethod.requestMethodStart(definitionMethod), timerMetric(metrics, method, annotation)); +- if (trackFilters) { +- timers.putIfAbsent(EventTypeAndMethod.requestMatched(definitionMethod), timerMetric(metrics, method, annotation, REQUEST_FILTERING)); +- timers.putIfAbsent(EventTypeAndMethod.respFiltersStart(definitionMethod), timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); +- timers.putIfAbsent(EventTypeAndMethod.finished(definitionMethod), timerMetric(metrics, method, annotation, TOTAL)); +- } ++ @Override ++ public void onEvent(ApplicationEvent event) { ++ if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { ++ registerMetricsForModel(event.getResourceModel()); ++ } ++ } ++ ++ @Override ++ public ResourceModel processResourceModel( ++ ResourceModel resourceModel, Configuration configuration) { ++ return resourceModel; ++ } ++ ++ @Override ++ public ResourceModel processSubResource( ++ ResourceModel subResourceModel, Configuration configuration) { ++ registerMetricsForModel(subResourceModel); ++ return subResourceModel; ++ } ++ ++ private void registerMetricsForModel(ResourceModel resourceModel) { ++ for (final Resource resource : resourceModel.getResources()) { ++ ++ final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); ++ final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); ++ final ExceptionMetered classLevelExceptionMetered = ++ getClassLevelAnnotation(resource, ExceptionMetered.class); ++ final ResponseMetered classLevelResponseMetered = ++ getClassLevelAnnotation(resource, ResponseMetered.class); ++ ++ for (final ResourceMethod method : resource.getAllMethods()) { ++ registerTimedAnnotations(method, classLevelTimed); ++ registerMeteredAnnotations(method, classLevelMetered); ++ registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); ++ registerResponseMeteredAnnotations(method, classLevelResponseMetered); ++ } ++ ++ for (final Resource childResource : resource.getChildResources()) { ++ ++ final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); ++ final Metered classLevelMeteredChild = ++ getClassLevelAnnotation(childResource, Metered.class); ++ final ExceptionMetered classLevelExceptionMeteredChild = ++ getClassLevelAnnotation(childResource, ExceptionMetered.class); ++ final ResponseMetered classLevelResponseMeteredChild = ++ getClassLevelAnnotation(childResource, ResponseMetered.class); ++ ++ for (final ResourceMethod method : childResource.getAllMethods()) { ++ registerTimedAnnotations(method, classLevelTimedChild); ++ registerMeteredAnnotations(method, classLevelMeteredChild); ++ registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); ++ registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); ++ } ++ } ++ } ++ } ++ ++ @Override ++ public RequestEventListener onRequest(final RequestEvent event) { ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); ++ } ++ ++ private T getClassLevelAnnotation( ++ final Resource resource, final Class annotationClazz) { ++ T annotation = null; ++ ++ for (final Class clazz : resource.getHandlerClasses()) { ++ annotation = clazz.getAnnotation(annotationClazz); ++ ++ if (annotation != null) { ++ break; ++ } ++ } ++ return annotation; ++ } ++ ++ private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ if (classLevelTimed != null) { ++ registerTimers(method, definitionMethod, classLevelTimed); ++ return; + } + +- private void registerMeteredAnnotations(final ResourceMethod method, final Metered classLevelMetered) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ final Timed annotation = definitionMethod.getAnnotation(Timed.class); ++ if (annotation != null) { ++ registerTimers(method, definitionMethod, annotation); ++ } ++ } ++ ++ private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { ++ timers.putIfAbsent( ++ EventTypeAndMethod.requestMethodStart(definitionMethod), ++ timerMetric(metrics, method, annotation)); ++ if (trackFilters) { ++ timers.putIfAbsent( ++ EventTypeAndMethod.requestMatched(definitionMethod), ++ timerMetric(metrics, method, annotation, REQUEST_FILTERING)); ++ timers.putIfAbsent( ++ EventTypeAndMethod.respFiltersStart(definitionMethod), ++ timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); ++ timers.putIfAbsent( ++ EventTypeAndMethod.finished(definitionMethod), ++ timerMetric(metrics, method, annotation, TOTAL)); ++ } ++ } + +- if (classLevelMetered != null) { +- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); +- return; +- } +- final Metered annotation = definitionMethod.getAnnotation(Metered.class); ++ private void registerMeteredAnnotations( ++ final ResourceMethod method, final Metered classLevelMetered) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + +- if (annotation != null) { +- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); +- } ++ if (classLevelMetered != null) { ++ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); ++ return; + } ++ final Metered annotation = definitionMethod.getAnnotation(Metered.class); + +- private void registerExceptionMeteredAnnotations(final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ if (annotation != null) { ++ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); ++ } ++ } + +- if (classLevelExceptionMetered != null) { +- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); +- return; +- } +- final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); ++ private void registerExceptionMeteredAnnotations( ++ final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + +- if (annotation != null) { +- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); +- } ++ if (classLevelExceptionMetered != null) { ++ exceptionMeters.putIfAbsent( ++ definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); ++ return; + } ++ final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); + +- private void registerResponseMeteredAnnotations(final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ if (annotation != null) { ++ exceptionMeters.putIfAbsent( ++ definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); ++ } ++ } + +- if (classLevelResponseMetered != null) { +- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); +- return; +- } +- final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); ++ private void registerResponseMeteredAnnotations( ++ final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + +- if (annotation != null) { +- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); +- } ++ if (classLevelResponseMetered != null) { ++ responseMeters.putIfAbsent( ++ definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); ++ return; + } ++ final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); + +- private Timer timerMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final Timed timed, +- final String... suffixes) { +- final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); +- return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); ++ if (annotation != null) { ++ responseMeters.putIfAbsent( ++ definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); + } +- +- private Meter meterMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final Metered metered) { +- final MetricName name = chooseName(metered.name(), metered.absolute(), method); +- return registry.meter(name, () -> new Meter(clock)); ++ } ++ ++ private Timer timerMetric( ++ final MetricRegistry registry, ++ final ResourceMethod method, ++ final Timed timed, ++ final String... suffixes) { ++ final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); ++ return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); ++ } ++ ++ private Meter meterMetric( ++ final MetricRegistry registry, final ResourceMethod method, final Metered metered) { ++ final MetricName name = chooseName(metered.name(), metered.absolute(), method); ++ return registry.meter(name, () -> new Meter(clock)); ++ } ++ ++ protected static MetricName chooseName( ++ final String explicitName, ++ final boolean absolute, ++ final ResourceMethod method, ++ final String... suffixes) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ MetricName metricName; ++ if (!Strings.isNullOrEmpty(explicitName)) { ++ metricName = ++ absolute ++ ? MetricRegistry.name(explicitName) ++ : MetricRegistry.name(definitionMethod.getDeclaringClass(), explicitName); ++ } else { ++ metricName = ++ MetricRegistry.name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); + } +- +- protected static MetricName chooseName(final String explicitName, final boolean absolute, final ResourceMethod method, +- final String... suffixes) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); +- MetricName metricName; +- if (explicitName != null && !explicitName.isEmpty()) { +- metricName = absolute ? MetricRegistry.name(explicitName) : MetricRegistry.name(definitionMethod.getDeclaringClass(), explicitName); +- } else { +- metricName = MetricRegistry.name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); +- } +- for (String suffix : suffixes) { +- metricName = metricName.resolve(suffix); +- } +- return metricName; ++ for (String suffix : suffixes) { ++ metricName = metricName.resolve(suffix); + } ++ return metricName; ++ } + +- private static class EventTypeAndMethod { ++ private static class EventTypeAndMethod { + +- private final RequestEvent.Type type; +- private final Method method; +- +- private EventTypeAndMethod(RequestEvent.Type type, Method method) { +- this.type = type; +- this.method = method; +- } +- +- static EventTypeAndMethod requestMethodStart(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); +- } ++ private final RequestEvent.Type type; ++ private final Method method; + +- static EventTypeAndMethod requestMatched(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); +- } ++ private EventTypeAndMethod(RequestEvent.Type type, Method method) { ++ this.type = type; ++ this.method = method; ++ } + +- static EventTypeAndMethod respFiltersStart(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); +- } ++ static EventTypeAndMethod requestMethodStart(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); ++ } + +- static EventTypeAndMethod finished(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); +- } ++ static EventTypeAndMethod requestMatched(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); ++ } + +- @Override +- public boolean equals(Object o) { +- if (this == o) { +- return true; +- } +- if (o == null || getClass() != o.getClass()) { +- return false; +- } ++ static EventTypeAndMethod respFiltersStart(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); ++ } + +- EventTypeAndMethod that = (EventTypeAndMethod) o; ++ static EventTypeAndMethod finished(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); ++ } + +- if (type != that.type) { +- return false; +- } +- return method.equals(that.method); +- } ++ @Override ++ public boolean equals(Object o) { ++ if (this == o) { ++ return true; ++ } ++ if (o == null || getClass() != o.getClass()) { ++ return false; ++ } ++ ++ EventTypeAndMethod that = (EventTypeAndMethod) o; ++ ++ if (type != that.type) { ++ return false; ++ } ++ return method.equals(that.method); ++ } + +- @Override +- public int hashCode() { +- int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; +- } ++ @Override ++ public int hashCode() { ++ int result = type.hashCode(); ++ return 31 * result + method.hashCode(); + } ++ } + } +--- a/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/MetricsFeature.java ++++ b/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/MetricsFeature.java +@@ -5,93 +5,98 @@ import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Reservoir; + import io.dropwizard.metrics5.SharedMetricRegistries; +- ++import java.util.function.Supplier; + import javax.ws.rs.core.Feature; + import javax.ws.rs.core.FeatureContext; +-import java.util.function.Supplier; + + /** +- * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} +- * for recording request events. ++ * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} for ++ * recording request events. + */ + public class MetricsFeature implements Feature { + +- private final MetricRegistry registry; +- private final Clock clock; +- private final boolean trackFilters; +- private final Supplier reservoirSupplier; ++ private final MetricRegistry registry; ++ private final Clock clock; ++ private final boolean trackFilters; ++ private final Supplier reservoirSupplier; + +- /* +- * @param registry the metrics registry where the metrics will be stored +- */ +- public MetricsFeature(MetricRegistry registry) { +- this(registry, Clock.defaultClock()); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ */ ++ public MetricsFeature(MetricRegistry registry) { ++ this(registry, Clock.defaultClock()); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. +- */ +- public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { +- this(registry, Clock.defaultClock(), false, reservoirSupplier); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. ++ */ ++ public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { ++ this(registry, Clock.defaultClock(), false, reservoirSupplier); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- */ +- public MetricsFeature(MetricRegistry registry, Clock clock) { +- this(registry, clock, false); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ */ ++ public MetricsFeature(MetricRegistry registry, Clock clock) { ++ this(registry, clock, false); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- */ +- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { +- this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be tracked ++ */ ++ public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { ++ this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. +- */ +- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters, Supplier reservoirSupplier) { +- this.registry = registry; +- this.clock = clock; +- this.trackFilters = trackFilters; +- this.reservoirSupplier = reservoirSupplier; +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be tracked ++ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. ++ */ ++ public MetricsFeature( ++ MetricRegistry registry, ++ Clock clock, ++ boolean trackFilters, ++ Supplier reservoirSupplier) { ++ this.registry = registry; ++ this.clock = clock; ++ this.trackFilters = trackFilters; ++ this.reservoirSupplier = reservoirSupplier; ++ } + +- public MetricsFeature(String registryName) { +- this(SharedMetricRegistries.getOrCreate(registryName)); +- } ++ public MetricsFeature(String registryName) { ++ this(SharedMetricRegistries.getOrCreate(registryName)); ++ } + +- /** +- * A call-back method called when the feature is to be enabled in a given +- * runtime configuration scope. +- *

    +- * The responsibility of the feature is to properly update the supplied runtime configuration context +- * and return {@code true} if the feature was successfully enabled or {@code false} otherwise. +- *

    +- * Note that under some circumstances the feature may decide not to enable itself, which +- * is indicated by returning {@code false}. In such case the configuration context does +- * not add the feature to the collection of enabled features and a subsequent call to +- * {@link javax.ws.rs.core.Configuration#isEnabled(javax.ws.rs.core.Feature)} or +- * {@link javax.ws.rs.core.Configuration#isEnabled(Class)} method +- * would return {@code false}. +- *

    +- * +- * @param context configurable context in which the feature should be enabled. +- * @return {@code true} if the feature was successfully enabled, {@code false} +- * otherwise. +- */ +- @Override +- public boolean configure(FeatureContext context) { +- context.register(new InstrumentedResourceMethodApplicationListener(registry, clock, trackFilters, reservoirSupplier)); +- return true; +- } ++ /** ++ * A call-back method called when the feature is to be enabled in a given runtime configuration ++ * scope. ++ * ++ *

    The responsibility of the feature is to properly update the supplied runtime configuration ++ * context and return {@code true} if the feature was successfully enabled or {@code false} ++ * otherwise. ++ * ++ *

    Note that under some circumstances the feature may decide not to enable itself, which is ++ * indicated by returning {@code false}. In such case the configuration context does not add the ++ * feature to the collection of enabled features and a subsequent call to {@link ++ * javax.ws.rs.core.Configuration#isEnabled(javax.ws.rs.core.Feature)} or {@link ++ * javax.ws.rs.core.Configuration#isEnabled(Class)} method would return {@code false}. ++ * ++ *

    ++ * ++ * @param context configurable context in which the feature should be enabled. ++ * @return {@code true} if the feature was successfully enabled, {@code false} otherwise. ++ */ ++ @Override ++ public boolean configure(FeatureContext context) { ++ context.register( ++ new InstrumentedResourceMethodApplicationListener( ++ registry, clock, trackFilters, reservoirSupplier)); ++ return true; ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java +@@ -1,45 +1,44 @@ + package io.dropwizard.metrics5.jersey2; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.UniformReservoir; +-import io.dropwizard.metrics5.jersey2.MetricsFeature; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceTimedPerClass; ++import java.util.logging.Level; ++import java.util.logging.Logger; ++import javax.ws.rs.core.Application; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import javax.ws.rs.core.Application; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +- +-class CustomReservoirImplementationTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } ++final class CustomReservoirImplementationTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- private MetricRegistry registry; ++ private MetricRegistry registry; + +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- return new ResourceConfig() ++ return new ResourceConfig() + .register(new MetricsFeature(this.registry, UniformReservoir::new)) + .register(InstrumentedResourceTimedPerClass.class); +- } ++ } + +- @Test +- void timerHistogramIsUsingCustomReservoirImplementation() { +- assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); ++ @Test ++ void timerHistogramIsUsingCustomReservoirImplementation() { ++ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); + +- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); +- assertThat(timer) ++ final Timer timer = ++ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); ++ assertThat(timer) + .extracting("histogram") + .extracting("reservoir") + .isInstanceOf(UniformReservoir.class); +- } ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java +@@ -1,161 +1,146 @@ + package io.dropwizard.metrics5.jersey2; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedFilteredResource; + import io.dropwizard.metrics5.jersey2.resources.TestRequestFilter; ++import java.util.logging.Level; ++import java.util.logging.Logger; ++import javax.ws.rs.core.Application; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import javax.ws.rs.core.Application; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static org.assertj.core.api.Assertions.assertThat; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} with filter tracking ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} with filter tracking + */ +-class SingletonFilterMetricsJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- private TestClock testClock; +- +- @Override +- protected Application configure() { +- registry = new MetricRegistry(); +- testClock = new TestClock(); +- ResourceConfig config = new ResourceConfig(); +- config = config.register(new MetricsFeature(this.registry, testClock, true)); +- config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; +- } +- +- @BeforeEach +- void resetClock() { +- testClock.tick = 0; +- } +- +- @Test +- void timedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); +- } +- +- @Test +- void explicitNamesAreTimed() { +- assertThat(target("named") +- .request() +- .get(String.class)) +- .isEqualTo("fancy"); +- +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "fancyName")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); +- } +- +- @Test +- void absoluteNamesAreTimed() { +- assertThat(target("absolute") +- .request() +- .get(String.class)) +- .isEqualTo("absolute"); +- +- final Timer timer = registry.timer("absolutelyFancy"); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); +- } +- +- @Test +- void requestFiltersOfTimedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); +- } +- +- @Test +- void responseFiltersOfTimedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- } +- +- @Test +- void totalTimeOfTimedMethodsIsTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "total")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); +- } +- +- @Test +- void requestFiltersOfNamedMethodsAreTimed() { +- assertThat(target("named") +- .request() +- .get(String.class)) +- .isEqualTo("fancy"); +- +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); +- } +- +- @Test +- void requestFiltersOfAbsoluteMethodsAreTimed() { +- assertThat(target("absolute") +- .request() +- .get(String.class)) +- .isEqualTo("absolute"); +- +- final Timer timer = registry.timer(MetricRegistry.name("absolutelyFancy", "request", "filtering")); +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); +- } +- +- @Test +- void subResourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, +- "timed")); +- assertThat(timer.getCount()).isEqualTo(1); +- +- } ++final class SingletonFilterMetricsJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } ++ ++ private MetricRegistry registry; ++ ++ private TestClock testClock; ++ ++ @Override ++ protected Application configure() { ++ registry = new MetricRegistry(); ++ testClock = new TestClock(); ++ ResourceConfig config = new ResourceConfig(); ++ config = config.register(new MetricsFeature(this.registry, testClock, true)); ++ config = config.register(new TestRequestFilter(testClock)); ++ return config.register(new InstrumentedFilteredResource(testClock)); ++ } ++ ++ @BeforeEach ++ void resetClock() { ++ testClock.tick = 0; ++ } ++ ++ @Test ++ void timedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); ++ } ++ ++ @Test ++ void explicitNamesAreTimed() { ++ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); ++ ++ final Timer timer = ++ registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "fancyName")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); ++ } ++ ++ @Test ++ void absoluteNamesAreTimed() { ++ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); ++ ++ final Timer timer = registry.timer("absolutelyFancy"); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); ++ } ++ ++ @Test ++ void requestFiltersOfTimedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer( ++ MetricRegistry.name( ++ InstrumentedFilteredResource.class, "timed", "request", "filtering")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); ++ } ++ ++ @Test ++ void responseFiltersOfTimedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer( ++ MetricRegistry.name( ++ InstrumentedFilteredResource.class, "timed", "response", "filtering")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void totalTimeOfTimedMethodsIsTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "total")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); ++ } ++ ++ @Test ++ void requestFiltersOfNamedMethodsAreTimed() { ++ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); ++ ++ final Timer timer = ++ registry.timer( ++ MetricRegistry.name( ++ InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); ++ } ++ ++ @Test ++ void requestFiltersOfAbsoluteMethodsAreTimed() { ++ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); ++ ++ final Timer timer = ++ registry.timer(MetricRegistry.name("absolutelyFancy", "request", "filtering")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); ++ } ++ ++ @Test ++ void subResourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer( ++ MetricRegistry.name( ++ InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, "timed")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -1,97 +1,91 @@ + package io.dropwizard.metrics5.jersey2; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceExceptionMeteredPerClass; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceExceptionMeteredPerClass; +-import org.glassfish.jersey.server.ResourceConfig; +-import org.glassfish.jersey.test.JerseyTest; +-import org.junit.jupiter.api.Test; +- +-import javax.ws.rs.ProcessingException; +-import javax.ws.rs.core.Application; + import java.io.IOException; + import java.util.logging.Level; + import java.util.logging.Logger; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++import javax.ws.rs.ProcessingException; ++import javax.ws.rs.core.Application; ++import org.glassfish.jersey.server.ResourceConfig; ++import org.glassfish.jersey.test.JerseyTest; ++import org.junit.jupiter.api.Test; + + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } ++final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- private MetricRegistry registry; ++ private MetricRegistry registry; + +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- ResourceConfig config = new ResourceConfig(); ++ ResourceConfig config = new ResourceConfig(); + +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); ++ } + +- return config; +- } +- +- @Test +- void exceptionMeteredMethodsAreExceptionMetered() { +- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResourceExceptionMeteredPerClass.class, +- "exceptionMetered", +- "exceptions")); +- +- assertThat(target("exception-metered") +- .request() +- .get(String.class)) +- .isEqualTo("fuh"); ++ @Test ++ void exceptionMeteredMethodsAreExceptionMetered() { ++ final Meter meter = ++ registry.meter( ++ MetricRegistry.name( ++ InstrumentedResourceExceptionMeteredPerClass.class, ++ "exceptionMetered", ++ "exceptions")); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- try { +- target("exception-metered") +- .queryParam("splode", true) +- .request() +- .get(String.class); ++ assertThat(meter.getCount()).isEqualTo(0); + +- failBecauseExceptionWasNotThrown(ProcessingException.class); +- } catch (ProcessingException e) { +- assertThat(e.getCause()).isInstanceOf(IOException.class); +- } ++ try { ++ target("exception-metered").queryParam("splode", true).request().get(String.class); + +- assertThat(meter.getCount()).isEqualTo(1); ++ failBecauseExceptionWasNotThrown(ProcessingException.class); ++ } catch (ProcessingException e) { ++ assertThat(e.getCause()).isInstanceOf(IOException.class); + } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedSubResourceExceptionMeteredPerClass.class, +- "exceptionMetered", +- "exceptions")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + +- assertThat(target("subresource/exception-metered") +- .request() +- .get(String.class)) +- .isEqualTo("fuh"); ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ final Meter meter = ++ registry.meter( ++ MetricRegistry.name( ++ InstrumentedSubResourceExceptionMeteredPerClass.class, ++ "exceptionMetered", ++ "exceptions")); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(target("subresource/exception-metered").request().get(String.class)) ++ .isEqualTo("fuh"); + +- try { +- target("subresource/exception-metered") +- .queryParam("splode", true) +- .request() +- .get(String.class); ++ assertThat(meter.getCount()).isEqualTo(0); + +- failBecauseExceptionWasNotThrown(ProcessingException.class); +- } catch (ProcessingException e) { +- assertThat(e.getCause()).isInstanceOf(IOException.class); +- } ++ try { ++ target("subresource/exception-metered") ++ .queryParam("splode", true) ++ .request() ++ .get(String.class); + +- assertThat(meter.getCount()).isEqualTo(1); ++ failBecauseExceptionWasNotThrown(ProcessingException.class); ++ } catch (ProcessingException e) { ++ assertThat(e.getCause()).isInstanceOf(IOException.class); + } + ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java +@@ -1,155 +1,127 @@ + package io.dropwizard.metrics5.jersey2; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedResource; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResource; +-import org.glassfish.jersey.client.ClientResponse; +-import org.glassfish.jersey.server.ResourceConfig; +-import org.glassfish.jersey.test.JerseyTest; +-import org.junit.jupiter.api.Test; +- ++import java.io.IOException; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import javax.ws.rs.NotFoundException; + import javax.ws.rs.ProcessingException; + import javax.ws.rs.core.Application; + import javax.ws.rs.core.Response; +-import java.io.IOException; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++import org.glassfish.jersey.client.ClientResponse; ++import org.glassfish.jersey.server.ResourceConfig; ++import org.glassfish.jersey.test.JerseyTest; ++import org.junit.jupiter.api.Test; + + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link org.glassfish.jersey.server.ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link org.glassfish.jersey.server.ResourceConfig} + */ +-class SingletonMetricsJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } ++final class SingletonMetricsJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- private MetricRegistry registry; ++ private MetricRegistry registry; + +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- ResourceConfig config = new ResourceConfig(); +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); ++ ResourceConfig config = new ResourceConfig(); ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResource.class); ++ } + +- return config; +- } ++ @Test ++ void timedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); + +- @Test +- void timedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ final Timer timer = registry.timer(MetricRegistry.name(InstrumentedResource.class, "timed")); + +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedResource.class, "timed")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + +- assertThat(timer.getCount()).isEqualTo(1); +- } ++ @Test ++ void meteredMethodsAreMetered() { ++ assertThat(target("metered").request().get(String.class)).isEqualTo("woo"); + +- @Test +- void meteredMethodsAreMetered() { +- assertThat(target("metered") +- .request() +- .get(String.class)) +- .isEqualTo("woo"); ++ final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResource.class, "metered")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + +- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResource.class, "metered")); +- assertThat(meter.getCount()).isEqualTo(1); +- } +- +- @Test +- void exceptionMeteredMethodsAreExceptionMetered() { +- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResource.class, +- "exceptionMetered", +- "exceptions")); ++ @Test ++ void exceptionMeteredMethodsAreExceptionMetered() { ++ final Meter meter = ++ registry.meter( ++ MetricRegistry.name(InstrumentedResource.class, "exceptionMetered", "exceptions")); + +- assertThat(target("exception-metered") +- .request() +- .get(String.class)) +- .isEqualTo("fuh"); ++ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + +- try { +- target("exception-metered") +- .queryParam("splode", true) +- .request() +- .get(String.class); ++ try { ++ target("exception-metered").queryParam("splode", true).request().get(String.class); + +- failBecauseExceptionWasNotThrown(ProcessingException.class); +- } catch (ProcessingException e) { +- assertThat(e.getCause()).isInstanceOf(IOException.class); +- } +- +- assertThat(meter.getCount()).isEqualTo(1); ++ failBecauseExceptionWasNotThrown(ProcessingException.class); ++ } catch (ProcessingException e) { ++ assertThat(e.getCause()).isInstanceOf(IOException.class); + } + +- @Test +- void responseMeteredMethodsAreMetered() { +- final Meter meter2xx = registry.meter(MetricRegistry.name(InstrumentedResource.class, +- "response2xxMetered", +- "2xx-responses")); +- final Meter meter4xx = registry.meter(MetricRegistry.name(InstrumentedResource.class, +- "response4xxMetered", +- "4xx-responses")); +- final Meter meter5xx = registry.meter(MetricRegistry.name(InstrumentedResource.class, +- "response5xxMetered", +- "5xx-responses")); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(target("response-2xx-metered") +- .request() +- .get().getStatus()) +- .isEqualTo(200); +- +- assertThat(meter4xx.getCount()).isZero(); +- assertThat(target("response-4xx-metered") +- .request() +- .get().getStatus()) +- .isEqualTo(400); +- +- assertThat(meter5xx.getCount()).isZero(); +- assertThat(target("response-5xx-metered") +- .request() +- .get().getStatus()) +- .isEqualTo(500); +- +- assertThat(meter2xx.getCount()).isEqualTo(1); +- assertThat(meter4xx.getCount()).isEqualTo(1); +- assertThat(meter5xx.getCount()).isEqualTo(1); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredMethodsAreMetered() { ++ final Meter meter2xx = ++ registry.meter( ++ MetricRegistry.name(InstrumentedResource.class, "response2xxMetered", "2xx-responses")); ++ final Meter meter4xx = ++ registry.meter( ++ MetricRegistry.name(InstrumentedResource.class, "response4xxMetered", "4xx-responses")); ++ final Meter meter5xx = ++ registry.meter( ++ MetricRegistry.name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); ++ ++ assertThat(meter4xx.getCount()).isEqualTo(0); ++ assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); ++ ++ assertThat(meter5xx.getCount()).isEqualTo(0); ++ assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter4xx.getCount()).isEqualTo(1); ++ assertThat(meter5xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void resourceNotFound() { ++ final Response response = target().path("not-found").request().get(); ++ assertThat(response.getStatus()).isEqualTo(404); ++ ++ try { ++ target().path("not-found").request().get(ClientResponse.class); ++ failBecauseExceptionWasNotThrown(NotFoundException.class); ++ } catch (NotFoundException e) { ++ assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); + } ++ } + +- @Test +- void testResourceNotFound() { +- final Response response = target().path("not-found").request().get(); +- assertThat(response.getStatus()).isEqualTo(404); +- +- try { +- target().path("not-found").request().get(ClientResponse.class); +- failBecauseExceptionWasNotThrown(NotFoundException.class); +- } catch (NotFoundException e) { +- assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); +- } +- } ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedSubResource.class, "timed")); +- assertThat(timer.getCount()).isEqualTo(1); +- +- } ++ final Timer timer = registry.timer(MetricRegistry.name(InstrumentedSubResource.class, "timed")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -1,65 +1,57 @@ + package io.dropwizard.metrics5.jersey2; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceMeteredPerClass; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceMeteredPerClass; ++import java.util.logging.Level; ++import java.util.logging.Logger; ++import javax.ws.rs.core.Application; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import javax.ws.rs.core.Application; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static org.assertj.core.api.Assertions.assertThat; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); +- +- ResourceConfig config = new ResourceConfig(); +- +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); ++final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- return config; +- } ++ private MetricRegistry registry; + +- @Test +- void meteredPerClassMethodsAreMetered() { +- assertThat(target("meteredPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); ++ ResourceConfig config = new ResourceConfig(); + +- assertThat(meter.getCount()).isEqualTo(1); +- } ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResourceMeteredPerClass.class); ++ } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/meteredPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Test ++ void meteredPerClassMethodsAreMetered() { ++ assertThat(target("meteredPerClass").request().get(String.class)).isEqualTo("yay"); + +- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); +- assertThat(meter.getCount()).isEqualTo(1); ++ final Meter meter = ++ registry.meter( ++ MetricRegistry.name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); + +- } ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/meteredPerClass").request().get(String.class)).isEqualTo("yay"); + ++ final Meter meter = ++ registry.meter( ++ MetricRegistry.name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -1,138 +1,138 @@ + package io.dropwizard.metrics5.jersey2; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jersey2.exception.mapper.TestExceptionMapper; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceResponseMeteredPerClass; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceResponseMeteredPerClass; ++import java.util.logging.Level; ++import java.util.logging.Logger; ++import javax.ws.rs.core.Application; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import javax.ws.rs.core.Application; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); +- +- +- ResourceConfig config = new ResourceConfig(); +- +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; +- } +- +- @Test +- void responseMetered2xxPerClassMethodsAreMetered() { +- assertThat(target("responseMetered2xxPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(200); +- +- final Meter meter2xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMetered2xxPerClass", +- "2xx-responses")); +- +- assertThat(meter2xx.getCount()).isEqualTo(1); +- } +- +- @Test +- void responseMetered4xxPerClassMethodsAreMetered() { +- assertThat(target("responseMetered4xxPerClass") +- .request() +- .get().getStatus()) ++final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } ++ ++ private MetricRegistry registry; ++ ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); ++ ++ ResourceConfig config = new ResourceConfig(); ++ ++ config = config.register(new MetricsFeature(this.registry)); ++ config = config.register(InstrumentedResourceResponseMeteredPerClass.class); ++ return config.register(new TestExceptionMapper()); ++ } ++ ++ @Test ++ void responseMetered2xxPerClassMethodsAreMetered() { ++ assertThat(target("responseMetered2xxPerClass").request().get().getStatus()).isEqualTo(200); ++ ++ final Meter meter2xx = ++ registry.meter( ++ MetricRegistry.name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMetered2xxPerClass", ++ "2xx-responses")); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMetered4xxPerClassMethodsAreMetered() { ++ assertThat(target("responseMetered4xxPerClass").request().get().getStatus()).isEqualTo(400); ++ assertThat(target("responseMeteredBadRequestPerClass").request().get().getStatus()) + .isEqualTo(400); +- assertThat(target("responseMeteredBadRequestPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(400); +- +- final Meter meter4xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMetered4xxPerClass", +- "4xx-responses")); +- final Meter meterException4xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMeteredBadRequestPerClass", +- "4xx-responses")); + +- assertThat(meter4xx.getCount()).isEqualTo(1); +- assertThat(meterException4xx.getCount()).isEqualTo(1); +- } +- +- @Test +- void responseMetered5xxPerClassMethodsAreMetered() { +- assertThat(target("responseMetered5xxPerClass") +- .request() +- .get().getStatus()) ++ final Meter meter4xx = ++ registry.meter( ++ MetricRegistry.name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMetered4xxPerClass", ++ "4xx-responses")); ++ final Meter meterException4xx = ++ registry.meter( ++ MetricRegistry.name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMeteredBadRequestPerClass", ++ "4xx-responses")); ++ ++ assertThat(meter4xx.getCount()).isEqualTo(1); ++ assertThat(meterException4xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMetered5xxPerClassMethodsAreMetered() { ++ assertThat(target("responseMetered5xxPerClass").request().get().getStatus()).isEqualTo(500); ++ ++ final Meter meter5xx = ++ registry.meter( ++ MetricRegistry.name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMetered5xxPerClass", ++ "5xx-responses")); ++ ++ assertThat(meter5xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredMappedExceptionPerClassMethodsAreMetered() { ++ assertThat(target("responseMeteredTestExceptionPerClass").request().get().getStatus()) + .isEqualTo(500); + +- final Meter meter5xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMetered5xxPerClass", +- "5xx-responses")); +- +- assertThat(meter5xx.getCount()).isEqualTo(1); ++ final Meter meterTestException = ++ registry.meter( ++ MetricRegistry.name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMeteredTestExceptionPerClass", ++ "5xx-responses")); ++ ++ assertThat(meterTestException.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { ++ try { ++ target("responseMeteredRuntimeExceptionPerClass").request().get(); ++ fail("expected RuntimeException"); ++ } catch (Exception e) { ++ assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + } + +- @Test +- void responseMeteredMappedExceptionPerClassMethodsAreMetered() { +- assertThat(target("responseMeteredTestExceptionPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(500); ++ final Meter meterException5xx = ++ registry.meter( ++ MetricRegistry.name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMeteredRuntimeExceptionPerClass", ++ "5xx-responses")); + +- final Meter meterTestException = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMeteredTestExceptionPerClass", +- "5xx-responses")); ++ assertThat(meterException5xx.getCount()).isEqualTo(1); ++ } + +- assertThat(meterTestException.getCount()).isEqualTo(1); +- } +- +- @Test +- void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { +- try { +- target("responseMeteredRuntimeExceptionPerClass") +- .request() +- .get(); +- fail("expected RuntimeException"); +- } catch (Exception e) { +- assertThat(e.getCause()).isInstanceOf(RuntimeException.class); +- } +- +- final Meter meterException5xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMeteredRuntimeExceptionPerClass", +- "5xx-responses")); +- +- assertThat(meterException5xx.getCount()).isEqualTo(1); +- } +- +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/responseMeteredPerClass") +- .request() +- .get().getStatus()) ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); + +- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedSubResourceResponseMeteredPerClass.class, +- "responseMeteredPerClass", +- "2xx-responses")); +- assertThat(meter.getCount()).isEqualTo(1); +- } ++ final Meter meter = ++ registry.meter( ++ MetricRegistry.name( ++ InstrumentedSubResourceResponseMeteredPerClass.class, ++ "responseMeteredPerClass", ++ "2xx-responses")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java +@@ -1,65 +1,57 @@ + package io.dropwizard.metrics5.jersey2; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceTimedPerClass; + import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceTimedPerClass; ++import java.util.logging.Level; ++import java.util.logging.Logger; ++import javax.ws.rs.core.Application; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import javax.ws.rs.core.Application; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static org.assertj.core.api.Assertions.assertThat; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); +- +- ResourceConfig config = new ResourceConfig(); +- +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); ++final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- return config; +- } ++ private MetricRegistry registry; + +- @Test +- void timedPerClassMethodsAreTimed() { +- assertThat(target("timedPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); ++ ResourceConfig config = new ResourceConfig(); + +- assertThat(timer.getCount()).isEqualTo(1); +- } ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResourceTimedPerClass.class); ++ } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/timedPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Test ++ void timedPerClassMethodsAreTimed() { ++ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); + +- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); +- assertThat(timer.getCount()).isEqualTo(1); ++ final Timer timer = ++ registry.timer( ++ MetricRegistry.name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); + +- } ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/timedPerClass").request().get(String.class)).isEqualTo("yay"); + ++ final Timer timer = ++ registry.timer( ++ MetricRegistry.name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/TestClock.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/TestClock.java +@@ -4,10 +4,10 @@ import io.dropwizard.metrics5.Clock; + + public class TestClock extends Clock { + +- public long tick; ++ public long tick; + +- @Override +- public long getTick() { +- return tick; +- } ++ @Override ++ public long getTick() { ++ return tick; ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/exception/TestException.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/exception/TestException.java +@@ -1,9 +1,9 @@ + package io.dropwizard.metrics5.jersey2.exception; + + public class TestException extends RuntimeException { +- private static final long serialVersionUID = 1L; ++ private static final long serialVersionUID = 1L; + +- public TestException(String message) { +- super(message); +- } ++ public TestException(String message) { ++ super(message); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/exception/mapper/TestExceptionMapper.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/exception/mapper/TestExceptionMapper.java +@@ -1,15 +1,14 @@ + package io.dropwizard.metrics5.jersey2.exception.mapper; + + import io.dropwizard.metrics5.jersey2.exception.TestException; +- + import javax.ws.rs.core.Response; + import javax.ws.rs.ext.ExceptionMapper; + import javax.ws.rs.ext.Provider; + + @Provider + public class TestExceptionMapper implements ExceptionMapper { +- @Override +- public Response toResponse(TestException exception) { +- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +- } ++ @Override ++ public Response toResponse(TestException exception) { ++ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java +@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.annotation.Timed; + import io.dropwizard.metrics5.jersey2.TestClock; +- + import javax.ws.rs.GET; + import javax.ws.rs.Path; + import javax.ws.rs.Produces; +@@ -12,51 +11,50 @@ import javax.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedFilteredResource { + +- private final TestClock testClock; +- +- public InstrumentedFilteredResource(TestClock testClock) { +- this.testClock = testClock; +- } ++ private final TestClock testClock; ++ ++ public InstrumentedFilteredResource(TestClock testClock) { ++ this.testClock = testClock; ++ } ++ ++ @GET ++ @Path("/timed") ++ @Timed ++ public String timed() { ++ testClock.tick++; ++ return "yay"; ++ } ++ ++ @GET ++ @Path("/named") ++ @Timed(name = "fancyName") ++ public String named() { ++ testClock.tick++; ++ return "fancy"; ++ } ++ ++ @GET ++ @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) ++ public String absolute() { ++ testClock.tick++; ++ return "absolute"; ++ } ++ ++ @Path("/subresource") ++ public InstrumentedFilteredSubResource locateSubResource() { ++ return new InstrumentedFilteredSubResource(); ++ } ++ ++ @Produces(MediaType.TEXT_PLAIN) ++ public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { +- testClock.tick++; +- return "yay"; +- } +- +- @GET +- @Timed(name = "fancyName") +- @Path("/named") +- public String named() { +- testClock.tick++; +- return "fancy"; +- } +- +- @GET +- @Timed(name = "absolutelyFancy", absolute = true) +- @Path("/absolute") +- public String absolute() { +- testClock.tick++; +- return "absolute"; +- } +- +- @Path("/subresource") +- public InstrumentedFilteredSubResource locateSubResource() { +- return new InstrumentedFilteredSubResource(); +- } +- +- @Produces(MediaType.TEXT_PLAIN) +- public class InstrumentedFilteredSubResource { +- +- @GET +- @Timed +- @Path("/timed") +- public String timed() { +- testClock.tick += 2; +- return "yay"; +- } +- ++ testClock.tick += 2; ++ return "yay"; + } ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java +@@ -1,10 +1,14 @@ + package io.dropwizard.metrics5.jersey2.resources; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++ + import io.dropwizard.metrics5.annotation.ExceptionMetered; + import io.dropwizard.metrics5.annotation.Metered; + import io.dropwizard.metrics5.annotation.ResponseMetered; + import io.dropwizard.metrics5.annotation.Timed; +- ++import java.io.IOException; + import javax.ws.rs.DefaultValue; + import javax.ws.rs.GET; + import javax.ws.rs.Path; +@@ -12,83 +16,82 @@ import javax.ws.rs.Produces; + import javax.ws.rs.QueryParam; + import javax.ws.rs.core.MediaType; + import javax.ws.rs.core.Response; +-import java.io.IOException; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; + + @Path("/") + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { +- @GET +- @Timed +- @Path("/timed") +- public String timed() { +- return "yay"; +- } ++ @GET ++ @Path("/timed") ++ @Timed ++ public String timed() { ++ return "yay"; ++ } + +- @GET +- @Metered +- @Path("/metered") +- public String metered() { +- return "woo"; +- } ++ @GET ++ @Metered ++ @Path("/metered") ++ public String metered() { ++ return "woo"; ++ } + +- @GET +- @ExceptionMetered(cause = IOException.class) +- @Path("/exception-metered") +- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { +- if (splode) { +- throw new IOException("AUGH"); +- } +- return "fuh"; ++ @ExceptionMetered(cause = IOException.class) ++ @GET ++ @Path("/exception-metered") ++ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) ++ throws IOException { ++ if (splode) { ++ throw new IOException("AUGH"); + } ++ return "fuh"; ++ } + +- @GET +- @ResponseMetered(level = DETAILED) +- @Path("/response-metered-detailed") +- public Response responseMeteredDetailed(@QueryParam("status_code") @DefaultValue("200") int statusCode) { +- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +- } ++ @GET ++ @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) ++ public Response responseMeteredDetailed( ++ @QueryParam("status_code") @DefaultValue("200") int statusCode) { ++ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ++ } + +- @GET +- @ResponseMetered(level = COARSE) +- @Path("/response-metered-coarse") +- public Response responseMeteredCoarse(@QueryParam("status_code") @DefaultValue("200") int statusCode) { +- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +- } ++ @GET ++ @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) ++ public Response responseMeteredCoarse( ++ @QueryParam("status_code") @DefaultValue("200") int statusCode) { ++ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ++ } + +- @GET +- @ResponseMetered(level = ALL) +- @Path("/response-metered-all") +- public Response responseMeteredAll(@QueryParam("status_code") @DefaultValue("200") int statusCode) { +- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +- } ++ @GET ++ @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) ++ public Response responseMeteredAll( ++ @QueryParam("status_code") @DefaultValue("200") int statusCode) { ++ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ++ } + +- @GET +- @ResponseMetered +- @Path("/response-2xx-metered") +- public Response response2xxMetered() { +- return Response.ok().build(); +- } ++ @GET ++ @Path("/response-2xx-metered") ++ @ResponseMetered ++ public Response response2xxMetered() { ++ return Response.ok().build(); ++ } + +- @GET +- @ResponseMetered +- @Path("/response-4xx-metered") +- public Response response4xxMetered() { +- return Response.status(Response.Status.BAD_REQUEST).build(); +- } ++ @GET ++ @Path("/response-4xx-metered") ++ @ResponseMetered ++ public Response response4xxMetered() { ++ return Response.status(Response.Status.BAD_REQUEST).build(); ++ } + +- @GET +- @ResponseMetered +- @Path("/response-5xx-metered") +- public Response response5xxMetered() { +- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +- } ++ @GET ++ @Path("/response-5xx-metered") ++ @ResponseMetered ++ public Response response5xxMetered() { ++ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); ++ } + +- @Path("/subresource") +- public InstrumentedSubResource locateSubResource() { +- return new InstrumentedSubResource(); +- } ++ @Path("/subresource") ++ public InstrumentedSubResource locateSubResource() { ++ return new InstrumentedSubResource(); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceExceptionMeteredPerClass.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceExceptionMeteredPerClass.java +@@ -1,32 +1,31 @@ + package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.annotation.ExceptionMetered; +- ++import java.io.IOException; + import javax.ws.rs.DefaultValue; + import javax.ws.rs.GET; + import javax.ws.rs.Path; + import javax.ws.rs.Produces; + import javax.ws.rs.QueryParam; + import javax.ws.rs.core.MediaType; +-import java.io.IOException; + + @ExceptionMetered(cause = IOException.class) + @Path("/") + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceExceptionMeteredPerClass { + +- @GET +- @Path("/exception-metered") +- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { +- if (splode) { +- throw new IOException("AUGH"); +- } +- return "fuh"; +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { +- return new InstrumentedSubResourceExceptionMeteredPerClass(); ++ @GET ++ @Path("/exception-metered") ++ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) ++ throws IOException { ++ if (splode) { ++ throw new IOException("AUGH"); + } ++ return "fuh"; ++ } + ++ @Path("/subresource") ++ public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { ++ return new InstrumentedSubResourceExceptionMeteredPerClass(); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceMeteredPerClass.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceMeteredPerClass.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.annotation.Metered; +- + import javax.ws.rs.GET; + import javax.ws.rs.Path; + import javax.ws.rs.Produces; +@@ -12,15 +11,14 @@ import javax.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceMeteredPerClass { + +- @GET +- @Path("/meteredPerClass") +- public String meteredPerClass() { +- return "yay"; +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceMeteredPerClass locateSubResource() { +- return new InstrumentedSubResourceMeteredPerClass(); +- } ++ @GET ++ @Path("/meteredPerClass") ++ public String meteredPerClass() { ++ return "yay"; ++ } + ++ @Path("/subresource") ++ public InstrumentedSubResourceMeteredPerClass locateSubResource() { ++ return new InstrumentedSubResourceMeteredPerClass(); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceResponseMeteredPerClass.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceResponseMeteredPerClass.java +@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.annotation.ResponseMetered; + import io.dropwizard.metrics5.jersey2.exception.TestException; +- + import javax.ws.rs.BadRequestException; + import javax.ws.rs.GET; + import javax.ws.rs.Path; +@@ -15,45 +14,44 @@ import javax.ws.rs.core.Response; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceResponseMeteredPerClass { + +- @GET +- @Path("/responseMetered2xxPerClass") +- public Response responseMetered2xxPerClass() { +- return Response.ok().build(); +- } +- +- @GET +- @Path("/responseMetered4xxPerClass") +- public Response responseMetered4xxPerClass() { +- return Response.status(Response.Status.BAD_REQUEST).build(); +- } +- +- @GET +- @Path("/responseMetered5xxPerClass") +- public Response responseMetered5xxPerClass() { +- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +- } +- +- @GET +- @Path("/responseMeteredBadRequestPerClass") +- public String responseMeteredBadRequestPerClass() { +- throw new BadRequestException(); +- } +- +- @GET +- @Path("/responseMeteredRuntimeExceptionPerClass") +- public String responseMeteredRuntimeExceptionPerClass() { +- throw new RuntimeException(); +- } +- +- @GET +- @Path("/responseMeteredTestExceptionPerClass") +- public String responseMeteredTestExceptionPerClass() { +- throw new TestException("test"); +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { +- return new InstrumentedSubResourceResponseMeteredPerClass(); +- } +- ++ @GET ++ @Path("/responseMetered2xxPerClass") ++ public Response responseMetered2xxPerClass() { ++ return Response.ok().build(); ++ } ++ ++ @GET ++ @Path("/responseMetered4xxPerClass") ++ public Response responseMetered4xxPerClass() { ++ return Response.status(Response.Status.BAD_REQUEST).build(); ++ } ++ ++ @GET ++ @Path("/responseMetered5xxPerClass") ++ public Response responseMetered5xxPerClass() { ++ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); ++ } ++ ++ @GET ++ @Path("/responseMeteredBadRequestPerClass") ++ public String responseMeteredBadRequestPerClass() { ++ throw new BadRequestException(); ++ } ++ ++ @GET ++ @Path("/responseMeteredRuntimeExceptionPerClass") ++ public String responseMeteredRuntimeExceptionPerClass() { ++ throw new RuntimeException(); ++ } ++ ++ @GET ++ @Path("/responseMeteredTestExceptionPerClass") ++ public String responseMeteredTestExceptionPerClass() { ++ throw new TestException("test"); ++ } ++ ++ @Path("/subresource") ++ public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { ++ return new InstrumentedSubResourceResponseMeteredPerClass(); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceTimedPerClass.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceTimedPerClass.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.annotation.Timed; +- + import javax.ws.rs.GET; + import javax.ws.rs.Path; + import javax.ws.rs.Produces; +@@ -12,15 +11,14 @@ import javax.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceTimedPerClass { + +- @GET +- @Path("/timedPerClass") +- public String timedPerClass() { +- return "yay"; +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceTimedPerClass locateSubResource() { +- return new InstrumentedSubResourceTimedPerClass(); +- } ++ @GET ++ @Path("/timedPerClass") ++ public String timedPerClass() { ++ return "yay"; ++ } + ++ @Path("/subresource") ++ public InstrumentedSubResourceTimedPerClass locateSubResource() { ++ return new InstrumentedSubResourceTimedPerClass(); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.annotation.Timed; +- + import javax.ws.rs.GET; + import javax.ws.rs.Path; + import javax.ws.rs.Produces; +@@ -10,11 +9,10 @@ import javax.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResource { + +- @GET +- @Timed +- @Path("/timed") +- public String timed() { +- return "yay"; +- } +- ++ @GET ++ @Path("/timed") ++ @Timed ++ public String timed() { ++ return "yay"; ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceExceptionMeteredPerClass.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceExceptionMeteredPerClass.java +@@ -1,24 +1,24 @@ + package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.annotation.ExceptionMetered; +- ++import java.io.IOException; + import javax.ws.rs.DefaultValue; + import javax.ws.rs.GET; + import javax.ws.rs.Path; + import javax.ws.rs.Produces; + import javax.ws.rs.QueryParam; + import javax.ws.rs.core.MediaType; +-import java.io.IOException; + + @ExceptionMetered(cause = IOException.class) + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceExceptionMeteredPerClass { +- @GET +- @Path("/exception-metered") +- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { +- if (splode) { +- throw new IOException("AUGH"); +- } +- return "fuh"; ++ @GET ++ @Path("/exception-metered") ++ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) ++ throws IOException { ++ if (splode) { ++ throw new IOException("AUGH"); + } ++ return "fuh"; ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceMeteredPerClass.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceMeteredPerClass.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.annotation.Metered; +- + import javax.ws.rs.GET; + import javax.ws.rs.Path; + import javax.ws.rs.Produces; +@@ -10,9 +9,9 @@ import javax.ws.rs.core.MediaType; + @Metered + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceMeteredPerClass { +- @GET +- @Path("/meteredPerClass") +- public String meteredPerClass() { +- return "yay"; +- } ++ @GET ++ @Path("/meteredPerClass") ++ public String meteredPerClass() { ++ return "yay"; ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceResponseMeteredPerClass.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceResponseMeteredPerClass.java +@@ -1,21 +1,20 @@ + package io.dropwizard.metrics5.jersey2.resources; + +-import io.dropwizard.metrics5.annotation.ResponseMetered; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + ++import io.dropwizard.metrics5.annotation.ResponseMetered; + import javax.ws.rs.GET; + import javax.ws.rs.Path; + import javax.ws.rs.Produces; + import javax.ws.rs.core.MediaType; + import javax.ws.rs.core.Response; + +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +- + @ResponseMetered(level = ALL) + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceResponseMeteredPerClass { +- @GET +- @Path("/responseMeteredPerClass") +- public Response responseMeteredPerClass() { +- return Response.status(Response.Status.OK).build(); +- } ++ @GET ++ @Path("/responseMeteredPerClass") ++ public Response responseMeteredPerClass() { ++ return Response.status(Response.Status.OK).build(); ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceTimedPerClass.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceTimedPerClass.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.annotation.Timed; +- + import javax.ws.rs.GET; + import javax.ws.rs.Path; + import javax.ws.rs.Produces; +@@ -10,9 +9,9 @@ import javax.ws.rs.core.MediaType; + @Timed + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceTimedPerClass { +- @GET +- @Path("/timedPerClass") +- public String timedPerClass() { +- return "yay"; +- } ++ @GET ++ @Path("/timedPerClass") ++ public String timedPerClass() { ++ return "yay"; ++ } + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/TestRequestFilter.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/TestRequestFilter.java +@@ -1,21 +1,20 @@ + package io.dropwizard.metrics5.jersey2.resources; + + import io.dropwizard.metrics5.jersey2.TestClock; +- ++import java.io.IOException; + import javax.ws.rs.container.ContainerRequestContext; + import javax.ws.rs.container.ContainerRequestFilter; +-import java.io.IOException; + + public class TestRequestFilter implements ContainerRequestFilter { + +- private final TestClock testClock; ++ private final TestClock testClock; + +- public TestRequestFilter(TestClock testClock) { +- this.testClock = testClock; +- } ++ public TestRequestFilter(TestClock testClock) { ++ this.testClock = testClock; ++ } + +- @Override +- public void filter(ContainerRequestContext containerRequestContext) throws IOException { +- testClock.tick += 4; +- } ++ @Override ++ public void filter(ContainerRequestContext containerRequestContext) throws IOException { ++ testClock.tick += 4; ++ } + } +--- a/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java +@@ -1,5 +1,14 @@ + package io.dropwizard.metrics5.jersey3; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; ++ ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Meter; +@@ -14,20 +23,9 @@ import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; + import io.dropwizard.metrics5.annotation.Timed; + import jakarta.ws.rs.core.Configuration; + import jakarta.ws.rs.ext.Provider; +-import org.glassfish.jersey.server.ContainerResponse; +-import org.glassfish.jersey.server.model.ModelProcessor; +-import org.glassfish.jersey.server.model.Resource; +-import org.glassfish.jersey.server.model.ResourceMethod; +-import org.glassfish.jersey.server.model.ResourceModel; +-import org.glassfish.jersey.server.monitoring.ApplicationEvent; +-import org.glassfish.jersey.server.monitoring.ApplicationEventListener; +-import org.glassfish.jersey.server.monitoring.RequestEvent; +-import org.glassfish.jersey.server.monitoring.RequestEventListener; +- + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -36,518 +34,573 @@ import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; + import java.util.concurrent.TimeUnit; + import java.util.function.Supplier; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import org.glassfish.jersey.server.ContainerResponse; ++import org.glassfish.jersey.server.model.ModelProcessor; ++import org.glassfish.jersey.server.model.Resource; ++import org.glassfish.jersey.server.model.ResourceMethod; ++import org.glassfish.jersey.server.model.ResourceModel; ++import org.glassfish.jersey.server.monitoring.ApplicationEvent; ++import org.glassfish.jersey.server.monitoring.ApplicationEventListener; ++import org.glassfish.jersey.server.monitoring.RequestEvent; ++import org.glassfish.jersey.server.monitoring.RequestEventListener; + + /** +- * An application event listener that listens for Jersey application initialization to +- * be finished, then creates a map of resource method that have metrics annotations. +- *

    +- * Finally, it listens for method start events, and returns a {@link RequestEventListener} +- * that updates the relevant metric for suitably annotated methods when it gets the +- * request events indicating that the method is about to be invoked, or just got done +- * being invoked. ++ * An application event listener that listens for Jersey application initialization to be finished, ++ * then creates a map of resource method that have metrics annotations. ++ * ++ *

    Finally, it listens for method start events, and returns a {@link RequestEventListener} that ++ * updates the relevant metric for suitably annotated methods when it gets the request events ++ * indicating that the method is about to be invoked, or just got done being invoked. + */ + @Provider +-public class InstrumentedResourceMethodApplicationListener implements ApplicationEventListener, ModelProcessor { +- +- private static final String[] REQUEST_FILTERING = {"request", "filtering"}; +- private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; +- private static final String TOTAL = "total"; +- +- private final MetricRegistry metrics; +- private final ConcurrentMap timers = new ConcurrentHashMap<>(); +- private final ConcurrentMap meters = new ConcurrentHashMap<>(); +- private final ConcurrentMap exceptionMeters = new ConcurrentHashMap<>(); +- private final ConcurrentMap responseMeters = new ConcurrentHashMap<>(); +- +- private final Clock clock; +- private final boolean trackFilters; +- private final Supplier reservoirSupplier; +- +- /** +- * Construct an application event listener using the given metrics registry. +- *

    +- * When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} +- * should be added to a Jersey {@code ResourceConfig} as a singleton. +- * +- * @param metrics a {@link MetricRegistry} +- */ +- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { +- this(metrics, Clock.defaultClock(), false); +- } +- +- /** +- * Constructs a custom application listener. +- * +- * @param metrics the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- */ +- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, +- final boolean trackFilters) { +- this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); +- } +- +- /** +- * Constructs a custom application listener. +- * +- * @param metrics the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. +- */ +- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, +- final boolean trackFilters, +- final Supplier reservoirSupplier) { +- this.metrics = metrics; +- this.clock = clock; +- this.trackFilters = trackFilters; +- this.reservoirSupplier = reservoirSupplier; +- } +- +- /** +- * A private class to maintain the metric for a method annotated with the +- * {@link ExceptionMetered} annotation, which needs to maintain both a meter +- * and a cause for which the meter should be updated. +- */ +- private static class ExceptionMeterMetric { +- public final Meter meter; +- public final Class cause; +- +- public ExceptionMeterMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final ExceptionMetered exceptionMetered) { +- final MetricName name = chooseName(exceptionMetered.name(), +- exceptionMetered.absolute(), method, ExceptionMetered.DEFAULT_NAME_SUFFIX); +- this.meter = registry.meter(name); +- this.cause = exceptionMetered.cause(); +- } ++public class InstrumentedResourceMethodApplicationListener ++ implements ApplicationEventListener, ModelProcessor { ++ ++ private static final String[] REQUEST_FILTERING = {"request", "filtering"}; ++ private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; ++ private static final String TOTAL = "total"; ++ ++ private final MetricRegistry metrics; ++ private final ConcurrentMap timers = new ConcurrentHashMap<>(); ++ private final ConcurrentMap meters = new ConcurrentHashMap<>(); ++ private final ConcurrentMap exceptionMeters = ++ new ConcurrentHashMap<>(); ++ private final ConcurrentMap responseMeters = ++ new ConcurrentHashMap<>(); ++ ++ private final Clock clock; ++ private final boolean trackFilters; ++ private final Supplier reservoirSupplier; ++ ++ /** ++ * Construct an application event listener using the given metrics registry. ++ * ++ *

    When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} ++ * should be added to a Jersey {@code ResourceConfig} as a singleton. ++ * ++ * @param metrics a {@link MetricRegistry} ++ */ ++ public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { ++ this(metrics, Clock.defaultClock(), false); ++ } ++ ++ /** ++ * Constructs a custom application listener. ++ * ++ * @param metrics the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be ++ * tracked ++ */ ++ public InstrumentedResourceMethodApplicationListener( ++ final MetricRegistry metrics, final Clock clock, final boolean trackFilters) { ++ this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); ++ } ++ ++ /** ++ * Constructs a custom application listener. ++ * ++ * @param metrics the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be ++ * tracked ++ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. ++ */ ++ public InstrumentedResourceMethodApplicationListener( ++ final MetricRegistry metrics, ++ final Clock clock, ++ final boolean trackFilters, ++ final Supplier reservoirSupplier) { ++ this.metrics = metrics; ++ this.clock = clock; ++ this.trackFilters = trackFilters; ++ this.reservoirSupplier = reservoirSupplier; ++ } ++ ++ /** ++ * A private class to maintain the metric for a method annotated with the {@link ExceptionMetered} ++ * annotation, which needs to maintain both a meter and a cause for which the meter should be ++ * updated. ++ */ ++ private static class ExceptionMeterMetric { ++ public final Meter meter; ++ public final Class cause; ++ ++ public ExceptionMeterMetric( ++ final MetricRegistry registry, ++ final ResourceMethod method, ++ final ExceptionMetered exceptionMetered) { ++ final MetricName name = ++ chooseName( ++ exceptionMetered.name(), ++ exceptionMetered.absolute(), ++ method, ++ ExceptionMetered.DEFAULT_NAME_SUFFIX); ++ this.meter = registry.meter(name); ++ this.cause = exceptionMetered.cause(); + } +- +- /** +- * A private class to maintain the metrics for a method annotated with the +- * {@link ResponseMetered} annotation, which needs to maintain meters for +- * different response codes +- */ +- private static class ResponseMeterMetric { +- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); +- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); +- private final List meters; +- private final Map responseCodeMeters; +- private final MetricRegistry metricRegistry; +- private final MetricName metricName; +- private final ResponseMeteredLevel level; +- +- public ResponseMeterMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final ResponseMetered responseMetered) { +- this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); +- this.level = responseMetered.level(); +- this.meters = COARSE_METER_LEVELS.contains(level) ? +- Collections.unmodifiableList(Arrays.asList( +- registry.meter(metricName.resolve("1xx-responses")), // 1xx +- registry.meter(metricName.resolve("2xx-responses")), // 2xx +- registry.meter(metricName.resolve("3xx-responses")), // 3xx +- registry.meter(metricName.resolve("4xx-responses")), // 4xx +- registry.meter(metricName.resolve("5xx-responses")) // 5xx +- )) : Collections.emptyList(); +- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : Collections.emptyMap(); +- this.metricRegistry = registry; +- } +- +- public void mark(int statusCode) { +- if (DETAILED_METER_LEVELS.contains(level)) { +- getResponseCodeMeter(statusCode).mark(); +- } +- +- if (COARSE_METER_LEVELS.contains(level)) { +- final int responseStatus = statusCode / 100; +- if (responseStatus >= 1 && responseStatus <= 5) { +- meters.get(responseStatus - 1).mark(); +- } +- } +- } +- +- private Meter getResponseCodeMeter(int statusCode) { +- return responseCodeMeters +- .computeIfAbsent(statusCode, sc -> metricRegistry +- .meter(metricName.resolve(String.format("%d-responses", sc)))); +- } ++ } ++ ++ /** ++ * A private class to maintain the metrics for a method annotated with the {@link ResponseMetered} ++ * annotation, which needs to maintain meters for different response codes ++ */ ++ private static class ResponseMeterMetric { ++ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); ++ private static final Set DETAILED_METER_LEVELS = ++ EnumSet.of(DETAILED, ALL); ++ private final List meters; ++ private final Map responseCodeMeters; ++ private final MetricRegistry metricRegistry; ++ private final MetricName metricName; ++ private final ResponseMeteredLevel level; ++ ++ public ResponseMeterMetric( ++ final MetricRegistry registry, ++ final ResourceMethod method, ++ final ResponseMetered responseMetered) { ++ this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); ++ this.level = responseMetered.level(); ++ this.meters = ++ COARSE_METER_LEVELS.contains(level) ++ ? unmodifiableList( ++ Arrays.asList( ++ registry.meter(metricName.resolve("1xx-responses")), // 1xx ++ registry.meter(metricName.resolve("2xx-responses")), // 2xx ++ registry.meter(metricName.resolve("3xx-responses")), // 3xx ++ registry.meter(metricName.resolve("4xx-responses")), // 4xx ++ registry.meter(metricName.resolve("5xx-responses")) // 5xx ++ )) ++ : ImmutableList.of(); ++ this.responseCodeMeters = ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); ++ this.metricRegistry = registry; + } + +- private static class TimerRequestEventListener implements RequestEventListener { +- +- private final ConcurrentMap timers; +- private final Clock clock; +- private final long start; +- private Timer.Context resourceMethodStartContext; +- private Timer.Context requestMatchedContext; +- private Timer.Context responseFiltersStartContext; +- +- public TimerRequestEventListener(final ConcurrentMap timers, final Clock clock) { +- this.timers = timers; +- this.clock = clock; +- start = clock.getTick(); +- } +- +- @Override +- public void onEvent(RequestEvent event) { +- switch (event.getType()) { +- case RESOURCE_METHOD_START: +- resourceMethodStartContext = context(event); +- break; +- case REQUEST_MATCHED: +- requestMatchedContext = context(event); +- break; +- case RESP_FILTERS_START: +- responseFiltersStartContext = context(event); +- break; +- case RESOURCE_METHOD_FINISHED: +- if (resourceMethodStartContext != null) { +- resourceMethodStartContext.close(); +- } +- break; +- case REQUEST_FILTERED: +- if (requestMatchedContext != null) { +- requestMatchedContext.close(); +- } +- break; +- case RESP_FILTERS_FINISHED: +- if (responseFiltersStartContext != null) { +- responseFiltersStartContext.close(); +- } +- break; +- case FINISHED: +- if (requestMatchedContext != null && responseFiltersStartContext != null) { +- final Timer timer = timer(event); +- if (timer != null) { +- timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); +- } +- } +- break; +- default: +- break; +- } +- } +- +- private Timer timer(RequestEvent event) { +- final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); +- if (resourceMethod == null) { +- return null; +- } +- return timers.get(new EventTypeAndMethod(event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); +- } ++ public void mark(int statusCode) { ++ if (DETAILED_METER_LEVELS.contains(level)) { ++ getResponseCodeMeter(statusCode).mark(); ++ } + +- private Timer.Context context(RequestEvent event) { +- final Timer timer = timer(event); +- return timer != null ? timer.time() : null; ++ if (COARSE_METER_LEVELS.contains(level)) { ++ final int responseStatus = statusCode / 100; ++ if (responseStatus >= 1 && responseStatus <= 5) { ++ meters.get(responseStatus - 1).mark(); + } ++ } + } + +- private static class MeterRequestEventListener implements RequestEventListener { +- private final ConcurrentMap meters; +- +- public MeterRequestEventListener(final ConcurrentMap meters) { +- this.meters = meters; +- } +- +- @Override +- public void onEvent(RequestEvent event) { +- if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { +- final Meter meter = this.meters.get(event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); +- if (meter != null) { +- meter.mark(); +- } +- } +- } ++ private Meter getResponseCodeMeter(int statusCode) { ++ return responseCodeMeters.computeIfAbsent( ++ statusCode, ++ sc -> metricRegistry.meter(metricName.resolve(String.format("%d-responses", sc)))); + } ++ } + +- private static class ExceptionMeterRequestEventListener implements RequestEventListener { +- private final ConcurrentMap exceptionMeters; ++ private static class TimerRequestEventListener implements RequestEventListener { + +- public ExceptionMeterRequestEventListener(final ConcurrentMap exceptionMeters) { +- this.exceptionMeters = exceptionMeters; +- } ++ private final ConcurrentMap timers; ++ private final Clock clock; ++ private final long start; ++ private Timer.Context resourceMethodStartContext; ++ private Timer.Context requestMatchedContext; ++ private Timer.Context responseFiltersStartContext; ++ ++ public TimerRequestEventListener( ++ final ConcurrentMap timers, final Clock clock) { ++ this.timers = timers; ++ this.clock = clock; ++ start = clock.getTick(); ++ } + +- @Override +- public void onEvent(RequestEvent event) { +- if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { +- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); +- final ExceptionMeterMetric metric = (method != null) ? +- this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) : null; +- +- if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) || +- (event.getException().getCause() != null && +- metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { +- metric.meter.mark(); +- } +- } ++ @Override ++ public void onEvent(RequestEvent event) { ++ switch (event.getType()) { ++ case RESOURCE_METHOD_START: ++ resourceMethodStartContext = context(event); ++ break; ++ case REQUEST_MATCHED: ++ requestMatchedContext = context(event); ++ break; ++ case RESP_FILTERS_START: ++ responseFiltersStartContext = context(event); ++ break; ++ case RESOURCE_METHOD_FINISHED: ++ if (resourceMethodStartContext != null) { ++ resourceMethodStartContext.close(); ++ } ++ break; ++ case REQUEST_FILTERED: ++ if (requestMatchedContext != null) { ++ requestMatchedContext.close(); ++ } ++ break; ++ case RESP_FILTERS_FINISHED: ++ if (responseFiltersStartContext != null) { ++ responseFiltersStartContext.close(); ++ } ++ break; ++ case FINISHED: ++ if (requestMatchedContext != null && responseFiltersStartContext != null) { ++ final Timer timer = timer(event); ++ if (timer != null) { ++ timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); + } +- } ++ } ++ break; ++ default: ++ break; ++ } + } + +- private static class ResponseMeterRequestEventListener implements RequestEventListener { +- private final ConcurrentMap responseMeters; +- +- public ResponseMeterRequestEventListener(final ConcurrentMap responseMeters) { +- this.responseMeters = responseMeters; +- } +- +- @Override +- public void onEvent(RequestEvent event) { +- if (event.getType() == RequestEvent.Type.FINISHED) { +- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); +- final ResponseMeterMetric metric = (method != null) ? +- this.responseMeters.get(method.getInvocable().getDefinitionMethod()) : null; +- +- if (metric != null) { +- ContainerResponse containerResponse = event.getContainerResponse(); +- if (containerResponse == null && event.getException() != null) { +- metric.mark(500); +- } else if (containerResponse != null) { +- metric.mark(containerResponse.getStatus()); +- } +- } +- } +- } ++ private Timer timer(RequestEvent event) { ++ final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); ++ if (resourceMethod == null) { ++ return null; ++ } ++ return timers.get( ++ new EventTypeAndMethod( ++ event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); + } + +- private static class ChainedRequestEventListener implements RequestEventListener { +- private final RequestEventListener[] listeners; ++ private Timer.Context context(RequestEvent event) { ++ final Timer timer = timer(event); ++ return timer != null ? timer.time() : null; ++ } ++ } + +- private ChainedRequestEventListener(final RequestEventListener... listeners) { +- this.listeners = listeners; +- } ++ private static class MeterRequestEventListener implements RequestEventListener { ++ private final ConcurrentMap meters; + +- @Override +- public void onEvent(final RequestEvent event) { +- for (RequestEventListener listener : listeners) { +- listener.onEvent(event); +- } +- } ++ public MeterRequestEventListener(final ConcurrentMap meters) { ++ this.meters = meters; + } + + @Override +- public void onEvent(ApplicationEvent event) { +- if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { +- registerMetricsForModel(event.getResourceModel()); +- } ++ public void onEvent(RequestEvent event) { ++ if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { ++ final Meter meter = ++ this.meters.get( ++ event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); ++ if (meter != null) { ++ meter.mark(); ++ } ++ } + } ++ } + +- @Override +- public ResourceModel processResourceModel(ResourceModel resourceModel, Configuration configuration) { +- return resourceModel; ++ private static class ExceptionMeterRequestEventListener implements RequestEventListener { ++ private final ConcurrentMap exceptionMeters; ++ ++ public ExceptionMeterRequestEventListener( ++ final ConcurrentMap exceptionMeters) { ++ this.exceptionMeters = exceptionMeters; + } + + @Override +- public ResourceModel processSubResource(ResourceModel subResourceModel, Configuration configuration) { +- registerMetricsForModel(subResourceModel); +- return subResourceModel; ++ public void onEvent(RequestEvent event) { ++ if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { ++ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); ++ final ExceptionMeterMetric metric = ++ (method != null) ++ ? this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) ++ : null; ++ ++ if (metric != null) { ++ if (metric.cause.isInstance(event.getException()) ++ || (event.getException().getCause() != null ++ && metric.cause.isInstance(event.getException().getCause()))) { ++ metric.meter.mark(); ++ } ++ } ++ } + } ++ } + +- private void registerMetricsForModel(ResourceModel resourceModel) { +- for (final Resource resource : resourceModel.getResources()) { +- +- final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); +- final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); +- final ExceptionMetered classLevelExceptionMetered = getClassLevelAnnotation(resource, ExceptionMetered.class); +- final ResponseMetered classLevelResponseMetered = getClassLevelAnnotation(resource, ResponseMetered.class); +- +- for (final ResourceMethod method : resource.getAllMethods()) { +- registerTimedAnnotations(method, classLevelTimed); +- registerMeteredAnnotations(method, classLevelMetered); +- registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); +- registerResponseMeteredAnnotations(method, classLevelResponseMetered); +- } +- +- for (final Resource childResource : resource.getChildResources()) { +- +- final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); +- final Metered classLevelMeteredChild = getClassLevelAnnotation(childResource, Metered.class); +- final ExceptionMetered classLevelExceptionMeteredChild = getClassLevelAnnotation(childResource, ExceptionMetered.class); +- final ResponseMetered classLevelResponseMeteredChild = getClassLevelAnnotation(childResource, ResponseMetered.class); ++ private static class ResponseMeterRequestEventListener implements RequestEventListener { ++ private final ConcurrentMap responseMeters; + +- for (final ResourceMethod method : childResource.getAllMethods()) { +- registerTimedAnnotations(method, classLevelTimedChild); +- registerMeteredAnnotations(method, classLevelMeteredChild); +- registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); +- registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); +- } +- } +- } ++ public ResponseMeterRequestEventListener( ++ final ConcurrentMap responseMeters) { ++ this.responseMeters = responseMeters; + } + + @Override +- public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ public void onEvent(RequestEvent event) { ++ if (event.getType() == RequestEvent.Type.FINISHED) { ++ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); ++ final ResponseMeterMetric metric = ++ (method != null) ++ ? this.responseMeters.get(method.getInvocable().getDefinitionMethod()) ++ : null; ++ ++ if (metric != null) { ++ ContainerResponse containerResponse = event.getContainerResponse(); ++ if (containerResponse == null && event.getException() != null) { ++ metric.mark(500); ++ } else if (containerResponse != null) { ++ metric.mark(containerResponse.getStatus()); ++ } ++ } ++ } + } ++ } + +- private T getClassLevelAnnotation(final Resource resource, final Class annotationClazz) { +- T annotation = null; +- +- for (final Class clazz : resource.getHandlerClasses()) { +- annotation = clazz.getAnnotation(annotationClazz); ++ private static class ChainedRequestEventListener implements RequestEventListener { ++ private final RequestEventListener[] listeners; + +- if (annotation != null) { +- break; +- } +- } +- return annotation; ++ private ChainedRequestEventListener(final RequestEventListener... listeners) { ++ this.listeners = listeners; + } + +- private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); +- if (classLevelTimed != null) { +- registerTimers(method, definitionMethod, classLevelTimed); +- return; +- } +- +- final Timed annotation = definitionMethod.getAnnotation(Timed.class); +- if (annotation != null) { +- registerTimers(method, definitionMethod, annotation); +- } ++ @Override ++ public void onEvent(final RequestEvent event) { ++ for (RequestEventListener listener : listeners) { ++ listener.onEvent(event); ++ } + } ++ } + +- private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { +- timers.putIfAbsent(EventTypeAndMethod.requestMethodStart(definitionMethod), timerMetric(metrics, method, annotation)); +- if (trackFilters) { +- timers.putIfAbsent(EventTypeAndMethod.requestMatched(definitionMethod), timerMetric(metrics, method, annotation, REQUEST_FILTERING)); +- timers.putIfAbsent(EventTypeAndMethod.respFiltersStart(definitionMethod), timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); +- timers.putIfAbsent(EventTypeAndMethod.finished(definitionMethod), timerMetric(metrics, method, annotation, TOTAL)); +- } ++ @Override ++ public void onEvent(ApplicationEvent event) { ++ if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { ++ registerMetricsForModel(event.getResourceModel()); ++ } ++ } ++ ++ @Override ++ public ResourceModel processResourceModel( ++ ResourceModel resourceModel, Configuration configuration) { ++ return resourceModel; ++ } ++ ++ @Override ++ public ResourceModel processSubResource( ++ ResourceModel subResourceModel, Configuration configuration) { ++ registerMetricsForModel(subResourceModel); ++ return subResourceModel; ++ } ++ ++ private void registerMetricsForModel(ResourceModel resourceModel) { ++ for (final Resource resource : resourceModel.getResources()) { ++ ++ final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); ++ final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); ++ final ExceptionMetered classLevelExceptionMetered = ++ getClassLevelAnnotation(resource, ExceptionMetered.class); ++ final ResponseMetered classLevelResponseMetered = ++ getClassLevelAnnotation(resource, ResponseMetered.class); ++ ++ for (final ResourceMethod method : resource.getAllMethods()) { ++ registerTimedAnnotations(method, classLevelTimed); ++ registerMeteredAnnotations(method, classLevelMetered); ++ registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); ++ registerResponseMeteredAnnotations(method, classLevelResponseMetered); ++ } ++ ++ for (final Resource childResource : resource.getChildResources()) { ++ ++ final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); ++ final Metered classLevelMeteredChild = ++ getClassLevelAnnotation(childResource, Metered.class); ++ final ExceptionMetered classLevelExceptionMeteredChild = ++ getClassLevelAnnotation(childResource, ExceptionMetered.class); ++ final ResponseMetered classLevelResponseMeteredChild = ++ getClassLevelAnnotation(childResource, ResponseMetered.class); ++ ++ for (final ResourceMethod method : childResource.getAllMethods()) { ++ registerTimedAnnotations(method, classLevelTimedChild); ++ registerMeteredAnnotations(method, classLevelMeteredChild); ++ registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); ++ registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); ++ } ++ } ++ } ++ } ++ ++ @Override ++ public RequestEventListener onRequest(final RequestEvent event) { ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); ++ } ++ ++ private T getClassLevelAnnotation( ++ final Resource resource, final Class annotationClazz) { ++ T annotation = null; ++ ++ for (final Class clazz : resource.getHandlerClasses()) { ++ annotation = clazz.getAnnotation(annotationClazz); ++ ++ if (annotation != null) { ++ break; ++ } ++ } ++ return annotation; ++ } ++ ++ private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ if (classLevelTimed != null) { ++ registerTimers(method, definitionMethod, classLevelTimed); ++ return; + } + +- private void registerMeteredAnnotations(final ResourceMethod method, final Metered classLevelMetered) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ final Timed annotation = definitionMethod.getAnnotation(Timed.class); ++ if (annotation != null) { ++ registerTimers(method, definitionMethod, annotation); ++ } ++ } ++ ++ private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { ++ timers.putIfAbsent( ++ EventTypeAndMethod.requestMethodStart(definitionMethod), ++ timerMetric(metrics, method, annotation)); ++ if (trackFilters) { ++ timers.putIfAbsent( ++ EventTypeAndMethod.requestMatched(definitionMethod), ++ timerMetric(metrics, method, annotation, REQUEST_FILTERING)); ++ timers.putIfAbsent( ++ EventTypeAndMethod.respFiltersStart(definitionMethod), ++ timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); ++ timers.putIfAbsent( ++ EventTypeAndMethod.finished(definitionMethod), ++ timerMetric(metrics, method, annotation, TOTAL)); ++ } ++ } + +- if (classLevelMetered != null) { +- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); +- return; +- } +- final Metered annotation = definitionMethod.getAnnotation(Metered.class); ++ private void registerMeteredAnnotations( ++ final ResourceMethod method, final Metered classLevelMetered) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + +- if (annotation != null) { +- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); +- } ++ if (classLevelMetered != null) { ++ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); ++ return; + } ++ final Metered annotation = definitionMethod.getAnnotation(Metered.class); + +- private void registerExceptionMeteredAnnotations(final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ if (annotation != null) { ++ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); ++ } ++ } + +- if (classLevelExceptionMetered != null) { +- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); +- return; +- } +- final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); ++ private void registerExceptionMeteredAnnotations( ++ final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + +- if (annotation != null) { +- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); +- } ++ if (classLevelExceptionMetered != null) { ++ exceptionMeters.putIfAbsent( ++ definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); ++ return; + } ++ final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); + +- private void registerResponseMeteredAnnotations(final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ if (annotation != null) { ++ exceptionMeters.putIfAbsent( ++ definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); ++ } ++ } + +- if (classLevelResponseMetered != null) { +- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); +- return; +- } +- final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); ++ private void registerResponseMeteredAnnotations( ++ final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + +- if (annotation != null) { +- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); +- } ++ if (classLevelResponseMetered != null) { ++ responseMeters.putIfAbsent( ++ definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); ++ return; + } ++ final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); + +- private Timer timerMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final Timed timed, +- final String... suffixes) { +- final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); +- return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); ++ if (annotation != null) { ++ responseMeters.putIfAbsent( ++ definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); + } +- +- private Meter meterMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final Metered metered) { +- final MetricName name = chooseName(metered.name(), metered.absolute(), method); +- return registry.meter(name, () -> new Meter(clock)); ++ } ++ ++ private Timer timerMetric( ++ final MetricRegistry registry, ++ final ResourceMethod method, ++ final Timed timed, ++ final String... suffixes) { ++ final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); ++ return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); ++ } ++ ++ private Meter meterMetric( ++ final MetricRegistry registry, final ResourceMethod method, final Metered metered) { ++ final MetricName name = chooseName(metered.name(), metered.absolute(), method); ++ return registry.meter(name, () -> new Meter(clock)); ++ } ++ ++ protected static MetricName chooseName( ++ final String explicitName, ++ final boolean absolute, ++ final ResourceMethod method, ++ final String... suffixes) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ MetricName metricName; ++ if (!Strings.isNullOrEmpty(explicitName)) { ++ metricName = ++ absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); ++ } else { ++ metricName = name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); + } +- +- protected static MetricName chooseName(final String explicitName, final boolean absolute, final ResourceMethod method, +- final String... suffixes) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); +- MetricName metricName; +- if (explicitName != null && !explicitName.isEmpty()) { +- metricName = absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); +- } else { +- metricName = name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); +- } +- for (String suffix : suffixes) { +- metricName = metricName.resolve(suffix); +- } +- return metricName; ++ for (String suffix : suffixes) { ++ metricName = metricName.resolve(suffix); + } ++ return metricName; ++ } + +- private static class EventTypeAndMethod { ++ private static class EventTypeAndMethod { + +- private final RequestEvent.Type type; +- private final Method method; +- +- private EventTypeAndMethod(RequestEvent.Type type, Method method) { +- this.type = type; +- this.method = method; +- } +- +- static EventTypeAndMethod requestMethodStart(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); +- } ++ private final RequestEvent.Type type; ++ private final Method method; + +- static EventTypeAndMethod requestMatched(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); +- } ++ private EventTypeAndMethod(RequestEvent.Type type, Method method) { ++ this.type = type; ++ this.method = method; ++ } + +- static EventTypeAndMethod respFiltersStart(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); +- } ++ static EventTypeAndMethod requestMethodStart(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); ++ } + +- static EventTypeAndMethod finished(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); +- } ++ static EventTypeAndMethod requestMatched(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); ++ } + +- @Override +- public boolean equals(Object o) { +- if (this == o) { +- return true; +- } +- if (o == null || getClass() != o.getClass()) { +- return false; +- } ++ static EventTypeAndMethod respFiltersStart(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); ++ } + +- EventTypeAndMethod that = (EventTypeAndMethod) o; ++ static EventTypeAndMethod finished(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); ++ } + +- if (type != that.type) { +- return false; +- } +- return method.equals(that.method); +- } ++ @Override ++ public boolean equals(Object o) { ++ if (this == o) { ++ return true; ++ } ++ if (o == null || getClass() != o.getClass()) { ++ return false; ++ } ++ ++ EventTypeAndMethod that = (EventTypeAndMethod) o; ++ ++ if (type != that.type) { ++ return false; ++ } ++ return method.equals(that.method); ++ } + +- @Override +- public int hashCode() { +- int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; +- } ++ @Override ++ public int hashCode() { ++ int result = type.hashCode(); ++ return 31 * result + method.hashCode(); + } ++ } + } +--- a/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/MetricsFeature.java ++++ b/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/MetricsFeature.java +@@ -7,91 +7,96 @@ import io.dropwizard.metrics5.Reservoir; + import io.dropwizard.metrics5.SharedMetricRegistries; + import jakarta.ws.rs.core.Feature; + import jakarta.ws.rs.core.FeatureContext; +- + import java.util.function.Supplier; + + /** +- * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} +- * for recording request events. ++ * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} for ++ * recording request events. + */ + public class MetricsFeature implements Feature { + +- private final MetricRegistry registry; +- private final Clock clock; +- private final boolean trackFilters; +- private final Supplier reservoirSupplier; ++ private final MetricRegistry registry; ++ private final Clock clock; ++ private final boolean trackFilters; ++ private final Supplier reservoirSupplier; + +- /* +- * @param registry the metrics registry where the metrics will be stored +- */ +- public MetricsFeature(MetricRegistry registry) { +- this(registry, Clock.defaultClock()); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ */ ++ public MetricsFeature(MetricRegistry registry) { ++ this(registry, Clock.defaultClock()); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. +- */ +- public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { +- this(registry, Clock.defaultClock(), false, reservoirSupplier); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. ++ */ ++ public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { ++ this(registry, Clock.defaultClock(), false, reservoirSupplier); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- */ +- public MetricsFeature(MetricRegistry registry, Clock clock) { +- this(registry, clock, false); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ */ ++ public MetricsFeature(MetricRegistry registry, Clock clock) { ++ this(registry, clock, false); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- */ +- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { +- this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be tracked ++ */ ++ public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { ++ this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. +- */ +- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters, Supplier reservoirSupplier) { +- this.registry = registry; +- this.clock = clock; +- this.trackFilters = trackFilters; +- this.reservoirSupplier = reservoirSupplier; +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be tracked ++ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. ++ */ ++ public MetricsFeature( ++ MetricRegistry registry, ++ Clock clock, ++ boolean trackFilters, ++ Supplier reservoirSupplier) { ++ this.registry = registry; ++ this.clock = clock; ++ this.trackFilters = trackFilters; ++ this.reservoirSupplier = reservoirSupplier; ++ } + +- public MetricsFeature(String registryName) { +- this(SharedMetricRegistries.getOrCreate(registryName)); +- } ++ public MetricsFeature(String registryName) { ++ this(SharedMetricRegistries.getOrCreate(registryName)); ++ } + +- /** +- * A call-back method called when the feature is to be enabled in a given +- * runtime configuration scope. +- *

    +- * The responsibility of the feature is to properly update the supplied runtime configuration context +- * and return {@code true} if the feature was successfully enabled or {@code false} otherwise. +- *

    +- * Note that under some circumstances the feature may decide not to enable itself, which +- * is indicated by returning {@code false}. In such case the configuration context does +- * not add the feature to the collection of enabled features and a subsequent call to +- * {@link jakarta.ws.rs.core.Configuration#isEnabled(jakarta.ws.rs.core.Feature)} or +- * {@link jakarta.ws.rs.core.Configuration#isEnabled(Class)} method +- * would return {@code false}. +- *

    +- * +- * @param context configurable context in which the feature should be enabled. +- * @return {@code true} if the feature was successfully enabled, {@code false} +- * otherwise. +- */ +- @Override +- public boolean configure(FeatureContext context) { +- context.register(new InstrumentedResourceMethodApplicationListener(registry, clock, trackFilters, reservoirSupplier)); +- return true; +- } ++ /** ++ * A call-back method called when the feature is to be enabled in a given runtime configuration ++ * scope. ++ * ++ *

    The responsibility of the feature is to properly update the supplied runtime configuration ++ * context and return {@code true} if the feature was successfully enabled or {@code false} ++ * otherwise. ++ * ++ *

    Note that under some circumstances the feature may decide not to enable itself, which is ++ * indicated by returning {@code false}. In such case the configuration context does not add the ++ * feature to the collection of enabled features and a subsequent call to {@link ++ * jakarta.ws.rs.core.Configuration#isEnabled(jakarta.ws.rs.core.Feature)} or {@link ++ * jakarta.ws.rs.core.Configuration#isEnabled(Class)} method would return {@code false}. ++ * ++ *

    ++ * ++ * @param context configurable context in which the feature should be enabled. ++ * @return {@code true} if the feature was successfully enabled, {@code false} otherwise. ++ */ ++ @Override ++ public boolean configure(FeatureContext context) { ++ context.register( ++ new InstrumentedResourceMethodApplicationListener( ++ registry, clock, trackFilters, reservoirSupplier)); ++ return true; ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java +@@ -1,44 +1,44 @@ + package io.dropwizard.metrics5.jersey3; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.UniformReservoir; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceTimedPerClass; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +- +-class CustomReservoirImplementationTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } ++final class CustomReservoirImplementationTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- private MetricRegistry registry; ++ private MetricRegistry registry; + +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- return new ResourceConfig() ++ return new ResourceConfig() + .register(new MetricsFeature(this.registry, UniformReservoir::new)) + .register(InstrumentedResourceTimedPerClass.class); +- } ++ } + +- @Test +- void timerHistogramIsUsingCustomReservoirImplementation() { +- assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); ++ @Test ++ void timerHistogramIsUsingCustomReservoirImplementation() { ++ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); + +- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); +- assertThat(timer) ++ final Timer timer = ++ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); ++ assertThat(timer) + .extracting("histogram") + .extracting("reservoir") + .isInstanceOf(UniformReservoir.class); +- } ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java +@@ -1,162 +1,137 @@ + package io.dropwizard.metrics5.jersey3; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedFilteredResource; + import io.dropwizard.metrics5.jersey3.resources.TestRequestFilter; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} with filter tracking ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} with filter tracking + */ +-class SingletonFilterMetricsJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- private TestClock testClock; +- +- @Override +- protected Application configure() { +- registry = new MetricRegistry(); +- testClock = new TestClock(); +- ResourceConfig config = new ResourceConfig(); +- config = config.register(new MetricsFeature(this.registry, testClock, true)); +- config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; +- } +- +- @BeforeEach +- void resetClock() { +- testClock.tick = 0; +- } +- +- @Test +- void timedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); +- } +- +- @Test +- void explicitNamesAreTimed() { +- assertThat(target("named") +- .request() +- .get(String.class)) +- .isEqualTo("fancy"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); +- } +- +- @Test +- void absoluteNamesAreTimed() { +- assertThat(target("absolute") +- .request() +- .get(String.class)) +- .isEqualTo("absolute"); +- +- final Timer timer = registry.timer("absolutelyFancy"); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); +- } +- +- @Test +- void requestFiltersOfTimedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); +- } +- +- @Test +- void responseFiltersOfTimedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- } +- +- @Test +- void totalTimeOfTimedMethodsIsTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); +- } +- +- @Test +- void requestFiltersOfNamedMethodsAreTimed() { +- assertThat(target("named") +- .request() +- .get(String.class)) +- .isEqualTo("fancy"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); +- } +- +- @Test +- void requestFiltersOfAbsoluteMethodsAreTimed() { +- assertThat(target("absolute") +- .request() +- .get(String.class)) +- .isEqualTo("absolute"); +- +- final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); +- } +- +- @Test +- void subResourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, +- "timed")); +- assertThat(timer.getCount()).isEqualTo(1); +- +- } ++final class SingletonFilterMetricsJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } ++ ++ private MetricRegistry registry; ++ ++ private TestClock testClock; ++ ++ @Override ++ protected Application configure() { ++ registry = new MetricRegistry(); ++ testClock = new TestClock(); ++ ResourceConfig config = new ResourceConfig(); ++ config = config.register(new MetricsFeature(this.registry, testClock, true)); ++ config = config.register(new TestRequestFilter(testClock)); ++ return config.register(new InstrumentedFilteredResource(testClock)); ++ } ++ ++ @BeforeEach ++ void resetClock() { ++ testClock.tick = 0; ++ } ++ ++ @Test ++ void timedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); ++ } ++ ++ @Test ++ void explicitNamesAreTimed() { ++ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); ++ ++ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); ++ } ++ ++ @Test ++ void absoluteNamesAreTimed() { ++ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); ++ ++ final Timer timer = registry.timer("absolutelyFancy"); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); ++ } ++ ++ @Test ++ void requestFiltersOfTimedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); ++ } ++ ++ @Test ++ void responseFiltersOfTimedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void totalTimeOfTimedMethodsIsTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); ++ } ++ ++ @Test ++ void requestFiltersOfNamedMethodsAreTimed() { ++ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); ++ ++ final Timer timer = ++ registry.timer( ++ name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); ++ } ++ ++ @Test ++ void requestFiltersOfAbsoluteMethodsAreTimed() { ++ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); ++ ++ final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); ++ } ++ ++ @Test ++ void subResourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer( ++ name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, "timed")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -1,98 +1,92 @@ + package io.dropwizard.metrics5.jersey3; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceExceptionMeteredPerClass; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceExceptionMeteredPerClass; + import jakarta.ws.rs.ProcessingException; + import jakarta.ws.rs.core.Application; +-import org.glassfish.jersey.server.ResourceConfig; +-import org.glassfish.jersey.test.JerseyTest; +-import org.junit.jupiter.api.Test; +- + import java.io.IOException; + import java.util.logging.Level; + import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++import org.glassfish.jersey.server.ResourceConfig; ++import org.glassfish.jersey.test.JerseyTest; ++import org.junit.jupiter.api.Test; + + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } ++final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- private MetricRegistry registry; ++ private MetricRegistry registry; + +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- ResourceConfig config = new ResourceConfig(); ++ ResourceConfig config = new ResourceConfig(); + +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); ++ } + +- return config; +- } ++ @Test ++ void exceptionMeteredMethodsAreExceptionMetered() { ++ final Meter meter = ++ registry.meter( ++ name( ++ InstrumentedResourceExceptionMeteredPerClass.class, ++ "exceptionMetered", ++ "exceptions")); + +- @Test +- void exceptionMeteredMethodsAreExceptionMetered() { +- final Meter meter = registry.meter(name(InstrumentedResourceExceptionMeteredPerClass.class, +- "exceptionMetered", +- "exceptions")); ++ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(target("exception-metered") +- .request() +- .get(String.class)) +- .isEqualTo("fuh"); +- +- assertThat(meter.getCount()).isZero(); +- +- try { +- target("exception-metered") +- .queryParam("splode", true) +- .request() +- .get(String.class); ++ assertThat(meter.getCount()).isEqualTo(0); + +- failBecauseExceptionWasNotThrown(ProcessingException.class); +- } catch (ProcessingException e) { +- assertThat(e.getCause()).isInstanceOf(IOException.class); +- } ++ try { ++ target("exception-metered").queryParam("splode", true).request().get(String.class); + +- assertThat(meter.getCount()).isEqualTo(1); ++ failBecauseExceptionWasNotThrown(ProcessingException.class); ++ } catch (ProcessingException e) { ++ assertThat(e.getCause()).isInstanceOf(IOException.class); + } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- final Meter meter = registry.meter(name(InstrumentedSubResourceExceptionMeteredPerClass.class, +- "exceptionMetered", +- "exceptions")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + +- assertThat(target("subresource/exception-metered") +- .request() +- .get(String.class)) +- .isEqualTo("fuh"); ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ final Meter meter = ++ registry.meter( ++ name( ++ InstrumentedSubResourceExceptionMeteredPerClass.class, ++ "exceptionMetered", ++ "exceptions")); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(target("subresource/exception-metered").request().get(String.class)) ++ .isEqualTo("fuh"); + +- try { +- target("subresource/exception-metered") +- .queryParam("splode", true) +- .request() +- .get(String.class); ++ assertThat(meter.getCount()).isEqualTo(0); + +- failBecauseExceptionWasNotThrown(ProcessingException.class); +- } catch (ProcessingException e) { +- assertThat(e.getCause()).isInstanceOf(IOException.class); +- } ++ try { ++ target("subresource/exception-metered") ++ .queryParam("splode", true) ++ .request() ++ .get(String.class); + +- assertThat(meter.getCount()).isEqualTo(1); ++ failBecauseExceptionWasNotThrown(ProcessingException.class); ++ } catch (ProcessingException e) { ++ assertThat(e.getCause()).isInstanceOf(IOException.class); + } + ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.jersey3; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; +@@ -9,197 +13,156 @@ import jakarta.ws.rs.NotFoundException; + import jakarta.ws.rs.ProcessingException; + import jakarta.ws.rs.core.Application; + import jakarta.ws.rs.core.Response; ++import java.io.IOException; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.client.ClientResponse; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.io.IOException; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link org.glassfish.jersey.server.ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link org.glassfish.jersey.server.ResourceConfig} + */ +-class SingletonMetricsJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); +- +- ResourceConfig config = new ResourceConfig(); +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); ++final class SingletonMetricsJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- return config; +- } +- +- @Test +- void timedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- } ++ private MetricRegistry registry; + +- @Test +- void meteredMethodsAreMetered() { +- assertThat(target("metered") +- .request() +- .get(String.class)) +- .isEqualTo("woo"); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); +- assertThat(meter.getCount()).isEqualTo(1); +- } ++ ResourceConfig config = new ResourceConfig(); ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResource.class); ++ } + +- @Test +- void exceptionMeteredMethodsAreExceptionMetered() { +- final Meter meter = registry.meter(name(InstrumentedResource.class, +- "exceptionMetered", +- "exceptions")); ++ @Test ++ void timedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); + +- assertThat(target("exception-metered") +- .request() +- .get(String.class)) +- .isEqualTo("fuh"); ++ final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + +- try { +- target("exception-metered") +- .queryParam("splode", true) +- .request() +- .get(String.class); ++ @Test ++ void meteredMethodsAreMetered() { ++ assertThat(target("metered").request().get(String.class)).isEqualTo("woo"); + +- failBecauseExceptionWasNotThrown(ProcessingException.class); +- } catch (ProcessingException e) { +- assertThat(e.getCause()).isInstanceOf(IOException.class); +- } ++ final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + +- assertThat(meter.getCount()).isEqualTo(1); +- } ++ @Test ++ void exceptionMeteredMethodsAreExceptionMetered() { ++ final Meter meter = ++ registry.meter(name(InstrumentedResource.class, "exceptionMetered", "exceptions")); + +- @Test +- void responseMeteredMethodsAreMetered() { +- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, +- "response2xxMetered", +- "2xx-responses")); +- final Meter meter4xx = registry.meter(name(InstrumentedResource.class, +- "response4xxMetered", +- "4xx-responses")); +- final Meter meter5xx = registry.meter(name(InstrumentedResource.class, +- "response5xxMetered", +- "5xx-responses")); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(target("response-2xx-metered") +- .request() +- .get().getStatus()) +- .isEqualTo(200); ++ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter4xx.getCount()).isZero(); +- assertThat(target("response-4xx-metered") +- .request() +- .get().getStatus()) +- .isEqualTo(400); ++ assertThat(meter.getCount()).isEqualTo(0); + +- assertThat(meter5xx.getCount()).isZero(); +- assertThat(target("response-5xx-metered") +- .request() +- .get().getStatus()) +- .isEqualTo(500); ++ try { ++ target("exception-metered").queryParam("splode", true).request().get(String.class); + +- assertThat(meter2xx.getCount()).isEqualTo(1); +- assertThat(meter4xx.getCount()).isEqualTo(1); +- assertThat(meter5xx.getCount()).isEqualTo(1); ++ failBecauseExceptionWasNotThrown(ProcessingException.class); ++ } catch (ProcessingException e) { ++ assertThat(e.getCause()).isInstanceOf(IOException.class); + } + +- @Test +- void responseMeteredMethodsAreMeteredWithDetailedLevel() { +- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, +- "responseMeteredDetailed", +- "2xx-responses")); +- final Meter meter200 = registry.meter(name(InstrumentedResource.class, +- "responseMeteredDetailed", +- "200-responses")); +- final Meter meter201 = registry.meter(name(InstrumentedResource.class, +- "responseMeteredDetailed", +- "201-responses")); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); +- assertThat(target("response-metered-detailed") +- .request() +- .get().getStatus()) +- .isEqualTo(200); +- assertThat(target("response-metered-detailed") ++ assertThat(meter.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredMethodsAreMetered() { ++ final Meter meter2xx = ++ registry.meter(name(InstrumentedResource.class, "response2xxMetered", "2xx-responses")); ++ final Meter meter4xx = ++ registry.meter(name(InstrumentedResource.class, "response4xxMetered", "4xx-responses")); ++ final Meter meter5xx = ++ registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); ++ ++ assertThat(meter4xx.getCount()).isEqualTo(0); ++ assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); ++ ++ assertThat(meter5xx.getCount()).isEqualTo(0); ++ assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter4xx.getCount()).isEqualTo(1); ++ assertThat(meter5xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredMethodsAreMeteredWithDetailedLevel() { ++ final Meter meter2xx = ++ registry.meter( ++ name(InstrumentedResource.class, "responseMeteredDetailed", "2xx-responses")); ++ final Meter meter200 = ++ registry.meter( ++ name(InstrumentedResource.class, "responseMeteredDetailed", "200-responses")); ++ final Meter meter201 = ++ registry.meter( ++ name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); ++ assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); ++ assertThat( ++ target("response-metered-detailed") + .queryParam("status_code", 201) + .request() +- .get().getStatus()) +- .isEqualTo(201); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ .get() ++ .getStatus()) ++ .isEqualTo(201); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredMethodsAreMeteredWithAllLevel() { ++ final Meter meter2xx = ++ registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); ++ final Meter meter200 = ++ registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void resourceNotFound() { ++ final Response response = target().path("not-found").request().get(); ++ assertThat(response.getStatus()).isEqualTo(404); ++ ++ try { ++ target().path("not-found").request().get(ClientResponse.class); ++ failBecauseExceptionWasNotThrown(NotFoundException.class); ++ } catch (NotFoundException e) { ++ assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); + } ++ } + +- @Test +- public void responseMeteredMethodsAreMeteredWithAllLevel() { +- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, +- "responseMeteredAll", +- "2xx-responses")); +- final Meter meter200 = registry.meter(name(InstrumentedResource.class, +- "responseMeteredAll", +- "200-responses")); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(target("response-metered-all") +- .request() +- .get().getStatus()) +- .isEqualTo(200); +- +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); +- } ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); + +- @Test +- void testResourceNotFound() { +- final Response response = target().path("not-found").request().get(); +- assertThat(response.getStatus()).isEqualTo(404); +- +- try { +- target().path("not-found").request().get(ClientResponse.class); +- failBecauseExceptionWasNotThrown(NotFoundException.class); +- } catch (NotFoundException e) { +- assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); +- } +- } +- +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); +- assertThat(timer.getCount()).isEqualTo(1); +- } ++ final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -1,66 +1,56 @@ + package io.dropwizard.metrics5.jersey3; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceMeteredPerClass; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceMeteredPerClass; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); +- +- ResourceConfig config = new ResourceConfig(); +- +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); ++final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- return config; +- } ++ private MetricRegistry registry; + +- @Test +- void meteredPerClassMethodsAreMetered() { +- assertThat(target("meteredPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- final Meter meter = registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); ++ ResourceConfig config = new ResourceConfig(); + +- assertThat(meter.getCount()).isEqualTo(1); +- } ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResourceMeteredPerClass.class); ++ } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/meteredPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Test ++ void meteredPerClassMethodsAreMetered() { ++ assertThat(target("meteredPerClass").request().get(String.class)).isEqualTo("yay"); + +- final Meter meter = registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); +- assertThat(meter.getCount()).isEqualTo(1); ++ final Meter meter = ++ registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); + +- } ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/meteredPerClass").request().get(String.class)).isEqualTo("yay"); + ++ final Meter meter = ++ registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -1,152 +1,158 @@ + package io.dropwizard.metrics5.jersey3; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jersey3.exception.mapper.TestExceptionMapper; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceResponseMeteredPerClass; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceResponseMeteredPerClass; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } ++final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- private MetricRegistry registry; ++ private MetricRegistry registry; + +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + ++ ResourceConfig config = new ResourceConfig(); + +- ResourceConfig config = new ResourceConfig(); ++ config = config.register(new MetricsFeature(this.registry)); ++ config = config.register(InstrumentedResourceResponseMeteredPerClass.class); ++ return config.register(new TestExceptionMapper()); ++ } + +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; +- } ++ @Test ++ void responseMetered2xxPerClassMethodsAreMetered() { ++ assertThat(target("responseMetered2xxPerClass").request().get().getStatus()).isEqualTo(200); + +- @Test +- void responseMetered2xxPerClassMethodsAreMetered() { +- assertThat(target("responseMetered2xxPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(200); +- +- final Meter meter2xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMetered2xxPerClass", +- "2xx-responses")); ++ final Meter meter2xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMetered2xxPerClass", ++ "2xx-responses")); + +- assertThat(meter2xx.getCount()).isEqualTo(1); +- } ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ } + +- @Test +- void responseMetered4xxPerClassMethodsAreMetered() { +- assertThat(target("responseMetered4xxPerClass") +- .request() +- .get().getStatus()) ++ @Test ++ void responseMetered4xxPerClassMethodsAreMetered() { ++ assertThat(target("responseMetered4xxPerClass").request().get().getStatus()).isEqualTo(400); ++ assertThat(target("responseMeteredBadRequestPerClass").request().get().getStatus()) + .isEqualTo(400); +- assertThat(target("responseMeteredBadRequestPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(400); +- +- final Meter meter4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMetered4xxPerClass", +- "4xx-responses")); +- final Meter meterException4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMeteredBadRequestPerClass", +- "4xx-responses")); + +- assertThat(meter4xx.getCount()).isEqualTo(1); +- assertThat(meterException4xx.getCount()).isEqualTo(1); +- } +- +- @Test +- void responseMetered5xxPerClassMethodsAreMetered() { +- assertThat(target("responseMetered5xxPerClass") +- .request() +- .get().getStatus()) ++ final Meter meter4xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMetered4xxPerClass", ++ "4xx-responses")); ++ final Meter meterException4xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMeteredBadRequestPerClass", ++ "4xx-responses")); ++ ++ assertThat(meter4xx.getCount()).isEqualTo(1); ++ assertThat(meterException4xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMetered5xxPerClassMethodsAreMetered() { ++ assertThat(target("responseMetered5xxPerClass").request().get().getStatus()).isEqualTo(500); ++ ++ final Meter meter5xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMetered5xxPerClass", ++ "5xx-responses")); ++ ++ assertThat(meter5xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredMappedExceptionPerClassMethodsAreMetered() { ++ assertThat(target("responseMeteredTestExceptionPerClass").request().get().getStatus()) + .isEqualTo(500); + +- final Meter meter5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMetered5xxPerClass", +- "5xx-responses")); +- +- assertThat(meter5xx.getCount()).isEqualTo(1); ++ final Meter meterTestException = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMeteredTestExceptionPerClass", ++ "5xx-responses")); ++ ++ assertThat(meterTestException.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { ++ try { ++ target("responseMeteredRuntimeExceptionPerClass").request().get(); ++ fail("expected RuntimeException"); ++ } catch (Exception e) { ++ assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + } + +- @Test +- void responseMeteredMappedExceptionPerClassMethodsAreMetered() { +- assertThat(target("responseMeteredTestExceptionPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(500); +- +- final Meter meterTestException = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMeteredTestExceptionPerClass", +- "5xx-responses")); +- +- assertThat(meterTestException.getCount()).isEqualTo(1); +- } +- +- @Test +- void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { +- try { +- target("responseMeteredRuntimeExceptionPerClass") +- .request() +- .get(); +- fail("expected RuntimeException"); +- } catch (Exception e) { +- assertThat(e.getCause()).isInstanceOf(RuntimeException.class); +- } +- +- final Meter meterException5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMeteredRuntimeExceptionPerClass", +- "5xx-responses")); +- +- assertThat(meterException5xx.getCount()).isEqualTo(1); +- } +- +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- final Meter meter2xx = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, ++ final Meter meterException5xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMeteredRuntimeExceptionPerClass", ++ "5xx-responses")); ++ ++ assertThat(meterException5xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ final Meter meter2xx = ++ registry.meter( ++ name( ++ InstrumentedSubResourceResponseMeteredPerClass.class, + "responseMeteredPerClass", + "2xx-responses")); +- final Meter meter200 = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, ++ final Meter meter200 = ++ registry.meter( ++ name( ++ InstrumentedSubResourceResponseMeteredPerClass.class, + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + +- assertThat(target("subresource/responseMeteredPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(200); ++ assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) ++ .isEqualTo(200); + +- final Meter meter = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, +- "responseMeteredPerClass", "2xx-responses")); +- assertThat(meter.getCount()).isEqualTo(1); ++ final Meter meter = ++ registry.meter( ++ name( ++ InstrumentedSubResourceResponseMeteredPerClass.class, ++ "responseMeteredPerClass", ++ "2xx-responses")); ++ assertThat(meter.getCount()).isEqualTo(1); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); +- } ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java +@@ -1,66 +1,56 @@ + package io.dropwizard.metrics5.jersey3; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceTimedPerClass; + import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceTimedPerClass; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); +- +- ResourceConfig config = new ResourceConfig(); +- +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); ++final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- return config; +- } ++ private MetricRegistry registry; + +- @Test +- void timedPerClassMethodsAreTimed() { +- assertThat(target("timedPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); ++ ResourceConfig config = new ResourceConfig(); + +- assertThat(timer.getCount()).isEqualTo(1); +- } ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResourceTimedPerClass.class); ++ } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/timedPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Test ++ void timedPerClassMethodsAreTimed() { ++ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); + +- final Timer timer = registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); +- assertThat(timer.getCount()).isEqualTo(1); ++ final Timer timer = ++ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); + +- } ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/timedPerClass").request().get(String.class)).isEqualTo("yay"); + ++ final Timer timer = ++ registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/TestClock.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/TestClock.java +@@ -4,10 +4,10 @@ import io.dropwizard.metrics5.Clock; + + public class TestClock extends Clock { + +- public long tick; ++ public long tick; + +- @Override +- public long getTick() { +- return tick; +- } ++ @Override ++ public long getTick() { ++ return tick; ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/exception/TestException.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/exception/TestException.java +@@ -1,9 +1,9 @@ + package io.dropwizard.metrics5.jersey3.exception; + + public class TestException extends RuntimeException { +- private static final long serialVersionUID = 1L; ++ private static final long serialVersionUID = 1L; + +- public TestException(String message) { +- super(message); +- } ++ public TestException(String message) { ++ super(message); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/exception/mapper/TestExceptionMapper.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/exception/mapper/TestExceptionMapper.java +@@ -7,8 +7,8 @@ import jakarta.ws.rs.ext.Provider; + + @Provider + public class TestExceptionMapper implements ExceptionMapper { +- @Override +- public Response toResponse(TestException exception) { +- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +- } ++ @Override ++ public Response toResponse(TestException exception) { ++ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java +@@ -11,51 +11,50 @@ import jakarta.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedFilteredResource { + +- private final TestClock testClock; +- +- public InstrumentedFilteredResource(TestClock testClock) { +- this.testClock = testClock; +- } ++ private final TestClock testClock; ++ ++ public InstrumentedFilteredResource(TestClock testClock) { ++ this.testClock = testClock; ++ } ++ ++ @GET ++ @Path("/timed") ++ @Timed ++ public String timed() { ++ testClock.tick++; ++ return "yay"; ++ } ++ ++ @GET ++ @Path("/named") ++ @Timed(name = "fancyName") ++ public String named() { ++ testClock.tick++; ++ return "fancy"; ++ } ++ ++ @GET ++ @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) ++ public String absolute() { ++ testClock.tick++; ++ return "absolute"; ++ } ++ ++ @Path("/subresource") ++ public InstrumentedFilteredSubResource locateSubResource() { ++ return new InstrumentedFilteredSubResource(); ++ } ++ ++ @Produces(MediaType.TEXT_PLAIN) ++ public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { +- testClock.tick++; +- return "yay"; +- } +- +- @GET +- @Timed(name = "fancyName") +- @Path("/named") +- public String named() { +- testClock.tick++; +- return "fancy"; +- } +- +- @GET +- @Timed(name = "absolutelyFancy", absolute = true) +- @Path("/absolute") +- public String absolute() { +- testClock.tick++; +- return "absolute"; +- } +- +- @Path("/subresource") +- public InstrumentedFilteredSubResource locateSubResource() { +- return new InstrumentedFilteredSubResource(); +- } +- +- @Produces(MediaType.TEXT_PLAIN) +- public class InstrumentedFilteredSubResource { +- +- @GET +- @Timed +- @Path("/timed") +- public String timed() { +- testClock.tick += 2; +- return "yay"; +- } +- ++ testClock.tick += 2; ++ return "yay"; + } ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.jersey3.resources; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++ + import io.dropwizard.metrics5.annotation.ExceptionMetered; + import io.dropwizard.metrics5.annotation.Metered; + import io.dropwizard.metrics5.annotation.ResponseMetered; +@@ -13,81 +17,81 @@ import jakarta.ws.rs.core.MediaType; + import jakarta.ws.rs.core.Response; + import java.io.IOException; + +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; +- + @Path("/") + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { +- @GET +- @Timed +- @Path("/timed") +- public String timed() { +- return "yay"; +- } ++ @GET ++ @Path("/timed") ++ @Timed ++ public String timed() { ++ return "yay"; ++ } + +- @GET +- @Metered +- @Path("/metered") +- public String metered() { +- return "woo"; +- } ++ @GET ++ @Metered ++ @Path("/metered") ++ public String metered() { ++ return "woo"; ++ } + +- @GET +- @ExceptionMetered(cause = IOException.class) +- @Path("/exception-metered") +- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { +- if (splode) { +- throw new IOException("AUGH"); +- } +- return "fuh"; ++ @ExceptionMetered(cause = IOException.class) ++ @GET ++ @Path("/exception-metered") ++ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) ++ throws IOException { ++ if (splode) { ++ throw new IOException("AUGH"); + } ++ return "fuh"; ++ } + +- @GET +- @ResponseMetered(level = DETAILED) +- @Path("/response-metered-detailed") +- public Response responseMeteredDetailed(@QueryParam("status_code") @DefaultValue("200") int statusCode) { +- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +- } ++ @GET ++ @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) ++ public Response responseMeteredDetailed( ++ @QueryParam("status_code") @DefaultValue("200") int statusCode) { ++ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ++ } + +- @GET +- @ResponseMetered(level = COARSE) +- @Path("/response-metered-coarse") +- public Response responseMeteredCoarse(@QueryParam("status_code") @DefaultValue("200") int statusCode) { +- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +- } ++ @GET ++ @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) ++ public Response responseMeteredCoarse( ++ @QueryParam("status_code") @DefaultValue("200") int statusCode) { ++ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ++ } + +- @GET +- @ResponseMetered(level = ALL) +- @Path("/response-metered-all") +- public Response responseMeteredAll(@QueryParam("status_code") @DefaultValue("200") int statusCode) { +- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +- } ++ @GET ++ @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) ++ public Response responseMeteredAll( ++ @QueryParam("status_code") @DefaultValue("200") int statusCode) { ++ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ++ } + +- @GET +- @ResponseMetered +- @Path("/response-2xx-metered") +- public Response response2xxMetered() { +- return Response.ok().build(); +- } ++ @GET ++ @Path("/response-2xx-metered") ++ @ResponseMetered ++ public Response response2xxMetered() { ++ return Response.ok().build(); ++ } + +- @GET +- @ResponseMetered +- @Path("/response-4xx-metered") +- public Response response4xxMetered() { +- return Response.status(Response.Status.BAD_REQUEST).build(); +- } ++ @GET ++ @Path("/response-4xx-metered") ++ @ResponseMetered ++ public Response response4xxMetered() { ++ return Response.status(Response.Status.BAD_REQUEST).build(); ++ } + +- @GET +- @ResponseMetered +- @Path("/response-5xx-metered") +- public Response response5xxMetered() { +- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +- } ++ @GET ++ @Path("/response-5xx-metered") ++ @ResponseMetered ++ public Response response5xxMetered() { ++ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); ++ } + +- @Path("/subresource") +- public InstrumentedSubResource locateSubResource() { +- return new InstrumentedSubResource(); +- } ++ @Path("/subresource") ++ public InstrumentedSubResource locateSubResource() { ++ return new InstrumentedSubResource(); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceExceptionMeteredPerClass.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceExceptionMeteredPerClass.java +@@ -7,7 +7,6 @@ import jakarta.ws.rs.Path; + import jakarta.ws.rs.Produces; + import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.core.MediaType; +- + import java.io.IOException; + + @ExceptionMetered(cause = IOException.class) +@@ -15,18 +14,18 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceExceptionMeteredPerClass { + +- @GET +- @Path("/exception-metered") +- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { +- if (splode) { +- throw new IOException("AUGH"); +- } +- return "fuh"; +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { +- return new InstrumentedSubResourceExceptionMeteredPerClass(); ++ @GET ++ @Path("/exception-metered") ++ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) ++ throws IOException { ++ if (splode) { ++ throw new IOException("AUGH"); + } ++ return "fuh"; ++ } + ++ @Path("/subresource") ++ public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { ++ return new InstrumentedSubResourceExceptionMeteredPerClass(); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceMeteredPerClass.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceMeteredPerClass.java +@@ -11,15 +11,14 @@ import jakarta.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceMeteredPerClass { + +- @GET +- @Path("/meteredPerClass") +- public String meteredPerClass() { +- return "yay"; +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceMeteredPerClass locateSubResource() { +- return new InstrumentedSubResourceMeteredPerClass(); +- } ++ @GET ++ @Path("/meteredPerClass") ++ public String meteredPerClass() { ++ return "yay"; ++ } + ++ @Path("/subresource") ++ public InstrumentedSubResourceMeteredPerClass locateSubResource() { ++ return new InstrumentedSubResourceMeteredPerClass(); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceResponseMeteredPerClass.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceResponseMeteredPerClass.java +@@ -14,45 +14,44 @@ import jakarta.ws.rs.core.Response; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceResponseMeteredPerClass { + +- @GET +- @Path("/responseMetered2xxPerClass") +- public Response responseMetered2xxPerClass() { +- return Response.ok().build(); +- } +- +- @GET +- @Path("/responseMetered4xxPerClass") +- public Response responseMetered4xxPerClass() { +- return Response.status(Response.Status.BAD_REQUEST).build(); +- } +- +- @GET +- @Path("/responseMetered5xxPerClass") +- public Response responseMetered5xxPerClass() { +- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +- } +- +- @GET +- @Path("/responseMeteredBadRequestPerClass") +- public String responseMeteredBadRequestPerClass() { +- throw new BadRequestException(); +- } +- +- @GET +- @Path("/responseMeteredRuntimeExceptionPerClass") +- public String responseMeteredRuntimeExceptionPerClass() { +- throw new RuntimeException(); +- } +- +- @GET +- @Path("/responseMeteredTestExceptionPerClass") +- public String responseMeteredTestExceptionPerClass() { +- throw new TestException("test"); +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { +- return new InstrumentedSubResourceResponseMeteredPerClass(); +- } +- ++ @GET ++ @Path("/responseMetered2xxPerClass") ++ public Response responseMetered2xxPerClass() { ++ return Response.ok().build(); ++ } ++ ++ @GET ++ @Path("/responseMetered4xxPerClass") ++ public Response responseMetered4xxPerClass() { ++ return Response.status(Response.Status.BAD_REQUEST).build(); ++ } ++ ++ @GET ++ @Path("/responseMetered5xxPerClass") ++ public Response responseMetered5xxPerClass() { ++ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); ++ } ++ ++ @GET ++ @Path("/responseMeteredBadRequestPerClass") ++ public String responseMeteredBadRequestPerClass() { ++ throw new BadRequestException(); ++ } ++ ++ @GET ++ @Path("/responseMeteredRuntimeExceptionPerClass") ++ public String responseMeteredRuntimeExceptionPerClass() { ++ throw new RuntimeException(); ++ } ++ ++ @GET ++ @Path("/responseMeteredTestExceptionPerClass") ++ public String responseMeteredTestExceptionPerClass() { ++ throw new TestException("test"); ++ } ++ ++ @Path("/subresource") ++ public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { ++ return new InstrumentedSubResourceResponseMeteredPerClass(); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceTimedPerClass.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceTimedPerClass.java +@@ -11,15 +11,14 @@ import jakarta.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceTimedPerClass { + +- @GET +- @Path("/timedPerClass") +- public String timedPerClass() { +- return "yay"; +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceTimedPerClass locateSubResource() { +- return new InstrumentedSubResourceTimedPerClass(); +- } ++ @GET ++ @Path("/timedPerClass") ++ public String timedPerClass() { ++ return "yay"; ++ } + ++ @Path("/subresource") ++ public InstrumentedSubResourceTimedPerClass locateSubResource() { ++ return new InstrumentedSubResourceTimedPerClass(); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java +@@ -9,11 +9,10 @@ import jakarta.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResource { + +- @GET +- @Timed +- @Path("/timed") +- public String timed() { +- return "yay"; +- } +- ++ @GET ++ @Path("/timed") ++ @Timed ++ public String timed() { ++ return "yay"; ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceExceptionMeteredPerClass.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceExceptionMeteredPerClass.java +@@ -7,18 +7,18 @@ import jakarta.ws.rs.Path; + import jakarta.ws.rs.Produces; + import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.core.MediaType; +- + import java.io.IOException; + + @ExceptionMetered(cause = IOException.class) + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceExceptionMeteredPerClass { +- @GET +- @Path("/exception-metered") +- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { +- if (splode) { +- throw new IOException("AUGH"); +- } +- return "fuh"; ++ @GET ++ @Path("/exception-metered") ++ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) ++ throws IOException { ++ if (splode) { ++ throw new IOException("AUGH"); + } ++ return "fuh"; ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceMeteredPerClass.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceMeteredPerClass.java +@@ -9,9 +9,9 @@ import jakarta.ws.rs.core.MediaType; + @Metered + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceMeteredPerClass { +- @GET +- @Path("/meteredPerClass") +- public String meteredPerClass() { +- return "yay"; +- } ++ @GET ++ @Path("/meteredPerClass") ++ public String meteredPerClass() { ++ return "yay"; ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceResponseMeteredPerClass.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceResponseMeteredPerClass.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.jersey3.resources; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++ + import io.dropwizard.metrics5.annotation.ResponseMetered; + import jakarta.ws.rs.GET; + import jakarta.ws.rs.Path; +@@ -7,14 +9,12 @@ import jakarta.ws.rs.Produces; + import jakarta.ws.rs.core.MediaType; + import jakarta.ws.rs.core.Response; + +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +- + @ResponseMetered(level = ALL) + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceResponseMeteredPerClass { +- @GET +- @Path("/responseMeteredPerClass") +- public Response responseMeteredPerClass() { +- return Response.status(Response.Status.OK).build(); +- } ++ @GET ++ @Path("/responseMeteredPerClass") ++ public Response responseMeteredPerClass() { ++ return Response.status(Response.Status.OK).build(); ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceTimedPerClass.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceTimedPerClass.java +@@ -9,9 +9,9 @@ import jakarta.ws.rs.core.MediaType; + @Timed + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceTimedPerClass { +- @GET +- @Path("/timedPerClass") +- public String timedPerClass() { +- return "yay"; +- } ++ @GET ++ @Path("/timedPerClass") ++ public String timedPerClass() { ++ return "yay"; ++ } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/TestRequestFilter.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/TestRequestFilter.java +@@ -3,19 +3,18 @@ package io.dropwizard.metrics5.jersey3.resources; + import io.dropwizard.metrics5.jersey3.TestClock; + import jakarta.ws.rs.container.ContainerRequestContext; + import jakarta.ws.rs.container.ContainerRequestFilter; +- + import java.io.IOException; + + public class TestRequestFilter implements ContainerRequestFilter { + +- private final TestClock testClock; ++ private final TestClock testClock; + +- public TestRequestFilter(TestClock testClock) { +- this.testClock = testClock; +- } ++ public TestRequestFilter(TestClock testClock) { ++ this.testClock = testClock; ++ } + +- @Override +- public void filter(ContainerRequestContext containerRequestContext) throws IOException { +- testClock.tick += 4; +- } ++ @Override ++ public void filter(ContainerRequestContext containerRequestContext) throws IOException { ++ testClock.tick += 4; ++ } + } +--- a/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java +@@ -1,5 +1,14 @@ + package io.dropwizard.metrics5.jersey31; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; ++ ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Meter; +@@ -14,20 +23,9 @@ import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; + import io.dropwizard.metrics5.annotation.Timed; + import jakarta.ws.rs.core.Configuration; + import jakarta.ws.rs.ext.Provider; +-import org.glassfish.jersey.server.ContainerResponse; +-import org.glassfish.jersey.server.model.ModelProcessor; +-import org.glassfish.jersey.server.model.Resource; +-import org.glassfish.jersey.server.model.ResourceMethod; +-import org.glassfish.jersey.server.model.ResourceModel; +-import org.glassfish.jersey.server.monitoring.ApplicationEvent; +-import org.glassfish.jersey.server.monitoring.ApplicationEventListener; +-import org.glassfish.jersey.server.monitoring.RequestEvent; +-import org.glassfish.jersey.server.monitoring.RequestEventListener; +- + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -36,518 +34,573 @@ import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; + import java.util.concurrent.TimeUnit; + import java.util.function.Supplier; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import org.glassfish.jersey.server.ContainerResponse; ++import org.glassfish.jersey.server.model.ModelProcessor; ++import org.glassfish.jersey.server.model.Resource; ++import org.glassfish.jersey.server.model.ResourceMethod; ++import org.glassfish.jersey.server.model.ResourceModel; ++import org.glassfish.jersey.server.monitoring.ApplicationEvent; ++import org.glassfish.jersey.server.monitoring.ApplicationEventListener; ++import org.glassfish.jersey.server.monitoring.RequestEvent; ++import org.glassfish.jersey.server.monitoring.RequestEventListener; + + /** +- * An application event listener that listens for Jersey application initialization to +- * be finished, then creates a map of resource method that have metrics annotations. +- *

    +- * Finally, it listens for method start events, and returns a {@link RequestEventListener} +- * that updates the relevant metric for suitably annotated methods when it gets the +- * request events indicating that the method is about to be invoked, or just got done +- * being invoked. ++ * An application event listener that listens for Jersey application initialization to be finished, ++ * then creates a map of resource method that have metrics annotations. ++ * ++ *

    Finally, it listens for method start events, and returns a {@link RequestEventListener} that ++ * updates the relevant metric for suitably annotated methods when it gets the request events ++ * indicating that the method is about to be invoked, or just got done being invoked. + */ + @Provider +-public class InstrumentedResourceMethodApplicationListener implements ApplicationEventListener, ModelProcessor { +- +- private static final String[] REQUEST_FILTERING = {"request", "filtering"}; +- private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; +- private static final String TOTAL = "total"; +- +- private final MetricRegistry metrics; +- private final ConcurrentMap timers = new ConcurrentHashMap<>(); +- private final ConcurrentMap meters = new ConcurrentHashMap<>(); +- private final ConcurrentMap exceptionMeters = new ConcurrentHashMap<>(); +- private final ConcurrentMap responseMeters = new ConcurrentHashMap<>(); +- +- private final Clock clock; +- private final boolean trackFilters; +- private final Supplier reservoirSupplier; +- +- /** +- * Construct an application event listener using the given metrics registry. +- *

    +- * When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} +- * should be added to a Jersey {@code ResourceConfig} as a singleton. +- * +- * @param metrics a {@link MetricRegistry} +- */ +- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { +- this(metrics, Clock.defaultClock(), false); +- } +- +- /** +- * Constructs a custom application listener. +- * +- * @param metrics the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- */ +- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, +- final boolean trackFilters) { +- this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); +- } +- +- /** +- * Constructs a custom application listener. +- * +- * @param metrics the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. +- */ +- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, +- final boolean trackFilters, +- final Supplier reservoirSupplier) { +- this.metrics = metrics; +- this.clock = clock; +- this.trackFilters = trackFilters; +- this.reservoirSupplier = reservoirSupplier; +- } +- +- /** +- * A private class to maintain the metric for a method annotated with the +- * {@link ExceptionMetered} annotation, which needs to maintain both a meter +- * and a cause for which the meter should be updated. +- */ +- private static class ExceptionMeterMetric { +- public final Meter meter; +- public final Class cause; +- +- public ExceptionMeterMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final ExceptionMetered exceptionMetered) { +- final MetricName name = chooseName(exceptionMetered.name(), +- exceptionMetered.absolute(), method, ExceptionMetered.DEFAULT_NAME_SUFFIX); +- this.meter = registry.meter(name); +- this.cause = exceptionMetered.cause(); +- } ++public class InstrumentedResourceMethodApplicationListener ++ implements ApplicationEventListener, ModelProcessor { ++ ++ private static final String[] REQUEST_FILTERING = {"request", "filtering"}; ++ private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; ++ private static final String TOTAL = "total"; ++ ++ private final MetricRegistry metrics; ++ private final ConcurrentMap timers = new ConcurrentHashMap<>(); ++ private final ConcurrentMap meters = new ConcurrentHashMap<>(); ++ private final ConcurrentMap exceptionMeters = ++ new ConcurrentHashMap<>(); ++ private final ConcurrentMap responseMeters = ++ new ConcurrentHashMap<>(); ++ ++ private final Clock clock; ++ private final boolean trackFilters; ++ private final Supplier reservoirSupplier; ++ ++ /** ++ * Construct an application event listener using the given metrics registry. ++ * ++ *

    When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} ++ * should be added to a Jersey {@code ResourceConfig} as a singleton. ++ * ++ * @param metrics a {@link MetricRegistry} ++ */ ++ public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { ++ this(metrics, Clock.defaultClock(), false); ++ } ++ ++ /** ++ * Constructs a custom application listener. ++ * ++ * @param metrics the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be ++ * tracked ++ */ ++ public InstrumentedResourceMethodApplicationListener( ++ final MetricRegistry metrics, final Clock clock, final boolean trackFilters) { ++ this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); ++ } ++ ++ /** ++ * Constructs a custom application listener. ++ * ++ * @param metrics the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be ++ * tracked ++ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. ++ */ ++ public InstrumentedResourceMethodApplicationListener( ++ final MetricRegistry metrics, ++ final Clock clock, ++ final boolean trackFilters, ++ final Supplier reservoirSupplier) { ++ this.metrics = metrics; ++ this.clock = clock; ++ this.trackFilters = trackFilters; ++ this.reservoirSupplier = reservoirSupplier; ++ } ++ ++ /** ++ * A private class to maintain the metric for a method annotated with the {@link ExceptionMetered} ++ * annotation, which needs to maintain both a meter and a cause for which the meter should be ++ * updated. ++ */ ++ private static class ExceptionMeterMetric { ++ public final Meter meter; ++ public final Class cause; ++ ++ public ExceptionMeterMetric( ++ final MetricRegistry registry, ++ final ResourceMethod method, ++ final ExceptionMetered exceptionMetered) { ++ final MetricName name = ++ chooseName( ++ exceptionMetered.name(), ++ exceptionMetered.absolute(), ++ method, ++ ExceptionMetered.DEFAULT_NAME_SUFFIX); ++ this.meter = registry.meter(name); ++ this.cause = exceptionMetered.cause(); + } +- +- /** +- * A private class to maintain the metrics for a method annotated with the +- * {@link ResponseMetered} annotation, which needs to maintain meters for +- * different response codes +- */ +- private static class ResponseMeterMetric { +- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); +- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); +- private final List meters; +- private final Map responseCodeMeters; +- private final MetricRegistry metricRegistry; +- private final MetricName metricName; +- private final ResponseMeteredLevel level; +- +- public ResponseMeterMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final ResponseMetered responseMetered) { +- this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); +- this.level = responseMetered.level(); +- this.meters = COARSE_METER_LEVELS.contains(level) ? +- Collections.unmodifiableList(Arrays.asList( +- registry.meter(metricName.resolve("1xx-responses")), // 1xx +- registry.meter(metricName.resolve("2xx-responses")), // 2xx +- registry.meter(metricName.resolve("3xx-responses")), // 3xx +- registry.meter(metricName.resolve("4xx-responses")), // 4xx +- registry.meter(metricName.resolve("5xx-responses")) // 5xx +- )) : Collections.emptyList(); +- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : Collections.emptyMap(); +- this.metricRegistry = registry; +- } +- +- public void mark(int statusCode) { +- if (DETAILED_METER_LEVELS.contains(level)) { +- getResponseCodeMeter(statusCode).mark(); +- } +- +- if (COARSE_METER_LEVELS.contains(level)) { +- final int responseStatus = statusCode / 100; +- if (responseStatus >= 1 && responseStatus <= 5) { +- meters.get(responseStatus - 1).mark(); +- } +- } +- } +- +- private Meter getResponseCodeMeter(int statusCode) { +- return responseCodeMeters +- .computeIfAbsent(statusCode, sc -> metricRegistry +- .meter(metricName.resolve(String.format("%d-responses", sc)))); +- } ++ } ++ ++ /** ++ * A private class to maintain the metrics for a method annotated with the {@link ResponseMetered} ++ * annotation, which needs to maintain meters for different response codes ++ */ ++ private static class ResponseMeterMetric { ++ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); ++ private static final Set DETAILED_METER_LEVELS = ++ EnumSet.of(DETAILED, ALL); ++ private final List meters; ++ private final Map responseCodeMeters; ++ private final MetricRegistry metricRegistry; ++ private final MetricName metricName; ++ private final ResponseMeteredLevel level; ++ ++ public ResponseMeterMetric( ++ final MetricRegistry registry, ++ final ResourceMethod method, ++ final ResponseMetered responseMetered) { ++ this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); ++ this.level = responseMetered.level(); ++ this.meters = ++ COARSE_METER_LEVELS.contains(level) ++ ? unmodifiableList( ++ Arrays.asList( ++ registry.meter(metricName.resolve("1xx-responses")), // 1xx ++ registry.meter(metricName.resolve("2xx-responses")), // 2xx ++ registry.meter(metricName.resolve("3xx-responses")), // 3xx ++ registry.meter(metricName.resolve("4xx-responses")), // 4xx ++ registry.meter(metricName.resolve("5xx-responses")) // 5xx ++ )) ++ : ImmutableList.of(); ++ this.responseCodeMeters = ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); ++ this.metricRegistry = registry; + } + +- private static class TimerRequestEventListener implements RequestEventListener { +- +- private final ConcurrentMap timers; +- private final Clock clock; +- private final long start; +- private Timer.Context resourceMethodStartContext; +- private Timer.Context requestMatchedContext; +- private Timer.Context responseFiltersStartContext; +- +- public TimerRequestEventListener(final ConcurrentMap timers, final Clock clock) { +- this.timers = timers; +- this.clock = clock; +- start = clock.getTick(); +- } +- +- @Override +- public void onEvent(RequestEvent event) { +- switch (event.getType()) { +- case RESOURCE_METHOD_START: +- resourceMethodStartContext = context(event); +- break; +- case REQUEST_MATCHED: +- requestMatchedContext = context(event); +- break; +- case RESP_FILTERS_START: +- responseFiltersStartContext = context(event); +- break; +- case RESOURCE_METHOD_FINISHED: +- if (resourceMethodStartContext != null) { +- resourceMethodStartContext.close(); +- } +- break; +- case REQUEST_FILTERED: +- if (requestMatchedContext != null) { +- requestMatchedContext.close(); +- } +- break; +- case RESP_FILTERS_FINISHED: +- if (responseFiltersStartContext != null) { +- responseFiltersStartContext.close(); +- } +- break; +- case FINISHED: +- if (requestMatchedContext != null && responseFiltersStartContext != null) { +- final Timer timer = timer(event); +- if (timer != null) { +- timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); +- } +- } +- break; +- default: +- break; +- } +- } +- +- private Timer timer(RequestEvent event) { +- final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); +- if (resourceMethod == null) { +- return null; +- } +- return timers.get(new EventTypeAndMethod(event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); +- } ++ public void mark(int statusCode) { ++ if (DETAILED_METER_LEVELS.contains(level)) { ++ getResponseCodeMeter(statusCode).mark(); ++ } + +- private Timer.Context context(RequestEvent event) { +- final Timer timer = timer(event); +- return timer != null ? timer.time() : null; ++ if (COARSE_METER_LEVELS.contains(level)) { ++ final int responseStatus = statusCode / 100; ++ if (responseStatus >= 1 && responseStatus <= 5) { ++ meters.get(responseStatus - 1).mark(); + } ++ } + } + +- private static class MeterRequestEventListener implements RequestEventListener { +- private final ConcurrentMap meters; +- +- public MeterRequestEventListener(final ConcurrentMap meters) { +- this.meters = meters; +- } +- +- @Override +- public void onEvent(RequestEvent event) { +- if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { +- final Meter meter = this.meters.get(event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); +- if (meter != null) { +- meter.mark(); +- } +- } +- } ++ private Meter getResponseCodeMeter(int statusCode) { ++ return responseCodeMeters.computeIfAbsent( ++ statusCode, ++ sc -> metricRegistry.meter(metricName.resolve(String.format("%d-responses", sc)))); + } ++ } + +- private static class ExceptionMeterRequestEventListener implements RequestEventListener { +- private final ConcurrentMap exceptionMeters; ++ private static class TimerRequestEventListener implements RequestEventListener { + +- public ExceptionMeterRequestEventListener(final ConcurrentMap exceptionMeters) { +- this.exceptionMeters = exceptionMeters; +- } ++ private final ConcurrentMap timers; ++ private final Clock clock; ++ private final long start; ++ private Timer.Context resourceMethodStartContext; ++ private Timer.Context requestMatchedContext; ++ private Timer.Context responseFiltersStartContext; ++ ++ public TimerRequestEventListener( ++ final ConcurrentMap timers, final Clock clock) { ++ this.timers = timers; ++ this.clock = clock; ++ start = clock.getTick(); ++ } + +- @Override +- public void onEvent(RequestEvent event) { +- if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { +- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); +- final ExceptionMeterMetric metric = (method != null) ? +- this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) : null; +- +- if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) || +- (event.getException().getCause() != null && +- metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { +- metric.meter.mark(); +- } +- } ++ @Override ++ public void onEvent(RequestEvent event) { ++ switch (event.getType()) { ++ case RESOURCE_METHOD_START: ++ resourceMethodStartContext = context(event); ++ break; ++ case REQUEST_MATCHED: ++ requestMatchedContext = context(event); ++ break; ++ case RESP_FILTERS_START: ++ responseFiltersStartContext = context(event); ++ break; ++ case RESOURCE_METHOD_FINISHED: ++ if (resourceMethodStartContext != null) { ++ resourceMethodStartContext.close(); ++ } ++ break; ++ case REQUEST_FILTERED: ++ if (requestMatchedContext != null) { ++ requestMatchedContext.close(); ++ } ++ break; ++ case RESP_FILTERS_FINISHED: ++ if (responseFiltersStartContext != null) { ++ responseFiltersStartContext.close(); ++ } ++ break; ++ case FINISHED: ++ if (requestMatchedContext != null && responseFiltersStartContext != null) { ++ final Timer timer = timer(event); ++ if (timer != null) { ++ timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); + } +- } ++ } ++ break; ++ default: ++ break; ++ } + } + +- private static class ResponseMeterRequestEventListener implements RequestEventListener { +- private final ConcurrentMap responseMeters; +- +- public ResponseMeterRequestEventListener(final ConcurrentMap responseMeters) { +- this.responseMeters = responseMeters; +- } +- +- @Override +- public void onEvent(RequestEvent event) { +- if (event.getType() == RequestEvent.Type.FINISHED) { +- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); +- final ResponseMeterMetric metric = (method != null) ? +- this.responseMeters.get(method.getInvocable().getDefinitionMethod()) : null; +- +- if (metric != null) { +- ContainerResponse containerResponse = event.getContainerResponse(); +- if (containerResponse == null && event.getException() != null) { +- metric.mark(500); +- } else if (containerResponse != null) { +- metric.mark(containerResponse.getStatus()); +- } +- } +- } +- } ++ private Timer timer(RequestEvent event) { ++ final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); ++ if (resourceMethod == null) { ++ return null; ++ } ++ return timers.get( ++ new EventTypeAndMethod( ++ event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); + } + +- private static class ChainedRequestEventListener implements RequestEventListener { +- private final RequestEventListener[] listeners; ++ private Timer.Context context(RequestEvent event) { ++ final Timer timer = timer(event); ++ return timer != null ? timer.time() : null; ++ } ++ } + +- private ChainedRequestEventListener(final RequestEventListener... listeners) { +- this.listeners = listeners; +- } ++ private static class MeterRequestEventListener implements RequestEventListener { ++ private final ConcurrentMap meters; + +- @Override +- public void onEvent(final RequestEvent event) { +- for (RequestEventListener listener : listeners) { +- listener.onEvent(event); +- } +- } ++ public MeterRequestEventListener(final ConcurrentMap meters) { ++ this.meters = meters; + } + + @Override +- public void onEvent(ApplicationEvent event) { +- if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { +- registerMetricsForModel(event.getResourceModel()); +- } ++ public void onEvent(RequestEvent event) { ++ if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { ++ final Meter meter = ++ this.meters.get( ++ event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); ++ if (meter != null) { ++ meter.mark(); ++ } ++ } + } ++ } + +- @Override +- public ResourceModel processResourceModel(ResourceModel resourceModel, Configuration configuration) { +- return resourceModel; ++ private static class ExceptionMeterRequestEventListener implements RequestEventListener { ++ private final ConcurrentMap exceptionMeters; ++ ++ public ExceptionMeterRequestEventListener( ++ final ConcurrentMap exceptionMeters) { ++ this.exceptionMeters = exceptionMeters; + } + + @Override +- public ResourceModel processSubResource(ResourceModel subResourceModel, Configuration configuration) { +- registerMetricsForModel(subResourceModel); +- return subResourceModel; ++ public void onEvent(RequestEvent event) { ++ if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { ++ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); ++ final ExceptionMeterMetric metric = ++ (method != null) ++ ? this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) ++ : null; ++ ++ if (metric != null) { ++ if (metric.cause.isInstance(event.getException()) ++ || (event.getException().getCause() != null ++ && metric.cause.isInstance(event.getException().getCause()))) { ++ metric.meter.mark(); ++ } ++ } ++ } + } ++ } + +- private void registerMetricsForModel(ResourceModel resourceModel) { +- for (final Resource resource : resourceModel.getResources()) { +- +- final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); +- final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); +- final ExceptionMetered classLevelExceptionMetered = getClassLevelAnnotation(resource, ExceptionMetered.class); +- final ResponseMetered classLevelResponseMetered = getClassLevelAnnotation(resource, ResponseMetered.class); +- +- for (final ResourceMethod method : resource.getAllMethods()) { +- registerTimedAnnotations(method, classLevelTimed); +- registerMeteredAnnotations(method, classLevelMetered); +- registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); +- registerResponseMeteredAnnotations(method, classLevelResponseMetered); +- } +- +- for (final Resource childResource : resource.getChildResources()) { +- +- final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); +- final Metered classLevelMeteredChild = getClassLevelAnnotation(childResource, Metered.class); +- final ExceptionMetered classLevelExceptionMeteredChild = getClassLevelAnnotation(childResource, ExceptionMetered.class); +- final ResponseMetered classLevelResponseMeteredChild = getClassLevelAnnotation(childResource, ResponseMetered.class); ++ private static class ResponseMeterRequestEventListener implements RequestEventListener { ++ private final ConcurrentMap responseMeters; + +- for (final ResourceMethod method : childResource.getAllMethods()) { +- registerTimedAnnotations(method, classLevelTimedChild); +- registerMeteredAnnotations(method, classLevelMeteredChild); +- registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); +- registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); +- } +- } +- } ++ public ResponseMeterRequestEventListener( ++ final ConcurrentMap responseMeters) { ++ this.responseMeters = responseMeters; + } + + @Override +- public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ public void onEvent(RequestEvent event) { ++ if (event.getType() == RequestEvent.Type.FINISHED) { ++ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); ++ final ResponseMeterMetric metric = ++ (method != null) ++ ? this.responseMeters.get(method.getInvocable().getDefinitionMethod()) ++ : null; ++ ++ if (metric != null) { ++ ContainerResponse containerResponse = event.getContainerResponse(); ++ if (containerResponse == null && event.getException() != null) { ++ metric.mark(500); ++ } else if (containerResponse != null) { ++ metric.mark(containerResponse.getStatus()); ++ } ++ } ++ } + } ++ } + +- private T getClassLevelAnnotation(final Resource resource, final Class annotationClazz) { +- T annotation = null; +- +- for (final Class clazz : resource.getHandlerClasses()) { +- annotation = clazz.getAnnotation(annotationClazz); ++ private static class ChainedRequestEventListener implements RequestEventListener { ++ private final RequestEventListener[] listeners; + +- if (annotation != null) { +- break; +- } +- } +- return annotation; ++ private ChainedRequestEventListener(final RequestEventListener... listeners) { ++ this.listeners = listeners; + } + +- private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); +- if (classLevelTimed != null) { +- registerTimers(method, definitionMethod, classLevelTimed); +- return; +- } +- +- final Timed annotation = definitionMethod.getAnnotation(Timed.class); +- if (annotation != null) { +- registerTimers(method, definitionMethod, annotation); +- } ++ @Override ++ public void onEvent(final RequestEvent event) { ++ for (RequestEventListener listener : listeners) { ++ listener.onEvent(event); ++ } + } ++ } + +- private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { +- timers.putIfAbsent(EventTypeAndMethod.requestMethodStart(definitionMethod), timerMetric(metrics, method, annotation)); +- if (trackFilters) { +- timers.putIfAbsent(EventTypeAndMethod.requestMatched(definitionMethod), timerMetric(metrics, method, annotation, REQUEST_FILTERING)); +- timers.putIfAbsent(EventTypeAndMethod.respFiltersStart(definitionMethod), timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); +- timers.putIfAbsent(EventTypeAndMethod.finished(definitionMethod), timerMetric(metrics, method, annotation, TOTAL)); +- } ++ @Override ++ public void onEvent(ApplicationEvent event) { ++ if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { ++ registerMetricsForModel(event.getResourceModel()); ++ } ++ } ++ ++ @Override ++ public ResourceModel processResourceModel( ++ ResourceModel resourceModel, Configuration configuration) { ++ return resourceModel; ++ } ++ ++ @Override ++ public ResourceModel processSubResource( ++ ResourceModel subResourceModel, Configuration configuration) { ++ registerMetricsForModel(subResourceModel); ++ return subResourceModel; ++ } ++ ++ private void registerMetricsForModel(ResourceModel resourceModel) { ++ for (final Resource resource : resourceModel.getResources()) { ++ ++ final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); ++ final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); ++ final ExceptionMetered classLevelExceptionMetered = ++ getClassLevelAnnotation(resource, ExceptionMetered.class); ++ final ResponseMetered classLevelResponseMetered = ++ getClassLevelAnnotation(resource, ResponseMetered.class); ++ ++ for (final ResourceMethod method : resource.getAllMethods()) { ++ registerTimedAnnotations(method, classLevelTimed); ++ registerMeteredAnnotations(method, classLevelMetered); ++ registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); ++ registerResponseMeteredAnnotations(method, classLevelResponseMetered); ++ } ++ ++ for (final Resource childResource : resource.getChildResources()) { ++ ++ final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); ++ final Metered classLevelMeteredChild = ++ getClassLevelAnnotation(childResource, Metered.class); ++ final ExceptionMetered classLevelExceptionMeteredChild = ++ getClassLevelAnnotation(childResource, ExceptionMetered.class); ++ final ResponseMetered classLevelResponseMeteredChild = ++ getClassLevelAnnotation(childResource, ResponseMetered.class); ++ ++ for (final ResourceMethod method : childResource.getAllMethods()) { ++ registerTimedAnnotations(method, classLevelTimedChild); ++ registerMeteredAnnotations(method, classLevelMeteredChild); ++ registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); ++ registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); ++ } ++ } ++ } ++ } ++ ++ @Override ++ public RequestEventListener onRequest(final RequestEvent event) { ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); ++ } ++ ++ private T getClassLevelAnnotation( ++ final Resource resource, final Class annotationClazz) { ++ T annotation = null; ++ ++ for (final Class clazz : resource.getHandlerClasses()) { ++ annotation = clazz.getAnnotation(annotationClazz); ++ ++ if (annotation != null) { ++ break; ++ } ++ } ++ return annotation; ++ } ++ ++ private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ if (classLevelTimed != null) { ++ registerTimers(method, definitionMethod, classLevelTimed); ++ return; + } + +- private void registerMeteredAnnotations(final ResourceMethod method, final Metered classLevelMetered) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ final Timed annotation = definitionMethod.getAnnotation(Timed.class); ++ if (annotation != null) { ++ registerTimers(method, definitionMethod, annotation); ++ } ++ } ++ ++ private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { ++ timers.putIfAbsent( ++ EventTypeAndMethod.requestMethodStart(definitionMethod), ++ timerMetric(metrics, method, annotation)); ++ if (trackFilters) { ++ timers.putIfAbsent( ++ EventTypeAndMethod.requestMatched(definitionMethod), ++ timerMetric(metrics, method, annotation, REQUEST_FILTERING)); ++ timers.putIfAbsent( ++ EventTypeAndMethod.respFiltersStart(definitionMethod), ++ timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); ++ timers.putIfAbsent( ++ EventTypeAndMethod.finished(definitionMethod), ++ timerMetric(metrics, method, annotation, TOTAL)); ++ } ++ } + +- if (classLevelMetered != null) { +- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); +- return; +- } +- final Metered annotation = definitionMethod.getAnnotation(Metered.class); ++ private void registerMeteredAnnotations( ++ final ResourceMethod method, final Metered classLevelMetered) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + +- if (annotation != null) { +- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); +- } ++ if (classLevelMetered != null) { ++ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); ++ return; + } ++ final Metered annotation = definitionMethod.getAnnotation(Metered.class); + +- private void registerExceptionMeteredAnnotations(final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ if (annotation != null) { ++ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); ++ } ++ } + +- if (classLevelExceptionMetered != null) { +- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); +- return; +- } +- final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); ++ private void registerExceptionMeteredAnnotations( ++ final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + +- if (annotation != null) { +- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); +- } ++ if (classLevelExceptionMetered != null) { ++ exceptionMeters.putIfAbsent( ++ definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); ++ return; + } ++ final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); + +- private void registerResponseMeteredAnnotations(final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ if (annotation != null) { ++ exceptionMeters.putIfAbsent( ++ definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); ++ } ++ } + +- if (classLevelResponseMetered != null) { +- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); +- return; +- } +- final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); ++ private void registerResponseMeteredAnnotations( ++ final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + +- if (annotation != null) { +- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); +- } ++ if (classLevelResponseMetered != null) { ++ responseMeters.putIfAbsent( ++ definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); ++ return; + } ++ final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); + +- private Timer timerMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final Timed timed, +- final String... suffixes) { +- final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); +- return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); ++ if (annotation != null) { ++ responseMeters.putIfAbsent( ++ definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); + } +- +- private Meter meterMetric(final MetricRegistry registry, +- final ResourceMethod method, +- final Metered metered) { +- final MetricName name = chooseName(metered.name(), metered.absolute(), method); +- return registry.meter(name, () -> new Meter(clock)); ++ } ++ ++ private Timer timerMetric( ++ final MetricRegistry registry, ++ final ResourceMethod method, ++ final Timed timed, ++ final String... suffixes) { ++ final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); ++ return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); ++ } ++ ++ private Meter meterMetric( ++ final MetricRegistry registry, final ResourceMethod method, final Metered metered) { ++ final MetricName name = chooseName(metered.name(), metered.absolute(), method); ++ return registry.meter(name, () -> new Meter(clock)); ++ } ++ ++ protected static MetricName chooseName( ++ final String explicitName, ++ final boolean absolute, ++ final ResourceMethod method, ++ final String... suffixes) { ++ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); ++ MetricName metricName; ++ if (!Strings.isNullOrEmpty(explicitName)) { ++ metricName = ++ absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); ++ } else { ++ metricName = name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); + } +- +- protected static MetricName chooseName(final String explicitName, final boolean absolute, final ResourceMethod method, +- final String... suffixes) { +- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); +- MetricName metricName; +- if (explicitName != null && !explicitName.isEmpty()) { +- metricName = absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); +- } else { +- metricName = name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); +- } +- for (String suffix : suffixes) { +- metricName = metricName.resolve(suffix); +- } +- return metricName; ++ for (String suffix : suffixes) { ++ metricName = metricName.resolve(suffix); + } ++ return metricName; ++ } + +- private static class EventTypeAndMethod { ++ private static class EventTypeAndMethod { + +- private final RequestEvent.Type type; +- private final Method method; +- +- private EventTypeAndMethod(RequestEvent.Type type, Method method) { +- this.type = type; +- this.method = method; +- } +- +- static EventTypeAndMethod requestMethodStart(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); +- } ++ private final RequestEvent.Type type; ++ private final Method method; + +- static EventTypeAndMethod requestMatched(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); +- } ++ private EventTypeAndMethod(RequestEvent.Type type, Method method) { ++ this.type = type; ++ this.method = method; ++ } + +- static EventTypeAndMethod respFiltersStart(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); +- } ++ static EventTypeAndMethod requestMethodStart(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); ++ } + +- static EventTypeAndMethod finished(Method method) { +- return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); +- } ++ static EventTypeAndMethod requestMatched(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); ++ } + +- @Override +- public boolean equals(Object o) { +- if (this == o) { +- return true; +- } +- if (o == null || getClass() != o.getClass()) { +- return false; +- } ++ static EventTypeAndMethod respFiltersStart(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); ++ } + +- EventTypeAndMethod that = (EventTypeAndMethod) o; ++ static EventTypeAndMethod finished(Method method) { ++ return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); ++ } + +- if (type != that.type) { +- return false; +- } +- return method.equals(that.method); +- } ++ @Override ++ public boolean equals(Object o) { ++ if (this == o) { ++ return true; ++ } ++ if (o == null || getClass() != o.getClass()) { ++ return false; ++ } ++ ++ EventTypeAndMethod that = (EventTypeAndMethod) o; ++ ++ if (type != that.type) { ++ return false; ++ } ++ return method.equals(that.method); ++ } + +- @Override +- public int hashCode() { +- int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; +- } ++ @Override ++ public int hashCode() { ++ int result = type.hashCode(); ++ return 31 * result + method.hashCode(); + } ++ } + } +--- a/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/MetricsFeature.java ++++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/MetricsFeature.java +@@ -7,91 +7,96 @@ import io.dropwizard.metrics5.Reservoir; + import io.dropwizard.metrics5.SharedMetricRegistries; + import jakarta.ws.rs.core.Feature; + import jakarta.ws.rs.core.FeatureContext; +- + import java.util.function.Supplier; + + /** +- * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} +- * for recording request events. ++ * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} for ++ * recording request events. + */ + public class MetricsFeature implements Feature { + +- private final MetricRegistry registry; +- private final Clock clock; +- private final boolean trackFilters; +- private final Supplier reservoirSupplier; ++ private final MetricRegistry registry; ++ private final Clock clock; ++ private final boolean trackFilters; ++ private final Supplier reservoirSupplier; + +- /* +- * @param registry the metrics registry where the metrics will be stored +- */ +- public MetricsFeature(MetricRegistry registry) { +- this(registry, Clock.defaultClock()); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ */ ++ public MetricsFeature(MetricRegistry registry) { ++ this(registry, Clock.defaultClock()); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. +- */ +- public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { +- this(registry, Clock.defaultClock(), false, reservoirSupplier); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. ++ */ ++ public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { ++ this(registry, Clock.defaultClock(), false, reservoirSupplier); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- */ +- public MetricsFeature(MetricRegistry registry, Clock clock) { +- this(registry, clock, false); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ */ ++ public MetricsFeature(MetricRegistry registry, Clock clock) { ++ this(registry, clock, false); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- */ +- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { +- this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be tracked ++ */ ++ public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { ++ this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); ++ } + +- /* +- * @param registry the metrics registry where the metrics will be stored +- * @param clock the {@link Clock} to track time (used mostly in testing) in timers +- * @param trackFilters whether the processing time for request and response filters should be tracked +- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. +- */ +- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters, Supplier reservoirSupplier) { +- this.registry = registry; +- this.clock = clock; +- this.trackFilters = trackFilters; +- this.reservoirSupplier = reservoirSupplier; +- } ++ /* ++ * @param registry the metrics registry where the metrics will be stored ++ * @param clock the {@link Clock} to track time (used mostly in testing) in timers ++ * @param trackFilters whether the processing time for request and response filters should be tracked ++ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. ++ */ ++ public MetricsFeature( ++ MetricRegistry registry, ++ Clock clock, ++ boolean trackFilters, ++ Supplier reservoirSupplier) { ++ this.registry = registry; ++ this.clock = clock; ++ this.trackFilters = trackFilters; ++ this.reservoirSupplier = reservoirSupplier; ++ } + +- public MetricsFeature(String registryName) { +- this(SharedMetricRegistries.getOrCreate(registryName)); +- } ++ public MetricsFeature(String registryName) { ++ this(SharedMetricRegistries.getOrCreate(registryName)); ++ } + +- /** +- * A call-back method called when the feature is to be enabled in a given +- * runtime configuration scope. +- *

    +- * The responsibility of the feature is to properly update the supplied runtime configuration context +- * and return {@code true} if the feature was successfully enabled or {@code false} otherwise. +- *

    +- * Note that under some circumstances the feature may decide not to enable itself, which +- * is indicated by returning {@code false}. In such case the configuration context does +- * not add the feature to the collection of enabled features and a subsequent call to +- * {@link jakarta.ws.rs.core.Configuration#isEnabled(Feature)} or +- * {@link jakarta.ws.rs.core.Configuration#isEnabled(Class)} method +- * would return {@code false}. +- *

    +- * +- * @param context configurable context in which the feature should be enabled. +- * @return {@code true} if the feature was successfully enabled, {@code false} +- * otherwise. +- */ +- @Override +- public boolean configure(FeatureContext context) { +- context.register(new InstrumentedResourceMethodApplicationListener(registry, clock, trackFilters, reservoirSupplier)); +- return true; +- } ++ /** ++ * A call-back method called when the feature is to be enabled in a given runtime configuration ++ * scope. ++ * ++ *

    The responsibility of the feature is to properly update the supplied runtime configuration ++ * context and return {@code true} if the feature was successfully enabled or {@code false} ++ * otherwise. ++ * ++ *

    Note that under some circumstances the feature may decide not to enable itself, which is ++ * indicated by returning {@code false}. In such case the configuration context does not add the ++ * feature to the collection of enabled features and a subsequent call to {@link ++ * jakarta.ws.rs.core.Configuration#isEnabled(Feature)} or {@link ++ * jakarta.ws.rs.core.Configuration#isEnabled(Class)} method would return {@code false}. ++ * ++ *

    ++ * ++ * @param context configurable context in which the feature should be enabled. ++ * @return {@code true} if the feature was successfully enabled, {@code false} otherwise. ++ */ ++ @Override ++ public boolean configure(FeatureContext context) { ++ context.register( ++ new InstrumentedResourceMethodApplicationListener( ++ registry, clock, trackFilters, reservoirSupplier)); ++ return true; ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java +@@ -1,44 +1,44 @@ + package io.dropwizard.metrics5.jersey31; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.UniformReservoir; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceTimedPerClass; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +- +-class CustomReservoirImplementationTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } ++final class CustomReservoirImplementationTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- private MetricRegistry registry; ++ private MetricRegistry registry; + +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- return new ResourceConfig() ++ return new ResourceConfig() + .register(new MetricsFeature(this.registry, UniformReservoir::new)) + .register(InstrumentedResourceTimedPerClass.class); +- } ++ } + +- @Test +- void timerHistogramIsUsingCustomReservoirImplementation() { +- assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); ++ @Test ++ void timerHistogramIsUsingCustomReservoirImplementation() { ++ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); + +- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); +- assertThat(timer) ++ final Timer timer = ++ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); ++ assertThat(timer) + .extracting("histogram") + .extracting("reservoir") + .isInstanceOf(UniformReservoir.class); +- } ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java +@@ -1,162 +1,137 @@ + package io.dropwizard.metrics5.jersey31; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedFilteredResource; + import io.dropwizard.metrics5.jersey31.resources.TestRequestFilter; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} with filter tracking ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} with filter tracking + */ +-class SingletonFilterMetricsJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- private TestClock testClock; +- +- @Override +- protected Application configure() { +- registry = new MetricRegistry(); +- testClock = new TestClock(); +- ResourceConfig config = new ResourceConfig(); +- config = config.register(new MetricsFeature(this.registry, testClock, true)); +- config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; +- } +- +- @BeforeEach +- void resetClock() { +- testClock.tick = 0; +- } +- +- @Test +- void timedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); +- } +- +- @Test +- void explicitNamesAreTimed() { +- assertThat(target("named") +- .request() +- .get(String.class)) +- .isEqualTo("fancy"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); +- } +- +- @Test +- void absoluteNamesAreTimed() { +- assertThat(target("absolute") +- .request() +- .get(String.class)) +- .isEqualTo("absolute"); +- +- final Timer timer = registry.timer("absolutelyFancy"); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); +- } +- +- @Test +- void requestFiltersOfTimedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); +- } +- +- @Test +- void responseFiltersOfTimedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- } +- +- @Test +- void totalTimeOfTimedMethodsIsTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); +- } +- +- @Test +- void requestFiltersOfNamedMethodsAreTimed() { +- assertThat(target("named") +- .request() +- .get(String.class)) +- .isEqualTo("fancy"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); +- +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); +- } +- +- @Test +- void requestFiltersOfAbsoluteMethodsAreTimed() { +- assertThat(target("absolute") +- .request() +- .get(String.class)) +- .isEqualTo("absolute"); +- +- final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); +- } +- +- @Test +- void subResourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); +- +- final Timer timer = registry.timer(name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, +- "timed")); +- assertThat(timer.getCount()).isEqualTo(1); +- +- } ++final class SingletonFilterMetricsJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } ++ ++ private MetricRegistry registry; ++ ++ private TestClock testClock; ++ ++ @Override ++ protected Application configure() { ++ registry = new MetricRegistry(); ++ testClock = new TestClock(); ++ ResourceConfig config = new ResourceConfig(); ++ config = config.register(new MetricsFeature(this.registry, testClock, true)); ++ config = config.register(new TestRequestFilter(testClock)); ++ return config.register(new InstrumentedFilteredResource(testClock)); ++ } ++ ++ @BeforeEach ++ void resetClock() { ++ testClock.tick = 0; ++ } ++ ++ @Test ++ void timedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); ++ } ++ ++ @Test ++ void explicitNamesAreTimed() { ++ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); ++ ++ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); ++ } ++ ++ @Test ++ void absoluteNamesAreTimed() { ++ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); ++ ++ final Timer timer = registry.timer("absolutelyFancy"); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); ++ } ++ ++ @Test ++ void requestFiltersOfTimedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); ++ } ++ ++ @Test ++ void responseFiltersOfTimedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void totalTimeOfTimedMethodsIsTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); ++ } ++ ++ @Test ++ void requestFiltersOfNamedMethodsAreTimed() { ++ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); ++ ++ final Timer timer = ++ registry.timer( ++ name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); ++ ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); ++ } ++ ++ @Test ++ void requestFiltersOfAbsoluteMethodsAreTimed() { ++ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); ++ ++ final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); ++ } ++ ++ @Test ++ void subResourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); ++ ++ final Timer timer = ++ registry.timer( ++ name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, "timed")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -1,98 +1,92 @@ + package io.dropwizard.metrics5.jersey31; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceExceptionMeteredPerClass; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceExceptionMeteredPerClass; + import jakarta.ws.rs.ProcessingException; + import jakarta.ws.rs.core.Application; +-import org.glassfish.jersey.server.ResourceConfig; +-import org.glassfish.jersey.test.JerseyTest; +-import org.junit.jupiter.api.Test; +- + import java.io.IOException; + import java.util.logging.Level; + import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++import org.glassfish.jersey.server.ResourceConfig; ++import org.glassfish.jersey.test.JerseyTest; ++import org.junit.jupiter.api.Test; + + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } ++final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- private MetricRegistry registry; ++ private MetricRegistry registry; + +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- ResourceConfig config = new ResourceConfig(); ++ ResourceConfig config = new ResourceConfig(); + +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); ++ } + +- return config; +- } ++ @Test ++ void exceptionMeteredMethodsAreExceptionMetered() { ++ final Meter meter = ++ registry.meter( ++ name( ++ InstrumentedResourceExceptionMeteredPerClass.class, ++ "exceptionMetered", ++ "exceptions")); + +- @Test +- void exceptionMeteredMethodsAreExceptionMetered() { +- final Meter meter = registry.meter(name(InstrumentedResourceExceptionMeteredPerClass.class, +- "exceptionMetered", +- "exceptions")); ++ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(target("exception-metered") +- .request() +- .get(String.class)) +- .isEqualTo("fuh"); +- +- assertThat(meter.getCount()).isZero(); +- +- try { +- target("exception-metered") +- .queryParam("splode", true) +- .request() +- .get(String.class); ++ assertThat(meter.getCount()).isEqualTo(0); + +- failBecauseExceptionWasNotThrown(ProcessingException.class); +- } catch (ProcessingException e) { +- assertThat(e.getCause()).isInstanceOf(IOException.class); +- } ++ try { ++ target("exception-metered").queryParam("splode", true).request().get(String.class); + +- assertThat(meter.getCount()).isEqualTo(1); ++ failBecauseExceptionWasNotThrown(ProcessingException.class); ++ } catch (ProcessingException e) { ++ assertThat(e.getCause()).isInstanceOf(IOException.class); + } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- final Meter meter = registry.meter(name(InstrumentedSubResourceExceptionMeteredPerClass.class, +- "exceptionMetered", +- "exceptions")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + +- assertThat(target("subresource/exception-metered") +- .request() +- .get(String.class)) +- .isEqualTo("fuh"); ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ final Meter meter = ++ registry.meter( ++ name( ++ InstrumentedSubResourceExceptionMeteredPerClass.class, ++ "exceptionMetered", ++ "exceptions")); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(target("subresource/exception-metered").request().get(String.class)) ++ .isEqualTo("fuh"); + +- try { +- target("subresource/exception-metered") +- .queryParam("splode", true) +- .request() +- .get(String.class); ++ assertThat(meter.getCount()).isEqualTo(0); + +- failBecauseExceptionWasNotThrown(ProcessingException.class); +- } catch (ProcessingException e) { +- assertThat(e.getCause()).isInstanceOf(IOException.class); +- } ++ try { ++ target("subresource/exception-metered") ++ .queryParam("splode", true) ++ .request() ++ .get(String.class); + +- assertThat(meter.getCount()).isEqualTo(1); ++ failBecauseExceptionWasNotThrown(ProcessingException.class); ++ } catch (ProcessingException e) { ++ assertThat(e.getCause()).isInstanceOf(IOException.class); + } + ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.jersey31; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; +@@ -9,214 +13,167 @@ import jakarta.ws.rs.NotFoundException; + import jakarta.ws.rs.ProcessingException; + import jakarta.ws.rs.core.Application; + import jakarta.ws.rs.core.Response; ++import java.io.IOException; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.client.ClientResponse; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.io.IOException; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); +- +- ResourceConfig config = new ResourceConfig(); +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; +- } ++final class SingletonMetricsJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- @Test +- void timedMethodsAreTimed() { +- assertThat(target("timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ private MetricRegistry registry; + +- final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- assertThat(timer.getCount()).isEqualTo(1); +- } +- +- @Test +- void meteredMethodsAreMetered() { +- assertThat(target("metered") +- .request() +- .get(String.class)) +- .isEqualTo("woo"); ++ ResourceConfig config = new ResourceConfig(); ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResource.class); ++ } + +- final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); +- assertThat(meter.getCount()).isEqualTo(1); +- } ++ @Test ++ void timedMethodsAreTimed() { ++ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); + +- @Test +- void exceptionMeteredMethodsAreExceptionMetered() { +- final Meter meter = registry.meter(name(InstrumentedResource.class, +- "exceptionMetered", +- "exceptions")); ++ final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); + +- assertThat(target("exception-metered") +- .request() +- .get(String.class)) +- .isEqualTo("fuh"); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + +- assertThat(meter.getCount()).isZero(); ++ @Test ++ void meteredMethodsAreMetered() { ++ assertThat(target("metered").request().get(String.class)).isEqualTo("woo"); + +- try { +- target("exception-metered") +- .queryParam("splode", true) +- .request() +- .get(String.class); ++ final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + +- failBecauseExceptionWasNotThrown(ProcessingException.class); +- } catch (ProcessingException e) { +- assertThat(e.getCause()).isInstanceOf(IOException.class); +- } ++ @Test ++ void exceptionMeteredMethodsAreExceptionMetered() { ++ final Meter meter = ++ registry.meter(name(InstrumentedResource.class, "exceptionMetered", "exceptions")); + +- assertThat(meter.getCount()).isEqualTo(1); +- } ++ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- @Test +- void responseMeteredMethodsAreMetered() { +- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, +- "response2xxMetered", +- "2xx-responses")); +- final Meter meter4xx = registry.meter(name(InstrumentedResource.class, +- "response4xxMetered", +- "4xx-responses")); +- final Meter meter5xx = registry.meter(name(InstrumentedResource.class, +- "response5xxMetered", +- "5xx-responses")); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(target("response-2xx-metered") +- .request() +- .get().getStatus()) +- .isEqualTo(200); ++ assertThat(meter.getCount()).isEqualTo(0); + +- assertThat(meter4xx.getCount()).isZero(); +- assertThat(target("response-4xx-metered") +- .request() +- .get().getStatus()) +- .isEqualTo(400); +- +- assertThat(meter5xx.getCount()).isZero(); +- assertThat(target("response-5xx-metered") +- .request() +- .get().getStatus()) +- .isEqualTo(500); +- } +- +- @Test +- public void responseMeteredMethodsAreMeteredWithCoarseLevel() { +- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, +- "responseMeteredCoarse", +- "2xx-responses")); +- final Meter meter200 = registry.meter(name(InstrumentedResource.class, +- "responseMeteredCoarse", +- "200-responses")); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(target("response-metered-coarse") +- .request() +- .get().getStatus()) +- .isEqualTo(200); ++ try { ++ target("exception-metered").queryParam("splode", true).request().get(String.class); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isZero(); ++ failBecauseExceptionWasNotThrown(ProcessingException.class); ++ } catch (ProcessingException e) { ++ assertThat(e.getCause()).isInstanceOf(IOException.class); + } + +- @Test +- public void responseMeteredMethodsAreMeteredWithDetailedLevel() { +- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, +- "responseMeteredDetailed", +- "2xx-responses")); +- final Meter meter200 = registry.meter(name(InstrumentedResource.class, +- "responseMeteredDetailed", +- "200-responses")); +- final Meter meter201 = registry.meter(name(InstrumentedResource.class, +- "responseMeteredDetailed", +- "201-responses")); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); +- assertThat(target("response-metered-detailed") +- .request() +- .get().getStatus()) +- .isEqualTo(200); +- assertThat(target("response-metered-detailed") ++ assertThat(meter.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredMethodsAreMetered() { ++ final Meter meter2xx = ++ registry.meter(name(InstrumentedResource.class, "response2xxMetered", "2xx-responses")); ++ final Meter meter4xx = ++ registry.meter(name(InstrumentedResource.class, "response4xxMetered", "4xx-responses")); ++ final Meter meter5xx = ++ registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); ++ ++ assertThat(meter4xx.getCount()).isEqualTo(0); ++ assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); ++ ++ assertThat(meter5xx.getCount()).isEqualTo(0); ++ assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); ++ } ++ ++ @Test ++ void responseMeteredMethodsAreMeteredWithCoarseLevel() { ++ final Meter meter2xx = ++ registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "2xx-responses")); ++ final Meter meter200 = ++ registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void responseMeteredMethodsAreMeteredWithDetailedLevel() { ++ final Meter meter2xx = ++ registry.meter( ++ name(InstrumentedResource.class, "responseMeteredDetailed", "2xx-responses")); ++ final Meter meter200 = ++ registry.meter( ++ name(InstrumentedResource.class, "responseMeteredDetailed", "200-responses")); ++ final Meter meter201 = ++ registry.meter( ++ name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); ++ assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); ++ assertThat( ++ target("response-metered-detailed") + .queryParam("status_code", 201) + .request() +- .get().getStatus()) +- .isEqualTo(201); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); +- } +- +- @Test +- public void responseMeteredMethodsAreMeteredWithAllLevel() { +- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, +- "responseMeteredAll", +- "2xx-responses")); +- final Meter meter200 = registry.meter(name(InstrumentedResource.class, +- "responseMeteredAll", +- "200-responses")); +- +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(target("response-metered-all") +- .request() +- .get().getStatus()) +- .isEqualTo(200); +- +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); +- } +- +- @Test +- void testResourceNotFound() { +- final Response response = target().path("not-found").request().get(); +- assertThat(response.getStatus()).isEqualTo(404); +- +- try { +- target().path("not-found").request().get(ClientResponse.class); +- failBecauseExceptionWasNotThrown(NotFoundException.class); +- } catch (NotFoundException e) { +- assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); +- } ++ .get() ++ .getStatus()) ++ .isEqualTo(201); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredMethodsAreMeteredWithAllLevel() { ++ final Meter meter2xx = ++ registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); ++ final Meter meter200 = ++ registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); ++ ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void resourceNotFound() { ++ final Response response = target().path("not-found").request().get(); ++ assertThat(response.getStatus()).isEqualTo(404); ++ ++ try { ++ target().path("not-found").request().get(ClientResponse.class); ++ failBecauseExceptionWasNotThrown(NotFoundException.class); ++ } catch (NotFoundException e) { ++ assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); + } ++ } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/timed") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); + +- final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); +- assertThat(timer.getCount()).isEqualTo(1); +- +- } ++ final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -1,66 +1,56 @@ + package io.dropwizard.metrics5.jersey31; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceMeteredPerClass; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceMeteredPerClass; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); +- +- ResourceConfig config = new ResourceConfig(); +- +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); ++final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- return config; +- } ++ private MetricRegistry registry; + +- @Test +- void meteredPerClassMethodsAreMetered() { +- assertThat(target("meteredPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- final Meter meter = registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); ++ ResourceConfig config = new ResourceConfig(); + +- assertThat(meter.getCount()).isEqualTo(1); +- } ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResourceMeteredPerClass.class); ++ } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/meteredPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Test ++ void meteredPerClassMethodsAreMetered() { ++ assertThat(target("meteredPerClass").request().get(String.class)).isEqualTo("yay"); + +- final Meter meter = registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); +- assertThat(meter.getCount()).isEqualTo(1); ++ final Meter meter = ++ registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); + +- } ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/meteredPerClass").request().get(String.class)).isEqualTo("yay"); + ++ final Meter meter = ++ registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); ++ assertThat(meter.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -1,147 +1,150 @@ + package io.dropwizard.metrics5.jersey31; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.jersey31.exception.mapper.TestExceptionMapper; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceResponseMeteredPerClass; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceResponseMeteredPerClass; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } ++final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- private MetricRegistry registry; ++ private MetricRegistry registry; + +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + ++ ResourceConfig config = new ResourceConfig(); + +- ResourceConfig config = new ResourceConfig(); ++ config = config.register(new MetricsFeature(this.registry)); ++ config = config.register(InstrumentedResourceResponseMeteredPerClass.class); ++ return config.register(new TestExceptionMapper()); ++ } + +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; +- } +- +- @Test +- void responseMetered2xxPerClassMethodsAreMetered() { +- assertThat(target("responseMetered2xxPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(200); ++ @Test ++ void responseMetered2xxPerClassMethodsAreMetered() { ++ assertThat(target("responseMetered2xxPerClass").request().get().getStatus()).isEqualTo(200); + +- final Meter meter2xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMetered2xxPerClass", +- "2xx-responses")); ++ final Meter meter2xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMetered2xxPerClass", ++ "2xx-responses")); + +- assertThat(meter2xx.getCount()).isEqualTo(1); +- } ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ } + +- @Test +- void responseMetered4xxPerClassMethodsAreMetered() { +- assertThat(target("responseMetered4xxPerClass") +- .request() +- .get().getStatus()) ++ @Test ++ void responseMetered4xxPerClassMethodsAreMetered() { ++ assertThat(target("responseMetered4xxPerClass").request().get().getStatus()).isEqualTo(400); ++ assertThat(target("responseMeteredBadRequestPerClass").request().get().getStatus()) + .isEqualTo(400); +- assertThat(target("responseMeteredBadRequestPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(400); +- +- final Meter meter4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMetered4xxPerClass", +- "4xx-responses")); +- final Meter meterException4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMeteredBadRequestPerClass", +- "4xx-responses")); + +- assertThat(meter4xx.getCount()).isEqualTo(1); +- assertThat(meterException4xx.getCount()).isEqualTo(1); +- } +- +- @Test +- void responseMetered5xxPerClassMethodsAreMetered() { +- assertThat(target("responseMetered5xxPerClass") +- .request() +- .get().getStatus()) ++ final Meter meter4xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMetered4xxPerClass", ++ "4xx-responses")); ++ final Meter meterException4xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMeteredBadRequestPerClass", ++ "4xx-responses")); ++ ++ assertThat(meter4xx.getCount()).isEqualTo(1); ++ assertThat(meterException4xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMetered5xxPerClassMethodsAreMetered() { ++ assertThat(target("responseMetered5xxPerClass").request().get().getStatus()).isEqualTo(500); ++ ++ final Meter meter5xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMetered5xxPerClass", ++ "5xx-responses")); ++ ++ assertThat(meter5xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredMappedExceptionPerClassMethodsAreMetered() { ++ assertThat(target("responseMeteredTestExceptionPerClass").request().get().getStatus()) + .isEqualTo(500); + +- final Meter meter5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMetered5xxPerClass", +- "5xx-responses")); +- +- assertThat(meter5xx.getCount()).isEqualTo(1); ++ final Meter meterTestException = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMeteredTestExceptionPerClass", ++ "5xx-responses")); ++ ++ assertThat(meterTestException.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { ++ try { ++ target("responseMeteredRuntimeExceptionPerClass").request().get(); ++ fail("expected RuntimeException"); ++ } catch (Exception e) { ++ assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + } + +- @Test +- void responseMeteredMappedExceptionPerClassMethodsAreMetered() { +- assertThat(target("responseMeteredTestExceptionPerClass") +- .request() +- .get().getStatus()) +- .isEqualTo(500); +- +- final Meter meterTestException = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMeteredTestExceptionPerClass", +- "5xx-responses")); +- +- assertThat(meterTestException.getCount()).isEqualTo(1); +- } +- +- @Test +- void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { +- try { +- target("responseMeteredRuntimeExceptionPerClass") +- .request() +- .get(); +- fail("expected RuntimeException"); +- } catch (Exception e) { +- assertThat(e.getCause()).isInstanceOf(RuntimeException.class); +- } +- +- final Meter meterException5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, +- "responseMeteredRuntimeExceptionPerClass", +- "5xx-responses")); +- +- assertThat(meterException5xx.getCount()).isEqualTo(1); +- } +- +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- final Meter meter2xx = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, ++ final Meter meterException5xx = ++ registry.meter( ++ name( ++ InstrumentedResourceResponseMeteredPerClass.class, ++ "responseMeteredRuntimeExceptionPerClass", ++ "5xx-responses")); ++ ++ assertThat(meterException5xx.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ final Meter meter2xx = ++ registry.meter( ++ name( ++ InstrumentedSubResourceResponseMeteredPerClass.class, + "responseMeteredPerClass", + "2xx-responses")); +- final Meter meter200 = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, ++ final Meter meter200 = ++ registry.meter( ++ name( ++ InstrumentedSubResourceResponseMeteredPerClass.class, + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + +- assertThat(target("subresource/responseMeteredPerClass") +- .request() +- .get().getStatus()) ++ assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); +- } ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java +@@ -1,66 +1,56 @@ + package io.dropwizard.metrics5.jersey31; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceTimedPerClass; + import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceTimedPerClass; + import jakarta.ws.rs.core.Application; ++import java.util.logging.Level; ++import java.util.logging.Logger; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static org.assertj.core.api.Assertions.assertThat; +- + /** +- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton +- * in a Jersey {@link ResourceConfig} ++ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a ++ * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { +- static { +- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); +- } +- +- private MetricRegistry registry; +- +- @Override +- protected Application configure() { +- this.registry = new MetricRegistry(); +- +- ResourceConfig config = new ResourceConfig(); +- +- config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); ++final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { ++ static { ++ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); ++ } + +- return config; +- } ++ private MetricRegistry registry; + +- @Test +- void timedPerClassMethodsAreTimed() { +- assertThat(target("timedPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Override ++ protected Application configure() { ++ this.registry = new MetricRegistry(); + +- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); ++ ResourceConfig config = new ResourceConfig(); + +- assertThat(timer.getCount()).isEqualTo(1); +- } ++ config = config.register(new MetricsFeature(this.registry)); ++ return config.register(InstrumentedResourceTimedPerClass.class); ++ } + +- @Test +- void subresourcesFromLocatorsRegisterMetrics() { +- assertThat(target("subresource/timedPerClass") +- .request() +- .get(String.class)) +- .isEqualTo("yay"); ++ @Test ++ void timedPerClassMethodsAreTimed() { ++ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); + +- final Timer timer = registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); +- assertThat(timer.getCount()).isEqualTo(1); ++ final Timer timer = ++ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); + +- } ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + ++ @Test ++ void subresourcesFromLocatorsRegisterMetrics() { ++ assertThat(target("subresource/timedPerClass").request().get(String.class)).isEqualTo("yay"); + ++ final Timer timer = ++ registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/TestClock.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/TestClock.java +@@ -4,10 +4,10 @@ import io.dropwizard.metrics5.Clock; + + public class TestClock extends Clock { + +- public long tick; ++ public long tick; + +- @Override +- public long getTick() { +- return tick; +- } ++ @Override ++ public long getTick() { ++ return tick; ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/exception/TestException.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/exception/TestException.java +@@ -1,9 +1,9 @@ + package io.dropwizard.metrics5.jersey31.exception; + + public class TestException extends RuntimeException { +- private static final long serialVersionUID = 1L; ++ private static final long serialVersionUID = 1L; + +- public TestException(String message) { +- super(message); +- } ++ public TestException(String message) { ++ super(message); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/exception/mapper/TestExceptionMapper.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/exception/mapper/TestExceptionMapper.java +@@ -7,8 +7,8 @@ import jakarta.ws.rs.ext.Provider; + + @Provider + public class TestExceptionMapper implements ExceptionMapper { +- @Override +- public Response toResponse(TestException exception) { +- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +- } ++ @Override ++ public Response toResponse(TestException exception) { ++ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java +@@ -11,51 +11,50 @@ import jakarta.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedFilteredResource { + +- private final TestClock testClock; +- +- public InstrumentedFilteredResource(TestClock testClock) { +- this.testClock = testClock; +- } ++ private final TestClock testClock; ++ ++ public InstrumentedFilteredResource(TestClock testClock) { ++ this.testClock = testClock; ++ } ++ ++ @GET ++ @Path("/timed") ++ @Timed ++ public String timed() { ++ testClock.tick++; ++ return "yay"; ++ } ++ ++ @GET ++ @Path("/named") ++ @Timed(name = "fancyName") ++ public String named() { ++ testClock.tick++; ++ return "fancy"; ++ } ++ ++ @GET ++ @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) ++ public String absolute() { ++ testClock.tick++; ++ return "absolute"; ++ } ++ ++ @Path("/subresource") ++ public InstrumentedFilteredSubResource locateSubResource() { ++ return new InstrumentedFilteredSubResource(); ++ } ++ ++ @Produces(MediaType.TEXT_PLAIN) ++ public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { +- testClock.tick++; +- return "yay"; +- } +- +- @GET +- @Timed(name = "fancyName") +- @Path("/named") +- public String named() { +- testClock.tick++; +- return "fancy"; +- } +- +- @GET +- @Timed(name = "absolutelyFancy", absolute = true) +- @Path("/absolute") +- public String absolute() { +- testClock.tick++; +- return "absolute"; +- } +- +- @Path("/subresource") +- public InstrumentedFilteredSubResource locateSubResource() { +- return new InstrumentedFilteredSubResource(); +- } +- +- @Produces(MediaType.TEXT_PLAIN) +- public class InstrumentedFilteredSubResource { +- +- @GET +- @Timed +- @Path("/timed") +- public String timed() { +- testClock.tick += 2; +- return "yay"; +- } +- ++ testClock.tick += 2; ++ return "yay"; + } ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.jersey31.resources; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++ + import io.dropwizard.metrics5.annotation.ExceptionMetered; + import io.dropwizard.metrics5.annotation.Metered; + import io.dropwizard.metrics5.annotation.ResponseMetered; +@@ -11,84 +15,83 @@ import jakarta.ws.rs.Produces; + import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.core.MediaType; + import jakarta.ws.rs.core.Response; +- + import java.io.IOException; + +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; +- + @Path("/") + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { +- @GET +- @Timed +- @Path("/timed") +- public String timed() { +- return "yay"; +- } ++ @GET ++ @Path("/timed") ++ @Timed ++ public String timed() { ++ return "yay"; ++ } + +- @GET +- @Metered +- @Path("/metered") +- public String metered() { +- return "woo"; +- } ++ @GET ++ @Metered ++ @Path("/metered") ++ public String metered() { ++ return "woo"; ++ } + +- @GET +- @ExceptionMetered(cause = IOException.class) +- @Path("/exception-metered") +- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { +- if (splode) { +- throw new IOException("AUGH"); +- } +- return "fuh"; ++ @ExceptionMetered(cause = IOException.class) ++ @GET ++ @Path("/exception-metered") ++ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) ++ throws IOException { ++ if (splode) { ++ throw new IOException("AUGH"); + } ++ return "fuh"; ++ } + +- @GET +- @ResponseMetered(level = DETAILED) +- @Path("/response-metered-detailed") +- public Response responseMeteredDetailed(@QueryParam("status_code") @DefaultValue("200") int statusCode) { +- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +- } ++ @GET ++ @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) ++ public Response responseMeteredDetailed( ++ @QueryParam("status_code") @DefaultValue("200") int statusCode) { ++ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ++ } + +- @GET +- @ResponseMetered(level = COARSE) +- @Path("/response-metered-coarse") +- public Response responseMeteredCoarse(@QueryParam("status_code") @DefaultValue("200") int statusCode) { +- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +- } ++ @GET ++ @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) ++ public Response responseMeteredCoarse( ++ @QueryParam("status_code") @DefaultValue("200") int statusCode) { ++ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ++ } + +- @GET +- @ResponseMetered(level = ALL) +- @Path("/response-metered-all") +- public Response responseMeteredAll(@QueryParam("status_code") @DefaultValue("200") int statusCode) { +- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); +- } ++ @GET ++ @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) ++ public Response responseMeteredAll( ++ @QueryParam("status_code") @DefaultValue("200") int statusCode) { ++ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); ++ } + +- @GET +- @ResponseMetered +- @Path("/response-2xx-metered") +- public Response response2xxMetered() { +- return Response.ok().build(); +- } ++ @GET ++ @Path("/response-2xx-metered") ++ @ResponseMetered ++ public Response response2xxMetered() { ++ return Response.ok().build(); ++ } + +- @GET +- @ResponseMetered +- @Path("/response-4xx-metered") +- public Response response4xxMetered() { +- return Response.status(Response.Status.BAD_REQUEST).build(); +- } ++ @GET ++ @Path("/response-4xx-metered") ++ @ResponseMetered ++ public Response response4xxMetered() { ++ return Response.status(Response.Status.BAD_REQUEST).build(); ++ } + +- @GET +- @ResponseMetered +- @Path("/response-5xx-metered") +- public Response response5xxMetered() { +- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +- } ++ @GET ++ @Path("/response-5xx-metered") ++ @ResponseMetered ++ public Response response5xxMetered() { ++ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); ++ } + +- @Path("/subresource") +- public InstrumentedSubResource locateSubResource() { +- return new InstrumentedSubResource(); +- } ++ @Path("/subresource") ++ public InstrumentedSubResource locateSubResource() { ++ return new InstrumentedSubResource(); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceExceptionMeteredPerClass.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceExceptionMeteredPerClass.java +@@ -7,7 +7,6 @@ import jakarta.ws.rs.Path; + import jakarta.ws.rs.Produces; + import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.core.MediaType; +- + import java.io.IOException; + + @ExceptionMetered(cause = IOException.class) +@@ -15,18 +14,18 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceExceptionMeteredPerClass { + +- @GET +- @Path("/exception-metered") +- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { +- if (splode) { +- throw new IOException("AUGH"); +- } +- return "fuh"; +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { +- return new InstrumentedSubResourceExceptionMeteredPerClass(); ++ @GET ++ @Path("/exception-metered") ++ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) ++ throws IOException { ++ if (splode) { ++ throw new IOException("AUGH"); + } ++ return "fuh"; ++ } + ++ @Path("/subresource") ++ public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { ++ return new InstrumentedSubResourceExceptionMeteredPerClass(); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceMeteredPerClass.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceMeteredPerClass.java +@@ -11,15 +11,14 @@ import jakarta.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceMeteredPerClass { + +- @GET +- @Path("/meteredPerClass") +- public String meteredPerClass() { +- return "yay"; +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceMeteredPerClass locateSubResource() { +- return new InstrumentedSubResourceMeteredPerClass(); +- } ++ @GET ++ @Path("/meteredPerClass") ++ public String meteredPerClass() { ++ return "yay"; ++ } + ++ @Path("/subresource") ++ public InstrumentedSubResourceMeteredPerClass locateSubResource() { ++ return new InstrumentedSubResourceMeteredPerClass(); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceResponseMeteredPerClass.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceResponseMeteredPerClass.java +@@ -14,45 +14,44 @@ import jakarta.ws.rs.core.Response; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceResponseMeteredPerClass { + +- @GET +- @Path("/responseMetered2xxPerClass") +- public Response responseMetered2xxPerClass() { +- return Response.ok().build(); +- } +- +- @GET +- @Path("/responseMetered4xxPerClass") +- public Response responseMetered4xxPerClass() { +- return Response.status(Response.Status.BAD_REQUEST).build(); +- } +- +- @GET +- @Path("/responseMetered5xxPerClass") +- public Response responseMetered5xxPerClass() { +- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); +- } +- +- @GET +- @Path("/responseMeteredBadRequestPerClass") +- public String responseMeteredBadRequestPerClass() { +- throw new BadRequestException(); +- } +- +- @GET +- @Path("/responseMeteredRuntimeExceptionPerClass") +- public String responseMeteredRuntimeExceptionPerClass() { +- throw new RuntimeException(); +- } +- +- @GET +- @Path("/responseMeteredTestExceptionPerClass") +- public String responseMeteredTestExceptionPerClass() { +- throw new TestException("test"); +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { +- return new InstrumentedSubResourceResponseMeteredPerClass(); +- } +- ++ @GET ++ @Path("/responseMetered2xxPerClass") ++ public Response responseMetered2xxPerClass() { ++ return Response.ok().build(); ++ } ++ ++ @GET ++ @Path("/responseMetered4xxPerClass") ++ public Response responseMetered4xxPerClass() { ++ return Response.status(Response.Status.BAD_REQUEST).build(); ++ } ++ ++ @GET ++ @Path("/responseMetered5xxPerClass") ++ public Response responseMetered5xxPerClass() { ++ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); ++ } ++ ++ @GET ++ @Path("/responseMeteredBadRequestPerClass") ++ public String responseMeteredBadRequestPerClass() { ++ throw new BadRequestException(); ++ } ++ ++ @GET ++ @Path("/responseMeteredRuntimeExceptionPerClass") ++ public String responseMeteredRuntimeExceptionPerClass() { ++ throw new RuntimeException(); ++ } ++ ++ @GET ++ @Path("/responseMeteredTestExceptionPerClass") ++ public String responseMeteredTestExceptionPerClass() { ++ throw new TestException("test"); ++ } ++ ++ @Path("/subresource") ++ public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { ++ return new InstrumentedSubResourceResponseMeteredPerClass(); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceTimedPerClass.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceTimedPerClass.java +@@ -11,15 +11,14 @@ import jakarta.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResourceTimedPerClass { + +- @GET +- @Path("/timedPerClass") +- public String timedPerClass() { +- return "yay"; +- } +- +- @Path("/subresource") +- public InstrumentedSubResourceTimedPerClass locateSubResource() { +- return new InstrumentedSubResourceTimedPerClass(); +- } ++ @GET ++ @Path("/timedPerClass") ++ public String timedPerClass() { ++ return "yay"; ++ } + ++ @Path("/subresource") ++ public InstrumentedSubResourceTimedPerClass locateSubResource() { ++ return new InstrumentedSubResourceTimedPerClass(); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java +@@ -9,11 +9,10 @@ import jakarta.ws.rs.core.MediaType; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResource { + +- @GET +- @Timed +- @Path("/timed") +- public String timed() { +- return "yay"; +- } +- ++ @GET ++ @Path("/timed") ++ @Timed ++ public String timed() { ++ return "yay"; ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceExceptionMeteredPerClass.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceExceptionMeteredPerClass.java +@@ -7,18 +7,18 @@ import jakarta.ws.rs.Path; + import jakarta.ws.rs.Produces; + import jakarta.ws.rs.QueryParam; + import jakarta.ws.rs.core.MediaType; +- + import java.io.IOException; + + @ExceptionMetered(cause = IOException.class) + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceExceptionMeteredPerClass { +- @GET +- @Path("/exception-metered") +- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { +- if (splode) { +- throw new IOException("AUGH"); +- } +- return "fuh"; ++ @GET ++ @Path("/exception-metered") ++ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) ++ throws IOException { ++ if (splode) { ++ throw new IOException("AUGH"); + } ++ return "fuh"; ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceMeteredPerClass.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceMeteredPerClass.java +@@ -9,9 +9,9 @@ import jakarta.ws.rs.core.MediaType; + @Metered + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceMeteredPerClass { +- @GET +- @Path("/meteredPerClass") +- public String meteredPerClass() { +- return "yay"; +- } ++ @GET ++ @Path("/meteredPerClass") ++ public String meteredPerClass() { ++ return "yay"; ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceResponseMeteredPerClass.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceResponseMeteredPerClass.java +@@ -11,9 +11,9 @@ import jakarta.ws.rs.core.Response; + @ResponseMetered(level = ResponseMeteredLevel.ALL) + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceResponseMeteredPerClass { +- @GET +- @Path("/responseMeteredPerClass") +- public Response responseMeteredPerClass() { +- return Response.status(Response.Status.OK).build(); +- } ++ @GET ++ @Path("/responseMeteredPerClass") ++ public Response responseMeteredPerClass() { ++ return Response.status(Response.Status.OK).build(); ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceTimedPerClass.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceTimedPerClass.java +@@ -9,9 +9,9 @@ import jakarta.ws.rs.core.MediaType; + @Timed + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedSubResourceTimedPerClass { +- @GET +- @Path("/timedPerClass") +- public String timedPerClass() { +- return "yay"; +- } ++ @GET ++ @Path("/timedPerClass") ++ public String timedPerClass() { ++ return "yay"; ++ } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/TestRequestFilter.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/TestRequestFilter.java +@@ -3,19 +3,18 @@ package io.dropwizard.metrics5.jersey31.resources; + import io.dropwizard.metrics5.jersey31.TestClock; + import jakarta.ws.rs.container.ContainerRequestContext; + import jakarta.ws.rs.container.ContainerRequestFilter; +- + import java.io.IOException; + + public class TestRequestFilter implements ContainerRequestFilter { + +- private final TestClock testClock; ++ private final TestClock testClock; + +- public TestRequestFilter(TestClock testClock) { +- this.testClock = testClock; +- } ++ public TestRequestFilter(TestClock testClock) { ++ this.testClock = testClock; ++ } + +- @Override +- public void filter(ContainerRequestContext containerRequestContext) throws IOException { +- testClock.tick += 4; +- } ++ @Override ++ public void filter(ContainerRequestContext containerRequestContext) throws IOException { ++ testClock.tick += 4; ++ } + } +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java +@@ -2,62 +2,63 @@ package io.dropwizard.metrics5.jetty10; + + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Timer; ++import java.util.List; + import org.eclipse.jetty.io.Connection; + import org.eclipse.jetty.io.EndPoint; + import org.eclipse.jetty.server.ConnectionFactory; + import org.eclipse.jetty.server.Connector; + import org.eclipse.jetty.util.component.ContainerLifeCycle; + +-import java.util.List; +- + public class InstrumentedConnectionFactory extends ContainerLifeCycle implements ConnectionFactory { +- private final ConnectionFactory connectionFactory; +- private final Timer timer; +- private final Counter counter; +- +- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { +- this(connectionFactory, timer, null); +- } +- +- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer, Counter counter) { +- this.connectionFactory = connectionFactory; +- this.timer = timer; +- this.counter = counter; +- addBean(connectionFactory); +- } +- +- @Override +- public String getProtocol() { +- return connectionFactory.getProtocol(); +- } +- +- @Override +- public List getProtocols() { +- return connectionFactory.getProtocols(); +- } +- +- @Override +- public Connection newConnection(Connector connector, EndPoint endPoint) { +- final Connection connection = connectionFactory.newConnection(connector, endPoint); +- connection.addEventListener(new Connection.Listener() { +- private Timer.Context context; +- +- @Override +- public void onOpened(Connection connection) { +- this.context = timer.time(); +- if (counter != null) { +- counter.inc(); +- } ++ private final ConnectionFactory connectionFactory; ++ private final Timer timer; ++ private final Counter counter; ++ ++ public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { ++ this(connectionFactory, timer, null); ++ } ++ ++ public InstrumentedConnectionFactory( ++ ConnectionFactory connectionFactory, Timer timer, Counter counter) { ++ this.connectionFactory = connectionFactory; ++ this.timer = timer; ++ this.counter = counter; ++ addBean(connectionFactory); ++ } ++ ++ @Override ++ public String getProtocol() { ++ return connectionFactory.getProtocol(); ++ } ++ ++ @Override ++ public List getProtocols() { ++ return connectionFactory.getProtocols(); ++ } ++ ++ @Override ++ public Connection newConnection(Connector connector, EndPoint endPoint) { ++ final Connection connection = connectionFactory.newConnection(connector, endPoint); ++ connection.addEventListener( ++ new Connection.Listener() { ++ private Timer.Context context; ++ ++ @Override ++ public void onOpened(Connection connection) { ++ this.context = timer.time(); ++ if (counter != null) { ++ counter.inc(); + } ++ } + +- @Override +- public void onClosed(Connection connection) { +- context.stop(); +- if (counter != null) { +- counter.dec(); +- } ++ @Override ++ public void onClosed(Connection connection) { ++ context.stop(); ++ if (counter != null) { ++ counter.dec(); + } ++ } + }); +- return connection; +- } ++ return connection; ++ } + } +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java +@@ -1,5 +1,13 @@ + package io.dropwizard.metrics5.jetty10; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; ++ ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -7,439 +15,450 @@ import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.RatioGauge; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; +-import org.eclipse.jetty.http.HttpMethod; +-import org.eclipse.jetty.server.AsyncContextState; +-import org.eclipse.jetty.server.Handler; +-import org.eclipse.jetty.server.HttpChannelState; +-import org.eclipse.jetty.server.Request; +-import org.eclipse.jetty.server.handler.HandlerWrapper; +- +-import javax.servlet.AsyncEvent; +-import javax.servlet.AsyncListener; +-import javax.servlet.ServletException; +-import javax.servlet.http.HttpServletRequest; +-import javax.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; + import java.util.Set; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import javax.servlet.AsyncEvent; ++import javax.servlet.AsyncListener; ++import javax.servlet.ServletException; ++import javax.servlet.http.HttpServletRequest; ++import javax.servlet.http.HttpServletResponse; ++import org.eclipse.jetty.http.HttpMethod; ++import org.eclipse.jetty.server.AsyncContextState; ++import org.eclipse.jetty.server.Handler; ++import org.eclipse.jetty.server.HttpChannelState; ++import org.eclipse.jetty.server.Request; ++import org.eclipse.jetty.server.handler.HandlerWrapper; + + /** + * A Jetty {@link Handler} which records various metrics about an underlying {@link Handler} + * instance. + */ + public class InstrumentedHandler extends HandlerWrapper { +- private static final String NAME_REQUESTS = "requests"; +- private static final String NAME_DISPATCHES = "dispatches"; +- private static final String NAME_ACTIVE_REQUESTS = "active-requests"; +- private static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; +- private static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; +- private static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; +- private static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; +- private static final String NAME_1XX_RESPONSES = "1xx-responses"; +- private static final String NAME_2XX_RESPONSES = "2xx-responses"; +- private static final String NAME_3XX_RESPONSES = "3xx-responses"; +- private static final String NAME_4XX_RESPONSES = "4xx-responses"; +- private static final String NAME_5XX_RESPONSES = "5xx-responses"; +- private static final String NAME_GET_REQUESTS = "get-requests"; +- private static final String NAME_POST_REQUESTS = "post-requests"; +- private static final String NAME_HEAD_REQUESTS = "head-requests"; +- private static final String NAME_PUT_REQUESTS = "put-requests"; +- private static final String NAME_DELETE_REQUESTS = "delete-requests"; +- private static final String NAME_OPTIONS_REQUESTS = "options-requests"; +- private static final String NAME_TRACE_REQUESTS = "trace-requests"; +- private static final String NAME_CONNECT_REQUESTS = "connect-requests"; +- private static final String NAME_MOVE_REQUESTS = "move-requests"; +- private static final String NAME_OTHER_REQUESTS = "other-requests"; +- private static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; +- private static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; +- private static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; +- private static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; +- private static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; +- private static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; +- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); +- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); +- +- private final MetricRegistry metricRegistry; +- +- private String name; +- private final String prefix; +- +- // the requests handled by this handler, excluding active +- private Timer requests; +- +- // the number of dispatches seen by this handler, excluding active +- private Timer dispatches; +- +- // the number of active requests +- private Counter activeRequests; +- +- // the number of active dispatches +- private Counter activeDispatches; +- +- // the number of requests currently suspended. +- private Counter activeSuspended; +- +- // the number of requests that have been asynchronously dispatched +- private Meter asyncDispatches; +- +- // the number of requests that expired while suspended +- private Meter asyncTimeouts; +- +- private final ResponseMeteredLevel responseMeteredLevel; +- private List responses; +- private Map responseCodeMeters; +- +- private Timer getRequests; +- private Timer postRequests; +- private Timer headRequests; +- private Timer putRequests; +- private Timer deleteRequests; +- private Timer optionsRequests; +- private Timer traceRequests; +- private Timer connectRequests; +- private Timer moveRequests; +- private Timer otherRequests; +- +- private AsyncListener listener; +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- */ +- public InstrumentedHandler(MetricRegistry registry) { +- this(registry, null); ++ private static final String NAME_REQUESTS = "requests"; ++ private static final String NAME_DISPATCHES = "dispatches"; ++ private static final String NAME_ACTIVE_REQUESTS = "active-requests"; ++ private static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; ++ private static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; ++ private static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; ++ private static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; ++ private static final String NAME_1XX_RESPONSES = "1xx-responses"; ++ private static final String NAME_2XX_RESPONSES = "2xx-responses"; ++ private static final String NAME_3XX_RESPONSES = "3xx-responses"; ++ private static final String NAME_4XX_RESPONSES = "4xx-responses"; ++ private static final String NAME_5XX_RESPONSES = "5xx-responses"; ++ private static final String NAME_GET_REQUESTS = "get-requests"; ++ private static final String NAME_POST_REQUESTS = "post-requests"; ++ private static final String NAME_HEAD_REQUESTS = "head-requests"; ++ private static final String NAME_PUT_REQUESTS = "put-requests"; ++ private static final String NAME_DELETE_REQUESTS = "delete-requests"; ++ private static final String NAME_OPTIONS_REQUESTS = "options-requests"; ++ private static final String NAME_TRACE_REQUESTS = "trace-requests"; ++ private static final String NAME_CONNECT_REQUESTS = "connect-requests"; ++ private static final String NAME_MOVE_REQUESTS = "move-requests"; ++ private static final String NAME_OTHER_REQUESTS = "other-requests"; ++ private static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; ++ private static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; ++ private static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; ++ private static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; ++ private static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; ++ private static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; ++ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); ++ private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); ++ ++ private final MetricRegistry metricRegistry; ++ ++ private String name; ++ private final String prefix; ++ ++ // the requests handled by this handler, excluding active ++ private Timer requests; ++ ++ // the number of dispatches seen by this handler, excluding active ++ private Timer dispatches; ++ ++ // the number of active requests ++ private Counter activeRequests; ++ ++ // the number of active dispatches ++ private Counter activeDispatches; ++ ++ // the number of requests currently suspended. ++ private Counter activeSuspended; ++ ++ // the number of requests that have been asynchronously dispatched ++ private Meter asyncDispatches; ++ ++ // the number of requests that expired while suspended ++ private Meter asyncTimeouts; ++ ++ private final ResponseMeteredLevel responseMeteredLevel; ++ private List responses; ++ private Map responseCodeMeters; ++ ++ private Timer getRequests; ++ private Timer postRequests; ++ private Timer headRequests; ++ private Timer putRequests; ++ private Timer deleteRequests; ++ private Timer optionsRequests; ++ private Timer traceRequests; ++ private Timer connectRequests; ++ private Timer moveRequests; ++ private Timer otherRequests; ++ ++ private AsyncListener listener; ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ */ ++ public InstrumentedHandler(MetricRegistry registry) { ++ this(registry, null); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param prefix the prefix to use for the metrics names ++ */ ++ public InstrumentedHandler(MetricRegistry registry, String prefix) { ++ this(registry, prefix, COARSE); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param prefix the prefix to use for the metrics names ++ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are ++ * instrumented ++ */ ++ public InstrumentedHandler( ++ MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { ++ this.metricRegistry = registry; ++ this.prefix = prefix; ++ this.responseMeteredLevel = responseMeteredLevel; ++ } ++ ++ public String getName() { ++ return name; ++ } ++ ++ public void setName(String name) { ++ this.name = name; ++ } ++ ++ @Override ++ protected void doStart() throws Exception { ++ super.doStart(); ++ ++ final MetricName prefix = getMetricPrefix(); ++ ++ this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); ++ this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); ++ ++ this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); ++ this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); ++ this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); ++ ++ this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); ++ this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); ++ ++ this.responseCodeMeters = ++ DETAILED_METER_LEVELS.contains(responseMeteredLevel) ++ ? new ConcurrentHashMap<>() ++ : ImmutableMap.of(); ++ ++ this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); ++ this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); ++ this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); ++ this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); ++ this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); ++ this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); ++ this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); ++ this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); ++ this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); ++ this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); ++ ++ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { ++ this.responses = ++ unmodifiableList( ++ Arrays.asList( ++ metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx ++ metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx ++ metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx ++ metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx ++ metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx ++ )); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_4XX_1M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_4XX_5M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_4XX_15M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of( ++ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_5XX_1M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_5XX_5M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_5XX_15M), ++ new RatioGauge() { ++ @Override ++ public Ratio getRatio() { ++ return Ratio.of( ++ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } ++ }); ++ } else { ++ this.responses = ImmutableList.of(); + } + +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param prefix the prefix to use for the metrics names +- */ +- public InstrumentedHandler(MetricRegistry registry, String prefix) { +- this(registry, prefix, COARSE); ++ this.listener = new AsyncAttachingListener(); ++ } ++ ++ @Override ++ protected void doStop() throws Exception { ++ final MetricName prefix = getMetricPrefix(); ++ ++ metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); ++ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); ++ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); ++ metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); ++ metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); ++ metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); ++ ++ if (responseCodeMeters != null) { ++ responseCodeMeters.keySet().stream() ++ .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) ++ .forEach(metricRegistry::remove); + } + +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param prefix the prefix to use for the metrics names +- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented +- */ +- public InstrumentedHandler(MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { +- this.metricRegistry = registry; +- this.prefix = prefix; +- this.responseMeteredLevel = responseMeteredLevel; ++ super.doStop(); ++ } ++ ++ @Override ++ public void handle( ++ String path, ++ Request request, ++ HttpServletRequest httpRequest, ++ HttpServletResponse httpResponse) ++ throws IOException, ServletException { ++ ++ activeDispatches.inc(); ++ ++ final long start; ++ final HttpChannelState state = request.getHttpChannelState(); ++ if (state.isInitial()) { ++ // new request ++ activeRequests.inc(); ++ start = request.getTimeStamp(); ++ state.addListener(listener); ++ } else { ++ // resumed request ++ start = System.currentTimeMillis(); ++ activeSuspended.dec(); ++ if (state.getState() == HttpChannelState.State.HANDLING) { ++ asyncDispatches.mark(); ++ } + } + +- public String getName() { +- return name; ++ try { ++ super.handle(path, request, httpRequest, httpResponse); ++ } finally { ++ final long now = System.currentTimeMillis(); ++ final long dispatched = now - start; ++ ++ activeDispatches.dec(); ++ dispatches.update(dispatched, TimeUnit.MILLISECONDS); ++ ++ if (state.isSuspended()) { ++ activeSuspended.inc(); ++ } else if (state.isInitial()) { ++ updateResponses(httpRequest, httpResponse, start, request.isHandled()); ++ } ++ // else onCompletion will handle it. + } +- +- public void setName(String name) { +- this.name = name; ++ } ++ ++ private Timer requestTimer(String method) { ++ final HttpMethod m = HttpMethod.fromString(method); ++ if (m == null) { ++ return otherRequests; ++ } else { ++ switch (m) { ++ case GET: ++ return getRequests; ++ case POST: ++ return postRequests; ++ case PUT: ++ return putRequests; ++ case HEAD: ++ return headRequests; ++ case DELETE: ++ return deleteRequests; ++ case OPTIONS: ++ return optionsRequests; ++ case TRACE: ++ return traceRequests; ++ case CONNECT: ++ return connectRequests; ++ case MOVE: ++ return moveRequests; ++ default: ++ return otherRequests; ++ } + } +- +- @Override +- protected void doStart() throws Exception { +- super.doStart(); +- +- final MetricName prefix = getMetricPrefix(); +- +- this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); +- this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); +- +- this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); +- this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); +- this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); +- +- this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); +- this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); +- +- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); +- +- this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); +- this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); +- this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); +- this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); +- this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); +- this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); +- this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); +- this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); +- this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); +- this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); +- +- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { +- this.responses = Collections.unmodifiableList(Arrays.asList( +- metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx +- metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx +- metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx +- metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx +- metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx +- )); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_1M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_5M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_15M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_1M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_5M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_15M), new RatioGauge() { +- @Override +- public Ratio getRatio() { +- return Ratio.of(responses.get(4).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } +- }); +- } else { +- this.responses = Collections.emptyList(); +- } +- +- this.listener = new AsyncAttachingListener(); ++ } ++ ++ private void updateResponses( ++ HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { ++ if (isHandled) { ++ mark(response.getStatus()); ++ } else { ++ mark(404); ++ ; // will end up with a 404 response sent by HttpChannel.handle ++ } ++ activeRequests.dec(); ++ final long elapsedTime = System.currentTimeMillis() - start; ++ requests.update(elapsedTime, TimeUnit.MILLISECONDS); ++ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); ++ } ++ ++ private void mark(int statusCode) { ++ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { ++ getResponseCodeMeter(statusCode).mark(); + } + +- @Override +- protected void doStop() throws Exception { +- final MetricName prefix = getMetricPrefix(); +- +- metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); +- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); +- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); +- metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); +- metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); +- metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); +- +- if (responseCodeMeters != null) { +- responseCodeMeters.keySet().stream() +- .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) +- .forEach(metricRegistry::remove); +- } +- +- super.doStop(); ++ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { ++ final int responseStatus = statusCode / 100; ++ if (responseStatus >= 1 && responseStatus <= 5) { ++ responses.get(responseStatus - 1).mark(); ++ } + } ++ } + +- @Override +- public void handle(String path, +- Request request, +- HttpServletRequest httpRequest, +- HttpServletResponse httpResponse) throws IOException, ServletException { +- +- activeDispatches.inc(); +- +- final long start; +- final HttpChannelState state = request.getHttpChannelState(); +- if (state.isInitial()) { +- // new request +- activeRequests.inc(); +- start = request.getTimeStamp(); +- state.addListener(listener); +- } else { +- // resumed request +- start = System.currentTimeMillis(); +- activeSuspended.dec(); +- if (state.getState() == HttpChannelState.State.HANDLING) { +- asyncDispatches.mark(); +- } +- } ++ private Meter getResponseCodeMeter(int statusCode) { ++ return responseCodeMeters.computeIfAbsent( ++ statusCode, ++ sc -> metricRegistry.meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); ++ } + +- try { +- super.handle(path, request, httpRequest, httpResponse); +- } finally { +- final long now = System.currentTimeMillis(); +- final long dispatched = now - start; ++ private MetricName getMetricPrefix() { ++ return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); ++ } + +- activeDispatches.dec(); +- dispatches.update(dispatched, TimeUnit.MILLISECONDS); ++ private class AsyncAttachingListener implements AsyncListener { + +- if (state.isSuspended()) { +- activeSuspended.inc(); +- } else if (state.isInitial()) { +- updateResponses(httpRequest, httpResponse, start, request.isHandled()); +- } +- // else onCompletion will handle it. +- } +- } ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException {} + +- private Timer requestTimer(String method) { +- final HttpMethod m = HttpMethod.fromString(method); +- if (m == null) { +- return otherRequests; +- } else { +- switch (m) { +- case GET: +- return getRequests; +- case POST: +- return postRequests; +- case PUT: +- return putRequests; +- case HEAD: +- return headRequests; +- case DELETE: +- return deleteRequests; +- case OPTIONS: +- return optionsRequests; +- case TRACE: +- return traceRequests; +- case CONNECT: +- return connectRequests; +- case MOVE: +- return moveRequests; +- default: +- return otherRequests; +- } +- } ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException { ++ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); + } + +- private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { +- if (isHandled) { +- mark(response.getStatus()); +- } else { +- mark(404);; // will end up with a 404 response sent by HttpChannel.handle +- } +- activeRequests.dec(); +- final long elapsedTime = System.currentTimeMillis() - start; +- requests.update(elapsedTime, TimeUnit.MILLISECONDS); +- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); +- } ++ @Override ++ public void onError(AsyncEvent event) throws IOException {} + +- private void mark(int statusCode) { +- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { +- getResponseCodeMeter(statusCode).mark(); +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException {} ++ } ++ ; + +- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { +- final int responseStatus = statusCode / 100; +- if (responseStatus >= 1 && responseStatus <= 5) { +- responses.get(responseStatus - 1).mark(); +- } +- } +- } ++ private class InstrumentedAsyncListener implements AsyncListener { ++ private final long startTime; + +- private Meter getResponseCodeMeter(int statusCode) { +- return responseCodeMeters +- .computeIfAbsent(statusCode, sc -> metricRegistry +- .meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); ++ InstrumentedAsyncListener() { ++ this.startTime = System.currentTimeMillis(); + } + +- private MetricName getMetricPrefix() { +- return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException { ++ asyncTimeouts.mark(); + } + +- private class AsyncAttachingListener implements AsyncListener { +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException {} +- +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); +- } +- +- @Override +- public void onError(AsyncEvent event) throws IOException {} +- +- @Override +- public void onComplete(AsyncEvent event) throws IOException {} +- }; +- +- private class InstrumentedAsyncListener implements AsyncListener { +- private final long startTime; +- +- InstrumentedAsyncListener() { +- this.startTime = System.currentTimeMillis(); +- } +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException { +- asyncTimeouts.mark(); +- } +- +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- } ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException {} + +- @Override +- public void onError(AsyncEvent event) throws IOException { +- } ++ @Override ++ public void onError(AsyncEvent event) throws IOException {} + +- @Override +- public void onComplete(AsyncEvent event) throws IOException { +- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); +- final HttpServletRequest request = (HttpServletRequest) state.getRequest(); +- final HttpServletResponse response = (HttpServletResponse) state.getResponse(); +- updateResponses(request, response, startTime, true); +- if (!state.getHttpChannelState().isSuspended()) { +- activeSuspended.dec(); +- } +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException { ++ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); ++ final HttpServletRequest request = (HttpServletRequest) state.getRequest(); ++ final HttpServletResponse response = (HttpServletResponse) state.getResponse(); ++ updateResponses(request, response, startTime, true); ++ if (!state.getHttpChannelState().isSuspended()) { ++ activeSuspended.dec(); ++ } + } ++ } + } +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java +@@ -1,5 +1,12 @@ + package io.dropwizard.metrics5.jetty10; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; ++ ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -7,418 +14,402 @@ import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.RatioGauge; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; +-import org.eclipse.jetty.http.HttpMethod; +-import org.eclipse.jetty.server.AsyncContextState; +-import org.eclipse.jetty.server.HttpChannel.Listener; +-import org.eclipse.jetty.server.HttpChannelState; +-import org.eclipse.jetty.server.Request; +- +-import javax.servlet.AsyncEvent; +-import javax.servlet.AsyncListener; +-import javax.servlet.http.HttpServletRequest; +-import javax.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; + import java.util.Set; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import javax.servlet.AsyncEvent; ++import javax.servlet.AsyncListener; ++import javax.servlet.http.HttpServletRequest; ++import javax.servlet.http.HttpServletResponse; ++import org.eclipse.jetty.http.HttpMethod; ++import org.eclipse.jetty.server.AsyncContextState; ++import org.eclipse.jetty.server.HttpChannel.Listener; ++import org.eclipse.jetty.server.HttpChannelState; ++import org.eclipse.jetty.server.Request; + + /** +- * A Jetty {@link org.eclipse.jetty.server.HttpChannel.Listener} implementation which records various metrics about +- * underlying channel instance. Unlike {@link InstrumentedHandler} that uses internal API, this class should be +- * future proof. To install it, just add instance of this class to {@link org.eclipse.jetty.server.Connector} as bean. ++ * A Jetty {@link org.eclipse.jetty.server.HttpChannel.Listener} implementation which records ++ * various metrics about underlying channel instance. Unlike {@link InstrumentedHandler} that uses ++ * internal API, this class should be future proof. To install it, just add instance of this class ++ * to {@link org.eclipse.jetty.server.Connector} as bean. + * + * @since TBD + */ +-public class InstrumentedHttpChannelListener +- implements Listener { +- private static final String START_ATTR = InstrumentedHttpChannelListener.class.getName() + ".start"; +- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); +- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); +- +- private final MetricRegistry metricRegistry; +- +- // the requests handled by this handler, excluding active +- private final Timer requests; +- +- // the number of dispatches seen by this handler, excluding active +- private final Timer dispatches; +- +- // the number of active requests +- private final Counter activeRequests; +- +- // the number of active dispatches +- private final Counter activeDispatches; +- +- // the number of requests currently suspended. +- private final Counter activeSuspended; +- +- // the number of requests that have been asynchronously dispatched +- private final Meter asyncDispatches; +- +- // the number of requests that expired while suspended +- private final Meter asyncTimeouts; +- +- private final ResponseMeteredLevel responseMeteredLevel; +- private final List responses; +- private final Map responseCodeMeters; +- private final MetricName prefix; +- private final Timer getRequests; +- private final Timer postRequests; +- private final Timer headRequests; +- private final Timer putRequests; +- private final Timer deleteRequests; +- private final Timer optionsRequests; +- private final Timer traceRequests; +- private final Timer connectRequests; +- private final Timer moveRequests; +- private final Timer otherRequests; +- +- private final AsyncListener listener; +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- */ +- public InstrumentedHttpChannelListener(MetricRegistry registry) { +- this(registry, null, COARSE); +- } +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param pref the prefix to use for the metrics names +- */ +- public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref) { +- this(registry, pref, COARSE); +- } +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param pref the prefix to use for the metrics names +- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented +- */ +- public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref, ResponseMeteredLevel responseMeteredLevel) { +- this.metricRegistry = registry; +- +- this.prefix = (pref == null) ? MetricName.build(getClass().getName()) : pref; +- +- this.requests = metricRegistry.timer(prefix.resolve("requests")); +- this.dispatches = metricRegistry.timer(prefix.resolve("dispatches")); +- +- this.activeRequests = metricRegistry.counter(prefix.resolve("active-requests")); +- this.activeDispatches = metricRegistry.counter(prefix.resolve("active-dispatches")); +- this.activeSuspended = metricRegistry.counter(prefix.resolve("active-suspended")); +- +- this.asyncDispatches = metricRegistry.meter(prefix.resolve("async-dispatches")); +- this.asyncTimeouts = metricRegistry.meter(prefix.resolve("async-timeouts")); +- +- this.responseMeteredLevel = responseMeteredLevel; +- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); +- this.responses = COARSE_METER_LEVELS.contains(responseMeteredLevel) ? +- Collections.unmodifiableList(Arrays.asList( +- registry.meter(prefix.resolve("1xx-responses")), // 1xx +- registry.meter(prefix.resolve("2xx-responses")), // 2xx +- registry.meter(prefix.resolve("3xx-responses")), // 3xx +- registry.meter(prefix.resolve("4xx-responses")), // 4xx +- registry.meter(prefix.resolve("5xx-responses")) // 5xx +- )) : Collections.emptyList(); +- +- this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); +- this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); +- this.headRequests = metricRegistry.timer(prefix.resolve("head-requests")); +- this.putRequests = metricRegistry.timer(prefix.resolve("put-requests")); +- this.deleteRequests = metricRegistry.timer(prefix.resolve("delete-requests")); +- this.optionsRequests = metricRegistry.timer(prefix.resolve("options-requests")); +- this.traceRequests = metricRegistry.timer(prefix.resolve("trace-requests")); +- this.connectRequests = metricRegistry.timer(prefix.resolve("connect-requests")); +- this.moveRequests = metricRegistry.timer(prefix.resolve("move-requests")); +- this.otherRequests = metricRegistry.timer(prefix.resolve("other-requests")); +- +- metricRegistry.register(prefix.resolve("percent-4xx-1m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } ++public class InstrumentedHttpChannelListener implements Listener { ++ private static final String START_ATTR = ++ InstrumentedHttpChannelListener.class.getName() + ".start"; ++ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); ++ private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); ++ ++ private final MetricRegistry metricRegistry; ++ ++ // the requests handled by this handler, excluding active ++ private final Timer requests; ++ ++ // the number of dispatches seen by this handler, excluding active ++ private final Timer dispatches; ++ ++ // the number of active requests ++ private final Counter activeRequests; ++ ++ // the number of active dispatches ++ private final Counter activeDispatches; ++ ++ // the number of requests currently suspended. ++ private final Counter activeSuspended; ++ ++ // the number of requests that have been asynchronously dispatched ++ private final Meter asyncDispatches; ++ ++ // the number of requests that expired while suspended ++ private final Meter asyncTimeouts; ++ ++ private final ResponseMeteredLevel responseMeteredLevel; ++ private final List responses; ++ private final Map responseCodeMeters; ++ private final MetricName prefix; ++ private final Timer getRequests; ++ private final Timer postRequests; ++ private final Timer headRequests; ++ private final Timer putRequests; ++ private final Timer deleteRequests; ++ private final Timer optionsRequests; ++ private final Timer traceRequests; ++ private final Timer connectRequests; ++ private final Timer moveRequests; ++ private final Timer otherRequests; ++ ++ private final AsyncListener listener; ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ */ ++ public InstrumentedHttpChannelListener(MetricRegistry registry) { ++ this(registry, null, COARSE); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param pref the prefix to use for the metrics names ++ */ ++ public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref) { ++ this(registry, pref, COARSE); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param pref the prefix to use for the metrics names ++ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are ++ * instrumented ++ */ ++ public InstrumentedHttpChannelListener( ++ MetricRegistry registry, MetricName pref, ResponseMeteredLevel responseMeteredLevel) { ++ this.metricRegistry = registry; ++ ++ this.prefix = (pref == null) ? MetricName.build(getClass().getName()) : pref; ++ ++ this.requests = metricRegistry.timer(prefix.resolve("requests")); ++ this.dispatches = metricRegistry.timer(prefix.resolve("dispatches")); ++ ++ this.activeRequests = metricRegistry.counter(prefix.resolve("active-requests")); ++ this.activeDispatches = metricRegistry.counter(prefix.resolve("active-dispatches")); ++ this.activeSuspended = metricRegistry.counter(prefix.resolve("active-suspended")); ++ ++ this.asyncDispatches = metricRegistry.meter(prefix.resolve("async-dispatches")); ++ this.asyncTimeouts = metricRegistry.meter(prefix.resolve("async-timeouts")); ++ ++ this.responseMeteredLevel = responseMeteredLevel; ++ this.responseCodeMeters = ++ DETAILED_METER_LEVELS.contains(responseMeteredLevel) ++ ? new ConcurrentHashMap<>() ++ : ImmutableMap.of(); ++ this.responses = ++ COARSE_METER_LEVELS.contains(responseMeteredLevel) ++ ? unmodifiableList( ++ Arrays.asList( ++ registry.meter(prefix.resolve("1xx-responses")), // 1xx ++ registry.meter(prefix.resolve("2xx-responses")), // 2xx ++ registry.meter(prefix.resolve("3xx-responses")), // 3xx ++ registry.meter(prefix.resolve("4xx-responses")), // 4xx ++ registry.meter(prefix.resolve("5xx-responses")) // 5xx ++ )) ++ : ImmutableList.of(); ++ ++ this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); ++ this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); ++ this.headRequests = metricRegistry.timer(prefix.resolve("head-requests")); ++ this.putRequests = metricRegistry.timer(prefix.resolve("put-requests")); ++ this.deleteRequests = metricRegistry.timer(prefix.resolve("delete-requests")); ++ this.optionsRequests = metricRegistry.timer(prefix.resolve("options-requests")); ++ this.traceRequests = metricRegistry.timer(prefix.resolve("trace-requests")); ++ this.connectRequests = metricRegistry.timer(prefix.resolve("connect-requests")); ++ this.moveRequests = metricRegistry.timer(prefix.resolve("move-requests")); ++ this.otherRequests = metricRegistry.timer(prefix.resolve("other-requests")); ++ ++ metricRegistry.register( ++ prefix.resolve("percent-4xx-1m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-4xx-5m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-4xx-5m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-4xx-15m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-4xx-15m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of( ++ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-5xx-1m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-5xx-1m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-5xx-5m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-5xx-5m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-5xx-15m"), new RatioGauge() { +- @Override +- public RatioGauge.Ratio getRatio() { +- return Ratio.of(responses.get(4).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-5xx-15m"), ++ new RatioGauge() { ++ @Override ++ public RatioGauge.Ratio getRatio() { ++ return Ratio.of( ++ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } + }); + +- this.listener = new AsyncAttachingListener(); +- } ++ this.listener = new AsyncAttachingListener(); ++ } + +- @Override +- public void onRequestBegin(final Request request) { ++ @Override ++ public void onRequestBegin(final Request request) {} + +- } ++ @Override ++ public void onBeforeDispatch(final Request request) { ++ before(request); ++ } + +- @Override +- public void onBeforeDispatch(final Request request) { +- before(request); +- } ++ @Override ++ public void onDispatchFailure(final Request request, final Throwable failure) {} + +- @Override +- public void onDispatchFailure(final Request request, final Throwable failure) { ++ @Override ++ public void onAfterDispatch(final Request request) { ++ after(request); ++ } + +- } ++ @Override ++ public void onRequestContent(final Request request, final ByteBuffer content) {} + +- @Override +- public void onAfterDispatch(final Request request) { +- after(request); +- } ++ @Override ++ public void onRequestContentEnd(final Request request) {} + +- @Override +- public void onRequestContent(final Request request, final ByteBuffer content) { ++ @Override ++ public void onRequestTrailers(final Request request) {} + +- } ++ @Override ++ public void onRequestEnd(final Request request) {} + +- @Override +- public void onRequestContentEnd(final Request request) { ++ @Override ++ public void onRequestFailure(final Request request, final Throwable failure) {} + +- } ++ @Override ++ public void onResponseBegin(final Request request) {} + +- @Override +- public void onRequestTrailers(final Request request) { ++ @Override ++ public void onResponseCommit(final Request request) {} + +- } ++ @Override ++ public void onResponseContent(final Request request, final ByteBuffer content) {} + +- @Override +- public void onRequestEnd(final Request request) { ++ @Override ++ public void onResponseEnd(final Request request) {} + +- } ++ @Override ++ public void onResponseFailure(final Request request, final Throwable failure) {} + +- @Override +- public void onRequestFailure(final Request request, final Throwable failure) { ++ @Override ++ public void onComplete(final Request request) {} + +- } +- +- @Override +- public void onResponseBegin(final Request request) { ++ private void before(final Request request) { ++ activeDispatches.inc(); + ++ final long start; ++ final HttpChannelState state = request.getHttpChannelState(); ++ if (state.isInitial()) { ++ // new request ++ activeRequests.inc(); ++ start = request.getTimeStamp(); ++ state.addListener(listener); ++ } else { ++ // resumed request ++ start = System.currentTimeMillis(); ++ activeSuspended.dec(); ++ if (state.isAsyncStarted()) { ++ asyncDispatches.mark(); ++ } + } +- +- @Override +- public void onResponseCommit(final Request request) { +- ++ request.setAttribute(START_ATTR, start); ++ } ++ ++ private void after(final Request request) { ++ final long start = (long) request.getAttribute(START_ATTR); ++ final long now = System.currentTimeMillis(); ++ final long dispatched = now - start; ++ ++ activeDispatches.dec(); ++ dispatches.update(dispatched, TimeUnit.MILLISECONDS); ++ ++ final HttpChannelState state = request.getHttpChannelState(); ++ if (state.isSuspended()) { ++ activeSuspended.inc(); ++ } else if (state.isInitial()) { ++ updateResponses(request, request.getResponse(), start, request.isHandled()); + } +- +- @Override +- public void onResponseContent(final Request request, final ByteBuffer content) { +- ++ // else onCompletion will handle it. ++ } ++ ++ private void updateResponses( ++ HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { ++ if (isHandled) { ++ mark(response.getStatus()); ++ } else { ++ mark(404); // will end up with a 404 response sent by HttpChannel.handle ++ } ++ activeRequests.dec(); ++ final long elapsedTime = System.currentTimeMillis() - start; ++ requests.update(elapsedTime, TimeUnit.MILLISECONDS); ++ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); ++ } ++ ++ private void mark(int statusCode) { ++ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { ++ getResponseCodeMeter(statusCode).mark(); + } + +- @Override +- public void onResponseEnd(final Request request) { +- ++ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { ++ final int responseStatus = statusCode / 100; ++ if (responseStatus >= 1 && responseStatus <= 5) { ++ responses.get(responseStatus - 1).mark(); ++ } ++ } ++ } ++ ++ private Meter getResponseCodeMeter(int statusCode) { ++ return responseCodeMeters.computeIfAbsent( ++ statusCode, sc -> metricRegistry.meter(prefix.resolve(String.format("%d-responses", sc)))); ++ } ++ ++ private Timer requestTimer(String method) { ++ final HttpMethod m = HttpMethod.fromString(method); ++ if (m == null) { ++ return otherRequests; ++ } else { ++ switch (m) { ++ case GET: ++ return getRequests; ++ case POST: ++ return postRequests; ++ case PUT: ++ return putRequests; ++ case HEAD: ++ return headRequests; ++ case DELETE: ++ return deleteRequests; ++ case OPTIONS: ++ return optionsRequests; ++ case TRACE: ++ return traceRequests; ++ case CONNECT: ++ return connectRequests; ++ case MOVE: ++ return moveRequests; ++ default: ++ return otherRequests; ++ } + } ++ } ++ ++ private class AsyncAttachingListener implements AsyncListener { + + @Override +- public void onResponseFailure(final Request request, final Throwable failure) { ++ public void onTimeout(AsyncEvent event) throws IOException {} + ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException { ++ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); + } + + @Override +- public void onComplete(final Request request) { +- +- } ++ public void onError(AsyncEvent event) throws IOException {} + +- private void before(final Request request) { +- activeDispatches.inc(); +- +- final long start; +- final HttpChannelState state = request.getHttpChannelState(); +- if (state.isInitial()) { +- // new request +- activeRequests.inc(); +- start = request.getTimeStamp(); +- state.addListener(listener); +- } else { +- // resumed request +- start = System.currentTimeMillis(); +- activeSuspended.dec(); +- if (state.isAsyncStarted()) { +- asyncDispatches.mark(); +- } +- } +- request.setAttribute(START_ATTR, start); +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException {} ++ } ++ ; + +- private void after(final Request request) { +- final long start = (long) request.getAttribute(START_ATTR); +- final long now = System.currentTimeMillis(); +- final long dispatched = now - start; +- +- activeDispatches.dec(); +- dispatches.update(dispatched, TimeUnit.MILLISECONDS); +- +- final HttpChannelState state = request.getHttpChannelState(); +- if (state.isSuspended()) { +- activeSuspended.inc(); +- } else if (state.isInitial()) { +- updateResponses(request, request.getResponse(), start, request.isHandled()); +- } +- // else onCompletion will handle it. +- } ++ private class InstrumentedAsyncListener implements AsyncListener { ++ private final long startTime; + +- private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { +- if (isHandled) { +- mark(response.getStatus()); +- } else { +- mark(404); // will end up with a 404 response sent by HttpChannel.handle +- } +- activeRequests.dec(); +- final long elapsedTime = System.currentTimeMillis() - start; +- requests.update(elapsedTime, TimeUnit.MILLISECONDS); +- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); ++ InstrumentedAsyncListener() { ++ this.startTime = System.currentTimeMillis(); + } + +- private void mark(int statusCode) { +- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { +- getResponseCodeMeter(statusCode).mark(); +- } +- +- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { +- final int responseStatus = statusCode / 100; +- if (responseStatus >= 1 && responseStatus <= 5) { +- responses.get(responseStatus - 1).mark(); +- } +- } ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException { ++ asyncTimeouts.mark(); + } + +- private Meter getResponseCodeMeter(int statusCode) { +- return responseCodeMeters +- .computeIfAbsent(statusCode, sc -> metricRegistry +- .meter(prefix.resolve(String.format("%d-responses", sc)))); +- } ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException {} + +- private Timer requestTimer(String method) { +- final HttpMethod m = HttpMethod.fromString(method); +- if (m == null) { +- return otherRequests; +- } else { +- switch (m) { +- case GET: +- return getRequests; +- case POST: +- return postRequests; +- case PUT: +- return putRequests; +- case HEAD: +- return headRequests; +- case DELETE: +- return deleteRequests; +- case OPTIONS: +- return optionsRequests; +- case TRACE: +- return traceRequests; +- case CONNECT: +- return connectRequests; +- case MOVE: +- return moveRequests; +- default: +- return otherRequests; +- } +- } +- } ++ @Override ++ public void onError(AsyncEvent event) throws IOException {} + +- private class AsyncAttachingListener implements AsyncListener { +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException {} +- +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); +- } +- +- @Override +- public void onError(AsyncEvent event) throws IOException {} +- +- @Override +- public void onComplete(AsyncEvent event) throws IOException {} +- }; +- +- private class InstrumentedAsyncListener implements AsyncListener { +- private final long startTime; +- +- InstrumentedAsyncListener() { +- this.startTime = System.currentTimeMillis(); +- } +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException { +- asyncTimeouts.mark(); +- } +- +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- } +- +- @Override +- public void onError(AsyncEvent event) throws IOException { +- } +- +- @Override +- public void onComplete(AsyncEvent event) throws IOException { +- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); +- final HttpServletRequest request = (HttpServletRequest) state.getRequest(); +- final HttpServletResponse response = (HttpServletResponse) state.getResponse(); +- updateResponses(request, response, startTime, true); +- if (!state.getHttpChannelState().isSuspended()) { +- activeSuspended.dec(); +- } +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException { ++ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); ++ final HttpServletRequest request = (HttpServletRequest) state.getRequest(); ++ final HttpServletResponse response = (HttpServletResponse) state.getResponse(); ++ updateResponses(request, response, startTime, true); ++ if (!state.getHttpChannelState().isSuspended()) { ++ activeSuspended.dec(); ++ } + } ++ } + } +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPool.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPool.java +@@ -1,120 +1,131 @@ + package io.dropwizard.metrics5.jetty10; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.RatioGauge; ++import java.util.concurrent.BlockingQueue; + import org.eclipse.jetty.util.annotation.Name; + import org.eclipse.jetty.util.thread.QueuedThreadPool; + +-import java.util.concurrent.BlockingQueue; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + public class InstrumentedQueuedThreadPool extends QueuedThreadPool { +- private static final String NAME_UTILIZATION = "utilization"; +- private static final String NAME_UTILIZATION_MAX = "utilization-max"; +- private static final String NAME_SIZE = "size"; +- private static final String NAME_JOBS = "jobs"; +- private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; +- +- private final MetricRegistry metricRegistry; +- private String prefix; +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { +- this(registry, 200); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads) { +- this(registry, maxThreads, 8); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads) { +- this(registry, maxThreads, minThreads, 60000); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout) { +- this(registry, maxThreads, minThreads, idleTimeout, null); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("queue") BlockingQueue queue) { +- this(registry, maxThreads, minThreads, idleTimeout, queue, null); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("queue") BlockingQueue queue, +- @Name("prefix") String prefix) { +- super(maxThreads, minThreads, idleTimeout, queue); +- this.metricRegistry = registry; +- this.prefix = prefix; +- } +- +- public String getPrefix() { +- return prefix; +- } +- +- public void setPrefix(String prefix) { +- this.prefix = prefix; +- } +- +- @Override +- protected void doStart() throws Exception { +- super.doStart(); +- +- final MetricName prefix = getMetricPrefix(); +- +- metricRegistry.register(prefix.resolve("utilization"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(getThreads() - getIdleThreads(), getThreads()); +- } ++ private static final String NAME_UTILIZATION = "utilization"; ++ private static final String NAME_UTILIZATION_MAX = "utilization-max"; ++ private static final String NAME_SIZE = "size"; ++ private static final String NAME_JOBS = "jobs"; ++ private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; ++ ++ private final MetricRegistry metricRegistry; ++ private String prefix; ++ ++ public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { ++ this(registry, 200); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, @Name("maxThreads") int maxThreads) { ++ this(registry, maxThreads, 8); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads) { ++ this(registry, maxThreads, minThreads, 60000); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout) { ++ this(registry, maxThreads, minThreads, idleTimeout, null); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("queue") BlockingQueue queue) { ++ this(registry, maxThreads, minThreads, idleTimeout, queue, null); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("queue") BlockingQueue queue, ++ @Name("prefix") String prefix) { ++ super(maxThreads, minThreads, idleTimeout, queue); ++ this.metricRegistry = registry; ++ this.prefix = prefix; ++ } ++ ++ public String getPrefix() { ++ return prefix; ++ } ++ ++ public void setPrefix(String prefix) { ++ this.prefix = prefix; ++ } ++ ++ @Override ++ protected void doStart() throws Exception { ++ super.doStart(); ++ ++ final MetricName prefix = getMetricPrefix(); ++ ++ metricRegistry.register( ++ prefix.resolve("utilization"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(getThreads() - getIdleThreads(), getThreads()); ++ } + }); +- metricRegistry.register(prefix.resolve("utilization-max"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); +- } ++ metricRegistry.register( ++ prefix.resolve("utilization-max"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); ++ } + }); +- // This assumes the QueuedThreadPool is using a BlockingArrayQueue or +- // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. +- +- metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); +- metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); +- metricRegistry.register(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- BlockingQueue queue = getQueue(); +- return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); +- } ++ // This assumes the QueuedThreadPool is using a BlockingArrayQueue or ++ // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. ++ ++ metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); ++ metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); ++ metricRegistry.register( ++ prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ BlockingQueue queue = getQueue(); ++ return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); ++ } + }); +- } +- +- @Override +- protected void doStop() throws Exception { +- final MetricName prefix = getMetricPrefix(); +- +- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); +- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); +- metricRegistry.remove(prefix.resolve(NAME_SIZE)); +- metricRegistry.remove(prefix.resolve(NAME_JOBS)); +- metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); +- +- super.doStop(); +- } +- +- private MetricName getMetricPrefix() { +- return this.prefix == null ? name(QueuedThreadPool.class, getName()) : name(this.prefix, getName()); +- } ++ } ++ ++ @Override ++ protected void doStop() throws Exception { ++ final MetricName prefix = getMetricPrefix(); ++ ++ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); ++ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); ++ metricRegistry.remove(prefix.resolve(NAME_SIZE)); ++ metricRegistry.remove(prefix.resolve(NAME_JOBS)); ++ metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); ++ ++ super.doStop(); ++ } ++ ++ private MetricName getMetricPrefix() { ++ return this.prefix == null ++ ? name(QueuedThreadPool.class, getName()) ++ : name(this.prefix, getName()); ++ } + } +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java +@@ -1,8 +1,15 @@ + package io.dropwizard.metrics5.jetty10; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; ++import java.io.IOException; ++import java.io.PrintWriter; ++import javax.servlet.ServletException; ++import javax.servlet.http.HttpServletRequest; ++import javax.servlet.http.HttpServletResponse; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.HttpConnectionFactory; +@@ -14,80 +21,75 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import javax.servlet.ServletException; +-import javax.servlet.http.HttpServletRequest; +-import javax.servlet.http.HttpServletResponse; +-import java.io.IOException; +-import java.io.PrintWriter; +- +-import static org.assertj.core.api.Assertions.assertThat; +- +-class InstrumentedConnectionFactoryTest { +- private final MetricRegistry registry = new MetricRegistry(); +- private final Server server = new Server(); +- private final ServerConnector connector = +- new ServerConnector(server, new InstrumentedConnectionFactory(new HttpConnectionFactory(), +- registry.timer("http.connections"), +- registry.counter("http.active-connections"))); +- private final HttpClient client = new HttpClient(); +- +- @BeforeEach +- void setUp() throws Exception { +- server.setHandler(new AbstractHandler() { +- @Override +- public void handle(String target, +- Request baseRequest, +- HttpServletRequest request, +- HttpServletResponse response) throws IOException, ServletException { +- try (PrintWriter writer = response.getWriter()) { +- writer.println("OK"); +- } ++final class InstrumentedConnectionFactoryTest { ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final Server server = new Server(); ++ private final ServerConnector connector = ++ new ServerConnector( ++ server, ++ new InstrumentedConnectionFactory( ++ new HttpConnectionFactory(), ++ registry.timer("http.connections"), ++ registry.counter("http.active-connections"))); ++ private final HttpClient client = new HttpClient(); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ server.setHandler( ++ new AbstractHandler() { ++ @Override ++ public void handle( ++ String target, ++ Request baseRequest, ++ HttpServletRequest request, ++ HttpServletResponse response) ++ throws IOException, ServletException { ++ try (PrintWriter writer = response.getWriter()) { ++ writer.println("OK"); + } ++ } + }); + +- server.addConnector(connector); +- server.start(); ++ server.addConnector(connector); ++ server.start(); + +- client.start(); +- } ++ client.start(); ++ } + +- @AfterEach +- void tearDown() throws Exception { +- server.stop(); +- client.stop(); +- } ++ @AfterEach ++ void tearDown() throws Exception { ++ server.stop(); ++ client.stop(); ++ } + +- @Test +- void instrumentsConnectionTimes() throws Exception { +- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); +- assertThat(response.getStatus()) +- .isEqualTo(200); ++ @Test ++ void instrumentsConnectionTimes() throws Exception { ++ final ContentResponse response = ++ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); ++ assertThat(response.getStatus()).isEqualTo(200); + +- client.stop(); // close the connection ++ client.stop(); // close the connection + +- Thread.sleep(100); // make sure the connection is closed ++ Thread.sleep(100); // make sure the connection is closed + +- final Timer timer = registry.timer(MetricRegistry.name("http.connections")); +- assertThat(timer.getCount()) +- .isEqualTo(1); +- } ++ final Timer timer = registry.timer(MetricRegistry.name("http.connections")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + +- @Test +- void instrumentsActiveConnections() throws Exception { +- final Counter counter = registry.counter("http.active-connections"); ++ @Test ++ void instrumentsActiveConnections() throws Exception { ++ final Counter counter = registry.counter("http.active-connections"); + +- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); +- assertThat(response.getStatus()) +- .isEqualTo(200); ++ final ContentResponse response = ++ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); ++ assertThat(response.getStatus()).isEqualTo(200); + +- assertThat(counter.getCount()) +- .isEqualTo(1); ++ assertThat(counter.getCount()).isEqualTo(1); + +- client.stop(); // close the connection ++ client.stop(); // close the connection + +- Thread.sleep(100); // make sure the connection is closed ++ Thread.sleep(100); // make sure the connection is closed + +- assertThat(counter.getCount()) +- .isEqualTo(0); +- } ++ assertThat(counter.getCount()).isEqualTo(0); ++ } + } +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java +@@ -1,7 +1,22 @@ + package io.dropwizard.metrics5.jetty10; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.nio.charset.StandardCharsets.UTF_8; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; ++import java.io.IOException; ++import java.util.concurrent.TimeUnit; ++import javax.servlet.AsyncContext; ++import javax.servlet.ServletException; ++import javax.servlet.ServletOutputStream; ++import javax.servlet.WriteListener; ++import javax.servlet.http.HttpServletRequest; ++import javax.servlet.http.HttpServletResponse; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.Request; +@@ -13,234 +28,221 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + +-import javax.servlet.AsyncContext; +-import javax.servlet.ServletException; +-import javax.servlet.ServletOutputStream; +-import javax.servlet.WriteListener; +-import javax.servlet.http.HttpServletRequest; +-import javax.servlet.http.HttpServletResponse; +-import java.io.IOException; +-import java.nio.charset.StandardCharsets; +-import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; +- +-class InstrumentedHandlerTest { +- private final HttpClient client = new HttpClient(); +- private final MetricRegistry registry = new MetricRegistry(); +- private final Server server = new Server(); +- private final ServerConnector connector = new ServerConnector(server); +- private final InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); +- +- @BeforeEach +- void setUp() throws Exception { +- handler.setName("handler"); +- handler.setHandler(new TestHandler()); +- server.addConnector(connector); +- server.setHandler(handler); +- server.start(); +- client.start(); +- } +- +- @AfterEach +- void tearDown() throws Exception { +- server.stop(); +- client.stop(); +- } +- +- @Test +- void hasAName() throws Exception { +- assertThat(handler.getName()) +- .isEqualTo("handler"); +- } +- +- @Test +- void createsAndRemovesMetricsForTheHandler() throws Exception { +- final ContentResponse response = client.GET(uri("/hello")); +- +- assertThat(response.getStatus()) +- .isEqualTo(404); +- +- assertThat(registry.getNames()) +- .containsOnly( +- MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.404-responses"), +- MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), +- MetricRegistry.name(TestHandler.class, "handler.requests"), +- MetricRegistry.name(TestHandler.class, "handler.active-suspended"), +- MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), +- MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), +- MetricRegistry.name(TestHandler.class, "handler.get-requests"), +- MetricRegistry.name(TestHandler.class, "handler.put-requests"), +- MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), +- MetricRegistry.name(TestHandler.class, "handler.trace-requests"), +- MetricRegistry.name(TestHandler.class, "handler.other-requests"), +- MetricRegistry.name(TestHandler.class, "handler.connect-requests"), +- MetricRegistry.name(TestHandler.class, "handler.dispatches"), +- MetricRegistry.name(TestHandler.class, "handler.head-requests"), +- MetricRegistry.name(TestHandler.class, "handler.post-requests"), +- MetricRegistry.name(TestHandler.class, "handler.options-requests"), +- MetricRegistry.name(TestHandler.class, "handler.active-requests"), +- MetricRegistry.name(TestHandler.class, "handler.delete-requests"), +- MetricRegistry.name(TestHandler.class, "handler.move-requests") +- ); +- +- server.stop(); +- +- assertThat(registry.getNames()) +- .isEmpty(); +- } +- +- @Test +- void responseTimesAreRecordedForBlockingResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/blocking")); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- +- assertResponseTimesValid(); +- } +- +- @Test +- void doStopDoesNotThrowNPE() throws Exception { +- InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); +- handler.setHandler(new TestHandler()); +- +- assertThatCode(handler::doStop).doesNotThrowAnyException(); +- } +- +- @Test +- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { +- InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); +- handler.setHandler(new TestHandler()); +- handler.setName("handler"); +- handler.doStart(); +- assertThat(registry.getGauges()).containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); +- } +- +- @Test +- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { +- InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); +- handler.setHandler(new TestHandler()); +- handler.setName("handler"); +- handler.doStart(); +- assertThat(registry.getGauges()).doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); +- } +- +- @Test +- @Disabled("flaky on virtual machines") +- void responseTimesAreRecordedForAsyncResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/async")); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- +- assertResponseTimesValid(); +- } +- +- private void assertResponseTimesValid() { +- assertThat(registry.getMeters().get(metricName().resolve("200-responses")) +- .getCount()).isGreaterThan(0L); +- +- +- assertThat(registry.getTimers().get(metricName().resolve("get-requests")) +- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); +- +- assertThat(registry.getTimers().get(metricName().resolve("requests")) +- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); +- } +- +- private String uri(String path) { +- return "http://localhost:" + connector.getLocalPort() + path; +- } +- +- private MetricName metricName() { +- return MetricRegistry.name(TestHandler.class.getName(), "handler"); +- } +- +- /** +- * test handler. +- *

    +- * Supports +- *

    +- * /blocking - uses the standard servlet api +- * /async - uses the 3.1 async api to complete the request +- *

    +- * all other requests will return 404 +- */ +- private static class TestHandler extends AbstractHandler { +- @Override +- public void handle( +- String path, +- Request request, +- final HttpServletRequest httpServletRequest, +- final HttpServletResponse httpServletResponse +- ) throws IOException, ServletException { +- switch (path) { +- case "/blocking": +- request.setHandled(true); ++final class InstrumentedHandlerTest { ++ private final HttpClient client = new HttpClient(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final Server server = new Server(); ++ private final ServerConnector connector = new ServerConnector(server); ++ private final InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ handler.setName("handler"); ++ handler.setHandler(new TestHandler()); ++ server.addConnector(connector); ++ server.setHandler(handler); ++ server.start(); ++ client.start(); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ server.stop(); ++ client.stop(); ++ } ++ ++ @Test ++ void hasAName() throws Exception { ++ assertThat(handler.getName()).isEqualTo("handler"); ++ } ++ ++ @Test ++ void createsAndRemovesMetricsForTheHandler() throws Exception { ++ final ContentResponse response = client.GET(uri("/hello")); ++ ++ assertThat(response.getStatus()).isEqualTo(404); ++ ++ assertThat(registry.getNames()) ++ .containsOnly( ++ MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.404-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), ++ MetricRegistry.name(TestHandler.class, "handler.requests"), ++ MetricRegistry.name(TestHandler.class, "handler.active-suspended"), ++ MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), ++ MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), ++ MetricRegistry.name(TestHandler.class, "handler.get-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.put-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), ++ MetricRegistry.name(TestHandler.class, "handler.trace-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.other-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.connect-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.dispatches"), ++ MetricRegistry.name(TestHandler.class, "handler.head-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.post-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.options-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.active-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.delete-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.move-requests")); ++ ++ server.stop(); ++ ++ assertThat(registry.getNames()).isEmpty(); ++ } ++ ++ @Test ++ void responseTimesAreRecordedForBlockingResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/blocking")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ ++ assertResponseTimesValid(); ++ } ++ ++ @Test ++ void doStopDoesNotThrowNPE() throws Exception { ++ InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); ++ handler.setHandler(new TestHandler()); ++ ++ assertThatCode(handler::doStop).doesNotThrowAnyException(); ++ } ++ ++ @Test ++ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { ++ InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); ++ handler.setHandler(new TestHandler()); ++ handler.setName("handler"); ++ handler.doStart(); ++ assertThat(registry.getGauges()) ++ .containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); ++ } ++ ++ @Test ++ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { ++ InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); ++ handler.setHandler(new TestHandler()); ++ handler.setName("handler"); ++ handler.doStart(); ++ assertThat(registry.getGauges()) ++ .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); ++ } ++ ++ @Disabled("flaky on virtual machines") ++ @Test ++ void responseTimesAreRecordedForAsyncResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/async")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ ++ assertResponseTimesValid(); ++ } ++ ++ private void assertResponseTimesValid() { ++ assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) ++ .isPositive(); ++ ++ assertThat( ++ registry ++ .getTimers() ++ .get(metricName().resolve("get-requests")) ++ .getSnapshot() ++ .getMedian()) ++ .isPositive() ++ .isLessThan(TimeUnit.SECONDS.toNanos(1)); ++ ++ assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) ++ .isPositive() ++ .isLessThan(TimeUnit.SECONDS.toNanos(1)); ++ } ++ ++ private String uri(String path) { ++ return "http://localhost:" + connector.getLocalPort() + path; ++ } ++ ++ private MetricName metricName() { ++ return MetricRegistry.name(TestHandler.class.getName(), "handler"); ++ } ++ ++ /** ++ * test handler. ++ * ++ *

    Supports ++ * ++ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the ++ * request ++ * ++ *

    all other requests will return 404 ++ */ ++ private static class TestHandler extends AbstractHandler { ++ @Override ++ public void handle( ++ String path, ++ Request request, ++ final HttpServletRequest httpServletRequest, ++ final HttpServletResponse httpServletResponse) ++ throws IOException, ServletException { ++ switch (path) { ++ case "/blocking": ++ request.setHandled(true); ++ try { ++ Thread.sleep(100); ++ } catch (InterruptedException e) { ++ Thread.currentThread().interrupt(); ++ } ++ httpServletResponse.setStatus(200); ++ httpServletResponse.setContentType("text/plain"); ++ httpServletResponse.getWriter().write("some content from the blocking request\n"); ++ break; ++ case "/async": ++ request.setHandled(true); ++ final AsyncContext context = request.startAsync(); ++ Thread t = ++ new Thread( ++ () -> { + try { +- Thread.sleep(100); ++ Thread.sleep(100); + } catch (InterruptedException e) { +- Thread.currentThread().interrupt(); ++ Thread.currentThread().interrupt(); + } + httpServletResponse.setStatus(200); + httpServletResponse.setContentType("text/plain"); +- httpServletResponse.getWriter().write("some content from the blocking request\n"); +- break; +- case "/async": +- request.setHandled(true); +- final AsyncContext context = request.startAsync(); +- Thread t = new Thread(() -> { +- try { +- Thread.sleep(100); +- } catch (InterruptedException e) { +- Thread.currentThread().interrupt(); +- } +- httpServletResponse.setStatus(200); +- httpServletResponse.setContentType("text/plain"); +- final ServletOutputStream servletOutputStream; +- try { +- servletOutputStream = httpServletResponse.getOutputStream(); +- servletOutputStream.setWriteListener( +- new WriteListener() { +- @Override +- public void onWritePossible() throws IOException { +- servletOutputStream.write("some content from the async\n" +- .getBytes(StandardCharsets.UTF_8)); +- context.complete(); +- } +- +- @Override +- public void onError(Throwable throwable) { +- context.complete(); +- } +- } +- ); +- } catch (IOException e) { +- context.complete(); +- } +- }); +- t.start(); +- break; +- default: +- break; +- } +- } ++ final ServletOutputStream servletOutputStream; ++ try { ++ servletOutputStream = httpServletResponse.getOutputStream(); ++ servletOutputStream.setWriteListener( ++ new WriteListener() { ++ @Override ++ public void onWritePossible() throws IOException { ++ servletOutputStream.write( ++ "some content from the async\n".getBytes(UTF_8)); ++ context.complete(); ++ } ++ ++ @Override ++ public void onError(Throwable throwable) { ++ context.complete(); ++ } ++ }); ++ } catch (IOException e) { ++ context.complete(); ++ } ++ }); ++ t.start(); ++ break; ++ default: ++ break; ++ } + } ++ } + } +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java +@@ -1,7 +1,17 @@ + package io.dropwizard.metrics5.jetty10; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; ++import java.io.IOException; ++import javax.servlet.AsyncContext; ++import javax.servlet.ServletOutputStream; ++import javax.servlet.WriteListener; ++import javax.servlet.http.HttpServletRequest; ++import javax.servlet.http.HttpServletResponse; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.Request; +@@ -12,202 +22,190 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import javax.servlet.AsyncContext; +-import javax.servlet.ServletOutputStream; +-import javax.servlet.WriteListener; +-import javax.servlet.http.HttpServletRequest; +-import javax.servlet.http.HttpServletResponse; +-import java.io.IOException; +-import java.nio.charset.StandardCharsets; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static org.assertj.core.api.Assertions.assertThat; +- +-class InstrumentedHttpChannelListenerTest { +- private final HttpClient client = new HttpClient(); +- private final Server server = new Server(); +- private final ServerConnector connector = new ServerConnector(server); +- private final TestHandler handler = new TestHandler(); +- private MetricRegistry registry; +- +- @BeforeEach +- void setUp() throws Exception { +- registry = new MetricRegistry(); +- connector.addBean(new InstrumentedHttpChannelListener(registry, MetricRegistry.name(TestHandler.class, "handler"), ALL)); +- server.addConnector(connector); +- server.setHandler(handler); +- server.start(); +- client.start(); +- } +- +- @AfterEach +- void tearDown() throws Exception { +- server.stop(); +- client.stop(); +- } +- +- @Test +- void createsMetricsForTheHandler() throws Exception { +- final ContentResponse response = client.GET(uri("/hello")); +- +- assertThat(response.getStatus()) +- .isEqualTo(404); +- +- assertThat(registry.getNames()) +- .containsOnly( +- metricName("1xx-responses"), +- metricName("2xx-responses"), +- metricName("3xx-responses"), +- metricName("404-responses"), +- metricName("4xx-responses"), +- metricName("5xx-responses"), +- metricName("percent-4xx-1m"), +- metricName("percent-4xx-5m"), +- metricName("percent-4xx-15m"), +- metricName("percent-5xx-1m"), +- metricName("percent-5xx-5m"), +- metricName("percent-5xx-15m"), +- metricName("requests"), +- metricName("active-suspended"), +- metricName("async-dispatches"), +- metricName("async-timeouts"), +- metricName("get-requests"), +- metricName("put-requests"), +- metricName("active-dispatches"), +- metricName("trace-requests"), +- metricName("other-requests"), +- metricName("connect-requests"), +- metricName("dispatches"), +- metricName("head-requests"), +- metricName("post-requests"), +- metricName("options-requests"), +- metricName("active-requests"), +- metricName("delete-requests"), +- metricName("move-requests") +- ); ++final class InstrumentedHttpChannelListenerTest { ++ private final HttpClient client = new HttpClient(); ++ private final Server server = new Server(); ++ private final ServerConnector connector = new ServerConnector(server); ++ private final TestHandler handler = new TestHandler(); ++ private MetricRegistry registry; ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ registry = new MetricRegistry(); ++ connector.addBean( ++ new InstrumentedHttpChannelListener( ++ registry, MetricRegistry.name(TestHandler.class, "handler"), ALL)); ++ server.addConnector(connector); ++ server.setHandler(handler); ++ server.start(); ++ client.start(); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ server.stop(); ++ client.stop(); ++ } ++ ++ @Test ++ void createsMetricsForTheHandler() throws Exception { ++ final ContentResponse response = client.GET(uri("/hello")); ++ ++ assertThat(response.getStatus()).isEqualTo(404); ++ ++ assertThat(registry.getNames()) ++ .containsOnly( ++ metricName("1xx-responses"), ++ metricName("2xx-responses"), ++ metricName("3xx-responses"), ++ metricName("404-responses"), ++ metricName("4xx-responses"), ++ metricName("5xx-responses"), ++ metricName("percent-4xx-1m"), ++ metricName("percent-4xx-5m"), ++ metricName("percent-4xx-15m"), ++ metricName("percent-5xx-1m"), ++ metricName("percent-5xx-5m"), ++ metricName("percent-5xx-15m"), ++ metricName("requests"), ++ metricName("active-suspended"), ++ metricName("async-dispatches"), ++ metricName("async-timeouts"), ++ metricName("get-requests"), ++ metricName("put-requests"), ++ metricName("active-dispatches"), ++ metricName("trace-requests"), ++ metricName("other-requests"), ++ metricName("connect-requests"), ++ metricName("dispatches"), ++ metricName("head-requests"), ++ metricName("post-requests"), ++ metricName("options-requests"), ++ metricName("active-requests"), ++ metricName("delete-requests"), ++ metricName("move-requests")); ++ } ++ ++ @Test ++ void responseTimesAreRecordedForBlockingResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/blocking")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.getMediaType()).isEqualTo("text/plain"); ++ assertThat(response.getContentAsString()).isEqualTo("some content from the blocking request"); ++ ++ assertResponseTimesValid(); ++ } ++ ++ @Test ++ void responseTimesAreRecordedForAsyncResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/async")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.getMediaType()).isEqualTo("text/plain"); ++ assertThat(response.getContentAsString()).isEqualTo("some content from the async"); ++ ++ assertResponseTimesValid(); ++ } ++ ++ private void assertResponseTimesValid() { ++ try { ++ Thread.sleep(100); ++ } catch (InterruptedException e) { ++ Thread.currentThread().interrupt(); + } + +- +- @Test +- void responseTimesAreRecordedForBlockingResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/blocking")); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.getMediaType()).isEqualTo("text/plain"); +- assertThat(response.getContentAsString()).isEqualTo("some content from the blocking request"); +- +- assertResponseTimesValid(); +- } +- +- @Test +- void responseTimesAreRecordedForAsyncResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/async")); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.getMediaType()).isEqualTo("text/plain"); +- assertThat(response.getContentAsString()).isEqualTo("some content from the async"); +- +- assertResponseTimesValid(); +- } +- +- private void assertResponseTimesValid() { +- try { ++ assertThat(registry.getMeters().get(metricName("2xx-responses")).getCount()).isPositive(); ++ assertThat(registry.getMeters().get(metricName("200-responses")).getCount()).isPositive(); ++ ++ assertThat(registry.getTimers().get(metricName("get-requests")).getSnapshot().getMedian()) ++ .isPositive(); ++ ++ assertThat(registry.getTimers().get(metricName("requests")).getSnapshot().getMedian()) ++ .isPositive(); ++ } ++ ++ private String uri(String path) { ++ return "http://localhost:" + connector.getLocalPort() + path; ++ } ++ ++ private MetricName metricName(String metricName) { ++ return MetricRegistry.name(TestHandler.class.getName(), "handler", metricName); ++ } ++ ++ /** ++ * test handler. ++ * ++ *

    Supports ++ * ++ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the ++ * request ++ * ++ *

    all other requests will return 404 ++ */ ++ private static class TestHandler extends AbstractHandler { ++ @Override ++ public void handle( ++ String path, ++ Request request, ++ final HttpServletRequest httpServletRequest, ++ final HttpServletResponse httpServletResponse) ++ throws IOException { ++ switch (path) { ++ case "/blocking": ++ request.setHandled(true); ++ httpServletResponse.setStatus(200); ++ httpServletResponse.setContentType("text/plain"); ++ httpServletResponse.getWriter().write("some content from the blocking request"); ++ try { + Thread.sleep(100); +- } catch (InterruptedException e) { ++ } catch (InterruptedException e) { ++ httpServletResponse.setStatus(500); + Thread.currentThread().interrupt(); +- } +- +- assertThat(registry.getMeters().get(metricName("2xx-responses")) +- .getCount()).isPositive(); +- assertThat(registry.getMeters().get(metricName("200-responses")) +- .getCount()).isPositive(); +- +- assertThat(registry.getTimers().get(metricName("get-requests")) +- .getSnapshot().getMedian()).isPositive(); +- +- assertThat(registry.getTimers().get(metricName("requests")) +- .getSnapshot().getMedian()).isPositive(); +- } +- +- private String uri(String path) { +- return "http://localhost:" + connector.getLocalPort() + path; +- } +- +- private MetricName metricName(String metricName) { +- return MetricRegistry.name(TestHandler.class.getName(), "handler", metricName); +- } +- +- /** +- * test handler. +- *

    +- * Supports +- *

    +- * /blocking - uses the standard servlet api +- * /async - uses the 3.1 async api to complete the request +- *

    +- * all other requests will return 404 +- */ +- private static class TestHandler extends AbstractHandler { +- @Override +- public void handle( +- String path, +- Request request, +- final HttpServletRequest httpServletRequest, +- final HttpServletResponse httpServletResponse) throws IOException { +- switch (path) { +- case "/blocking": +- request.setHandled(true); ++ } ++ break; ++ case "/async": ++ request.setHandled(true); ++ final AsyncContext context = request.startAsync(); ++ Thread t = ++ new Thread( ++ () -> { + httpServletResponse.setStatus(200); + httpServletResponse.setContentType("text/plain"); +- httpServletResponse.getWriter().write("some content from the blocking request"); + try { +- Thread.sleep(100); ++ Thread.sleep(100); + } catch (InterruptedException e) { +- httpServletResponse.setStatus(500); +- Thread.currentThread().interrupt(); ++ httpServletResponse.setStatus(500); ++ Thread.currentThread().interrupt(); ++ } ++ final ServletOutputStream servletOutputStream; ++ try { ++ servletOutputStream = httpServletResponse.getOutputStream(); ++ servletOutputStream.setWriteListener( ++ new WriteListener() { ++ @Override ++ public void onWritePossible() throws IOException { ++ servletOutputStream.write( ++ "some content from the async".getBytes(UTF_8)); ++ context.complete(); ++ } ++ ++ @Override ++ public void onError(Throwable throwable) { ++ context.complete(); ++ } ++ }); ++ } catch (IOException e) { ++ context.complete(); + } +- break; +- case "/async": +- request.setHandled(true); +- final AsyncContext context = request.startAsync(); +- Thread t = new Thread(() -> { +- httpServletResponse.setStatus(200); +- httpServletResponse.setContentType("text/plain"); +- try { +- Thread.sleep(100); +- } catch (InterruptedException e) { +- httpServletResponse.setStatus(500); +- Thread.currentThread().interrupt(); +- } +- final ServletOutputStream servletOutputStream; +- try { +- servletOutputStream = httpServletResponse.getOutputStream(); +- servletOutputStream.setWriteListener( +- new WriteListener() { +- @Override +- public void onWritePossible() throws IOException { +- servletOutputStream.write("some content from the async" +- .getBytes(StandardCharsets.UTF_8)); +- context.complete(); +- } +- +- @Override +- public void onError(Throwable throwable) { +- context.complete(); +- } +- } +- ); +- } catch (IOException e) { +- context.complete(); +- } +- }); +- t.start(); +- break; +- default: +- break; +- } +- } ++ }); ++ t.start(); ++ break; ++ default: ++ break; ++ } + } ++ } + } +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java +@@ -1,52 +1,52 @@ + package io.dropwizard.metrics5.jetty10; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.eclipse.jetty.util.thread.QueuedThreadPool; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class InstrumentedQueuedThreadPoolTest { +- private static final String PREFIX = "prefix"; +- +- private MetricRegistry metricRegistry; +- private InstrumentedQueuedThreadPool iqtp; +- +- @BeforeEach +- void setUp() { +- metricRegistry = new MetricRegistry(); +- iqtp = new InstrumentedQueuedThreadPool(metricRegistry); +- } +- +- @Test +- void customMetricsPrefix() throws Exception { +- iqtp.setPrefix(PREFIX); +- iqtp.start(); +- +- assertThat(metricRegistry.getNames()) +- .extracting(MetricName::getKey) +- .overridingErrorMessage("Custom metrics prefix doesn't match") +- .allSatisfy(name -> assertThat(name).startsWith(PREFIX)); +- +- iqtp.stop(); +- assertThat(metricRegistry.getMetrics()) +- .overridingErrorMessage("The default metrics prefix was changed") +- .isEmpty(); +- } +- +- @Test +- void metricsPrefixBackwardCompatible() throws Exception { +- iqtp.start(); +- assertThat(metricRegistry.getNames()) +- .extracting(MetricName::getKey) +- .overridingErrorMessage("The default metrics prefix was changed") +- .allSatisfy(name -> assertThat(name).startsWith(QueuedThreadPool.class.getName())); +- +- iqtp.stop(); +- assertThat(metricRegistry.getMetrics()) +- .overridingErrorMessage("The default metrics prefix was changed") +- .isEmpty(); +- } ++final class InstrumentedQueuedThreadPoolTest { ++ private static final String PREFIX = "prefix"; ++ ++ private MetricRegistry metricRegistry; ++ private InstrumentedQueuedThreadPool iqtp; ++ ++ @BeforeEach ++ void setUp() { ++ metricRegistry = new MetricRegistry(); ++ iqtp = new InstrumentedQueuedThreadPool(metricRegistry); ++ } ++ ++ @Test ++ void customMetricsPrefix() throws Exception { ++ iqtp.setPrefix(PREFIX); ++ iqtp.start(); ++ ++ assertThat(metricRegistry.getNames()) ++ .extracting(MetricName::getKey) ++ .overridingErrorMessage("Custom metrics prefix doesn't match") ++ .allSatisfy(name -> assertThat(name).startsWith(PREFIX)); ++ ++ iqtp.stop(); ++ assertThat(metricRegistry.getMetrics()) ++ .overridingErrorMessage("The default metrics prefix was changed") ++ .isEmpty(); ++ } ++ ++ @Test ++ void metricsPrefixBackwardCompatible() throws Exception { ++ iqtp.start(); ++ assertThat(metricRegistry.getNames()) ++ .extracting(MetricName::getKey) ++ .overridingErrorMessage("The default metrics prefix was changed") ++ .allSatisfy(name -> assertThat(name).startsWith(QueuedThreadPool.class.getName())); ++ ++ iqtp.stop(); ++ assertThat(metricRegistry.getMetrics()) ++ .overridingErrorMessage("The default metrics prefix was changed") ++ .isEmpty(); ++ } + } +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java +@@ -2,62 +2,63 @@ package io.dropwizard.metrics5.jetty11; + + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Timer; ++import java.util.List; + import org.eclipse.jetty.io.Connection; + import org.eclipse.jetty.io.EndPoint; + import org.eclipse.jetty.server.ConnectionFactory; + import org.eclipse.jetty.server.Connector; + import org.eclipse.jetty.util.component.ContainerLifeCycle; + +-import java.util.List; +- + public class InstrumentedConnectionFactory extends ContainerLifeCycle implements ConnectionFactory { +- private final ConnectionFactory connectionFactory; +- private final Timer timer; +- private final Counter counter; +- +- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { +- this(connectionFactory, timer, null); +- } +- +- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer, Counter counter) { +- this.connectionFactory = connectionFactory; +- this.timer = timer; +- this.counter = counter; +- addBean(connectionFactory); +- } +- +- @Override +- public String getProtocol() { +- return connectionFactory.getProtocol(); +- } +- +- @Override +- public List getProtocols() { +- return connectionFactory.getProtocols(); +- } +- +- @Override +- public Connection newConnection(Connector connector, EndPoint endPoint) { +- final Connection connection = connectionFactory.newConnection(connector, endPoint); +- connection.addEventListener(new Connection.Listener() { +- private Timer.Context context; +- +- @Override +- public void onOpened(Connection connection) { +- this.context = timer.time(); +- if (counter != null) { +- counter.inc(); +- } ++ private final ConnectionFactory connectionFactory; ++ private final Timer timer; ++ private final Counter counter; ++ ++ public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { ++ this(connectionFactory, timer, null); ++ } ++ ++ public InstrumentedConnectionFactory( ++ ConnectionFactory connectionFactory, Timer timer, Counter counter) { ++ this.connectionFactory = connectionFactory; ++ this.timer = timer; ++ this.counter = counter; ++ addBean(connectionFactory); ++ } ++ ++ @Override ++ public String getProtocol() { ++ return connectionFactory.getProtocol(); ++ } ++ ++ @Override ++ public List getProtocols() { ++ return connectionFactory.getProtocols(); ++ } ++ ++ @Override ++ public Connection newConnection(Connector connector, EndPoint endPoint) { ++ final Connection connection = connectionFactory.newConnection(connector, endPoint); ++ connection.addEventListener( ++ new Connection.Listener() { ++ private Timer.Context context; ++ ++ @Override ++ public void onOpened(Connection connection) { ++ this.context = timer.time(); ++ if (counter != null) { ++ counter.inc(); + } ++ } + +- @Override +- public void onClosed(Connection connection) { +- context.stop(); +- if (counter != null) { +- counter.dec(); +- } ++ @Override ++ public void onClosed(Connection connection) { ++ context.stop(); ++ if (counter != null) { ++ counter.dec(); + } ++ } + }); +- return connection; +- } ++ return connection; ++ } + } +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java +@@ -1,5 +1,13 @@ + package io.dropwizard.metrics5.jetty11; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; ++ ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -12,433 +20,444 @@ import jakarta.servlet.AsyncListener; + import jakarta.servlet.ServletException; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; +-import org.eclipse.jetty.http.HttpMethod; +-import org.eclipse.jetty.server.AsyncContextState; +-import org.eclipse.jetty.server.Handler; +-import org.eclipse.jetty.server.HttpChannelState; +-import org.eclipse.jetty.server.Request; +-import org.eclipse.jetty.server.handler.HandlerWrapper; +- + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; + import java.util.Set; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import org.eclipse.jetty.http.HttpMethod; ++import org.eclipse.jetty.server.AsyncContextState; ++import org.eclipse.jetty.server.Handler; ++import org.eclipse.jetty.server.HttpChannelState; ++import org.eclipse.jetty.server.Request; ++import org.eclipse.jetty.server.handler.HandlerWrapper; + + /** + * A Jetty {@link Handler} which records various metrics about an underlying {@link Handler} + * instance. + */ + public class InstrumentedHandler extends HandlerWrapper { +- private static final String NAME_REQUESTS = "requests"; +- private static final String NAME_DISPATCHES = "dispatches"; +- private static final String NAME_ACTIVE_REQUESTS = "active-requests"; +- private static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; +- private static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; +- private static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; +- private static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; +- private static final String NAME_1XX_RESPONSES = "1xx-responses"; +- private static final String NAME_2XX_RESPONSES = "2xx-responses"; +- private static final String NAME_3XX_RESPONSES = "3xx-responses"; +- private static final String NAME_4XX_RESPONSES = "4xx-responses"; +- private static final String NAME_5XX_RESPONSES = "5xx-responses"; +- private static final String NAME_GET_REQUESTS = "get-requests"; +- private static final String NAME_POST_REQUESTS = "post-requests"; +- private static final String NAME_HEAD_REQUESTS = "head-requests"; +- private static final String NAME_PUT_REQUESTS = "put-requests"; +- private static final String NAME_DELETE_REQUESTS = "delete-requests"; +- private static final String NAME_OPTIONS_REQUESTS = "options-requests"; +- private static final String NAME_TRACE_REQUESTS = "trace-requests"; +- private static final String NAME_CONNECT_REQUESTS = "connect-requests"; +- private static final String NAME_MOVE_REQUESTS = "move-requests"; +- private static final String NAME_OTHER_REQUESTS = "other-requests"; +- private static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; +- private static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; +- private static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; +- private static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; +- private static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; +- private static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; +- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); +- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); +- +- private final MetricRegistry metricRegistry; +- +- private String name; +- private final String prefix; +- +- // the requests handled by this handler, excluding active +- private Timer requests; +- +- // the number of dispatches seen by this handler, excluding active +- private Timer dispatches; +- +- // the number of active requests +- private Counter activeRequests; +- +- // the number of active dispatches +- private Counter activeDispatches; +- +- // the number of requests currently suspended. +- private Counter activeSuspended; +- +- // the number of requests that have been asynchronously dispatched +- private Meter asyncDispatches; +- +- // the number of requests that expired while suspended +- private Meter asyncTimeouts; +- +- private final ResponseMeteredLevel responseMeteredLevel; +- private List responses; +- private Map responseCodeMeters; +- +- private Timer getRequests; +- private Timer postRequests; +- private Timer headRequests; +- private Timer putRequests; +- private Timer deleteRequests; +- private Timer optionsRequests; +- private Timer traceRequests; +- private Timer connectRequests; +- private Timer moveRequests; +- private Timer otherRequests; +- +- private AsyncListener listener; +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- */ +- public InstrumentedHandler(MetricRegistry registry) { +- this(registry, null); ++ private static final String NAME_REQUESTS = "requests"; ++ private static final String NAME_DISPATCHES = "dispatches"; ++ private static final String NAME_ACTIVE_REQUESTS = "active-requests"; ++ private static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; ++ private static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; ++ private static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; ++ private static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; ++ private static final String NAME_1XX_RESPONSES = "1xx-responses"; ++ private static final String NAME_2XX_RESPONSES = "2xx-responses"; ++ private static final String NAME_3XX_RESPONSES = "3xx-responses"; ++ private static final String NAME_4XX_RESPONSES = "4xx-responses"; ++ private static final String NAME_5XX_RESPONSES = "5xx-responses"; ++ private static final String NAME_GET_REQUESTS = "get-requests"; ++ private static final String NAME_POST_REQUESTS = "post-requests"; ++ private static final String NAME_HEAD_REQUESTS = "head-requests"; ++ private static final String NAME_PUT_REQUESTS = "put-requests"; ++ private static final String NAME_DELETE_REQUESTS = "delete-requests"; ++ private static final String NAME_OPTIONS_REQUESTS = "options-requests"; ++ private static final String NAME_TRACE_REQUESTS = "trace-requests"; ++ private static final String NAME_CONNECT_REQUESTS = "connect-requests"; ++ private static final String NAME_MOVE_REQUESTS = "move-requests"; ++ private static final String NAME_OTHER_REQUESTS = "other-requests"; ++ private static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; ++ private static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; ++ private static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; ++ private static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; ++ private static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; ++ private static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; ++ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); ++ private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); ++ ++ private final MetricRegistry metricRegistry; ++ ++ private String name; ++ private final String prefix; ++ ++ // the requests handled by this handler, excluding active ++ private Timer requests; ++ ++ // the number of dispatches seen by this handler, excluding active ++ private Timer dispatches; ++ ++ // the number of active requests ++ private Counter activeRequests; ++ ++ // the number of active dispatches ++ private Counter activeDispatches; ++ ++ // the number of requests currently suspended. ++ private Counter activeSuspended; ++ ++ // the number of requests that have been asynchronously dispatched ++ private Meter asyncDispatches; ++ ++ // the number of requests that expired while suspended ++ private Meter asyncTimeouts; ++ ++ private final ResponseMeteredLevel responseMeteredLevel; ++ private List responses; ++ private Map responseCodeMeters; ++ ++ private Timer getRequests; ++ private Timer postRequests; ++ private Timer headRequests; ++ private Timer putRequests; ++ private Timer deleteRequests; ++ private Timer optionsRequests; ++ private Timer traceRequests; ++ private Timer connectRequests; ++ private Timer moveRequests; ++ private Timer otherRequests; ++ ++ private AsyncListener listener; ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ */ ++ public InstrumentedHandler(MetricRegistry registry) { ++ this(registry, null); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param prefix the prefix to use for the metrics names ++ */ ++ public InstrumentedHandler(MetricRegistry registry, String prefix) { ++ this(registry, prefix, COARSE); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param prefix the prefix to use for the metrics names ++ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are ++ * instrumented ++ */ ++ public InstrumentedHandler( ++ MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { ++ this.responseMeteredLevel = responseMeteredLevel; ++ this.metricRegistry = registry; ++ this.prefix = prefix; ++ } ++ ++ public String getName() { ++ return name; ++ } ++ ++ public void setName(String name) { ++ this.name = name; ++ } ++ ++ @Override ++ protected void doStart() throws Exception { ++ super.doStart(); ++ ++ final MetricName prefix = getMetricPrefix(); ++ ++ this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); ++ this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); ++ ++ this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); ++ this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); ++ this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); ++ ++ this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); ++ this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); ++ ++ this.responseCodeMeters = ++ DETAILED_METER_LEVELS.contains(responseMeteredLevel) ++ ? new ConcurrentHashMap<>() ++ : ImmutableMap.of(); ++ ++ this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); ++ this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); ++ this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); ++ this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); ++ this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); ++ this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); ++ this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); ++ this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); ++ this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); ++ this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); ++ ++ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { ++ this.responses = ++ unmodifiableList( ++ Arrays.asList( ++ metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx ++ metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx ++ metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx ++ metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx ++ metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx ++ )); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_4XX_1M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_4XX_5M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_4XX_15M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of( ++ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_5XX_1M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_5XX_5M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_5XX_15M), ++ new RatioGauge() { ++ @Override ++ public Ratio getRatio() { ++ return Ratio.of( ++ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } ++ }); ++ } else { ++ this.responses = ImmutableList.of(); + } + +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param prefix the prefix to use for the metrics names +- */ +- public InstrumentedHandler(MetricRegistry registry, String prefix) { +- this(registry, prefix, COARSE); ++ this.listener = new AsyncAttachingListener(); ++ } ++ ++ @Override ++ protected void doStop() throws Exception { ++ final MetricName prefix = getMetricPrefix(); ++ ++ metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); ++ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); ++ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); ++ metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); ++ metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); ++ metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); ++ ++ if (responseCodeMeters != null) { ++ responseCodeMeters.keySet().stream() ++ .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) ++ .forEach(metricRegistry::remove); + } +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param prefix the prefix to use for the metrics names +- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented +- */ +- public InstrumentedHandler(MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { +- this.responseMeteredLevel = responseMeteredLevel; +- this.metricRegistry = registry; +- this.prefix = prefix; ++ super.doStop(); ++ } ++ ++ @Override ++ public void handle( ++ String path, ++ Request request, ++ HttpServletRequest httpRequest, ++ HttpServletResponse httpResponse) ++ throws IOException, ServletException { ++ ++ activeDispatches.inc(); ++ ++ final long start; ++ final HttpChannelState state = request.getHttpChannelState(); ++ if (state.isInitial()) { ++ // new request ++ activeRequests.inc(); ++ start = request.getTimeStamp(); ++ state.addListener(listener); ++ } else { ++ // resumed request ++ start = System.currentTimeMillis(); ++ activeSuspended.dec(); ++ if (state.getState() == HttpChannelState.State.HANDLING) { ++ asyncDispatches.mark(); ++ } + } + +- public String getName() { +- return name; ++ try { ++ super.handle(path, request, httpRequest, httpResponse); ++ } finally { ++ final long now = System.currentTimeMillis(); ++ final long dispatched = now - start; ++ ++ activeDispatches.dec(); ++ dispatches.update(dispatched, TimeUnit.MILLISECONDS); ++ ++ if (state.isSuspended()) { ++ activeSuspended.inc(); ++ } else if (state.isInitial()) { ++ updateResponses(httpRequest, httpResponse, start, request.isHandled()); ++ } ++ // else onCompletion will handle it. + } +- +- public void setName(String name) { +- this.name = name; ++ } ++ ++ private Timer requestTimer(String method) { ++ final HttpMethod m = HttpMethod.fromString(method); ++ if (m == null) { ++ return otherRequests; ++ } else { ++ switch (m) { ++ case GET: ++ return getRequests; ++ case POST: ++ return postRequests; ++ case PUT: ++ return putRequests; ++ case HEAD: ++ return headRequests; ++ case DELETE: ++ return deleteRequests; ++ case OPTIONS: ++ return optionsRequests; ++ case TRACE: ++ return traceRequests; ++ case CONNECT: ++ return connectRequests; ++ case MOVE: ++ return moveRequests; ++ default: ++ return otherRequests; ++ } + } +- +- @Override +- protected void doStart() throws Exception { +- super.doStart(); +- +- final MetricName prefix = getMetricPrefix(); +- +- this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); +- this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); +- +- this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); +- this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); +- this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); +- +- this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); +- this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); +- +- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); +- +- this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); +- this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); +- this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); +- this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); +- this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); +- this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); +- this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); +- this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); +- this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); +- this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); +- +- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { +- this.responses = Collections.unmodifiableList(Arrays.asList( +- metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx +- metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx +- metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx +- metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx +- metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx +- )); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_1M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_5M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_15M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_1M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_5M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_15M), new RatioGauge() { +- @Override +- public Ratio getRatio() { +- return Ratio.of(responses.get(4).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } +- }); +- } else { +- this.responses = Collections.emptyList(); +- } +- +- this.listener = new AsyncAttachingListener(); ++ } ++ ++ private void updateResponses( ++ HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { ++ if (isHandled) { ++ mark(response.getStatus()); ++ } else { ++ mark(404); ++ ; // will end up with a 404 response sent by HttpChannel.handle + } +- +- @Override +- protected void doStop() throws Exception { +- final MetricName prefix = getMetricPrefix(); +- +- metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); +- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); +- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); +- metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); +- metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); +- metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); +- +- if (responseCodeMeters != null) { +- responseCodeMeters.keySet().stream() +- .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) +- .forEach(metricRegistry::remove); +- } +- super.doStop(); ++ activeRequests.dec(); ++ final long elapsedTime = System.currentTimeMillis() - start; ++ requests.update(elapsedTime, TimeUnit.MILLISECONDS); ++ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); ++ } ++ ++ private MetricName getMetricPrefix() { ++ return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); ++ } ++ ++ private void mark(int statusCode) { ++ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { ++ getResponseCodeMeter(statusCode).mark(); + } + +- @Override +- public void handle(String path, +- Request request, +- HttpServletRequest httpRequest, +- HttpServletResponse httpResponse) throws IOException, ServletException { +- +- activeDispatches.inc(); +- +- final long start; +- final HttpChannelState state = request.getHttpChannelState(); +- if (state.isInitial()) { +- // new request +- activeRequests.inc(); +- start = request.getTimeStamp(); +- state.addListener(listener); +- } else { +- // resumed request +- start = System.currentTimeMillis(); +- activeSuspended.dec(); +- if (state.getState() == HttpChannelState.State.HANDLING) { +- asyncDispatches.mark(); +- } +- } ++ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { ++ final int responseStatus = statusCode / 100; ++ if (responseStatus >= 1 && responseStatus <= 5) { ++ responses.get(responseStatus - 1).mark(); ++ } ++ } ++ } + +- try { +- super.handle(path, request, httpRequest, httpResponse); +- } finally { +- final long now = System.currentTimeMillis(); +- final long dispatched = now - start; ++ private Meter getResponseCodeMeter(int statusCode) { ++ return responseCodeMeters.computeIfAbsent( ++ statusCode, ++ sc -> metricRegistry.meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); ++ } + +- activeDispatches.dec(); +- dispatches.update(dispatched, TimeUnit.MILLISECONDS); ++ private class AsyncAttachingListener implements AsyncListener { + +- if (state.isSuspended()) { +- activeSuspended.inc(); +- } else if (state.isInitial()) { +- updateResponses(httpRequest, httpResponse, start, request.isHandled()); +- } +- // else onCompletion will handle it. +- } +- } ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException {} + +- private Timer requestTimer(String method) { +- final HttpMethod m = HttpMethod.fromString(method); +- if (m == null) { +- return otherRequests; +- } else { +- switch (m) { +- case GET: +- return getRequests; +- case POST: +- return postRequests; +- case PUT: +- return putRequests; +- case HEAD: +- return headRequests; +- case DELETE: +- return deleteRequests; +- case OPTIONS: +- return optionsRequests; +- case TRACE: +- return traceRequests; +- case CONNECT: +- return connectRequests; +- case MOVE: +- return moveRequests; +- default: +- return otherRequests; +- } +- } ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException { ++ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); + } + +- private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { +- if (isHandled) { +- mark(response.getStatus()); +- } else { +- mark(404);; // will end up with a 404 response sent by HttpChannel.handle +- } +- activeRequests.dec(); +- final long elapsedTime = System.currentTimeMillis() - start; +- requests.update(elapsedTime, TimeUnit.MILLISECONDS); +- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); +- } ++ @Override ++ public void onError(AsyncEvent event) throws IOException {} + +- private MetricName getMetricPrefix() { +- return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException {} ++ } ++ ; + +- private void mark(int statusCode) { +- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { +- getResponseCodeMeter(statusCode).mark(); +- } ++ private class InstrumentedAsyncListener implements AsyncListener { ++ private final long startTime; + +- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { +- final int responseStatus = statusCode / 100; +- if (responseStatus >= 1 && responseStatus <= 5) { +- responses.get(responseStatus - 1).mark(); +- } +- } ++ InstrumentedAsyncListener() { ++ this.startTime = System.currentTimeMillis(); + } + +- private Meter getResponseCodeMeter(int statusCode) { +- return responseCodeMeters +- .computeIfAbsent(statusCode, sc -> metricRegistry +- .meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException { ++ asyncTimeouts.mark(); + } + +- private class AsyncAttachingListener implements AsyncListener { +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException {} +- +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); +- } +- +- @Override +- public void onError(AsyncEvent event) throws IOException {} +- +- @Override +- public void onComplete(AsyncEvent event) throws IOException {} +- }; +- +- private class InstrumentedAsyncListener implements AsyncListener { +- private final long startTime; +- +- InstrumentedAsyncListener() { +- this.startTime = System.currentTimeMillis(); +- } +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException { +- asyncTimeouts.mark(); +- } +- +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- } ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException {} + +- @Override +- public void onError(AsyncEvent event) throws IOException { +- } ++ @Override ++ public void onError(AsyncEvent event) throws IOException {} + +- @Override +- public void onComplete(AsyncEvent event) throws IOException { +- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); +- final HttpServletRequest request = (HttpServletRequest) state.getRequest(); +- final HttpServletResponse response = (HttpServletResponse) state.getResponse(); +- updateResponses(request, response, startTime, true); +- if (!state.getHttpChannelState().isSuspended()) { +- activeSuspended.dec(); +- } +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException { ++ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); ++ final HttpServletRequest request = (HttpServletRequest) state.getRequest(); ++ final HttpServletResponse response = (HttpServletResponse) state.getResponse(); ++ updateResponses(request, response, startTime, true); ++ if (!state.getHttpChannelState().isSuspended()) { ++ activeSuspended.dec(); ++ } + } ++ } + } +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java +@@ -1,5 +1,12 @@ + package io.dropwizard.metrics5.jetty11; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; ++ ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -11,415 +18,398 @@ import jakarta.servlet.AsyncEvent; + import jakarta.servlet.AsyncListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; +-import org.eclipse.jetty.http.HttpMethod; +-import org.eclipse.jetty.server.AsyncContextState; +-import org.eclipse.jetty.server.HttpChannel.Listener; +-import org.eclipse.jetty.server.HttpChannelState; +-import org.eclipse.jetty.server.Request; +- + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; + import java.util.Set; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; +- ++import org.eclipse.jetty.http.HttpMethod; ++import org.eclipse.jetty.server.AsyncContextState; ++import org.eclipse.jetty.server.HttpChannel.Listener; ++import org.eclipse.jetty.server.HttpChannelState; ++import org.eclipse.jetty.server.Request; + + /** +- * A Jetty {@link org.eclipse.jetty.server.HttpChannel.Listener} implementation which records various metrics about +- * underlying channel instance. Unlike {@link InstrumentedHandler} that uses internal API, this class should be +- * future proof. To install it, just add instance of this class to {@link org.eclipse.jetty.server.Connector} as bean. ++ * A Jetty {@link org.eclipse.jetty.server.HttpChannel.Listener} implementation which records ++ * various metrics about underlying channel instance. Unlike {@link InstrumentedHandler} that uses ++ * internal API, this class should be future proof. To install it, just add instance of this class ++ * to {@link org.eclipse.jetty.server.Connector} as bean. + * + * @since TBD + */ +-public class InstrumentedHttpChannelListener +- implements Listener { +- private static final String START_ATTR = InstrumentedHttpChannelListener.class.getName() + ".start"; +- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); +- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); +- +- private final MetricRegistry metricRegistry; +- +- // the requests handled by this handler, excluding active +- private final Timer requests; +- +- // the number of dispatches seen by this handler, excluding active +- private final Timer dispatches; +- +- // the number of active requests +- private final Counter activeRequests; +- +- // the number of active dispatches +- private final Counter activeDispatches; +- +- // the number of requests currently suspended. +- private final Counter activeSuspended; +- +- // the number of requests that have been asynchronously dispatched +- private final Meter asyncDispatches; +- +- // the number of requests that expired while suspended +- private final Meter asyncTimeouts; +- +- private final ResponseMeteredLevel responseMeteredLevel; +- private final List responses; +- private final Map responseCodeMeters; +- private final MetricName prefix; +- private final Timer getRequests; +- private final Timer postRequests; +- private final Timer headRequests; +- private final Timer putRequests; +- private final Timer deleteRequests; +- private final Timer optionsRequests; +- private final Timer traceRequests; +- private final Timer connectRequests; +- private final Timer moveRequests; +- private final Timer otherRequests; +- +- private final AsyncListener listener; +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- */ +- public InstrumentedHttpChannelListener(MetricRegistry registry) { +- this(registry, null, COARSE); +- } +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param pref the prefix to use for the metrics names +- */ +- public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref) { +- this(registry, pref, COARSE); +- } +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param pref the prefix to use for the metrics names +- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented +- */ +- public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref, ResponseMeteredLevel responseMeteredLevel) { +- this.metricRegistry = registry; +- +- this.prefix = (pref == null) ? MetricName.build(getClass().getName()) : pref; +- +- this.requests = metricRegistry.timer(prefix.resolve("requests")); +- this.dispatches = metricRegistry.timer(prefix.resolve("dispatches")); +- +- this.activeRequests = metricRegistry.counter(prefix.resolve("active-requests")); +- this.activeDispatches = metricRegistry.counter(prefix.resolve("active-dispatches")); +- this.activeSuspended = metricRegistry.counter(prefix.resolve("active-suspended")); +- +- this.asyncDispatches = metricRegistry.meter(prefix.resolve("async-dispatches")); +- this.asyncTimeouts = metricRegistry.meter(prefix.resolve("async-timeouts")); +- +- this.responseMeteredLevel = responseMeteredLevel; +- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); +- this.responses = COARSE_METER_LEVELS.contains(responseMeteredLevel) ? +- Collections.unmodifiableList(Arrays.asList( +- registry.meter(prefix.resolve("1xx-responses")), // 1xx +- registry.meter(prefix.resolve("2xx-responses")), // 2xx +- registry.meter(prefix.resolve("3xx-responses")), // 3xx +- registry.meter(prefix.resolve("4xx-responses")), // 4xx +- registry.meter(prefix.resolve("5xx-responses")) // 5xx +- )) : Collections.emptyList(); +- +- this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); +- this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); +- this.headRequests = metricRegistry.timer(prefix.resolve("head-requests")); +- this.putRequests = metricRegistry.timer(prefix.resolve("put-requests")); +- this.deleteRequests = metricRegistry.timer(prefix.resolve("delete-requests")); +- this.optionsRequests = metricRegistry.timer(prefix.resolve("options-requests")); +- this.traceRequests = metricRegistry.timer(prefix.resolve("trace-requests")); +- this.connectRequests = metricRegistry.timer(prefix.resolve("connect-requests")); +- this.moveRequests = metricRegistry.timer(prefix.resolve("move-requests")); +- this.otherRequests = metricRegistry.timer(prefix.resolve("other-requests")); +- +- metricRegistry.register(prefix.resolve("percent-4xx-1m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } ++public class InstrumentedHttpChannelListener implements Listener { ++ private static final String START_ATTR = ++ InstrumentedHttpChannelListener.class.getName() + ".start"; ++ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); ++ private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); ++ ++ private final MetricRegistry metricRegistry; ++ ++ // the requests handled by this handler, excluding active ++ private final Timer requests; ++ ++ // the number of dispatches seen by this handler, excluding active ++ private final Timer dispatches; ++ ++ // the number of active requests ++ private final Counter activeRequests; ++ ++ // the number of active dispatches ++ private final Counter activeDispatches; ++ ++ // the number of requests currently suspended. ++ private final Counter activeSuspended; ++ ++ // the number of requests that have been asynchronously dispatched ++ private final Meter asyncDispatches; ++ ++ // the number of requests that expired while suspended ++ private final Meter asyncTimeouts; ++ ++ private final ResponseMeteredLevel responseMeteredLevel; ++ private final List responses; ++ private final Map responseCodeMeters; ++ private final MetricName prefix; ++ private final Timer getRequests; ++ private final Timer postRequests; ++ private final Timer headRequests; ++ private final Timer putRequests; ++ private final Timer deleteRequests; ++ private final Timer optionsRequests; ++ private final Timer traceRequests; ++ private final Timer connectRequests; ++ private final Timer moveRequests; ++ private final Timer otherRequests; ++ ++ private final AsyncListener listener; ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ */ ++ public InstrumentedHttpChannelListener(MetricRegistry registry) { ++ this(registry, null, COARSE); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param pref the prefix to use for the metrics names ++ */ ++ public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref) { ++ this(registry, pref, COARSE); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param pref the prefix to use for the metrics names ++ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are ++ * instrumented ++ */ ++ public InstrumentedHttpChannelListener( ++ MetricRegistry registry, MetricName pref, ResponseMeteredLevel responseMeteredLevel) { ++ this.metricRegistry = registry; ++ ++ this.prefix = (pref == null) ? MetricName.build(getClass().getName()) : pref; ++ ++ this.requests = metricRegistry.timer(prefix.resolve("requests")); ++ this.dispatches = metricRegistry.timer(prefix.resolve("dispatches")); ++ ++ this.activeRequests = metricRegistry.counter(prefix.resolve("active-requests")); ++ this.activeDispatches = metricRegistry.counter(prefix.resolve("active-dispatches")); ++ this.activeSuspended = metricRegistry.counter(prefix.resolve("active-suspended")); ++ ++ this.asyncDispatches = metricRegistry.meter(prefix.resolve("async-dispatches")); ++ this.asyncTimeouts = metricRegistry.meter(prefix.resolve("async-timeouts")); ++ ++ this.responseMeteredLevel = responseMeteredLevel; ++ this.responseCodeMeters = ++ DETAILED_METER_LEVELS.contains(responseMeteredLevel) ++ ? new ConcurrentHashMap<>() ++ : ImmutableMap.of(); ++ this.responses = ++ COARSE_METER_LEVELS.contains(responseMeteredLevel) ++ ? unmodifiableList( ++ Arrays.asList( ++ registry.meter(prefix.resolve("1xx-responses")), // 1xx ++ registry.meter(prefix.resolve("2xx-responses")), // 2xx ++ registry.meter(prefix.resolve("3xx-responses")), // 3xx ++ registry.meter(prefix.resolve("4xx-responses")), // 4xx ++ registry.meter(prefix.resolve("5xx-responses")) // 5xx ++ )) ++ : ImmutableList.of(); ++ ++ this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); ++ this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); ++ this.headRequests = metricRegistry.timer(prefix.resolve("head-requests")); ++ this.putRequests = metricRegistry.timer(prefix.resolve("put-requests")); ++ this.deleteRequests = metricRegistry.timer(prefix.resolve("delete-requests")); ++ this.optionsRequests = metricRegistry.timer(prefix.resolve("options-requests")); ++ this.traceRequests = metricRegistry.timer(prefix.resolve("trace-requests")); ++ this.connectRequests = metricRegistry.timer(prefix.resolve("connect-requests")); ++ this.moveRequests = metricRegistry.timer(prefix.resolve("move-requests")); ++ this.otherRequests = metricRegistry.timer(prefix.resolve("other-requests")); ++ ++ metricRegistry.register( ++ prefix.resolve("percent-4xx-1m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-4xx-5m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-4xx-5m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-4xx-15m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-4xx-15m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of( ++ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-5xx-1m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-5xx-1m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-5xx-5m"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-5xx-5m"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } + }); + +- metricRegistry.register(prefix.resolve("percent-5xx-15m"), new RatioGauge() { +- @Override +- public RatioGauge.Ratio getRatio() { +- return Ratio.of(responses.get(4).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } ++ metricRegistry.register( ++ prefix.resolve("percent-5xx-15m"), ++ new RatioGauge() { ++ @Override ++ public RatioGauge.Ratio getRatio() { ++ return Ratio.of( ++ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } + }); + +- this.listener = new AsyncAttachingListener(); +- } ++ this.listener = new AsyncAttachingListener(); ++ } + +- @Override +- public void onRequestBegin(final Request request) { ++ @Override ++ public void onRequestBegin(final Request request) {} + +- } +- +- @Override +- public void onBeforeDispatch(final Request request) { +- before(request); +- } ++ @Override ++ public void onBeforeDispatch(final Request request) { ++ before(request); ++ } + +- @Override +- public void onDispatchFailure(final Request request, final Throwable failure) { ++ @Override ++ public void onDispatchFailure(final Request request, final Throwable failure) {} + +- } ++ @Override ++ public void onAfterDispatch(final Request request) { ++ after(request); ++ } + +- @Override +- public void onAfterDispatch(final Request request) { +- after(request); +- } ++ @Override ++ public void onRequestContent(final Request request, final ByteBuffer content) {} + +- @Override +- public void onRequestContent(final Request request, final ByteBuffer content) { ++ @Override ++ public void onRequestContentEnd(final Request request) {} + +- } ++ @Override ++ public void onRequestTrailers(final Request request) {} + +- @Override +- public void onRequestContentEnd(final Request request) { ++ @Override ++ public void onRequestEnd(final Request request) {} + +- } ++ @Override ++ public void onRequestFailure(final Request request, final Throwable failure) {} + +- @Override +- public void onRequestTrailers(final Request request) { ++ @Override ++ public void onResponseBegin(final Request request) {} + +- } ++ @Override ++ public void onResponseCommit(final Request request) {} + +- @Override +- public void onRequestEnd(final Request request) { ++ @Override ++ public void onResponseContent(final Request request, final ByteBuffer content) {} + +- } ++ @Override ++ public void onResponseEnd(final Request request) {} + +- @Override +- public void onRequestFailure(final Request request, final Throwable failure) { ++ @Override ++ public void onResponseFailure(final Request request, final Throwable failure) {} + +- } ++ @Override ++ public void onComplete(final Request request) {} + +- @Override +- public void onResponseBegin(final Request request) { ++ private void before(final Request request) { ++ activeDispatches.inc(); + ++ final long start; ++ final HttpChannelState state = request.getHttpChannelState(); ++ if (state.isInitial()) { ++ // new request ++ activeRequests.inc(); ++ start = request.getTimeStamp(); ++ state.addListener(listener); ++ } else { ++ // resumed request ++ start = System.currentTimeMillis(); ++ activeSuspended.dec(); ++ if (state.isAsyncStarted()) { ++ asyncDispatches.mark(); ++ } + } +- +- @Override +- public void onResponseCommit(final Request request) { +- ++ request.setAttribute(START_ATTR, start); ++ } ++ ++ private void after(final Request request) { ++ final long start = (long) request.getAttribute(START_ATTR); ++ final long now = System.currentTimeMillis(); ++ final long dispatched = now - start; ++ ++ activeDispatches.dec(); ++ dispatches.update(dispatched, TimeUnit.MILLISECONDS); ++ ++ final HttpChannelState state = request.getHttpChannelState(); ++ if (state.isSuspended()) { ++ activeSuspended.inc(); ++ } else if (state.isInitial()) { ++ updateResponses(request, request.getResponse(), start, request.isHandled()); + } +- +- @Override +- public void onResponseContent(final Request request, final ByteBuffer content) { +- ++ // else onCompletion will handle it. ++ } ++ ++ private void updateResponses( ++ HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { ++ if (isHandled) { ++ mark(response.getStatus()); ++ } else { ++ mark(404); // will end up with a 404 response sent by HttpChannel.handle ++ } ++ activeRequests.dec(); ++ final long elapsedTime = System.currentTimeMillis() - start; ++ requests.update(elapsedTime, TimeUnit.MILLISECONDS); ++ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); ++ } ++ ++ private void mark(int statusCode) { ++ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { ++ getResponseCodeMeter(statusCode).mark(); + } + +- @Override +- public void onResponseEnd(final Request request) { +- ++ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { ++ final int responseStatus = statusCode / 100; ++ if (responseStatus >= 1 && responseStatus <= 5) { ++ responses.get(responseStatus - 1).mark(); ++ } + } ++ } ++ ++ private Meter getResponseCodeMeter(int statusCode) { ++ return responseCodeMeters.computeIfAbsent( ++ statusCode, sc -> metricRegistry.meter(prefix.resolve(String.format("%d-responses", sc)))); ++ } ++ ++ private Timer requestTimer(String method) { ++ final HttpMethod m = HttpMethod.fromString(method); ++ if (m == null) { ++ return otherRequests; ++ } else { ++ switch (m) { ++ case GET: ++ return getRequests; ++ case POST: ++ return postRequests; ++ case PUT: ++ return putRequests; ++ case HEAD: ++ return headRequests; ++ case DELETE: ++ return deleteRequests; ++ case OPTIONS: ++ return optionsRequests; ++ case TRACE: ++ return traceRequests; ++ case CONNECT: ++ return connectRequests; ++ case MOVE: ++ return moveRequests; ++ default: ++ return otherRequests; ++ } ++ } ++ } ++ ++ private class AsyncAttachingListener implements AsyncListener { + + @Override +- public void onResponseFailure(final Request request, final Throwable failure) { ++ public void onTimeout(AsyncEvent event) throws IOException {} + ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException { ++ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); + } + + @Override +- public void onComplete(final Request request) { +- +- } ++ public void onError(AsyncEvent event) throws IOException {} + +- private void before(final Request request) { +- activeDispatches.inc(); +- +- final long start; +- final HttpChannelState state = request.getHttpChannelState(); +- if (state.isInitial()) { +- // new request +- activeRequests.inc(); +- start = request.getTimeStamp(); +- state.addListener(listener); +- } else { +- // resumed request +- start = System.currentTimeMillis(); +- activeSuspended.dec(); +- if (state.isAsyncStarted()) { +- asyncDispatches.mark(); +- } +- } +- request.setAttribute(START_ATTR, start); +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException {} ++ } ++ ; + +- private void after(final Request request) { +- final long start = (long) request.getAttribute(START_ATTR); +- final long now = System.currentTimeMillis(); +- final long dispatched = now - start; +- +- activeDispatches.dec(); +- dispatches.update(dispatched, TimeUnit.MILLISECONDS); +- +- final HttpChannelState state = request.getHttpChannelState(); +- if (state.isSuspended()) { +- activeSuspended.inc(); +- } else if (state.isInitial()) { +- updateResponses(request, request.getResponse(), start, request.isHandled()); +- } +- // else onCompletion will handle it. +- } ++ private class InstrumentedAsyncListener implements AsyncListener { ++ private final long startTime; + +- private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { +- if (isHandled) { +- mark(response.getStatus()); +- } else { +- mark(404); // will end up with a 404 response sent by HttpChannel.handle +- } +- activeRequests.dec(); +- final long elapsedTime = System.currentTimeMillis() - start; +- requests.update(elapsedTime, TimeUnit.MILLISECONDS); +- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); ++ InstrumentedAsyncListener() { ++ this.startTime = System.currentTimeMillis(); + } + +- private void mark(int statusCode) { +- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { +- getResponseCodeMeter(statusCode).mark(); +- } +- +- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { +- final int responseStatus = statusCode / 100; +- if (responseStatus >= 1 && responseStatus <= 5) { +- responses.get(responseStatus - 1).mark(); +- } +- } ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException { ++ asyncTimeouts.mark(); + } + +- private Meter getResponseCodeMeter(int statusCode) { +- return responseCodeMeters +- .computeIfAbsent(statusCode, sc -> metricRegistry +- .meter(prefix.resolve(String.format("%d-responses", sc)))); +- } ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException {} + +- private Timer requestTimer(String method) { +- final HttpMethod m = HttpMethod.fromString(method); +- if (m == null) { +- return otherRequests; +- } else { +- switch (m) { +- case GET: +- return getRequests; +- case POST: +- return postRequests; +- case PUT: +- return putRequests; +- case HEAD: +- return headRequests; +- case DELETE: +- return deleteRequests; +- case OPTIONS: +- return optionsRequests; +- case TRACE: +- return traceRequests; +- case CONNECT: +- return connectRequests; +- case MOVE: +- return moveRequests; +- default: +- return otherRequests; +- } +- } +- } ++ @Override ++ public void onError(AsyncEvent event) throws IOException {} + +- private class AsyncAttachingListener implements AsyncListener { +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException {} +- +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); +- } +- +- @Override +- public void onError(AsyncEvent event) throws IOException {} +- +- @Override +- public void onComplete(AsyncEvent event) throws IOException {} +- }; +- +- private class InstrumentedAsyncListener implements AsyncListener { +- private final long startTime; +- +- InstrumentedAsyncListener() { +- this.startTime = System.currentTimeMillis(); +- } +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException { +- asyncTimeouts.mark(); +- } +- +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- } +- +- @Override +- public void onError(AsyncEvent event) throws IOException { +- } +- +- @Override +- public void onComplete(AsyncEvent event) throws IOException { +- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); +- final HttpServletRequest request = (HttpServletRequest) state.getRequest(); +- final HttpServletResponse response = (HttpServletResponse) state.getResponse(); +- updateResponses(request, response, startTime, true); +- if (!state.getHttpChannelState().isSuspended()) { +- activeSuspended.dec(); +- } +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException { ++ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); ++ final HttpServletRequest request = (HttpServletRequest) state.getRequest(); ++ final HttpServletResponse response = (HttpServletResponse) state.getResponse(); ++ updateResponses(request, response, startTime, true); ++ if (!state.getHttpChannelState().isSuspended()) { ++ activeSuspended.dec(); ++ } + } ++ } + } +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPool.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPool.java +@@ -1,119 +1,130 @@ + package io.dropwizard.metrics5.jetty11; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.RatioGauge; ++import java.util.concurrent.BlockingQueue; + import org.eclipse.jetty.util.annotation.Name; + import org.eclipse.jetty.util.thread.QueuedThreadPool; + +-import java.util.concurrent.BlockingQueue; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + public class InstrumentedQueuedThreadPool extends QueuedThreadPool { +- private static final String NAME_UTILIZATION = "utilization"; +- private static final String NAME_UTILIZATION_MAX = "utilization-max"; +- private static final String NAME_SIZE = "size"; +- private static final String NAME_JOBS = "jobs"; +- private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; +- +- private final MetricRegistry metricRegistry; +- private String prefix; +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { +- this(registry, 200); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads) { +- this(registry, maxThreads, 8); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads) { +- this(registry, maxThreads, minThreads, 60000); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout) { +- this(registry, maxThreads, minThreads, idleTimeout, null); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("queue") BlockingQueue queue) { +- this(registry, maxThreads, minThreads, idleTimeout, queue, null); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("queue") BlockingQueue queue, +- @Name("prefix") String prefix) { +- super(maxThreads, minThreads, idleTimeout, queue); +- this.metricRegistry = registry; +- this.prefix = prefix; +- } +- +- public String getPrefix() { +- return prefix; +- } +- +- public void setPrefix(String prefix) { +- this.prefix = prefix; +- } +- +- @Override +- protected void doStart() throws Exception { +- super.doStart(); +- +- final MetricName prefix = getMetricPrefix(); +- +- metricRegistry.register(prefix.resolve(NAME_UTILIZATION), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(getThreads() - getIdleThreads(), getThreads()); +- } ++ private static final String NAME_UTILIZATION = "utilization"; ++ private static final String NAME_UTILIZATION_MAX = "utilization-max"; ++ private static final String NAME_SIZE = "size"; ++ private static final String NAME_JOBS = "jobs"; ++ private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; ++ ++ private final MetricRegistry metricRegistry; ++ private String prefix; ++ ++ public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { ++ this(registry, 200); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, @Name("maxThreads") int maxThreads) { ++ this(registry, maxThreads, 8); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads) { ++ this(registry, maxThreads, minThreads, 60000); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout) { ++ this(registry, maxThreads, minThreads, idleTimeout, null); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("queue") BlockingQueue queue) { ++ this(registry, maxThreads, minThreads, idleTimeout, queue, null); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("queue") BlockingQueue queue, ++ @Name("prefix") String prefix) { ++ super(maxThreads, minThreads, idleTimeout, queue); ++ this.metricRegistry = registry; ++ this.prefix = prefix; ++ } ++ ++ public String getPrefix() { ++ return prefix; ++ } ++ ++ public void setPrefix(String prefix) { ++ this.prefix = prefix; ++ } ++ ++ @Override ++ protected void doStart() throws Exception { ++ super.doStart(); ++ ++ final MetricName prefix = getMetricPrefix(); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_UTILIZATION), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(getThreads() - getIdleThreads(), getThreads()); ++ } + }); +- metricRegistry.register(prefix.resolve(NAME_UTILIZATION_MAX), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); +- } ++ metricRegistry.register( ++ prefix.resolve(NAME_UTILIZATION_MAX), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); ++ } + }); +- metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); +- // This assumes the QueuedThreadPool is using a BlockingArrayQueue or +- // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. +- metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); +- metricRegistry.register(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- BlockingQueue queue = getQueue(); +- return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); +- } ++ metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); ++ // This assumes the QueuedThreadPool is using a BlockingArrayQueue or ++ // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. ++ metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); ++ metricRegistry.register( ++ prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ BlockingQueue queue = getQueue(); ++ return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); ++ } + }); +- } +- +- @Override +- protected void doStop() throws Exception { +- final MetricName prefix = getMetricPrefix(); +- +- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); +- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); +- metricRegistry.remove(prefix.resolve(NAME_SIZE)); +- metricRegistry.remove(prefix.resolve(NAME_JOBS)); +- metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); +- +- super.doStop(); +- } +- +- private MetricName getMetricPrefix() { +- return this.prefix == null ? name(QueuedThreadPool.class, getName()) : name(this.prefix, getName()); +- } ++ } ++ ++ @Override ++ protected void doStop() throws Exception { ++ final MetricName prefix = getMetricPrefix(); ++ ++ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); ++ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); ++ metricRegistry.remove(prefix.resolve(NAME_SIZE)); ++ metricRegistry.remove(prefix.resolve(NAME_JOBS)); ++ metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); ++ ++ super.doStop(); ++ } ++ ++ private MetricName getMetricPrefix() { ++ return this.prefix == null ++ ? name(QueuedThreadPool.class, getName()) ++ : name(this.prefix, getName()); ++ } + } +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java +@@ -1,11 +1,15 @@ + package io.dropwizard.metrics5.jetty11; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; + import jakarta.servlet.ServletException; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; ++import java.io.IOException; ++import java.io.PrintWriter; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.HttpConnectionFactory; +@@ -17,77 +21,75 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.io.IOException; +-import java.io.PrintWriter; +- +-import static org.assertj.core.api.Assertions.assertThat; +- +-class InstrumentedConnectionFactoryTest { +- private final MetricRegistry registry = new MetricRegistry(); +- private final Server server = new Server(); +- private final ServerConnector connector = +- new ServerConnector(server, new InstrumentedConnectionFactory(new HttpConnectionFactory(), +- registry.timer("http.connections"), +- registry.counter("http.active-connections"))); +- private final HttpClient client = new HttpClient(); +- +- @BeforeEach +- void setUp() throws Exception { +- server.setHandler(new AbstractHandler() { +- @Override +- public void handle(String target, +- Request baseRequest, +- HttpServletRequest request, +- HttpServletResponse response) throws IOException, ServletException { +- try (PrintWriter writer = response.getWriter()) { +- writer.println("OK"); +- } ++final class InstrumentedConnectionFactoryTest { ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final Server server = new Server(); ++ private final ServerConnector connector = ++ new ServerConnector( ++ server, ++ new InstrumentedConnectionFactory( ++ new HttpConnectionFactory(), ++ registry.timer("http.connections"), ++ registry.counter("http.active-connections"))); ++ private final HttpClient client = new HttpClient(); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ server.setHandler( ++ new AbstractHandler() { ++ @Override ++ public void handle( ++ String target, ++ Request baseRequest, ++ HttpServletRequest request, ++ HttpServletResponse response) ++ throws IOException, ServletException { ++ try (PrintWriter writer = response.getWriter()) { ++ writer.println("OK"); + } ++ } + }); + +- server.addConnector(connector); +- server.start(); ++ server.addConnector(connector); ++ server.start(); + +- client.start(); +- } ++ client.start(); ++ } + +- @AfterEach +- void tearDown() throws Exception { +- server.stop(); +- client.stop(); +- } ++ @AfterEach ++ void tearDown() throws Exception { ++ server.stop(); ++ client.stop(); ++ } + +- @Test +- void instrumentsConnectionTimes() throws Exception { +- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); +- assertThat(response.getStatus()) +- .isEqualTo(200); ++ @Test ++ void instrumentsConnectionTimes() throws Exception { ++ final ContentResponse response = ++ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); ++ assertThat(response.getStatus()).isEqualTo(200); + +- client.stop(); // close the connection ++ client.stop(); // close the connection + +- Thread.sleep(100); // make sure the connection is closed ++ Thread.sleep(100); // make sure the connection is closed + +- final Timer timer = registry.timer(MetricRegistry.name("http.connections")); +- assertThat(timer.getCount()) +- .isEqualTo(1); +- } ++ final Timer timer = registry.timer(MetricRegistry.name("http.connections")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + +- @Test +- void instrumentsActiveConnections() throws Exception { +- final Counter counter = registry.counter("http.active-connections"); ++ @Test ++ void instrumentsActiveConnections() throws Exception { ++ final Counter counter = registry.counter("http.active-connections"); + +- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); +- assertThat(response.getStatus()) +- .isEqualTo(200); ++ final ContentResponse response = ++ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); ++ assertThat(response.getStatus()).isEqualTo(200); + +- assertThat(counter.getCount()) +- .isEqualTo(1); ++ assertThat(counter.getCount()).isEqualTo(1); + +- client.stop(); // close the connection ++ client.stop(); // close the connection + +- Thread.sleep(100); // make sure the connection is closed ++ Thread.sleep(100); // make sure the connection is closed + +- assertThat(counter.getCount()) +- .isEqualTo(0); +- } ++ assertThat(counter.getCount()).isEqualTo(0); ++ } + } +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java +@@ -1,5 +1,12 @@ + package io.dropwizard.metrics5.jetty11; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.nio.charset.StandardCharsets.UTF_8; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import jakarta.servlet.AsyncContext; +@@ -8,6 +15,8 @@ import jakarta.servlet.ServletOutputStream; + import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; ++import java.io.IOException; ++import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.Request; +@@ -19,228 +28,221 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + +-import java.io.IOException; +-import java.nio.charset.StandardCharsets; +-import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; +- +-class InstrumentedHandlerTest { +- private final HttpClient client = new HttpClient(); +- private final MetricRegistry registry = new MetricRegistry(); +- private final Server server = new Server(); +- private final ServerConnector connector = new ServerConnector(server); +- private final InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); +- +- @BeforeEach +- void setUp() throws Exception { +- handler.setName("handler"); +- handler.setHandler(new TestHandler()); +- server.addConnector(connector); +- server.setHandler(handler); +- server.start(); +- client.start(); +- } +- +- @AfterEach +- void tearDown() throws Exception { +- server.stop(); +- client.stop(); +- } +- +- @Test +- void hasAName() throws Exception { +- assertThat(handler.getName()) +- .isEqualTo("handler"); +- } +- +- @Test +- void createsAndRemovesMetricsForTheHandler() throws Exception { +- final ContentResponse response = client.GET(uri("/hello")); +- +- assertThat(response.getStatus()) +- .isEqualTo(404); +- +- assertThat(registry.getNames()) +- .containsOnly( +- MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.404-responses"), +- MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), +- MetricRegistry.name(TestHandler.class, "handler.requests"), +- MetricRegistry.name(TestHandler.class, "handler.active-suspended"), +- MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), +- MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), +- MetricRegistry.name(TestHandler.class, "handler.get-requests"), +- MetricRegistry.name(TestHandler.class, "handler.put-requests"), +- MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), +- MetricRegistry.name(TestHandler.class, "handler.trace-requests"), +- MetricRegistry.name(TestHandler.class, "handler.other-requests"), +- MetricRegistry.name(TestHandler.class, "handler.connect-requests"), +- MetricRegistry.name(TestHandler.class, "handler.dispatches"), +- MetricRegistry.name(TestHandler.class, "handler.head-requests"), +- MetricRegistry.name(TestHandler.class, "handler.post-requests"), +- MetricRegistry.name(TestHandler.class, "handler.options-requests"), +- MetricRegistry.name(TestHandler.class, "handler.active-requests"), +- MetricRegistry.name(TestHandler.class, "handler.delete-requests"), +- MetricRegistry.name(TestHandler.class, "handler.move-requests") +- ); +- +- server.stop(); +- +- assertThat(registry.getNames()) +- .isEmpty(); +- } +- +- @Test +- void responseTimesAreRecordedForBlockingResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/blocking")); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- +- assertResponseTimesValid(); +- } +- +- @Test +- void doStopDoesNotThrowNPE() throws Exception { +- InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); +- handler.setHandler(new TestHandler()); +- +- assertThatCode(handler::doStop).doesNotThrowAnyException(); +- } +- +- @Test +- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { +- InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); +- handler.setHandler(new TestHandler()); +- handler.setName("handler"); +- handler.doStart(); +- assertThat(registry.getGauges()).containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); +- } +- +- @Test +- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { +- InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); +- handler.setHandler(new TestHandler()); +- handler.setName("handler"); +- handler.doStart(); +- assertThat(registry.getGauges()).doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); +- } +- +- @Test +- @Disabled("flaky on virtual machines") +- void responseTimesAreRecordedForAsyncResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/async")); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- +- assertResponseTimesValid(); +- } +- +- private void assertResponseTimesValid() { +- assertThat(registry.getMeters().get(metricName().resolve("200-responses")) +- .getCount()).isGreaterThan(0L); +- +- +- assertThat(registry.getTimers().get(metricName().resolve("get-requests")) +- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); +- +- assertThat(registry.getTimers().get(metricName().resolve("requests")) +- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); +- } +- +- private String uri(String path) { +- return "http://localhost:" + connector.getLocalPort() + path; +- } +- +- private MetricName metricName() { +- return MetricRegistry.name(TestHandler.class.getName(), "handler"); +- } +- +- /** +- * test handler. +- *

    +- * Supports +- *

    +- * /blocking - uses the standard servlet api +- * /async - uses the 3.1 async api to complete the request +- *

    +- * all other requests will return 404 +- */ +- private static class TestHandler extends AbstractHandler { +- @Override +- public void handle( +- String path, +- Request request, +- final HttpServletRequest httpServletRequest, +- final HttpServletResponse httpServletResponse +- ) throws IOException, ServletException { +- switch (path) { +- case "/blocking": +- request.setHandled(true); ++final class InstrumentedHandlerTest { ++ private final HttpClient client = new HttpClient(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final Server server = new Server(); ++ private final ServerConnector connector = new ServerConnector(server); ++ private final InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ handler.setName("handler"); ++ handler.setHandler(new TestHandler()); ++ server.addConnector(connector); ++ server.setHandler(handler); ++ server.start(); ++ client.start(); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ server.stop(); ++ client.stop(); ++ } ++ ++ @Test ++ void hasAName() throws Exception { ++ assertThat(handler.getName()).isEqualTo("handler"); ++ } ++ ++ @Test ++ void createsAndRemovesMetricsForTheHandler() throws Exception { ++ final ContentResponse response = client.GET(uri("/hello")); ++ ++ assertThat(response.getStatus()).isEqualTo(404); ++ ++ assertThat(registry.getNames()) ++ .containsOnly( ++ MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.404-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), ++ MetricRegistry.name(TestHandler.class, "handler.requests"), ++ MetricRegistry.name(TestHandler.class, "handler.active-suspended"), ++ MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), ++ MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), ++ MetricRegistry.name(TestHandler.class, "handler.get-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.put-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), ++ MetricRegistry.name(TestHandler.class, "handler.trace-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.other-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.connect-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.dispatches"), ++ MetricRegistry.name(TestHandler.class, "handler.head-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.post-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.options-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.active-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.delete-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.move-requests")); ++ ++ server.stop(); ++ ++ assertThat(registry.getNames()).isEmpty(); ++ } ++ ++ @Test ++ void responseTimesAreRecordedForBlockingResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/blocking")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ ++ assertResponseTimesValid(); ++ } ++ ++ @Test ++ void doStopDoesNotThrowNPE() throws Exception { ++ InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); ++ handler.setHandler(new TestHandler()); ++ ++ assertThatCode(handler::doStop).doesNotThrowAnyException(); ++ } ++ ++ @Test ++ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { ++ InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); ++ handler.setHandler(new TestHandler()); ++ handler.setName("handler"); ++ handler.doStart(); ++ assertThat(registry.getGauges()) ++ .containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); ++ } ++ ++ @Test ++ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { ++ InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); ++ handler.setHandler(new TestHandler()); ++ handler.setName("handler"); ++ handler.doStart(); ++ assertThat(registry.getGauges()) ++ .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); ++ } ++ ++ @Disabled("flaky on virtual machines") ++ @Test ++ void responseTimesAreRecordedForAsyncResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/async")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ ++ assertResponseTimesValid(); ++ } ++ ++ private void assertResponseTimesValid() { ++ assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) ++ .isPositive(); ++ ++ assertThat( ++ registry ++ .getTimers() ++ .get(metricName().resolve("get-requests")) ++ .getSnapshot() ++ .getMedian()) ++ .isPositive() ++ .isLessThan(TimeUnit.SECONDS.toNanos(1)); ++ ++ assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) ++ .isPositive() ++ .isLessThan(TimeUnit.SECONDS.toNanos(1)); ++ } ++ ++ private String uri(String path) { ++ return "http://localhost:" + connector.getLocalPort() + path; ++ } ++ ++ private MetricName metricName() { ++ return MetricRegistry.name(TestHandler.class.getName(), "handler"); ++ } ++ ++ /** ++ * test handler. ++ * ++ *

    Supports ++ * ++ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the ++ * request ++ * ++ *

    all other requests will return 404 ++ */ ++ private static class TestHandler extends AbstractHandler { ++ @Override ++ public void handle( ++ String path, ++ Request request, ++ final HttpServletRequest httpServletRequest, ++ final HttpServletResponse httpServletResponse) ++ throws IOException, ServletException { ++ switch (path) { ++ case "/blocking": ++ request.setHandled(true); ++ try { ++ Thread.sleep(100); ++ } catch (InterruptedException e) { ++ Thread.currentThread().interrupt(); ++ } ++ httpServletResponse.setStatus(200); ++ httpServletResponse.setContentType("text/plain"); ++ httpServletResponse.getWriter().write("some content from the blocking request\n"); ++ break; ++ case "/async": ++ request.setHandled(true); ++ final AsyncContext context = request.startAsync(); ++ Thread t = ++ new Thread( ++ () -> { + try { +- Thread.sleep(100); ++ Thread.sleep(100); + } catch (InterruptedException e) { +- Thread.currentThread().interrupt(); ++ Thread.currentThread().interrupt(); + } + httpServletResponse.setStatus(200); + httpServletResponse.setContentType("text/plain"); +- httpServletResponse.getWriter().write("some content from the blocking request\n"); +- break; +- case "/async": +- request.setHandled(true); +- final AsyncContext context = request.startAsync(); +- Thread t = new Thread(() -> { +- try { +- Thread.sleep(100); +- } catch (InterruptedException e) { +- Thread.currentThread().interrupt(); +- } +- httpServletResponse.setStatus(200); +- httpServletResponse.setContentType("text/plain"); +- final ServletOutputStream servletOutputStream; +- try { +- servletOutputStream = httpServletResponse.getOutputStream(); +- servletOutputStream.setWriteListener( +- new WriteListener() { +- @Override +- public void onWritePossible() throws IOException { +- servletOutputStream.write("some content from the async\n" +- .getBytes(StandardCharsets.UTF_8)); +- context.complete(); +- } +- +- @Override +- public void onError(Throwable throwable) { +- context.complete(); +- } +- } +- ); +- } catch (IOException e) { +- context.complete(); +- } +- }); +- t.start(); +- break; +- default: +- break; +- } +- } ++ final ServletOutputStream servletOutputStream; ++ try { ++ servletOutputStream = httpServletResponse.getOutputStream(); ++ servletOutputStream.setWriteListener( ++ new WriteListener() { ++ @Override ++ public void onWritePossible() throws IOException { ++ servletOutputStream.write( ++ "some content from the async\n".getBytes(UTF_8)); ++ context.complete(); ++ } ++ ++ @Override ++ public void onError(Throwable throwable) { ++ context.complete(); ++ } ++ }); ++ } catch (IOException e) { ++ context.complete(); ++ } ++ }); ++ t.start(); ++ break; ++ default: ++ break; ++ } + } ++ } + } +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.jetty11; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import jakarta.servlet.AsyncContext; +@@ -7,6 +11,7 @@ import jakarta.servlet.ServletOutputStream; + import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; ++import java.io.IOException; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.Request; +@@ -17,197 +22,190 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.io.IOException; +-import java.nio.charset.StandardCharsets; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static org.assertj.core.api.Assertions.assertThat; +- +-class InstrumentedHttpChannelListenerTest { +- private final HttpClient client = new HttpClient(); +- private final Server server = new Server(); +- private final ServerConnector connector = new ServerConnector(server); +- private final TestHandler handler = new TestHandler(); +- private MetricRegistry registry; +- +- @BeforeEach +- void setUp() throws Exception { +- registry = new MetricRegistry(); +- connector.addBean(new InstrumentedHttpChannelListener(registry, MetricRegistry.name(TestHandler.class, "handler"), ALL)); +- server.addConnector(connector); +- server.setHandler(handler); +- server.start(); +- client.start(); ++final class InstrumentedHttpChannelListenerTest { ++ private final HttpClient client = new HttpClient(); ++ private final Server server = new Server(); ++ private final ServerConnector connector = new ServerConnector(server); ++ private final TestHandler handler = new TestHandler(); ++ private MetricRegistry registry; ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ registry = new MetricRegistry(); ++ connector.addBean( ++ new InstrumentedHttpChannelListener( ++ registry, MetricRegistry.name(TestHandler.class, "handler"), ALL)); ++ server.addConnector(connector); ++ server.setHandler(handler); ++ server.start(); ++ client.start(); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ server.stop(); ++ client.stop(); ++ } ++ ++ @Test ++ void createsMetricsForTheHandler() throws Exception { ++ final ContentResponse response = client.GET(uri("/hello")); ++ ++ assertThat(response.getStatus()).isEqualTo(404); ++ ++ assertThat(registry.getNames()) ++ .containsOnly( ++ metricName("1xx-responses"), ++ metricName("2xx-responses"), ++ metricName("3xx-responses"), ++ metricName("404-responses"), ++ metricName("4xx-responses"), ++ metricName("5xx-responses"), ++ metricName("percent-4xx-1m"), ++ metricName("percent-4xx-5m"), ++ metricName("percent-4xx-15m"), ++ metricName("percent-5xx-1m"), ++ metricName("percent-5xx-5m"), ++ metricName("percent-5xx-15m"), ++ metricName("requests"), ++ metricName("active-suspended"), ++ metricName("async-dispatches"), ++ metricName("async-timeouts"), ++ metricName("get-requests"), ++ metricName("put-requests"), ++ metricName("active-dispatches"), ++ metricName("trace-requests"), ++ metricName("other-requests"), ++ metricName("connect-requests"), ++ metricName("dispatches"), ++ metricName("head-requests"), ++ metricName("post-requests"), ++ metricName("options-requests"), ++ metricName("active-requests"), ++ metricName("delete-requests"), ++ metricName("move-requests")); ++ } ++ ++ @Test ++ void responseTimesAreRecordedForBlockingResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/blocking")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.getMediaType()).isEqualTo("text/plain"); ++ assertThat(response.getContentAsString()).isEqualTo("some content from the blocking request"); ++ ++ assertResponseTimesValid(); ++ } ++ ++ @Test ++ void responseTimesAreRecordedForAsyncResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/async")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.getMediaType()).isEqualTo("text/plain"); ++ assertThat(response.getContentAsString()).isEqualTo("some content from the async"); ++ ++ assertResponseTimesValid(); ++ } ++ ++ private void assertResponseTimesValid() { ++ try { ++ Thread.sleep(100); ++ } catch (InterruptedException e) { ++ Thread.currentThread().interrupt(); + } + +- @AfterEach +- void tearDown() throws Exception { +- server.stop(); +- client.stop(); +- } +- +- @Test +- void createsMetricsForTheHandler() throws Exception { +- final ContentResponse response = client.GET(uri("/hello")); +- +- assertThat(response.getStatus()) +- .isEqualTo(404); +- +- assertThat(registry.getNames()) +- .containsOnly( +- metricName("1xx-responses"), +- metricName("2xx-responses"), +- metricName("3xx-responses"), +- metricName("404-responses"), +- metricName("4xx-responses"), +- metricName("5xx-responses"), +- metricName("percent-4xx-1m"), +- metricName("percent-4xx-5m"), +- metricName("percent-4xx-15m"), +- metricName("percent-5xx-1m"), +- metricName("percent-5xx-5m"), +- metricName("percent-5xx-15m"), +- metricName("requests"), +- metricName("active-suspended"), +- metricName("async-dispatches"), +- metricName("async-timeouts"), +- metricName("get-requests"), +- metricName("put-requests"), +- metricName("active-dispatches"), +- metricName("trace-requests"), +- metricName("other-requests"), +- metricName("connect-requests"), +- metricName("dispatches"), +- metricName("head-requests"), +- metricName("post-requests"), +- metricName("options-requests"), +- metricName("active-requests"), +- metricName("delete-requests"), +- metricName("move-requests") +- ); +- } +- +- +- @Test +- void responseTimesAreRecordedForBlockingResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/blocking")); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.getMediaType()).isEqualTo("text/plain"); +- assertThat(response.getContentAsString()).isEqualTo("some content from the blocking request"); +- +- assertResponseTimesValid(); +- } +- +- @Test +- void responseTimesAreRecordedForAsyncResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/async")); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.getMediaType()).isEqualTo("text/plain"); +- assertThat(response.getContentAsString()).isEqualTo("some content from the async"); +- +- assertResponseTimesValid(); +- } +- +- private void assertResponseTimesValid() { +- try { ++ assertThat(registry.getMeters().get(metricName("2xx-responses")).getCount()).isPositive(); ++ assertThat(registry.getMeters().get(metricName("200-responses")).getCount()).isPositive(); ++ ++ assertThat(registry.getTimers().get(metricName("get-requests")).getSnapshot().getMedian()) ++ .isPositive(); ++ ++ assertThat(registry.getTimers().get(metricName("requests")).getSnapshot().getMedian()) ++ .isPositive(); ++ } ++ ++ private String uri(String path) { ++ return "http://localhost:" + connector.getLocalPort() + path; ++ } ++ ++ private MetricName metricName(String metricName) { ++ return MetricRegistry.name(TestHandler.class.getName(), "handler", metricName); ++ } ++ ++ /** ++ * test handler. ++ * ++ *

    Supports ++ * ++ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the ++ * request ++ * ++ *

    all other requests will return 404 ++ */ ++ private static class TestHandler extends AbstractHandler { ++ @Override ++ public void handle( ++ String path, ++ Request request, ++ final HttpServletRequest httpServletRequest, ++ final HttpServletResponse httpServletResponse) ++ throws IOException { ++ switch (path) { ++ case "/blocking": ++ request.setHandled(true); ++ httpServletResponse.setStatus(200); ++ httpServletResponse.setContentType("text/plain"); ++ httpServletResponse.getWriter().write("some content from the blocking request"); ++ try { + Thread.sleep(100); +- } catch (InterruptedException e) { ++ } catch (InterruptedException e) { ++ httpServletResponse.setStatus(500); + Thread.currentThread().interrupt(); +- } +- +- assertThat(registry.getMeters().get(metricName("2xx-responses")) +- .getCount()).isPositive(); +- assertThat(registry.getMeters().get(metricName("200-responses")) +- .getCount()).isPositive(); +- +- assertThat(registry.getTimers().get(metricName("get-requests")) +- .getSnapshot().getMedian()).isPositive(); +- +- assertThat(registry.getTimers().get(metricName("requests")) +- .getSnapshot().getMedian()).isPositive(); +- } +- +- private String uri(String path) { +- return "http://localhost:" + connector.getLocalPort() + path; +- } +- +- private MetricName metricName(String metricName) { +- return MetricRegistry.name(TestHandler.class.getName(), "handler", metricName); +- } +- +- /** +- * test handler. +- *

    +- * Supports +- *

    +- * /blocking - uses the standard servlet api +- * /async - uses the 3.1 async api to complete the request +- *

    +- * all other requests will return 404 +- */ +- private static class TestHandler extends AbstractHandler { +- @Override +- public void handle( +- String path, +- Request request, +- final HttpServletRequest httpServletRequest, +- final HttpServletResponse httpServletResponse) throws IOException { +- switch (path) { +- case "/blocking": +- request.setHandled(true); ++ } ++ break; ++ case "/async": ++ request.setHandled(true); ++ final AsyncContext context = request.startAsync(); ++ Thread t = ++ new Thread( ++ () -> { + httpServletResponse.setStatus(200); + httpServletResponse.setContentType("text/plain"); +- httpServletResponse.getWriter().write("some content from the blocking request"); + try { +- Thread.sleep(100); ++ Thread.sleep(100); + } catch (InterruptedException e) { +- httpServletResponse.setStatus(500); +- Thread.currentThread().interrupt(); ++ httpServletResponse.setStatus(500); ++ Thread.currentThread().interrupt(); ++ } ++ final ServletOutputStream servletOutputStream; ++ try { ++ servletOutputStream = httpServletResponse.getOutputStream(); ++ servletOutputStream.setWriteListener( ++ new WriteListener() { ++ @Override ++ public void onWritePossible() throws IOException { ++ servletOutputStream.write( ++ "some content from the async".getBytes(UTF_8)); ++ context.complete(); ++ } ++ ++ @Override ++ public void onError(Throwable throwable) { ++ context.complete(); ++ } ++ }); ++ } catch (IOException e) { ++ context.complete(); + } +- break; +- case "/async": +- request.setHandled(true); +- final AsyncContext context = request.startAsync(); +- Thread t = new Thread(() -> { +- httpServletResponse.setStatus(200); +- httpServletResponse.setContentType("text/plain"); +- try { +- Thread.sleep(100); +- } catch (InterruptedException e) { +- httpServletResponse.setStatus(500); +- Thread.currentThread().interrupt(); +- } +- final ServletOutputStream servletOutputStream; +- try { +- servletOutputStream = httpServletResponse.getOutputStream(); +- servletOutputStream.setWriteListener( +- new WriteListener() { +- @Override +- public void onWritePossible() throws IOException { +- servletOutputStream.write("some content from the async" +- .getBytes(StandardCharsets.UTF_8)); +- context.complete(); +- } +- +- @Override +- public void onError(Throwable throwable) { +- context.complete(); +- } +- } +- ); +- } catch (IOException e) { +- context.complete(); +- } +- }); +- t.start(); +- break; +- default: +- break; +- } +- } ++ }); ++ t.start(); ++ break; ++ default: ++ break; ++ } + } ++ } + } +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java +@@ -1,52 +1,52 @@ + package io.dropwizard.metrics5.jetty11; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.eclipse.jetty.util.thread.QueuedThreadPool; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class InstrumentedQueuedThreadPoolTest { +- private static final String PREFIX = "prefix"; +- +- private MetricRegistry metricRegistry; +- private InstrumentedQueuedThreadPool iqtp; +- +- @BeforeEach +- void setUp() { +- metricRegistry = new MetricRegistry(); +- iqtp = new InstrumentedQueuedThreadPool(metricRegistry); +- } +- +- @Test +- void customMetricsPrefix() throws Exception { +- iqtp.setPrefix(PREFIX); +- iqtp.start(); +- +- assertThat(metricRegistry.getNames()) +- .extracting(MetricName::getKey) +- .overridingErrorMessage("Custom metrics prefix doesn't match") +- .allSatisfy(name -> assertThat(name).startsWith(PREFIX)); +- +- iqtp.stop(); +- assertThat(metricRegistry.getMetrics()) +- .overridingErrorMessage("The default metrics prefix was changed") +- .isEmpty(); +- } +- +- @Test +- void metricsPrefixBackwardCompatible() throws Exception { +- iqtp.start(); +- assertThat(metricRegistry.getNames()) +- .extracting(MetricName::getKey) +- .overridingErrorMessage("The default metrics prefix was changed") +- .allSatisfy(name -> assertThat(name).startsWith(QueuedThreadPool.class.getName())); +- +- iqtp.stop(); +- assertThat(metricRegistry.getMetrics()) +- .overridingErrorMessage("The default metrics prefix was changed") +- .isEmpty(); +- } ++final class InstrumentedQueuedThreadPoolTest { ++ private static final String PREFIX = "prefix"; ++ ++ private MetricRegistry metricRegistry; ++ private InstrumentedQueuedThreadPool iqtp; ++ ++ @BeforeEach ++ void setUp() { ++ metricRegistry = new MetricRegistry(); ++ iqtp = new InstrumentedQueuedThreadPool(metricRegistry); ++ } ++ ++ @Test ++ void customMetricsPrefix() throws Exception { ++ iqtp.setPrefix(PREFIX); ++ iqtp.start(); ++ ++ assertThat(metricRegistry.getNames()) ++ .extracting(MetricName::getKey) ++ .overridingErrorMessage("Custom metrics prefix doesn't match") ++ .allSatisfy(name -> assertThat(name).startsWith(PREFIX)); ++ ++ iqtp.stop(); ++ assertThat(metricRegistry.getMetrics()) ++ .overridingErrorMessage("The default metrics prefix was changed") ++ .isEmpty(); ++ } ++ ++ @Test ++ void metricsPrefixBackwardCompatible() throws Exception { ++ iqtp.start(); ++ assertThat(metricRegistry.getNames()) ++ .extracting(MetricName::getKey) ++ .overridingErrorMessage("The default metrics prefix was changed") ++ .allSatisfy(name -> assertThat(name).startsWith(QueuedThreadPool.class.getName())); ++ ++ iqtp.stop(); ++ assertThat(metricRegistry.getMetrics()) ++ .overridingErrorMessage("The default metrics prefix was changed") ++ .isEmpty(); ++ } + } +--- a/metrics-jetty12-ee10/src/main/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10Handler.java ++++ b/metrics-jetty12-ee10/src/main/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10Handler.java +@@ -1,10 +1,14 @@ + package io.dropwizard.metrics.jetty12.ee10; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++ ++import io.dropwizard.metrics.jetty12.AbstractInstrumentedHandler; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; +-import io.dropwizard.metrics.jetty12.AbstractInstrumentedHandler; + import jakarta.servlet.AsyncEvent; + import jakarta.servlet.AsyncListener; ++import java.io.IOException; ++import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.ee10.servlet.AsyncContextState; + import org.eclipse.jetty.ee10.servlet.ServletApiRequest; + import org.eclipse.jetty.ee10.servlet.ServletApiResponse; +@@ -15,162 +19,160 @@ import org.eclipse.jetty.server.Request; + import org.eclipse.jetty.server.Response; + import org.eclipse.jetty.util.Callback; + +-import java.io.IOException; +-import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +- + /** + * A Jetty {@link Handler} which records various metrics about an underlying {@link Handler} +- * instance. This {@link Handler} requires a {@link org.eclipse.jetty.ee10.servlet.ServletContextHandler} to be present. +- * For correct behaviour, the {@link org.eclipse.jetty.ee10.servlet.ServletContextHandler} should be before this handler +- * in the handler chain. To achieve this, one can use +- * {@link org.eclipse.jetty.ee10.servlet.ServletContextHandler#insertHandler(Singleton)}. ++ * instance. This {@link Handler} requires a {@link ++ * org.eclipse.jetty.ee10.servlet.ServletContextHandler} to be present. For correct behaviour, the ++ * {@link org.eclipse.jetty.ee10.servlet.ServletContextHandler} should be before this handler in the ++ * handler chain. To achieve this, one can use {@link ++ * org.eclipse.jetty.ee10.servlet.ServletContextHandler#insertHandler(Singleton)}. + */ + public class InstrumentedEE10Handler extends AbstractInstrumentedHandler { +- private AsyncListener listener; +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- */ +- public InstrumentedEE10Handler(MetricRegistry registry) { +- super(registry, null); ++ private AsyncListener listener; ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ */ ++ public InstrumentedEE10Handler(MetricRegistry registry) { ++ super(registry, null); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param prefix the prefix to use for the metrics names ++ */ ++ public InstrumentedEE10Handler(MetricRegistry registry, String prefix) { ++ super(registry, prefix, COARSE); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param prefix the prefix to use for the metrics names ++ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are ++ * instrumented ++ */ ++ public InstrumentedEE10Handler( ++ MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { ++ super(registry, prefix, responseMeteredLevel); ++ } ++ ++ @Override ++ protected void doStart() throws Exception { ++ super.doStart(); ++ ++ this.listener = new AsyncAttachingListener(); ++ } ++ ++ @Override ++ protected void doStop() throws Exception { ++ super.doStop(); ++ } ++ ++ @Override ++ public boolean handle(Request request, Response response, Callback callback) throws Exception { ++ ServletContextRequest servletContextRequest = Request.as(request, ServletContextRequest.class); ++ ++ // only handle servlet requests with the InstrumentedHandler ++ // because it depends on the ServletRequestState ++ if (servletContextRequest == null) { ++ return super.handle(request, response, callback); + } + +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param prefix the prefix to use for the metrics names +- */ +- public InstrumentedEE10Handler(MetricRegistry registry, String prefix) { +- super(registry, prefix, COARSE); ++ activeDispatches.inc(); ++ ++ final long start; ++ final ServletChannelState state = servletContextRequest.getServletRequestState(); ++ if (state.isInitial()) { ++ // new request ++ activeRequests.inc(); ++ start = Request.getTimeStamp(request); ++ state.addListener(listener); ++ } else { ++ // resumed request ++ start = System.currentTimeMillis(); ++ activeSuspended.dec(); ++ if (state.getState() == ServletChannelState.State.HANDLING) { ++ asyncDispatches.mark(); ++ } + } + +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param prefix the prefix to use for the metrics names +- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented +- */ +- public InstrumentedEE10Handler(MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { +- super(registry, prefix, responseMeteredLevel); +- } ++ boolean handled = false; + +- @Override +- protected void doStart() throws Exception { +- super.doStart(); ++ try { ++ handled = super.handle(request, response, callback); ++ } finally { ++ final long now = System.currentTimeMillis(); ++ final long dispatched = now - start; + +- this.listener = new AsyncAttachingListener(); ++ activeDispatches.dec(); ++ dispatches.update(dispatched, TimeUnit.MILLISECONDS); ++ ++ if (state.isSuspended()) { ++ activeSuspended.inc(); ++ } else if (state.isInitial()) { ++ updateResponses(request, response, start, handled); ++ } ++ // else onCompletion will handle it. + } + ++ return handled; ++ } ++ ++ private class AsyncAttachingListener implements AsyncListener { ++ + @Override +- protected void doStop() throws Exception { +- super.doStop(); +- } ++ public void onTimeout(AsyncEvent event) throws IOException {} + + @Override +- public boolean handle(Request request, Response response, Callback callback) throws Exception { +- ServletContextRequest servletContextRequest = Request.as(request, ServletContextRequest.class); +- +- // only handle servlet requests with the InstrumentedHandler +- // because it depends on the ServletRequestState +- if (servletContextRequest == null) { +- return super.handle(request, response, callback); +- } +- +- activeDispatches.inc(); +- +- final long start; +- final ServletChannelState state = servletContextRequest.getServletRequestState(); +- if (state.isInitial()) { +- // new request +- activeRequests.inc(); +- start = Request.getTimeStamp(request); +- state.addListener(listener); +- } else { +- // resumed request +- start = System.currentTimeMillis(); +- activeSuspended.dec(); +- if (state.getState() == ServletChannelState.State.HANDLING) { +- asyncDispatches.mark(); +- } +- } +- +- boolean handled = false; +- +- try { +- handled = super.handle(request, response, callback); +- } finally { +- final long now = System.currentTimeMillis(); +- final long dispatched = now - start; +- +- activeDispatches.dec(); +- dispatches.update(dispatched, TimeUnit.MILLISECONDS); +- +- if (state.isSuspended()) { +- activeSuspended.inc(); +- } else if (state.isInitial()) { +- updateResponses(request, response, start, handled); +- } +- // else onCompletion will handle it. +- } +- +- return handled; ++ public void onStartAsync(AsyncEvent event) throws IOException { ++ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); + } + +- private class AsyncAttachingListener implements AsyncListener { ++ @Override ++ public void onError(AsyncEvent event) throws IOException {} + +- @Override +- public void onTimeout(AsyncEvent event) throws IOException {} ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException {} ++ } + +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); +- } ++ private class InstrumentedAsyncListener implements AsyncListener { ++ private final long startTime; + +- @Override +- public void onError(AsyncEvent event) throws IOException {} ++ InstrumentedAsyncListener() { ++ this.startTime = System.currentTimeMillis(); ++ } + +- @Override +- public void onComplete(AsyncEvent event) throws IOException {} ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException { ++ asyncTimeouts.mark(); + } + +- private class InstrumentedAsyncListener implements AsyncListener { +- private final long startTime; +- +- InstrumentedAsyncListener() { +- this.startTime = System.currentTimeMillis(); +- } +- +- @Override +- public void onTimeout(AsyncEvent event) throws IOException { +- asyncTimeouts.mark(); +- } +- +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { +- } +- +- @Override +- public void onError(AsyncEvent event) throws IOException { +- } +- +- @Override +- public void onComplete(AsyncEvent event) throws IOException { +- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); +- final ServletApiRequest request = (ServletApiRequest) state.getRequest(); +- final ServletApiResponse response = (ServletApiResponse) state.getResponse(); +- updateResponses(request.getRequest(), response.getResponse(), startTime, true); +- +- final ServletContextRequest servletContextRequest = Request.as(request.getRequest(), ServletContextRequest.class); +- final ServletChannelState servletRequestState = servletContextRequest.getServletRequestState(); +- if (!servletRequestState.isSuspended()) { +- activeSuspended.dec(); +- } +- } ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException {} ++ ++ @Override ++ public void onError(AsyncEvent event) throws IOException {} ++ ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException { ++ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); ++ final ServletApiRequest request = (ServletApiRequest) state.getRequest(); ++ final ServletApiResponse response = (ServletApiResponse) state.getResponse(); ++ updateResponses(request.getRequest(), response.getResponse(), startTime, true); ++ ++ final ServletContextRequest servletContextRequest = ++ Request.as(request.getRequest(), ServletContextRequest.class); ++ final ServletChannelState servletRequestState = ++ servletContextRequest.getServletRequestState(); ++ if (!servletRequestState.isSuspended()) { ++ activeSuspended.dec(); ++ } + } ++ } + } +--- a/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java ++++ b/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java +@@ -1,7 +1,21 @@ + package io.dropwizard.metrics.jetty12.ee10; + ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.nio.charset.StandardCharsets.UTF_8; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatCode; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; ++import jakarta.servlet.AsyncContext; ++import jakarta.servlet.ServletOutputStream; ++import jakarta.servlet.WriteListener; ++import jakarta.servlet.http.HttpServletRequest; ++import jakarta.servlet.http.HttpServletResponse; ++import java.io.IOException; ++import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.client.ContentResponse; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.ee10.servlet.DefaultServlet; +@@ -13,262 +27,251 @@ import org.eclipse.jetty.server.Response; + import org.eclipse.jetty.server.Server; + import org.eclipse.jetty.server.ServerConnector; + import org.eclipse.jetty.util.Callback; +- +-import jakarta.servlet.AsyncContext; +-import jakarta.servlet.ServletOutputStream; +-import jakarta.servlet.WriteListener; +-import jakarta.servlet.http.HttpServletRequest; +-import jakarta.servlet.http.HttpServletResponse; + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + +-import java.io.IOException; +-import java.nio.charset.StandardCharsets; +-import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatCode; +- +-public class InstrumentedEE10HandlerTest { +- private final HttpClient client = new HttpClient(); +- private final MetricRegistry registry = new MetricRegistry(); +- private final Server server = new Server(); +- private final ServerConnector connector = new ServerConnector(server); +- private final InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); +- +- @BeforeEach +- public void setUp() throws Exception { +- handler.setName("handler"); +- +- TestHandler testHandler = new TestHandler(); +- // a servlet handler needs a servlet mapping, else the request will be short-circuited +- // so use the DefaultServlet here +- testHandler.addServletWithMapping(DefaultServlet.class, "/"); +- +- // builds the following handler chain: +- // ServletContextHandler -> InstrumentedHandler -> TestHandler +- // the ServletContextHandler is needed to utilize servlet related classes +- ServletContextHandler servletContextHandler = new ServletContextHandler(); +- servletContextHandler.setHandler(testHandler); +- servletContextHandler.insertHandler(handler); +- server.setHandler(servletContextHandler); +- +- server.addConnector(connector); +- server.start(); +- client.start(); +- } +- +- @AfterEach +- public void tearDown() throws Exception { +- server.stop(); +- client.stop(); +- } +- +- @Test +- public void hasAName() throws Exception { +- assertThat(handler.getName()) +- .isEqualTo("handler"); +- } +- +- @Test +- public void createsAndRemovesMetricsForTheHandler() throws Exception { +- final ContentResponse response = client.GET(uri("/hello")); +- +- assertThat(response.getStatus()) +- .isEqualTo(404); +- +- assertThat(registry.getNames()) +- .containsOnly( +- MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.404-responses"), +- MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), +- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), +- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), +- MetricRegistry.name(TestHandler.class, "handler.requests"), +- MetricRegistry.name(TestHandler.class, "handler.active-suspended"), +- MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), +- MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), +- MetricRegistry.name(TestHandler.class, "handler.get-requests"), +- MetricRegistry.name(TestHandler.class, "handler.put-requests"), +- MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), +- MetricRegistry.name(TestHandler.class, "handler.trace-requests"), +- MetricRegistry.name(TestHandler.class, "handler.other-requests"), +- MetricRegistry.name(TestHandler.class, "handler.connect-requests"), +- MetricRegistry.name(TestHandler.class, "handler.dispatches"), +- MetricRegistry.name(TestHandler.class, "handler.head-requests"), +- MetricRegistry.name(TestHandler.class, "handler.post-requests"), +- MetricRegistry.name(TestHandler.class, "handler.options-requests"), +- MetricRegistry.name(TestHandler.class, "handler.active-requests"), +- MetricRegistry.name(TestHandler.class, "handler.delete-requests"), +- MetricRegistry.name(TestHandler.class, "handler.move-requests") +- ); +- +- server.stop(); +- +- assertThat(registry.getNames()) +- .isEmpty(); +- } +- +- @Test +- @Disabled("flaky on virtual machines") +- public void responseTimesAreRecordedForBlockingResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/blocking")); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- +- assertResponseTimesValid(); +- } +- +- @Test +- public void doStopDoesNotThrowNPE() throws Exception { +- InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); +- handler.setHandler(new TestHandler()); +- +- assertThatCode(handler::doStop).doesNotThrowAnyException(); +- } +- +- @Test +- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { +- InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "coarse", COARSE); +- handler.setHandler(new TestHandler()); +- handler.setName("handler"); +- handler.doStart(); +- assertThat(registry.getGauges()).containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); +- } +- +- @Test +- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { +- InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "detailed", DETAILED); +- handler.setHandler(new TestHandler()); +- handler.setName("handler"); +- handler.doStart(); +- assertThat(registry.getGauges()).doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); +- } +- +- @Test +- @Disabled("flaky on virtual machines") +- public void responseTimesAreRecordedForAsyncResponses() throws Exception { +- +- final ContentResponse response = client.GET(uri("/async")); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- +- assertResponseTimesValid(); +- } +- +- private void assertResponseTimesValid() { +- assertThat(registry.getMeters().get(metricName().resolve("2xx-responses")) +- .getCount()).isGreaterThan(0L); +- assertThat(registry.getMeters().get(metricName().resolve(".200-responses")) +- .getCount()).isGreaterThan(0L); +- +- +- assertThat(registry.getTimers().get(metricName().resolve(".get-requests")) +- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); +- +- assertThat(registry.getTimers().get(metricName().resolve(".requests")) +- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); +- } +- +- private String uri(String path) { +- return "http://localhost:" + connector.getLocalPort() + path; +- } +- +- private MetricName metricName() { +- return MetricRegistry.name(TestHandler.class.getName(), "handler"); +- } +- +- /** +- * test handler. +- *

    +- * Supports +- *

    +- * /blocking - uses the standard servlet api +- * /async - uses the 3.1 async api to complete the request +- *

    +- * all other requests will return 404 +- */ +- private static class TestHandler extends ServletHandler { +- @Override +- public boolean handle(Request request, Response response, Callback callback) throws Exception { +- ServletContextRequest servletContextRequest = Request.as(request, ServletContextRequest.class); +- if (servletContextRequest == null) { +- return false; +- } +- +- HttpServletRequest httpServletRequest = servletContextRequest.getServletApiRequest(); +- HttpServletResponse httpServletResponse = servletContextRequest.getHttpServletResponse(); +- +- String path = request.getHttpURI().getPath(); +- switch (path) { +- case "/blocking": ++final class InstrumentedEE10HandlerTest { ++ private final HttpClient client = new HttpClient(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final Server server = new Server(); ++ private final ServerConnector connector = new ServerConnector(server); ++ private final InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ handler.setName("handler"); ++ ++ TestHandler testHandler = new TestHandler(); ++ // a servlet handler needs a servlet mapping, else the request will be short-circuited ++ // so use the DefaultServlet here ++ testHandler.addServletWithMapping(DefaultServlet.class, "/"); ++ ++ // builds the following handler chain: ++ // ServletContextHandler -> InstrumentedHandler -> TestHandler ++ // the ServletContextHandler is needed to utilize servlet related classes ++ ServletContextHandler servletContextHandler = new ServletContextHandler(); ++ servletContextHandler.setHandler(testHandler); ++ servletContextHandler.insertHandler(handler); ++ server.setHandler(servletContextHandler); ++ ++ server.addConnector(connector); ++ server.start(); ++ client.start(); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ server.stop(); ++ client.stop(); ++ } ++ ++ @Test ++ void hasAName() throws Exception { ++ assertThat(handler.getName()).isEqualTo("handler"); ++ } ++ ++ @Test ++ void createsAndRemovesMetricsForTheHandler() throws Exception { ++ final ContentResponse response = client.GET(uri("/hello")); ++ ++ assertThat(response.getStatus()).isEqualTo(404); ++ ++ assertThat(registry.getNames()) ++ .containsOnly( ++ MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.404-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), ++ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), ++ MetricRegistry.name(TestHandler.class, "handler.requests"), ++ MetricRegistry.name(TestHandler.class, "handler.active-suspended"), ++ MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), ++ MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), ++ MetricRegistry.name(TestHandler.class, "handler.get-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.put-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), ++ MetricRegistry.name(TestHandler.class, "handler.trace-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.other-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.connect-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.dispatches"), ++ MetricRegistry.name(TestHandler.class, "handler.head-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.post-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.options-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.active-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.delete-requests"), ++ MetricRegistry.name(TestHandler.class, "handler.move-requests")); ++ ++ server.stop(); ++ ++ assertThat(registry.getNames()).isEmpty(); ++ } ++ ++ @Disabled("flaky on virtual machines") ++ @Test ++ void responseTimesAreRecordedForBlockingResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/blocking")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ ++ assertResponseTimesValid(); ++ } ++ ++ @Test ++ void doStopDoesNotThrowNPE() throws Exception { ++ InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); ++ handler.setHandler(new TestHandler()); ++ ++ assertThatCode(handler::doStop).doesNotThrowAnyException(); ++ } ++ ++ @Test ++ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { ++ InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "coarse", COARSE); ++ handler.setHandler(new TestHandler()); ++ handler.setName("handler"); ++ handler.doStart(); ++ assertThat(registry.getGauges()) ++ .containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); ++ } ++ ++ @Test ++ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { ++ InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "detailed", DETAILED); ++ handler.setHandler(new TestHandler()); ++ handler.setName("handler"); ++ handler.doStart(); ++ assertThat(registry.getGauges()) ++ .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); ++ } ++ ++ @Disabled("flaky on virtual machines") ++ @Test ++ void responseTimesAreRecordedForAsyncResponses() throws Exception { ++ ++ final ContentResponse response = client.GET(uri("/async")); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ ++ assertResponseTimesValid(); ++ } ++ ++ private void assertResponseTimesValid() { ++ assertThat(registry.getMeters().get(metricName().resolve("2xx-responses")).getCount()) ++ .isPositive(); ++ assertThat(registry.getMeters().get(metricName().resolve(".200-responses")).getCount()) ++ .isPositive(); ++ ++ assertThat( ++ registry ++ .getTimers() ++ .get(metricName().resolve(".get-requests")) ++ .getSnapshot() ++ .getMedian()) ++ .isPositive() ++ .isLessThan(TimeUnit.SECONDS.toNanos(1)); ++ ++ assertThat( ++ registry.getTimers().get(metricName().resolve(".requests")).getSnapshot().getMedian()) ++ .isPositive() ++ .isLessThan(TimeUnit.SECONDS.toNanos(1)); ++ } ++ ++ private String uri(String path) { ++ return "http://localhost:" + connector.getLocalPort() + path; ++ } ++ ++ private MetricName metricName() { ++ return MetricRegistry.name(TestHandler.class.getName(), "handler"); ++ } ++ ++ /** ++ * test handler. ++ * ++ *

    Supports ++ * ++ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the ++ * request ++ * ++ *

    all other requests will return 404 ++ */ ++ private static class TestHandler extends ServletHandler { ++ @Override ++ public boolean handle(Request request, Response response, Callback callback) throws Exception { ++ ServletContextRequest servletContextRequest = ++ Request.as(request, ServletContextRequest.class); ++ if (servletContextRequest == null) { ++ return false; ++ } ++ ++ HttpServletRequest httpServletRequest = servletContextRequest.getServletApiRequest(); ++ HttpServletResponse httpServletResponse = servletContextRequest.getHttpServletResponse(); ++ ++ String path = request.getHttpURI().getPath(); ++ switch (path) { ++ case "/blocking": ++ try { ++ Thread.sleep(100); ++ } catch (InterruptedException e) { ++ Thread.currentThread().interrupt(); ++ } ++ httpServletResponse.setStatus(200); ++ httpServletResponse.setContentType("text/plain"); ++ httpServletResponse.getWriter().write("some content from the blocking request\n"); ++ callback.succeeded(); ++ return true; ++ case "/async": ++ servletContextRequest.getState().handling(); ++ final AsyncContext context = httpServletRequest.startAsync(); ++ Thread t = ++ new Thread( ++ () -> { + try { +- Thread.sleep(100); ++ Thread.sleep(100); + } catch (InterruptedException e) { +- Thread.currentThread().interrupt(); ++ Thread.currentThread().interrupt(); + } + httpServletResponse.setStatus(200); + httpServletResponse.setContentType("text/plain"); +- httpServletResponse.getWriter().write("some content from the blocking request\n"); +- callback.succeeded(); +- return true; +- case "/async": +- servletContextRequest.getState().handling(); +- final AsyncContext context = httpServletRequest.startAsync(); +- Thread t = new Thread(() -> { +- try { +- Thread.sleep(100); +- } catch (InterruptedException e) { +- Thread.currentThread().interrupt(); +- } +- httpServletResponse.setStatus(200); +- httpServletResponse.setContentType("text/plain"); +- final ServletOutputStream servletOutputStream; +- try { +- servletOutputStream = httpServletResponse.getOutputStream(); +- servletOutputStream.setWriteListener( +- new WriteListener() { +- @Override +- public void onWritePossible() throws IOException { +- servletOutputStream.write("some content from the async\n" +- .getBytes(StandardCharsets.UTF_8)); +- context.complete(); +- servletContextRequest.getServletChannel().handle(); +- } +- +- @Override +- public void onError(Throwable throwable) { +- context.complete(); +- servletContextRequest.getServletChannel().handle(); +- } +- } +- ); +- servletContextRequest.getHttpOutput().run(); +- } catch (IOException e) { +- context.complete(); +- servletContextRequest.getServletChannel().handle(); +- } +- }); +- t.start(); +- return true; +- default: +- return false; +- } +- } ++ final ServletOutputStream servletOutputStream; ++ try { ++ servletOutputStream = httpServletResponse.getOutputStream(); ++ servletOutputStream.setWriteListener( ++ new WriteListener() { ++ @Override ++ public void onWritePossible() throws IOException { ++ servletOutputStream.write( ++ "some content from the async\n".getBytes(UTF_8)); ++ context.complete(); ++ servletContextRequest.getServletChannel().handle(); ++ } ++ ++ @Override ++ public void onError(Throwable throwable) { ++ context.complete(); ++ servletContextRequest.getServletChannel().handle(); ++ } ++ }); ++ servletContextRequest.getHttpOutput().run(); ++ } catch (IOException e) { ++ context.complete(); ++ servletContextRequest.getServletChannel().handle(); ++ } ++ }); ++ t.start(); ++ return true; ++ default: ++ return false; ++ } + } ++ } + } +--- a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java ++++ b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java +@@ -1,5 +1,13 @@ + package io.dropwizard.metrics.jetty12; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; ++import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; ++ ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -7,335 +15,345 @@ import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.RatioGauge; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; +-import org.eclipse.jetty.http.HttpMethod; +-import org.eclipse.jetty.server.Handler; +-import org.eclipse.jetty.server.Request; +-import org.eclipse.jetty.server.Response; +- + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; + import java.util.Set; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.TimeUnit; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; +-import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import org.eclipse.jetty.http.HttpMethod; ++import org.eclipse.jetty.server.Handler; ++import org.eclipse.jetty.server.Request; ++import org.eclipse.jetty.server.Response; + + /** +- * An abstract base class of a Jetty {@link Handler} which records various metrics about an underlying {@link Handler} +- * instance. ++ * An abstract base class of a Jetty {@link Handler} which records various metrics about an ++ * underlying {@link Handler} instance. + */ + public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { +- protected static final String NAME_REQUESTS = "requests"; +- protected static final String NAME_DISPATCHES = "dispatches"; +- protected static final String NAME_ACTIVE_REQUESTS = "active-requests"; +- protected static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; +- protected static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; +- protected static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; +- protected static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; +- protected static final String NAME_1XX_RESPONSES = "1xx-responses"; +- protected static final String NAME_2XX_RESPONSES = "2xx-responses"; +- protected static final String NAME_3XX_RESPONSES = "3xx-responses"; +- protected static final String NAME_4XX_RESPONSES = "4xx-responses"; +- protected static final String NAME_5XX_RESPONSES = "5xx-responses"; +- protected static final String NAME_GET_REQUESTS = "get-requests"; +- protected static final String NAME_POST_REQUESTS = "post-requests"; +- protected static final String NAME_HEAD_REQUESTS = "head-requests"; +- protected static final String NAME_PUT_REQUESTS = "put-requests"; +- protected static final String NAME_DELETE_REQUESTS = "delete-requests"; +- protected static final String NAME_OPTIONS_REQUESTS = "options-requests"; +- protected static final String NAME_TRACE_REQUESTS = "trace-requests"; +- protected static final String NAME_CONNECT_REQUESTS = "connect-requests"; +- protected static final String NAME_MOVE_REQUESTS = "move-requests"; +- protected static final String NAME_OTHER_REQUESTS = "other-requests"; +- protected static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; +- protected static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; +- protected static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; +- protected static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; +- protected static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; +- protected static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; +- protected static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); +- protected static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); +- +- protected final MetricRegistry metricRegistry; +- +- private String name; +- protected final String prefix; +- +- // the requests handled by this handler, excluding active +- protected Timer requests; +- +- // the number of dispatches seen by this handler, excluding active +- protected Timer dispatches; +- +- // the number of active requests +- protected Counter activeRequests; +- +- // the number of active dispatches +- protected Counter activeDispatches; +- +- // the number of requests currently suspended. +- protected Counter activeSuspended; +- +- // the number of requests that have been asynchronously dispatched +- protected Meter asyncDispatches; +- +- // the number of requests that expired while suspended +- protected Meter asyncTimeouts; +- +- protected final ResponseMeteredLevel responseMeteredLevel; +- protected List responses; +- protected Map responseCodeMeters; +- +- protected Timer getRequests; +- protected Timer postRequests; +- protected Timer headRequests; +- protected Timer putRequests; +- protected Timer deleteRequests; +- protected Timer optionsRequests; +- protected Timer traceRequests; +- protected Timer connectRequests; +- protected Timer moveRequests; +- protected Timer otherRequests; +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- */ +- protected AbstractInstrumentedHandler(MetricRegistry registry) { +- this(registry, null); +- } +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param prefix the prefix to use for the metrics names +- */ +- protected AbstractInstrumentedHandler(MetricRegistry registry, String prefix) { +- this(registry, prefix, COARSE); +- } +- +- /** +- * Create a new instrumented handler using a given metrics registry. +- * +- * @param registry the registry for the metrics +- * @param prefix the prefix to use for the metrics names +- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented +- */ +- protected AbstractInstrumentedHandler(MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { +- this.responseMeteredLevel = responseMeteredLevel; +- this.metricRegistry = registry; +- this.prefix = prefix; +- } +- +- public String getName() { +- return name; +- } +- +- public void setName(String name) { +- this.name = name; ++ protected static final String NAME_REQUESTS = "requests"; ++ protected static final String NAME_DISPATCHES = "dispatches"; ++ protected static final String NAME_ACTIVE_REQUESTS = "active-requests"; ++ protected static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; ++ protected static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; ++ protected static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; ++ protected static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; ++ protected static final String NAME_1XX_RESPONSES = "1xx-responses"; ++ protected static final String NAME_2XX_RESPONSES = "2xx-responses"; ++ protected static final String NAME_3XX_RESPONSES = "3xx-responses"; ++ protected static final String NAME_4XX_RESPONSES = "4xx-responses"; ++ protected static final String NAME_5XX_RESPONSES = "5xx-responses"; ++ protected static final String NAME_GET_REQUESTS = "get-requests"; ++ protected static final String NAME_POST_REQUESTS = "post-requests"; ++ protected static final String NAME_HEAD_REQUESTS = "head-requests"; ++ protected static final String NAME_PUT_REQUESTS = "put-requests"; ++ protected static final String NAME_DELETE_REQUESTS = "delete-requests"; ++ protected static final String NAME_OPTIONS_REQUESTS = "options-requests"; ++ protected static final String NAME_TRACE_REQUESTS = "trace-requests"; ++ protected static final String NAME_CONNECT_REQUESTS = "connect-requests"; ++ protected static final String NAME_MOVE_REQUESTS = "move-requests"; ++ protected static final String NAME_OTHER_REQUESTS = "other-requests"; ++ protected static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; ++ protected static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; ++ protected static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; ++ protected static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; ++ protected static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; ++ protected static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; ++ protected static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); ++ protected static final Set DETAILED_METER_LEVELS = ++ EnumSet.of(DETAILED, ALL); ++ ++ protected final MetricRegistry metricRegistry; ++ ++ private String name; ++ protected final String prefix; ++ ++ // the requests handled by this handler, excluding active ++ protected Timer requests; ++ ++ // the number of dispatches seen by this handler, excluding active ++ protected Timer dispatches; ++ ++ // the number of active requests ++ protected Counter activeRequests; ++ ++ // the number of active dispatches ++ protected Counter activeDispatches; ++ ++ // the number of requests currently suspended. ++ protected Counter activeSuspended; ++ ++ // the number of requests that have been asynchronously dispatched ++ protected Meter asyncDispatches; ++ ++ // the number of requests that expired while suspended ++ protected Meter asyncTimeouts; ++ ++ protected final ResponseMeteredLevel responseMeteredLevel; ++ protected List responses; ++ protected Map responseCodeMeters; ++ ++ protected Timer getRequests; ++ protected Timer postRequests; ++ protected Timer headRequests; ++ protected Timer putRequests; ++ protected Timer deleteRequests; ++ protected Timer optionsRequests; ++ protected Timer traceRequests; ++ protected Timer connectRequests; ++ protected Timer moveRequests; ++ protected Timer otherRequests; ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ */ ++ protected AbstractInstrumentedHandler(MetricRegistry registry) { ++ this(registry, null); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param prefix the prefix to use for the metrics names ++ */ ++ protected AbstractInstrumentedHandler(MetricRegistry registry, String prefix) { ++ this(registry, prefix, COARSE); ++ } ++ ++ /** ++ * Create a new instrumented handler using a given metrics registry. ++ * ++ * @param registry the registry for the metrics ++ * @param prefix the prefix to use for the metrics names ++ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are ++ * instrumented ++ */ ++ protected AbstractInstrumentedHandler( ++ MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { ++ this.responseMeteredLevel = responseMeteredLevel; ++ this.metricRegistry = registry; ++ this.prefix = prefix; ++ } ++ ++ public String getName() { ++ return name; ++ } ++ ++ public void setName(String name) { ++ this.name = name; ++ } ++ ++ @Override ++ protected void doStart() throws Exception { ++ super.doStart(); ++ ++ final MetricName prefix = getMetricPrefix(); ++ ++ this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); ++ this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); ++ ++ this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); ++ this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); ++ this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); ++ ++ this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); ++ this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); ++ ++ this.responseCodeMeters = ++ DETAILED_METER_LEVELS.contains(responseMeteredLevel) ++ ? new ConcurrentHashMap<>() ++ : ImmutableMap.of(); ++ ++ this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); ++ this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); ++ this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); ++ this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); ++ this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); ++ this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); ++ this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); ++ this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); ++ this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); ++ this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); ++ ++ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { ++ this.responses = ++ unmodifiableList( ++ Arrays.asList( ++ metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx ++ metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx ++ metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx ++ metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx ++ metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx ++ )); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_4XX_1M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_4XX_5M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_4XX_15M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of( ++ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_5XX_1M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_5XX_5M), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); ++ } ++ }); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_PERCENT_5XX_15M), ++ new RatioGauge() { ++ @Override ++ public Ratio getRatio() { ++ return Ratio.of( ++ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); ++ } ++ }); ++ } else { ++ this.responses = ImmutableList.of(); + } +- +- @Override +- protected void doStart() throws Exception { +- super.doStart(); +- +- final MetricName prefix = getMetricPrefix(); +- +- this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); +- this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); +- +- this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); +- this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); +- this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); +- +- this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); +- this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); +- +- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); +- +- this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); +- this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); +- this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); +- this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); +- this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); +- this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); +- this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); +- this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); +- this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); +- this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); +- +- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { +- this.responses = Collections.unmodifiableList(Arrays.asList( +- metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx +- metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx +- metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx +- metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx +- metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx +- )); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_1M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_5M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_15M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(3).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_1M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getOneMinuteRate(), +- requests.getOneMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_5M), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(responses.get(4).getFiveMinuteRate(), +- requests.getFiveMinuteRate()); +- } +- }); +- +- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_15M), new RatioGauge() { +- @Override +- public Ratio getRatio() { +- return Ratio.of(responses.get(4).getFifteenMinuteRate(), +- requests.getFifteenMinuteRate()); +- } +- }); +- } else { +- this.responses = Collections.emptyList(); +- } ++ } ++ ++ @Override ++ protected void doStop() throws Exception { ++ final MetricName prefix = getMetricPrefix(); ++ ++ metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); ++ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); ++ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); ++ metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); ++ metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); ++ metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); ++ metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); ++ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); ++ ++ if (responseCodeMeters != null) { ++ responseCodeMeters.keySet().stream() ++ .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) ++ .forEach(metricRegistry::remove); + } +- +- @Override +- protected void doStop() throws Exception { +- final MetricName prefix = getMetricPrefix(); +- +- metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); +- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); +- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); +- metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); +- metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); +- metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); +- metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); +- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); +- +- if (responseCodeMeters != null) { +- responseCodeMeters.keySet().stream() +- .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) +- .forEach(metricRegistry::remove); +- } +- super.doStop(); ++ super.doStop(); ++ } ++ ++ protected Timer requestTimer(String method) { ++ final HttpMethod m = HttpMethod.fromString(method); ++ if (m == null) { ++ return otherRequests; ++ } else { ++ switch (m) { ++ case GET: ++ return getRequests; ++ case POST: ++ return postRequests; ++ case PUT: ++ return putRequests; ++ case HEAD: ++ return headRequests; ++ case DELETE: ++ return deleteRequests; ++ case OPTIONS: ++ return optionsRequests; ++ case TRACE: ++ return traceRequests; ++ case CONNECT: ++ return connectRequests; ++ case MOVE: ++ return moveRequests; ++ default: ++ return otherRequests; ++ } + } +- +- protected Timer requestTimer(String method) { +- final HttpMethod m = HttpMethod.fromString(method); +- if (m == null) { +- return otherRequests; +- } else { +- switch (m) { +- case GET: +- return getRequests; +- case POST: +- return postRequests; +- case PUT: +- return putRequests; +- case HEAD: +- return headRequests; +- case DELETE: +- return deleteRequests; +- case OPTIONS: +- return optionsRequests; +- case TRACE: +- return traceRequests; +- case CONNECT: +- return connectRequests; +- case MOVE: +- return moveRequests; +- default: +- return otherRequests; +- } +- } ++ } ++ ++ protected void updateResponses( ++ Request request, Response response, long start, boolean isHandled) { ++ if (isHandled) { ++ mark(response.getStatus()); ++ } else { ++ mark(404); // will end up with a 404 response sent by HttpChannel.handle + } +- +- protected void updateResponses(Request request, Response response, long start, boolean isHandled) { +- if (isHandled) { +- mark(response.getStatus()); +- } else { +- mark(404); // will end up with a 404 response sent by HttpChannel.handle +- } +- activeRequests.dec(); +- final long elapsedTime = System.currentTimeMillis() - start; +- requests.update(elapsedTime, TimeUnit.MILLISECONDS); +- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); ++ activeRequests.dec(); ++ final long elapsedTime = System.currentTimeMillis() - start; ++ requests.update(elapsedTime, TimeUnit.MILLISECONDS); ++ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); ++ } ++ ++ protected void mark(int statusCode) { ++ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { ++ getResponseCodeMeter(statusCode).mark(); + } + +- protected void mark(int statusCode) { +- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { +- getResponseCodeMeter(statusCode).mark(); +- } +- +- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { +- final int responseStatus = statusCode / 100; +- if (responseStatus >= 1 && responseStatus <= 5) { +- responses.get(responseStatus - 1).mark(); +- } +- } ++ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { ++ final int responseStatus = statusCode / 100; ++ if (responseStatus >= 1 && responseStatus <= 5) { ++ responses.get(responseStatus - 1).mark(); ++ } + } ++ } + +- protected Meter getResponseCodeMeter(int statusCode) { +- return responseCodeMeters +- .computeIfAbsent(statusCode, sc -> metricRegistry +- .meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); +- } ++ protected Meter getResponseCodeMeter(int statusCode) { ++ return responseCodeMeters.computeIfAbsent( ++ statusCode, ++ sc -> metricRegistry.meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); ++ } + +- protected MetricName getMetricPrefix() { +- return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); +- } ++ protected MetricName getMetricPrefix() { ++ return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); ++ } + } +--- a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java ++++ b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java +@@ -2,62 +2,63 @@ package io.dropwizard.metrics.jetty12; + + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Timer; ++import java.util.List; + import org.eclipse.jetty.io.Connection; + import org.eclipse.jetty.io.EndPoint; + import org.eclipse.jetty.server.ConnectionFactory; + import org.eclipse.jetty.server.Connector; + import org.eclipse.jetty.util.component.ContainerLifeCycle; + +-import java.util.List; +- + public class InstrumentedConnectionFactory extends ContainerLifeCycle implements ConnectionFactory { +- private final ConnectionFactory connectionFactory; +- private final Timer timer; +- private final Counter counter; +- +- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { +- this(connectionFactory, timer, null); +- } +- +- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer, Counter counter) { +- this.connectionFactory = connectionFactory; +- this.timer = timer; +- this.counter = counter; +- addBean(connectionFactory); +- } +- +- @Override +- public String getProtocol() { +- return connectionFactory.getProtocol(); +- } +- +- @Override +- public List getProtocols() { +- return connectionFactory.getProtocols(); +- } +- +- @Override +- public Connection newConnection(Connector connector, EndPoint endPoint) { +- final Connection connection = connectionFactory.newConnection(connector, endPoint); +- connection.addEventListener(new Connection.Listener() { +- private Timer.Context context; +- +- @Override +- public void onOpened(Connection connection) { +- this.context = timer.time(); +- if (counter != null) { +- counter.inc(); +- } ++ private final ConnectionFactory connectionFactory; ++ private final Timer timer; ++ private final Counter counter; ++ ++ public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { ++ this(connectionFactory, timer, null); ++ } ++ ++ public InstrumentedConnectionFactory( ++ ConnectionFactory connectionFactory, Timer timer, Counter counter) { ++ this.connectionFactory = connectionFactory; ++ this.timer = timer; ++ this.counter = counter; ++ addBean(connectionFactory); ++ } ++ ++ @Override ++ public String getProtocol() { ++ return connectionFactory.getProtocol(); ++ } ++ ++ @Override ++ public List getProtocols() { ++ return connectionFactory.getProtocols(); ++ } ++ ++ @Override ++ public Connection newConnection(Connector connector, EndPoint endPoint) { ++ final Connection connection = connectionFactory.newConnection(connector, endPoint); ++ connection.addEventListener( ++ new Connection.Listener() { ++ private Timer.Context context; ++ ++ @Override ++ public void onOpened(Connection connection) { ++ this.context = timer.time(); ++ if (counter != null) { ++ counter.inc(); + } ++ } + +- @Override +- public void onClosed(Connection connection) { +- context.stop(); +- if (counter != null) { +- counter.dec(); +- } ++ @Override ++ public void onClosed(Connection connection) { ++ context.stop(); ++ if (counter != null) { ++ counter.dec(); + } ++ } + }); +- return connection; +- } ++ return connection; ++ } + } +--- a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPool.java ++++ b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPool.java +@@ -1,164 +1,187 @@ + package io.dropwizard.metrics.jetty12; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.RatioGauge; +-import org.eclipse.jetty.util.annotation.Name; +-import org.eclipse.jetty.util.thread.QueuedThreadPool; +- + import java.util.concurrent.BlockingQueue; + import java.util.concurrent.ThreadFactory; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; ++import org.eclipse.jetty.util.annotation.Name; ++import org.eclipse.jetty.util.thread.QueuedThreadPool; + + public class InstrumentedQueuedThreadPool extends QueuedThreadPool { +- private static final String NAME_UTILIZATION = "utilization"; +- private static final String NAME_UTILIZATION_MAX = "utilization-max"; +- private static final String NAME_SIZE = "size"; +- private static final String NAME_JOBS = "jobs"; +- private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; +- +- private final MetricRegistry metricRegistry; +- private String prefix; +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { +- this(registry, 200); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads) { +- this(registry, maxThreads, 8); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads) { +- this(registry, maxThreads, minThreads, 60000); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("queue") BlockingQueue queue) { +- this(registry, maxThreads, minThreads, 60000, queue); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout) { +- this(registry, maxThreads, minThreads, idleTimeout, null); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("queue") BlockingQueue queue) { +- this(registry, maxThreads, minThreads, idleTimeout, queue, (ThreadGroup) null); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("queue") BlockingQueue queue, +- @Name("threadFactory") ThreadFactory threadFactory) { +- this(registry, maxThreads, minThreads, idleTimeout, -1, queue, null, threadFactory); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("queue") BlockingQueue queue, +- @Name("threadGroup") ThreadGroup threadGroup) { +- this(registry, maxThreads, minThreads, idleTimeout, -1, queue, threadGroup); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("reservedThreads") int reservedThreads, +- @Name("queue") BlockingQueue queue, +- @Name("threadGroup") ThreadGroup threadGroup) { +- this(registry, maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, null); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("reservedThreads") int reservedThreads, +- @Name("queue") BlockingQueue queue, +- @Name("threadGroup") ThreadGroup threadGroup, +- @Name("threadFactory") ThreadFactory threadFactory) { +- this(registry, maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, threadFactory, null); +- } +- +- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, +- @Name("maxThreads") int maxThreads, +- @Name("minThreads") int minThreads, +- @Name("idleTimeout") int idleTimeout, +- @Name("reservedThreads") int reservedThreads, +- @Name("queue") BlockingQueue queue, +- @Name("threadGroup") ThreadGroup threadGroup, +- @Name("threadFactory") ThreadFactory threadFactory, +- @Name("prefix") String prefix) { +- super(maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, threadFactory); +- this.metricRegistry = registry; +- this.prefix = prefix; +- } +- +- public String getPrefix() { +- return prefix; +- } +- +- public void setPrefix(String prefix) { +- this.prefix = prefix; +- } +- +- @Override +- protected void doStart() throws Exception { +- super.doStart(); +- +- final MetricName prefix = getMetricPrefix(); +- +- metricRegistry.register(prefix.resolve(NAME_UTILIZATION), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(getUtilizedThreads(), getThreads() - getLeasedThreads()); +- } ++ private static final String NAME_UTILIZATION = "utilization"; ++ private static final String NAME_UTILIZATION_MAX = "utilization-max"; ++ private static final String NAME_SIZE = "size"; ++ private static final String NAME_JOBS = "jobs"; ++ private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; ++ ++ private final MetricRegistry metricRegistry; ++ private String prefix; ++ ++ public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { ++ this(registry, 200); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, @Name("maxThreads") int maxThreads) { ++ this(registry, maxThreads, 8); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads) { ++ this(registry, maxThreads, minThreads, 60000); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("queue") BlockingQueue queue) { ++ this(registry, maxThreads, minThreads, 60000, queue); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout) { ++ this(registry, maxThreads, minThreads, idleTimeout, null); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("queue") BlockingQueue queue) { ++ this(registry, maxThreads, minThreads, idleTimeout, queue, (ThreadGroup) null); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("queue") BlockingQueue queue, ++ @Name("threadFactory") ThreadFactory threadFactory) { ++ this(registry, maxThreads, minThreads, idleTimeout, -1, queue, null, threadFactory); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("queue") BlockingQueue queue, ++ @Name("threadGroup") ThreadGroup threadGroup) { ++ this(registry, maxThreads, minThreads, idleTimeout, -1, queue, threadGroup); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("reservedThreads") int reservedThreads, ++ @Name("queue") BlockingQueue queue, ++ @Name("threadGroup") ThreadGroup threadGroup) { ++ this(registry, maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, null); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("reservedThreads") int reservedThreads, ++ @Name("queue") BlockingQueue queue, ++ @Name("threadGroup") ThreadGroup threadGroup, ++ @Name("threadFactory") ThreadFactory threadFactory) { ++ this( ++ registry, ++ maxThreads, ++ minThreads, ++ idleTimeout, ++ reservedThreads, ++ queue, ++ threadGroup, ++ threadFactory, ++ null); ++ } ++ ++ public InstrumentedQueuedThreadPool( ++ @Name("registry") MetricRegistry registry, ++ @Name("maxThreads") int maxThreads, ++ @Name("minThreads") int minThreads, ++ @Name("idleTimeout") int idleTimeout, ++ @Name("reservedThreads") int reservedThreads, ++ @Name("queue") BlockingQueue queue, ++ @Name("threadGroup") ThreadGroup threadGroup, ++ @Name("threadFactory") ThreadFactory threadFactory, ++ @Name("prefix") String prefix) { ++ super(maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, threadFactory); ++ this.metricRegistry = registry; ++ this.prefix = prefix; ++ } ++ ++ public String getPrefix() { ++ return prefix; ++ } ++ ++ public void setPrefix(String prefix) { ++ this.prefix = prefix; ++ } ++ ++ @Override ++ protected void doStart() throws Exception { ++ super.doStart(); ++ ++ final MetricName prefix = getMetricPrefix(); ++ ++ metricRegistry.register( ++ prefix.resolve(NAME_UTILIZATION), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(getUtilizedThreads(), getThreads() - getLeasedThreads()); ++ } + }); +- metricRegistry.registerGauge(prefix.resolve(NAME_UTILIZATION_MAX), this::getUtilizationRate); +- metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); +- // This assumes the QueuedThreadPool is using a BlockingArrayQueue or +- // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. +- metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); +- metricRegistry.register(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- BlockingQueue queue = getQueue(); +- return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); +- } ++ metricRegistry.registerGauge(prefix.resolve(NAME_UTILIZATION_MAX), this::getUtilizationRate); ++ metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); ++ // This assumes the QueuedThreadPool is using a BlockingArrayQueue or ++ // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. ++ metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); ++ metricRegistry.register( ++ prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ BlockingQueue queue = getQueue(); ++ return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); ++ } + }); +- } +- +- @Override +- protected void doStop() throws Exception { +- final MetricName prefix = getMetricPrefix(); +- +- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); +- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); +- metricRegistry.remove(prefix.resolve(NAME_SIZE)); +- metricRegistry.remove(prefix.resolve(NAME_JOBS)); +- metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); +- +- super.doStop(); +- } +- +- private MetricName getMetricPrefix() { +- return this.prefix == null ? name(QueuedThreadPool.class, getName()) : name(this.prefix, getName()); +- } ++ } ++ ++ @Override ++ protected void doStop() throws Exception { ++ final MetricName prefix = getMetricPrefix(); ++ ++ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); ++ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); ++ metricRegistry.remove(prefix.resolve(NAME_SIZE)); ++ metricRegistry.remove(prefix.resolve(NAME_JOBS)); ++ metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); ++ ++ super.doStop(); ++ } ++ ++ private MetricName getMetricPrefix() { ++ return this.prefix == null ++ ? name(QueuedThreadPool.class, getName()) ++ : name(this.prefix, getName()); ++ } + } +--- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java ++++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics.jetty12; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; +@@ -17,70 +19,70 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-public class InstrumentedConnectionFactoryTest { +- private final MetricRegistry registry = new MetricRegistry(); +- private final Server server = new Server(); +- private final ServerConnector connector = +- new ServerConnector(server, new InstrumentedConnectionFactory(new HttpConnectionFactory(), +- registry.timer("http.connections"), +- registry.counter("http.active-connections"))); +- private final HttpClient client = new HttpClient(); +- +- @BeforeEach +- public void setUp() throws Exception { +- server.setHandler(new Handler.Abstract() { +- @Override +- public boolean handle(Request request, Response response, Callback callback) throws Exception { +- Content.Sink.write(response, true, "OK", callback); +- return true; +- } ++final class InstrumentedConnectionFactoryTest { ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final Server server = new Server(); ++ private final ServerConnector connector = ++ new ServerConnector( ++ server, ++ new InstrumentedConnectionFactory( ++ new HttpConnectionFactory(), ++ registry.timer("http.connections"), ++ registry.counter("http.active-connections"))); ++ private final HttpClient client = new HttpClient(); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ server.setHandler( ++ new Handler.Abstract() { ++ @Override ++ public boolean handle(Request request, Response response, Callback callback) ++ throws Exception { ++ Content.Sink.write(response, true, "OK", callback); ++ return true; ++ } + }); + +- server.addConnector(connector); +- server.start(); ++ server.addConnector(connector); ++ server.start(); + +- client.start(); +- } ++ client.start(); ++ } + +- @AfterEach +- public void tearDown() throws Exception { +- server.stop(); +- client.stop(); +- } ++ @AfterEach ++ void tearDown() throws Exception { ++ server.stop(); ++ client.stop(); ++ } + +- @Test +- public void instrumentsConnectionTimes() throws Exception { +- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); +- assertThat(response.getStatus()) +- .isEqualTo(200); ++ @Test ++ void instrumentsConnectionTimes() throws Exception { ++ final ContentResponse response = ++ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); ++ assertThat(response.getStatus()).isEqualTo(200); + +- client.stop(); // close the connection ++ client.stop(); // close the connection + +- Thread.sleep(100); // make sure the connection is closed ++ Thread.sleep(100); // make sure the connection is closed + +- final Timer timer = registry.timer(MetricRegistry.name("http.connections")); +- assertThat(timer.getCount()) +- .isEqualTo(1); +- } ++ final Timer timer = registry.timer(MetricRegistry.name("http.connections")); ++ assertThat(timer.getCount()).isEqualTo(1); ++ } + +- @Test +- public void instrumentsActiveConnections() throws Exception { +- final Counter counter = registry.counter("http.active-connections"); ++ @Test ++ void instrumentsActiveConnections() throws Exception { ++ final Counter counter = registry.counter("http.active-connections"); + +- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); +- assertThat(response.getStatus()) +- .isEqualTo(200); ++ final ContentResponse response = ++ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); ++ assertThat(response.getStatus()).isEqualTo(200); + +- assertThat(counter.getCount()) +- .isEqualTo(1); ++ assertThat(counter.getCount()).isEqualTo(1); + +- client.stop(); // close the connection ++ client.stop(); // close the connection + +- Thread.sleep(100); // make sure the connection is closed ++ Thread.sleep(100); // make sure the connection is closed + +- assertThat(counter.getCount()) +- .isEqualTo(0); +- } ++ assertThat(counter.getCount()).isEqualTo(0); ++ } + } +--- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java ++++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java +@@ -1,49 +1,49 @@ + package io.dropwizard.metrics.jetty12; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import org.eclipse.jetty.util.thread.QueuedThreadPool; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-public class InstrumentedQueuedThreadPoolTest { +- private static final String PREFIX = "prefix"; +- +- private MetricRegistry metricRegistry; +- private InstrumentedQueuedThreadPool iqtp; +- +- @BeforeEach +- public void setUp() { +- metricRegistry = new MetricRegistry(); +- iqtp = new InstrumentedQueuedThreadPool(metricRegistry); +- } +- +- @Test +- public void customMetricsPrefix() throws Exception { +- iqtp.setPrefix(PREFIX); +- iqtp.start(); +- +- assertThat(metricRegistry.getNames()) +- .overridingErrorMessage("Custom metrics prefix doesn't match") +- .allSatisfy(name -> assertThat(name.getKey()).startsWith(PREFIX)); +- +- iqtp.stop(); +- assertThat(metricRegistry.getMetrics()) +- .overridingErrorMessage("The default metrics prefix was changed") +- .isEmpty(); +- } +- +- @Test +- public void metricsPrefixBackwardCompatible() throws Exception { +- iqtp.start(); +- assertThat(metricRegistry.getNames()) +- .overridingErrorMessage("The default metrics prefix was changed") +- .allSatisfy(name -> assertThat(name.getKey()).startsWith(QueuedThreadPool.class.getName())); +- +- iqtp.stop(); +- assertThat(metricRegistry.getMetrics()) +- .overridingErrorMessage("The default metrics prefix was changed") +- .isEmpty(); +- } ++final class InstrumentedQueuedThreadPoolTest { ++ private static final String PREFIX = "prefix"; ++ ++ private MetricRegistry metricRegistry; ++ private InstrumentedQueuedThreadPool iqtp; ++ ++ @BeforeEach ++ void setUp() { ++ metricRegistry = new MetricRegistry(); ++ iqtp = new InstrumentedQueuedThreadPool(metricRegistry); ++ } ++ ++ @Test ++ void customMetricsPrefix() throws Exception { ++ iqtp.setPrefix(PREFIX); ++ iqtp.start(); ++ ++ assertThat(metricRegistry.getNames()) ++ .overridingErrorMessage("Custom metrics prefix doesn't match") ++ .allSatisfy(name -> assertThat(name.getKey()).startsWith(PREFIX)); ++ ++ iqtp.stop(); ++ assertThat(metricRegistry.getMetrics()) ++ .overridingErrorMessage("The default metrics prefix was changed") ++ .isEmpty(); ++ } ++ ++ @Test ++ void metricsPrefixBackwardCompatible() throws Exception { ++ iqtp.start(); ++ assertThat(metricRegistry.getNames()) ++ .overridingErrorMessage("The default metrics prefix was changed") ++ .allSatisfy(name -> assertThat(name.getKey()).startsWith(QueuedThreadPool.class.getName())); ++ ++ iqtp.stop(); ++ assertThat(metricRegistry.getMetrics()) ++ .overridingErrorMessage("The default metrics prefix was changed") ++ .isEmpty(); ++ } + } +--- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java ++++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java +@@ -2,70 +2,68 @@ package io.dropwizard.metrics5.jmx; + + import io.dropwizard.metrics5.MetricName; + import java.util.Hashtable; +- + import javax.management.MalformedObjectNameException; + import javax.management.ObjectName; +- + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + + public class DefaultObjectNameFactory implements ObjectNameFactory { + +- private static final char[] QUOTABLE_CHARS = new char[] {',', '=', ':', '"'}; +- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); ++ private static final char[] QUOTABLE_CHARS = new char[] {',', '=', ':', '"'}; ++ private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectNameFactory.class); + +- @Override +- public ObjectName createName(String type, String domain, MetricName name) { +- try { +- ObjectName objectName; +- Hashtable properties = new Hashtable<>(); ++ @Override ++ public ObjectName createName(String type, String domain, MetricName name) { ++ try { ++ ObjectName objectName; ++ Hashtable properties = new Hashtable<>(); + +- properties.put("name", name.getKey()); +- properties.put("type", type); +- properties.putAll(name.getTags()); +- objectName = new ObjectName(domain, properties); ++ properties.put("name", name.getKey()); ++ properties.put("type", type); ++ properties.putAll(name.getTags()); ++ objectName = new ObjectName(domain, properties); + +- /* +- * The only way we can find out if we need to quote the properties is by +- * checking an ObjectName that we've constructed. +- */ +- if (objectName.isDomainPattern()) { +- domain = ObjectName.quote(domain); +- } +- if (objectName.isPropertyValuePattern("name") || shouldQuote(objectName.getKeyProperty("name"))) { +- properties.put("name", ObjectName.quote(name.getKey())); +- } +- if (objectName.isPropertyValuePattern("type") || shouldQuote(objectName.getKeyProperty("type"))) { +- properties.put("type", ObjectName.quote(type)); +- } +- objectName = new ObjectName(domain, properties); ++ /* ++ * The only way we can find out if we need to quote the properties is by ++ * checking an ObjectName that we've constructed. ++ */ ++ if (objectName.isDomainPattern()) { ++ domain = ObjectName.quote(domain); ++ } ++ if (objectName.isPropertyValuePattern("name") ++ || shouldQuote(objectName.getKeyProperty("name"))) { ++ properties.put("name", ObjectName.quote(name.getKey())); ++ } ++ if (objectName.isPropertyValuePattern("type") ++ || shouldQuote(objectName.getKeyProperty("type"))) { ++ properties.put("type", ObjectName.quote(type)); ++ } ++ return new ObjectName(domain, properties); + +- return objectName; +- } catch (MalformedObjectNameException e) { +- try { +- return new ObjectName(domain, "name", ObjectName.quote(name.getKey())); +- } catch (MalformedObjectNameException e1) { +- LOGGER.warn("Unable to register {} {}", type, name, e1); +- throw new RuntimeException(e1); +- } +- } ++ } catch (MalformedObjectNameException e) { ++ try { ++ return new ObjectName(domain, "name", ObjectName.quote(name.getKey())); ++ } catch (MalformedObjectNameException e1) { ++ LOG.warn("Unable to register {} {}", type, name, e1); ++ throw new RuntimeException(e1); ++ } + } ++ } + +- /** +- * Determines whether the value requires quoting. +- * According to the {@link ObjectName} documentation, values can be quoted or unquoted. Unquoted +- * values may not contain any of the characters comma, equals, colon, or quote. +- * +- * @param value a value to test +- * @return true when it requires quoting, false otherwise +- */ +- private boolean shouldQuote(final String value) { +- for (char quotableChar : QUOTABLE_CHARS) { +- if (value.indexOf(quotableChar) != -1) { +- return true; +- } +- } +- return false; ++ /** ++ * Determines whether the value requires quoting. According to the {@link ObjectName} ++ * documentation, values can be quoted or unquoted. Unquoted values may not contain any of the ++ * characters comma, equals, colon, or quote. ++ * ++ * @param value a value to test ++ * @return true when it requires quoting, false otherwise ++ */ ++ private boolean shouldQuote(final String value) { ++ for (char quotableChar : QUOTABLE_CHARS) { ++ if (value.indexOf(quotableChar) != -1) { ++ return true; ++ } + } +- ++ return false; ++ } + } +--- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java ++++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.jmx; + ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Collections.unmodifiableMap; ++ ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Histogram; +@@ -11,9 +15,12 @@ import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricRegistryListener; + import io.dropwizard.metrics5.Reporter; + import io.dropwizard.metrics5.Timer; +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; +- ++import java.io.Closeable; ++import java.lang.management.ManagementFactory; ++import java.util.Locale; ++import java.util.Map; ++import java.util.concurrent.ConcurrentHashMap; ++import java.util.concurrent.TimeUnit; + import javax.management.InstanceAlreadyExistsException; + import javax.management.InstanceNotFoundException; + import javax.management.JMException; +@@ -21,758 +28,755 @@ import javax.management.MBeanRegistrationException; + import javax.management.MBeanServer; + import javax.management.ObjectInstance; + import javax.management.ObjectName; +-import java.io.Closeable; +-import java.lang.management.ManagementFactory; +-import java.util.Collections; +-import java.util.Locale; +-import java.util.Map; +-import java.util.concurrent.ConcurrentHashMap; +-import java.util.concurrent.TimeUnit; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + +-/** +- * A reporter which listens for new metrics and exposes them as namespaced MBeans. +- */ ++/** A reporter which listens for new metrics and exposes them as namespaced MBeans. */ + public class JmxReporter implements Reporter, Closeable { ++ /** ++ * Returns a new {@link Builder} for {@link JmxReporter}. ++ * ++ * @param registry the registry to report ++ * @return a {@link Builder} instance for a {@link JmxReporter} ++ */ ++ public static Builder forRegistry(MetricRegistry registry) { ++ return new Builder(registry); ++ } ++ ++ /** ++ * A builder for {@link JmxReporter} instances. Defaults to using the default MBean server and not ++ * filtering metrics. ++ */ ++ public static class Builder { ++ private final MetricRegistry registry; ++ private MBeanServer mBeanServer; ++ private TimeUnit rateUnit; ++ private TimeUnit durationUnit; ++ private ObjectNameFactory objectNameFactory; ++ private MetricFilter filter = MetricFilter.ALL; ++ private String domain; ++ private Map specificDurationUnits; ++ private Map specificRateUnits; ++ ++ private Builder(MetricRegistry registry) { ++ this.registry = registry; ++ this.rateUnit = TimeUnit.SECONDS; ++ this.durationUnit = TimeUnit.MILLISECONDS; ++ this.domain = "metrics"; ++ this.objectNameFactory = new DefaultObjectNameFactory(); ++ this.specificDurationUnits = ImmutableMap.of(); ++ this.specificRateUnits = ImmutableMap.of(); ++ } ++ + /** +- * Returns a new {@link Builder} for {@link JmxReporter}. ++ * Register MBeans with the given {@link MBeanServer}. + * +- * @param registry the registry to report +- * @return a {@link Builder} instance for a {@link JmxReporter} ++ * @param mBeanServer an {@link MBeanServer} ++ * @return {@code this} + */ +- public static Builder forRegistry(MetricRegistry registry) { +- return new Builder(registry); ++ public Builder registerWith(MBeanServer mBeanServer) { ++ this.mBeanServer = mBeanServer; ++ return this; + } + + /** +- * A builder for {@link JmxReporter} instances. Defaults to using the default MBean server and +- * not filtering metrics. ++ * Convert rates to the given time unit. ++ * ++ * @param rateUnit a unit of time ++ * @return {@code this} + */ +- public static class Builder { +- private final MetricRegistry registry; +- private MBeanServer mBeanServer; +- private TimeUnit rateUnit; +- private TimeUnit durationUnit; +- private ObjectNameFactory objectNameFactory; +- private MetricFilter filter = MetricFilter.ALL; +- private String domain; +- private Map specificDurationUnits; +- private Map specificRateUnits; +- +- private Builder(MetricRegistry registry) { +- this.registry = registry; +- this.rateUnit = TimeUnit.SECONDS; +- this.durationUnit = TimeUnit.MILLISECONDS; +- this.domain = "metrics"; +- this.objectNameFactory = new DefaultObjectNameFactory(); +- this.specificDurationUnits = Collections.emptyMap(); +- this.specificRateUnits = Collections.emptyMap(); +- } +- +- /** +- * Register MBeans with the given {@link MBeanServer}. +- * +- * @param mBeanServer an {@link MBeanServer} +- * @return {@code this} +- */ +- public Builder registerWith(MBeanServer mBeanServer) { +- this.mBeanServer = mBeanServer; +- return this; +- } +- +- /** +- * Convert rates to the given time unit. +- * +- * @param rateUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertRatesTo(TimeUnit rateUnit) { +- this.rateUnit = rateUnit; +- return this; +- } +- +- public Builder createsObjectNamesWith(ObjectNameFactory onFactory) { +- if (onFactory == null) { +- throw new IllegalArgumentException("null objectNameFactory"); +- } +- this.objectNameFactory = onFactory; +- return this; +- } +- +- /** +- * Convert durations to the given time unit. +- * +- * @param durationUnit a unit of time +- * @return {@code this} +- */ +- public Builder convertDurationsTo(TimeUnit durationUnit) { +- this.durationUnit = durationUnit; +- return this; +- } +- +- /** +- * Only report metrics which match the given filter. +- * +- * @param filter a {@link MetricFilter} +- * @return {@code this} +- */ +- public Builder filter(MetricFilter filter) { +- this.filter = filter; +- return this; +- } +- +- public Builder inDomain(String domain) { +- this.domain = domain; +- return this; +- } +- +- /** +- * Use specific {@link TimeUnit}s for the duration of the metrics with these names. +- * +- * @param specificDurationUnits a map of metric names and specific {@link TimeUnit}s +- * @return {@code this} +- */ +- public Builder specificDurationUnits(Map specificDurationUnits) { +- this.specificDurationUnits = Collections.unmodifiableMap(specificDurationUnits); +- return this; +- } +- +- +- /** +- * Use specific {@link TimeUnit}s for the rate of the metrics with these names. +- * +- * @param specificRateUnits a map of metric names and specific {@link TimeUnit}s +- * @return {@code this} +- */ +- public Builder specificRateUnits(Map specificRateUnits) { +- this.specificRateUnits = Collections.unmodifiableMap(specificRateUnits); +- return this; +- } ++ public Builder convertRatesTo(TimeUnit rateUnit) { ++ this.rateUnit = rateUnit; ++ return this; ++ } + +- /** +- * Builds a {@link JmxReporter} with the given properties. +- * +- * @return a {@link JmxReporter} +- */ +- public JmxReporter build() { +- final MetricTimeUnits timeUnits = new MetricTimeUnits(rateUnit, durationUnit, specificRateUnits, specificDurationUnits); +- if (mBeanServer == null) { +- mBeanServer = ManagementFactory.getPlatformMBeanServer(); +- } +- return new JmxReporter(mBeanServer, domain, registry, filter, timeUnits, objectNameFactory); +- } ++ public Builder createsObjectNamesWith(ObjectNameFactory onFactory) { ++ checkArgument(onFactory != null, "null objectNameFactory"); ++ this.objectNameFactory = onFactory; ++ return this; + } + +- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); ++ /** ++ * Convert durations to the given time unit. ++ * ++ * @param durationUnit a unit of time ++ * @return {@code this} ++ */ ++ public Builder convertDurationsTo(TimeUnit durationUnit) { ++ this.durationUnit = durationUnit; ++ return this; ++ } + +- @SuppressWarnings("UnusedDeclaration") +- public interface MetricMBean { +- ObjectName objectName(); ++ /** ++ * Only report metrics which match the given filter. ++ * ++ * @param filter a {@link MetricFilter} ++ * @return {@code this} ++ */ ++ public Builder filter(MetricFilter filter) { ++ this.filter = filter; ++ return this; + } + +- private abstract static class AbstractBean implements MetricMBean { +- private final ObjectName objectName; ++ public Builder inDomain(String domain) { ++ this.domain = domain; ++ return this; ++ } + +- AbstractBean(ObjectName objectName) { +- this.objectName = objectName; +- } ++ /** ++ * Use specific {@link TimeUnit}s for the duration of the metrics with these names. ++ * ++ * @param specificDurationUnits a map of metric names and specific {@link TimeUnit}s ++ * @return {@code this} ++ */ ++ public Builder specificDurationUnits(Map specificDurationUnits) { ++ this.specificDurationUnits = unmodifiableMap(specificDurationUnits); ++ return this; ++ } + +- @Override +- public ObjectName objectName() { +- return objectName; +- } ++ /** ++ * Use specific {@link TimeUnit}s for the rate of the metrics with these names. ++ * ++ * @param specificRateUnits a map of metric names and specific {@link TimeUnit}s ++ * @return {@code this} ++ */ ++ public Builder specificRateUnits(Map specificRateUnits) { ++ this.specificRateUnits = unmodifiableMap(specificRateUnits); ++ return this; + } + +- @SuppressWarnings("UnusedDeclaration") +- public interface JmxGaugeMBean extends MetricMBean { +- Object getValue(); +- Number getNumber(); ++ /** ++ * Builds a {@link JmxReporter} with the given properties. ++ * ++ * @return a {@link JmxReporter} ++ */ ++ public JmxReporter build() { ++ final MetricTimeUnits timeUnits = ++ new MetricTimeUnits(rateUnit, durationUnit, specificRateUnits, specificDurationUnits); ++ if (mBeanServer == null) { ++ mBeanServer = ManagementFactory.getPlatformMBeanServer(); ++ } ++ return new JmxReporter(mBeanServer, domain, registry, filter, timeUnits, objectNameFactory); + } ++ } + +- private static class JmxGauge extends AbstractBean implements JmxGaugeMBean { +- private final Gauge metric; ++ private static final Logger LOG = LoggerFactory.getLogger(JmxReporter.class); + +- private JmxGauge(Gauge metric, ObjectName objectName) { +- super(objectName); +- this.metric = metric; +- } ++ @SuppressWarnings("UnusedDeclaration") ++ public interface MetricMBean { ++ ObjectName objectName(); ++ } + +- @Override +- public Object getValue() { +- return metric.getValue(); +- } ++ private abstract static class AbstractBean implements MetricMBean { ++ private final ObjectName objectName; + +- @Override +- public Number getNumber() { +- Object value = metric.getValue(); +- return value instanceof Number ? (Number) value : 0; +- } ++ AbstractBean(ObjectName objectName) { ++ this.objectName = objectName; + } + +- @SuppressWarnings("UnusedDeclaration") +- public interface JmxCounterMBean extends MetricMBean { +- long getCount(); ++ @Override ++ public ObjectName objectName() { ++ return objectName; + } ++ } + +- private static class JmxCounter extends AbstractBean implements JmxCounterMBean { +- private final Counter metric; ++ @SuppressWarnings("UnusedDeclaration") ++ public interface JmxGaugeMBean extends MetricMBean { ++ Object getValue(); + +- private JmxCounter(Counter metric, ObjectName objectName) { +- super(objectName); +- this.metric = metric; +- } ++ Number getNumber(); ++ } + +- @Override +- public long getCount() { +- return metric.getCount(); +- } +- } +- +- @SuppressWarnings("UnusedDeclaration") +- public interface JmxHistogramMBean extends MetricMBean { +- long getCount(); ++ private static class JmxGauge extends AbstractBean implements JmxGaugeMBean { ++ private final Gauge metric; + +- long getSum(); ++ private JmxGauge(Gauge metric, ObjectName objectName) { ++ super(objectName); ++ this.metric = metric; ++ } + +- long getMin(); ++ @Override ++ public Object getValue() { ++ return metric.getValue(); ++ } + +- long getMax(); ++ @Override ++ public Number getNumber() { ++ Object value = metric.getValue(); ++ return value instanceof Number ? (Number) value : 0; ++ } ++ } + +- double getMean(); ++ @SuppressWarnings("UnusedDeclaration") ++ public interface JmxCounterMBean extends MetricMBean { ++ long getCount(); ++ } + +- double getStdDev(); ++ private static class JmxCounter extends AbstractBean implements JmxCounterMBean { ++ private final Counter metric; + +- double get50thPercentile(); ++ private JmxCounter(Counter metric, ObjectName objectName) { ++ super(objectName); ++ this.metric = metric; ++ } + +- double get75thPercentile(); ++ @Override ++ public long getCount() { ++ return metric.getCount(); ++ } ++ } + +- double get95thPercentile(); ++ @SuppressWarnings("UnusedDeclaration") ++ public interface JmxHistogramMBean extends MetricMBean { ++ long getCount(); + +- double get98thPercentile(); ++ long getSum(); + +- double get99thPercentile(); ++ long getMin(); + +- double get999thPercentile(); ++ long getMax(); + +- long[] values(); ++ double getMean(); + +- long getSnapshotSize(); +- } ++ double getStdDev(); + +- private static class JmxHistogram implements JmxHistogramMBean { +- private final ObjectName objectName; +- private final Histogram metric; ++ double get50thPercentile(); + +- private JmxHistogram(Histogram metric, ObjectName objectName) { +- this.metric = metric; +- this.objectName = objectName; +- } ++ double get75thPercentile(); + +- @Override +- public ObjectName objectName() { +- return objectName; +- } ++ double get95thPercentile(); + +- @Override +- public double get50thPercentile() { +- return metric.getSnapshot().getMedian(); +- } ++ double get98thPercentile(); + +- @Override +- public long getCount() { +- return metric.getCount(); +- } ++ double get99thPercentile(); + +- @Override +- public long getSum() { +- return metric.getSum(); +- } ++ double get999thPercentile(); + +- @Override +- public long getMin() { +- return metric.getSnapshot().getMin(); +- } ++ long[] values(); + +- @Override +- public long getMax() { +- return metric.getSnapshot().getMax(); +- } ++ long getSnapshotSize(); ++ } + +- @Override +- public double getMean() { +- return metric.getSnapshot().getMean(); +- } ++ private static class JmxHistogram implements JmxHistogramMBean { ++ private final ObjectName objectName; ++ private final Histogram metric; + +- @Override +- public double getStdDev() { +- return metric.getSnapshot().getStdDev(); +- } ++ private JmxHistogram(Histogram metric, ObjectName objectName) { ++ this.metric = metric; ++ this.objectName = objectName; ++ } + +- @Override +- public double get75thPercentile() { +- return metric.getSnapshot().get75thPercentile(); +- } ++ @Override ++ public ObjectName objectName() { ++ return objectName; ++ } + +- @Override +- public double get95thPercentile() { +- return metric.getSnapshot().get95thPercentile(); +- } ++ @Override ++ public double get50thPercentile() { ++ return metric.getSnapshot().getMedian(); ++ } + +- @Override +- public double get98thPercentile() { +- return metric.getSnapshot().get98thPercentile(); +- } ++ @Override ++ public long getCount() { ++ return metric.getCount(); ++ } + +- @Override +- public double get99thPercentile() { +- return metric.getSnapshot().get99thPercentile(); +- } ++ @Override ++ public long getSum() { ++ return metric.getSum(); ++ } + +- @Override +- public double get999thPercentile() { +- return metric.getSnapshot().get999thPercentile(); +- } ++ @Override ++ public long getMin() { ++ return metric.getSnapshot().getMin(); ++ } + +- @Override +- public long[] values() { +- return metric.getSnapshot().getValues(); +- } ++ @Override ++ public long getMax() { ++ return metric.getSnapshot().getMax(); ++ } + +- @Override +- public long getSnapshotSize() { +- return metric.getSnapshot().size(); +- } ++ @Override ++ public double getMean() { ++ return metric.getSnapshot().getMean(); + } + +- @SuppressWarnings("UnusedDeclaration") +- public interface JmxMeterMBean extends MetricMBean { +- long getCount(); ++ @Override ++ public double getStdDev() { ++ return metric.getSnapshot().getStdDev(); ++ } + +- double getSum(); ++ @Override ++ public double get75thPercentile() { ++ return metric.getSnapshot().get75thPercentile(); ++ } + +- double getMeanRate(); ++ @Override ++ public double get95thPercentile() { ++ return metric.getSnapshot().get95thPercentile(); ++ } + +- double getOneMinuteRate(); ++ @Override ++ public double get98thPercentile() { ++ return metric.getSnapshot().get98thPercentile(); ++ } + +- double getFiveMinuteRate(); ++ @Override ++ public double get99thPercentile() { ++ return metric.getSnapshot().get99thPercentile(); ++ } + +- double getFifteenMinuteRate(); ++ @Override ++ public double get999thPercentile() { ++ return metric.getSnapshot().get999thPercentile(); ++ } + +- String getRateUnit(); ++ @Override ++ public long[] values() { ++ return metric.getSnapshot().getValues(); + } + +- private static class JmxMeter extends AbstractBean implements JmxMeterMBean { +- private final Metered metric; +- private final double rateFactor; +- private final String rateUnit; ++ @Override ++ public long getSnapshotSize() { ++ return metric.getSnapshot().size(); ++ } ++ } + +- private JmxMeter(Metered metric, ObjectName objectName, TimeUnit rateUnit) { +- super(objectName); +- this.metric = metric; +- this.rateFactor = rateUnit.toSeconds(1); +- this.rateUnit = ("events/" + calculateRateUnit(rateUnit)).intern(); +- } ++ @SuppressWarnings("UnusedDeclaration") ++ public interface JmxMeterMBean extends MetricMBean { ++ long getCount(); + +- @Override +- public long getCount() { +- return metric.getCount(); +- } ++ double getSum(); + +- @Override +- public double getSum() { +- return metric.getSum(); +- } ++ double getMeanRate(); + +- @Override +- public double getMeanRate() { +- return metric.getMeanRate() * rateFactor; +- } ++ double getOneMinuteRate(); + +- @Override +- public double getOneMinuteRate() { +- return metric.getOneMinuteRate() * rateFactor; +- } ++ double getFiveMinuteRate(); + +- @Override +- public double getFiveMinuteRate() { +- return metric.getFiveMinuteRate() * rateFactor; +- } ++ double getFifteenMinuteRate(); + +- @Override +- public double getFifteenMinuteRate() { +- return metric.getFifteenMinuteRate() * rateFactor; +- } ++ String getRateUnit(); ++ } + +- @Override +- public String getRateUnit() { +- return rateUnit; +- } ++ private static class JmxMeter extends AbstractBean implements JmxMeterMBean { ++ private final Metered metric; ++ private final double rateFactor; ++ private final String rateUnit; + +- private String calculateRateUnit(TimeUnit unit) { +- final String s = unit.toString().toLowerCase(Locale.US); +- return s.substring(0, s.length() - 1); +- } ++ private JmxMeter(Metered metric, ObjectName objectName, TimeUnit rateUnit) { ++ super(objectName); ++ this.metric = metric; ++ this.rateFactor = rateUnit.toSeconds(1); ++ this.rateUnit = ("events/" + calculateRateUnit(rateUnit)).intern(); + } + +- @SuppressWarnings("UnusedDeclaration") +- public interface JmxTimerMBean extends JmxMeterMBean { +- double getMin(); ++ @Override ++ public long getCount() { ++ return metric.getCount(); ++ } + +- double getMax(); ++ @Override ++ public double getSum() { ++ return metric.getSum(); ++ } + +- double getMean(); ++ @Override ++ public double getMeanRate() { ++ return metric.getMeanRate() * rateFactor; ++ } + +- double getStdDev(); ++ @Override ++ public double getOneMinuteRate() { ++ return metric.getOneMinuteRate() * rateFactor; ++ } + +- double get50thPercentile(); ++ @Override ++ public double getFiveMinuteRate() { ++ return metric.getFiveMinuteRate() * rateFactor; ++ } + +- double get75thPercentile(); ++ @Override ++ public double getFifteenMinuteRate() { ++ return metric.getFifteenMinuteRate() * rateFactor; ++ } + +- double get95thPercentile(); ++ @Override ++ public String getRateUnit() { ++ return rateUnit; ++ } + +- double get98thPercentile(); ++ private String calculateRateUnit(TimeUnit unit) { ++ final String s = unit.toString().toLowerCase(Locale.US); ++ return s.substring(0, s.length() - 1); ++ } ++ } + +- double get99thPercentile(); ++ @SuppressWarnings("UnusedDeclaration") ++ public interface JmxTimerMBean extends JmxMeterMBean { ++ double getMin(); + +- double get999thPercentile(); ++ double getMax(); + +- long[] values(); ++ double getMean(); + +- String getDurationUnit(); +- } ++ double getStdDev(); + +- static class JmxTimer extends JmxMeter implements JmxTimerMBean { +- private final Timer metric; +- private final double durationFactor; +- private final String durationUnit; ++ double get50thPercentile(); + +- private JmxTimer(Timer metric, +- ObjectName objectName, +- TimeUnit rateUnit, +- TimeUnit durationUnit) { +- super(metric, objectName, rateUnit); +- this.metric = metric; +- this.durationFactor = 1.0 / durationUnit.toNanos(1); +- this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); +- } ++ double get75thPercentile(); + +- @Override +- public double get50thPercentile() { +- return metric.getSnapshot().getMedian() * durationFactor; +- } ++ double get95thPercentile(); + +- @Override +- public double getMin() { +- return metric.getSnapshot().getMin() * durationFactor; +- } ++ double get98thPercentile(); + +- @Override +- public double getMax() { +- return metric.getSnapshot().getMax() * durationFactor; +- } ++ double get99thPercentile(); + +- @Override +- public double getMean() { +- return metric.getSnapshot().getMean() * durationFactor; +- } ++ double get999thPercentile(); + +- @Override +- public double getStdDev() { +- return metric.getSnapshot().getStdDev() * durationFactor; +- } ++ long[] values(); + +- @Override +- public double get75thPercentile() { +- return metric.getSnapshot().get75thPercentile() * durationFactor; +- } ++ String getDurationUnit(); ++ } + +- @Override +- public double get95thPercentile() { +- return metric.getSnapshot().get95thPercentile() * durationFactor; +- } ++ static class JmxTimer extends JmxMeter implements JmxTimerMBean { ++ private final Timer metric; ++ private final double durationFactor; ++ private final String durationUnit; + +- @Override +- public double get98thPercentile() { +- return metric.getSnapshot().get98thPercentile() * durationFactor; +- } ++ private JmxTimer( ++ Timer metric, ObjectName objectName, TimeUnit rateUnit, TimeUnit durationUnit) { ++ super(metric, objectName, rateUnit); ++ this.metric = metric; ++ this.durationFactor = 1.0 / durationUnit.toNanos(1); ++ this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); ++ } + +- @Override +- public double get99thPercentile() { +- return metric.getSnapshot().get99thPercentile() * durationFactor; +- } ++ @Override ++ public double get50thPercentile() { ++ return metric.getSnapshot().getMedian() * durationFactor; ++ } + +- @Override +- public double get999thPercentile() { +- return metric.getSnapshot().get999thPercentile() * durationFactor; +- } +- +- @Override +- public double getSum() { +- return super.getSum() * durationFactor; +- } ++ @Override ++ public double getMin() { ++ return metric.getSnapshot().getMin() * durationFactor; ++ } + +- @Override +- public long[] values() { +- return metric.getSnapshot().getValues(); +- } ++ @Override ++ public double getMax() { ++ return metric.getSnapshot().getMax() * durationFactor; ++ } + +- @Override +- public String getDurationUnit() { +- return durationUnit; +- } ++ @Override ++ public double getMean() { ++ return metric.getSnapshot().getMean() * durationFactor; + } + +- private static class JmxListener implements MetricRegistryListener { +- private final String name; +- private final MBeanServer mBeanServer; +- private final MetricFilter filter; +- private final MetricTimeUnits timeUnits; +- private final Map registered; +- private final ObjectNameFactory objectNameFactory; +- +- private JmxListener(MBeanServer mBeanServer, String name, MetricFilter filter, MetricTimeUnits timeUnits, ObjectNameFactory objectNameFactory) { +- this.mBeanServer = mBeanServer; +- this.name = name; +- this.filter = filter; +- this.timeUnits = timeUnits; +- this.registered = new ConcurrentHashMap<>(); +- this.objectNameFactory = objectNameFactory; +- } ++ @Override ++ public double getStdDev() { ++ return metric.getSnapshot().getStdDev() * durationFactor; ++ } + +- private void registerMBean(Object mBean, ObjectName objectName) throws InstanceAlreadyExistsException, JMException { +- ObjectInstance objectInstance = mBeanServer.registerMBean(mBean, objectName); +- if (objectInstance != null) { +- // the websphere mbeanserver rewrites the objectname to include +- // cell, node & server info +- // make sure we capture the new objectName for unregistration +- registered.put(objectName, objectInstance.getObjectName()); +- } else { +- registered.put(objectName, objectName); +- } +- } ++ @Override ++ public double get75thPercentile() { ++ return metric.getSnapshot().get75thPercentile() * durationFactor; ++ } + +- private void unregisterMBean(ObjectName originalObjectName) throws InstanceNotFoundException, MBeanRegistrationException { +- ObjectName storedObjectName = registered.remove(originalObjectName); +- if (storedObjectName != null) { +- mBeanServer.unregisterMBean(storedObjectName); +- } else { +- mBeanServer.unregisterMBean(originalObjectName); +- } +- } ++ @Override ++ public double get95thPercentile() { ++ return metric.getSnapshot().get95thPercentile() * durationFactor; ++ } + +- @Override +- public void onGaugeAdded(MetricName name, Gauge gauge) { +- try { +- if (filter.matches(name, gauge)) { +- final ObjectName objectName = createName("gauges", name); +- registerMBean(new JmxGauge(gauge, objectName), objectName); +- } +- } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register gauge", e); +- } catch (JMException e) { +- LOGGER.warn("Unable to register gauge", e); +- } +- } ++ @Override ++ public double get98thPercentile() { ++ return metric.getSnapshot().get98thPercentile() * durationFactor; ++ } + +- @Override +- public void onGaugeRemoved(MetricName name) { +- try { +- final ObjectName objectName = createName("gauges", name); +- unregisterMBean(objectName); +- } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister gauge", e); +- } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister gauge", e); +- } +- } ++ @Override ++ public double get99thPercentile() { ++ return metric.getSnapshot().get99thPercentile() * durationFactor; ++ } + +- @Override +- public void onCounterAdded(MetricName name, Counter counter) { +- try { +- if (filter.matches(name, counter)) { +- final ObjectName objectName = createName("counters", name); +- registerMBean(new JmxCounter(counter, objectName), objectName); +- } +- } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register counter", e); +- } catch (JMException e) { +- LOGGER.warn("Unable to register counter", e); +- } +- } ++ @Override ++ public double get999thPercentile() { ++ return metric.getSnapshot().get999thPercentile() * durationFactor; ++ } + +- @Override +- public void onCounterRemoved(MetricName name) { +- try { +- final ObjectName objectName = createName("counters", name); +- unregisterMBean(objectName); +- } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister counter", e); +- } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister counter", e); +- } +- } ++ @Override ++ public double getSum() { ++ return super.getSum() * durationFactor; ++ } + +- @Override +- public void onHistogramAdded(MetricName name, Histogram histogram) { +- try { +- if (filter.matches(name, histogram)) { +- final ObjectName objectName = createName("histograms", name); +- registerMBean(new JmxHistogram(histogram, objectName), objectName); +- } +- } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register histogram", e); +- } catch (JMException e) { +- LOGGER.warn("Unable to register histogram", e); +- } +- } ++ @Override ++ public long[] values() { ++ return metric.getSnapshot().getValues(); ++ } + +- @Override +- public void onHistogramRemoved(MetricName name) { +- try { +- final ObjectName objectName = createName("histograms", name); +- unregisterMBean(objectName); +- } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister histogram", e); +- } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister histogram", e); +- } +- } ++ @Override ++ public String getDurationUnit() { ++ return durationUnit; ++ } ++ } ++ ++ private static class JmxListener implements MetricRegistryListener { ++ private final String name; ++ private final MBeanServer mBeanServer; ++ private final MetricFilter filter; ++ private final MetricTimeUnits timeUnits; ++ private final Map registered; ++ private final ObjectNameFactory objectNameFactory; ++ ++ private JmxListener( ++ MBeanServer mBeanServer, ++ String name, ++ MetricFilter filter, ++ MetricTimeUnits timeUnits, ++ ObjectNameFactory objectNameFactory) { ++ this.mBeanServer = mBeanServer; ++ this.name = name; ++ this.filter = filter; ++ this.timeUnits = timeUnits; ++ this.registered = new ConcurrentHashMap<>(); ++ this.objectNameFactory = objectNameFactory; ++ } + +- @Override +- public void onMeterAdded(MetricName name, Meter meter) { +- try { +- if (filter.matches(name, meter)) { +- final ObjectName objectName = createName("meters", name); +- registerMBean(new JmxMeter(meter, objectName, timeUnits.rateFor(name.getKey())), objectName); +- } +- } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register meter", e); +- } catch (JMException e) { +- LOGGER.warn("Unable to register meter", e); +- } +- } ++ private void registerMBean(Object mBean, ObjectName objectName) ++ throws InstanceAlreadyExistsException, JMException { ++ ObjectInstance objectInstance = mBeanServer.registerMBean(mBean, objectName); ++ if (objectInstance != null) { ++ // the websphere mbeanserver rewrites the objectname to include ++ // cell, node & server info ++ // make sure we capture the new objectName for unregistration ++ registered.put(objectName, objectInstance.getObjectName()); ++ } else { ++ registered.put(objectName, objectName); ++ } ++ } + +- @Override +- public void onMeterRemoved(MetricName name) { +- try { +- final ObjectName objectName = createName("meters", name); +- unregisterMBean(objectName); +- } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister meter", e); +- } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister meter", e); +- } +- } ++ private void unregisterMBean(ObjectName originalObjectName) ++ throws InstanceNotFoundException, MBeanRegistrationException { ++ ObjectName storedObjectName = registered.remove(originalObjectName); ++ if (storedObjectName != null) { ++ mBeanServer.unregisterMBean(storedObjectName); ++ } else { ++ mBeanServer.unregisterMBean(originalObjectName); ++ } ++ } + +- @Override +- public void onTimerAdded(MetricName name, Timer timer) { +- try { +- if (filter.matches(name, timer)) { +- final ObjectName objectName = createName("timers", name); +- registerMBean(new JmxTimer(timer, objectName, timeUnits.rateFor(name.getKey()), timeUnits.durationFor(name.getKey())), objectName); +- } +- } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register timer", e); +- } catch (JMException e) { +- LOGGER.warn("Unable to register timer", e); +- } +- } ++ @Override ++ public void onGaugeAdded(MetricName name, Gauge gauge) { ++ try { ++ if (filter.matches(name, gauge)) { ++ final ObjectName objectName = createName("gauges", name); ++ registerMBean(new JmxGauge(gauge, objectName), objectName); ++ } ++ } catch (InstanceAlreadyExistsException e) { ++ LOG.debug("Unable to register gauge", e); ++ } catch (JMException e) { ++ LOG.warn("Unable to register gauge", e); ++ } ++ } + +- @Override +- public void onTimerRemoved(MetricName name) { +- try { +- final ObjectName objectName = createName("timers", name); +- unregisterMBean(objectName); +- } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister timer", e); +- } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister timer", e); +- } +- } ++ @Override ++ public void onGaugeRemoved(MetricName name) { ++ try { ++ final ObjectName objectName = createName("gauges", name); ++ unregisterMBean(objectName); ++ } catch (InstanceNotFoundException e) { ++ LOG.debug("Unable to unregister gauge", e); ++ } catch (MBeanRegistrationException e) { ++ LOG.warn("Unable to unregister gauge", e); ++ } ++ } + +- private ObjectName createName(String type, MetricName name) { +- return objectNameFactory.createName(type, this.name, name); +- } ++ @Override ++ public void onCounterAdded(MetricName name, Counter counter) { ++ try { ++ if (filter.matches(name, counter)) { ++ final ObjectName objectName = createName("counters", name); ++ registerMBean(new JmxCounter(counter, objectName), objectName); ++ } ++ } catch (InstanceAlreadyExistsException e) { ++ LOG.debug("Unable to register counter", e); ++ } catch (JMException e) { ++ LOG.warn("Unable to register counter", e); ++ } ++ } + +- void unregisterAll() { +- for (ObjectName name : registered.keySet()) { +- try { +- unregisterMBean(name); +- } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister metric", e); +- } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister metric", e); +- } +- } +- registered.clear(); +- } ++ @Override ++ public void onCounterRemoved(MetricName name) { ++ try { ++ final ObjectName objectName = createName("counters", name); ++ unregisterMBean(objectName); ++ } catch (InstanceNotFoundException e) { ++ LOG.debug("Unable to unregister counter", e); ++ } catch (MBeanRegistrationException e) { ++ LOG.warn("Unable to unregister counter", e); ++ } + } + +- private static class MetricTimeUnits { +- private final TimeUnit defaultRate; +- private final TimeUnit defaultDuration; +- private final Map rateOverrides; +- private final Map durationOverrides; +- +- MetricTimeUnits(TimeUnit defaultRate, +- TimeUnit defaultDuration, +- Map rateOverrides, +- Map durationOverrides) { +- this.defaultRate = defaultRate; +- this.defaultDuration = defaultDuration; +- this.rateOverrides = rateOverrides; +- this.durationOverrides = durationOverrides; +- } ++ @Override ++ public void onHistogramAdded(MetricName name, Histogram histogram) { ++ try { ++ if (filter.matches(name, histogram)) { ++ final ObjectName objectName = createName("histograms", name); ++ registerMBean(new JmxHistogram(histogram, objectName), objectName); ++ } ++ } catch (InstanceAlreadyExistsException e) { ++ LOG.debug("Unable to register histogram", e); ++ } catch (JMException e) { ++ LOG.warn("Unable to register histogram", e); ++ } ++ } + +- public TimeUnit durationFor(String name) { +- return durationOverrides.getOrDefault(name, defaultDuration); +- } ++ @Override ++ public void onHistogramRemoved(MetricName name) { ++ try { ++ final ObjectName objectName = createName("histograms", name); ++ unregisterMBean(objectName); ++ } catch (InstanceNotFoundException e) { ++ LOG.debug("Unable to unregister histogram", e); ++ } catch (MBeanRegistrationException e) { ++ LOG.warn("Unable to unregister histogram", e); ++ } ++ } + +- public TimeUnit rateFor(String name) { +- return rateOverrides.getOrDefault(name, defaultRate); +- } ++ @Override ++ public void onMeterAdded(MetricName name, Meter meter) { ++ try { ++ if (filter.matches(name, meter)) { ++ final ObjectName objectName = createName("meters", name); ++ registerMBean( ++ new JmxMeter(meter, objectName, timeUnits.rateFor(name.getKey())), objectName); ++ } ++ } catch (InstanceAlreadyExistsException e) { ++ LOG.debug("Unable to register meter", e); ++ } catch (JMException e) { ++ LOG.warn("Unable to register meter", e); ++ } + } + +- private final MetricRegistry registry; +- private final JmxListener listener; ++ @Override ++ public void onMeterRemoved(MetricName name) { ++ try { ++ final ObjectName objectName = createName("meters", name); ++ unregisterMBean(objectName); ++ } catch (InstanceNotFoundException e) { ++ LOG.debug("Unable to unregister meter", e); ++ } catch (MBeanRegistrationException e) { ++ LOG.warn("Unable to unregister meter", e); ++ } ++ } + +- private JmxReporter(MBeanServer mBeanServer, +- String domain, +- MetricRegistry registry, +- MetricFilter filter, +- MetricTimeUnits timeUnits, +- ObjectNameFactory objectNameFactory) { +- this.registry = registry; +- this.listener = new JmxListener(mBeanServer, domain, filter, timeUnits, objectNameFactory); ++ @Override ++ public void onTimerAdded(MetricName name, Timer timer) { ++ try { ++ if (filter.matches(name, timer)) { ++ final ObjectName objectName = createName("timers", name); ++ registerMBean( ++ new JmxTimer( ++ timer, ++ objectName, ++ timeUnits.rateFor(name.getKey()), ++ timeUnits.durationFor(name.getKey())), ++ objectName); ++ } ++ } catch (InstanceAlreadyExistsException e) { ++ LOG.debug("Unable to register timer", e); ++ } catch (JMException e) { ++ LOG.warn("Unable to register timer", e); ++ } + } + +- /** +- * Starts the reporter. +- */ +- public void start() { +- registry.addListener(listener); ++ @Override ++ public void onTimerRemoved(MetricName name) { ++ try { ++ final ObjectName objectName = createName("timers", name); ++ unregisterMBean(objectName); ++ } catch (InstanceNotFoundException e) { ++ LOG.debug("Unable to unregister timer", e); ++ } catch (MBeanRegistrationException e) { ++ LOG.warn("Unable to unregister timer", e); ++ } + } + +- /** +- * Stops the reporter. +- */ +- public void stop() { +- registry.removeListener(listener); +- listener.unregisterAll(); ++ private ObjectName createName(String type, MetricName name) { ++ return objectNameFactory.createName(type, this.name, name); + } + +- /** +- * Stops the reporter. +- */ +- @Override +- public void close() { +- stop(); ++ void unregisterAll() { ++ for (ObjectName name : registered.keySet()) { ++ try { ++ unregisterMBean(name); ++ } catch (InstanceNotFoundException e) { ++ LOG.debug("Unable to unregister metric", e); ++ } catch (MBeanRegistrationException e) { ++ LOG.warn("Unable to unregister metric", e); ++ } ++ } ++ registered.clear(); ++ } ++ } ++ ++ private static class MetricTimeUnits { ++ private final TimeUnit defaultRate; ++ private final TimeUnit defaultDuration; ++ private final Map rateOverrides; ++ private final Map durationOverrides; ++ ++ MetricTimeUnits( ++ TimeUnit defaultRate, ++ TimeUnit defaultDuration, ++ Map rateOverrides, ++ Map durationOverrides) { ++ this.defaultRate = defaultRate; ++ this.defaultDuration = defaultDuration; ++ this.rateOverrides = rateOverrides; ++ this.durationOverrides = durationOverrides; + } + +- /** +- * Visible for testing +- */ +- ObjectNameFactory getObjectNameFactory() { +- return listener.objectNameFactory; ++ public TimeUnit durationFor(String name) { ++ return durationOverrides.getOrDefault(name, defaultDuration); + } + ++ public TimeUnit rateFor(String name) { ++ return rateOverrides.getOrDefault(name, defaultRate); ++ } ++ } ++ ++ private final MetricRegistry registry; ++ private final JmxListener listener; ++ ++ private JmxReporter( ++ MBeanServer mBeanServer, ++ String domain, ++ MetricRegistry registry, ++ MetricFilter filter, ++ MetricTimeUnits timeUnits, ++ ObjectNameFactory objectNameFactory) { ++ this.registry = registry; ++ this.listener = new JmxListener(mBeanServer, domain, filter, timeUnits, objectNameFactory); ++ } ++ ++ /** Starts the reporter. */ ++ public void start() { ++ registry.addListener(listener); ++ } ++ ++ /** Stops the reporter. */ ++ public void stop() { ++ registry.removeListener(listener); ++ listener.unregisterAll(); ++ } ++ ++ /** Stops the reporter. */ ++ @Override ++ public void close() { ++ stop(); ++ } ++ ++ /** Visible for testing */ ++ ObjectNameFactory getObjectNameFactory() { ++ return listener.objectNameFactory; ++ } + } +--- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/ObjectNameFactory.java ++++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/ObjectNameFactory.java +@@ -1,10 +1,9 @@ + package io.dropwizard.metrics5.jmx; + + import io.dropwizard.metrics5.MetricName; +- + import javax.management.ObjectName; + + public interface ObjectNameFactory { + +- ObjectName createName(String type, String domain, MetricName name); ++ ObjectName createName(String type, String domain, MetricName name); + } +--- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java ++++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java +@@ -1,41 +1,51 @@ + package io.dropwizard.metrics5.jmx; + +-import io.dropwizard.metrics5.MetricName; +-import org.junit.jupiter.api.Test; +- +-import javax.management.ObjectName; +- +-import static org.assertj.core.api.Assertions.assertThatCode; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatCode; + +-class DefaultObjectNameFactoryTest { +- +- @Test +- void createsObjectNameWithDomainInInput() { +- DefaultObjectNameFactory f = new DefaultObjectNameFactory(); +- ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); +- assertThat(on.getDomain()).isEqualTo("com.domain"); +- assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); +- assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); +- } +- +- @Test +- void createsObjectNameWithNameAsKeyPropertyName() { +- DefaultObjectNameFactory f = new DefaultObjectNameFactory(); +- ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); +- assertThat(on.getKeyProperty("name")).isEqualTo("something.with.dots"); +- assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); +- assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); +- +- } ++import io.dropwizard.metrics5.MetricName; ++import javax.management.ObjectName; ++import org.junit.jupiter.api.Test; + +- @Test +- void createsObjectNameWithNameWithDisallowedUnquotedCharacters() { +- DefaultObjectNameFactory f = new DefaultObjectNameFactory(); +- ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.quotes(\"ABcd\")").tagged("foo", "bar", "baz", "biz")); +- assertThatCode(() -> new ObjectName(on.toString())).doesNotThrowAnyException(); +- assertThat(on.getKeyProperty("name")).isEqualTo("\"something.with.quotes(\\\"ABcd\\\")\""); +- assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); +- assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); +- } ++final class DefaultObjectNameFactoryTest { ++ ++ @Test ++ void createsObjectNameWithDomainInInput() { ++ DefaultObjectNameFactory f = new DefaultObjectNameFactory(); ++ ObjectName on = ++ f.createName( ++ "type", ++ "com.domain", ++ MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); ++ assertThat(on.getDomain()).isEqualTo("com.domain"); ++ assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); ++ assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); ++ } ++ ++ @Test ++ void createsObjectNameWithNameAsKeyPropertyName() { ++ DefaultObjectNameFactory f = new DefaultObjectNameFactory(); ++ ObjectName on = ++ f.createName( ++ "type", ++ "com.domain", ++ MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); ++ assertThat(on.getKeyProperty("name")).isEqualTo("something.with.dots"); ++ assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); ++ assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); ++ } ++ ++ @Test ++ void createsObjectNameWithNameWithDisallowedUnquotedCharacters() { ++ DefaultObjectNameFactory f = new DefaultObjectNameFactory(); ++ ObjectName on = ++ f.createName( ++ "type", ++ "com.domain", ++ MetricName.build("something.with.quotes(\"ABcd\")").tagged("foo", "bar", "baz", "biz")); ++ assertThatCode(() -> new ObjectName(on.toString())).doesNotThrowAnyException(); ++ assertThat(on.getKeyProperty("name")).isEqualTo("\"something.with.quotes(\\\"ABcd\\\")\""); ++ assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); ++ assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); ++ } + } +--- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java ++++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java +@@ -1,5 +1,15 @@ + package io.dropwizard.metrics5.jmx; + ++import static java.util.UUID.randomUUID; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.entry; ++import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; ++import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.ArgumentMatchers.eq; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Histogram; +@@ -9,10 +19,10 @@ import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- ++import java.lang.management.ManagementFactory; ++import java.util.SortedMap; ++import java.util.TreeMap; ++import java.util.concurrent.TimeUnit; + import javax.management.Attribute; + import javax.management.AttributeList; + import javax.management.InstanceNotFoundException; +@@ -20,301 +30,304 @@ import javax.management.JMException; + import javax.management.MBeanServer; + import javax.management.ObjectInstance; + import javax.management.ObjectName; +-import java.lang.management.ManagementFactory; +-import java.util.SortedMap; +-import java.util.TreeMap; +-import java.util.UUID; +-import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.entry; +-import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +-import static org.mockito.ArgumentMatchers.any; +-import static org.mockito.ArgumentMatchers.eq; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("rawtypes") +-class JmxReporterTest { +- private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); +- private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); +- private final MetricRegistry registry = new MetricRegistry(); +- +- private final JmxReporter reporter = JmxReporter.forRegistry(registry) +- .registerWith(mBeanServer) +- .inDomain(name) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .convertRatesTo(TimeUnit.SECONDS) +- .filter(MetricFilter.ALL) +- .build(); +- +- private final Gauge gauge = mock(Gauge.class); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); +- private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); +- private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); +- +- @BeforeEach +- void setUp() throws Exception { +- when(gauge.getValue()).thenReturn(1); +- +- when(counter.getCount()).thenReturn(100L); +- +- when(histogram.getCount()).thenReturn(1L); +- when(histogram.getSum()).thenReturn(12L); +- +- final Snapshot hSnapshot = mock(Snapshot.class); +- when(hSnapshot.getMax()).thenReturn(2L); +- when(hSnapshot.getMean()).thenReturn(3.0); +- when(hSnapshot.getMin()).thenReturn(4L); +- when(hSnapshot.getStdDev()).thenReturn(5.0); +- when(hSnapshot.getMedian()).thenReturn(6.0); +- when(hSnapshot.get75thPercentile()).thenReturn(7.0); +- when(hSnapshot.get95thPercentile()).thenReturn(8.0); +- when(hSnapshot.get98thPercentile()).thenReturn(9.0); +- when(hSnapshot.get99thPercentile()).thenReturn(10.0); +- when(hSnapshot.get999thPercentile()).thenReturn(11.0); +- when(hSnapshot.size()).thenReturn(1); +- +- when(histogram.getSnapshot()).thenReturn(hSnapshot); +- +- when(meter.getCount()).thenReturn(1L); +- when(meter.getSum()).thenReturn(6L); +- when(meter.getMeanRate()).thenReturn(2.0); +- when(meter.getOneMinuteRate()).thenReturn(3.0); +- when(meter.getFiveMinuteRate()).thenReturn(4.0); +- when(meter.getFifteenMinuteRate()).thenReturn(5.0); +- +- when(timer.getCount()).thenReturn(1L); +- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); +- when(timer.getMeanRate()).thenReturn(2.0); +- when(timer.getOneMinuteRate()).thenReturn(3.0); +- when(timer.getFiveMinuteRate()).thenReturn(4.0); +- when(timer.getFifteenMinuteRate()).thenReturn(5.0); +- +- final Snapshot tSnapshot = mock(Snapshot.class); +- when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); +- when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); +- when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +- when(tSnapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); +- when(tSnapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); +- when(tSnapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); +- when(tSnapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); +- when(tSnapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); +- when(tSnapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); +- when(tSnapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); +- when(tSnapshot.size()).thenReturn(1); +- +- when(timer.getSnapshot()).thenReturn(tSnapshot); +- +- registry.register(MetricName.build("gauge"), gauge); +- registry.register(MetricName.build("test", "counter"), counter); +- registry.register(MetricName.build("test", "histogram"), histogram); +- registry.register(MetricName.build("test", "meter"), meter); +- registry.register(MetricName.build("test", "another", "timer"), timer); +- +- reporter.start(); +- } +- +- @AfterEach +- void tearDown() { +- reporter.stop(); +- } +- +- @Test +- void registersMBeansForMetricObjectsUsingProvidedObjectNameFactory() throws Exception { +- ObjectName n = new ObjectName(name + ":name=dummy"); +- try { +- String widgetName = "something"; +- when(mockObjectNameFactory.createName(any(String.class), any(String.class), any(MetricName.class))).thenReturn(n); +- JmxReporter reporter = JmxReporter.forRegistry(registry) +- .registerWith(mBeanServer) +- .inDomain(name) +- .createsObjectNamesWith(mockObjectNameFactory) +- .build(); +- registry.registerGauge(widgetName, () -> 1); +- reporter.start(); +- verify(mockObjectNameFactory).createName(eq("gauges"), any(String.class), eq(MetricName.build("something"))); +- //verifyNoMoreInteractions(mockObjectNameFactory); +- } finally { +- reporter.stop(); +- if (mBeanServer.isRegistered(n)) { +- mBeanServer.unregisterMBean(n); +- } +- } +- } +- +- @Test +- void registersMBeansForGauges() throws Exception { +- final AttributeList attributes = getAttributes("gauges", "gauge", "Value", "Number"); +- +- assertThat(values(attributes)) +- .contains(entry("Value", 1), entry("Number", 1)); +- } +- +- @Test +- void registersMBeansForCounters() throws Exception { +- final AttributeList attributes = getAttributes("counters", "test.counter", "Count"); +- +- assertThat(values(attributes)) +- .contains(entry("Count", 100L)); +- } +- +- @Test +- void registersMBeansForHistograms() throws Exception { +- final AttributeList attributes = getAttributes("histograms", "test.histogram", +- "Count", +- "Sum", +- "Max", +- "Mean", +- "Min", +- "StdDev", +- "50thPercentile", +- "75thPercentile", +- "95thPercentile", +- "98thPercentile", +- "99thPercentile", +- "999thPercentile", +- "SnapshotSize"); +- +- assertThat(values(attributes)) +- .contains(entry("Count", 1L)) +- .contains(entry("Sum", 12L)) +- .contains(entry("Max", 2L)) +- .contains(entry("Mean", 3.0)) +- .contains(entry("Min", 4L)) +- .contains(entry("StdDev", 5.0)) +- .contains(entry("50thPercentile", 6.0)) +- .contains(entry("75thPercentile", 7.0)) +- .contains(entry("95thPercentile", 8.0)) +- .contains(entry("98thPercentile", 9.0)) +- .contains(entry("99thPercentile", 10.0)) +- .contains(entry("999thPercentile", 11.0)) +- .contains(entry("SnapshotSize", 1L)); +- } +- +- @Test +- void registersMBeansForMeters() throws Exception { +- final AttributeList attributes = getAttributes("meters", "test.meter", +- "Count", +- "Sum", +- "MeanRate", +- "OneMinuteRate", +- "FiveMinuteRate", +- "FifteenMinuteRate", +- "RateUnit"); +- +- assertThat(values(attributes)) +- .contains(entry("Count", 1L)) +- .contains(entry("Sum", 6.0)) +- .contains(entry("MeanRate", 2.0)) +- .contains(entry("OneMinuteRate", 3.0)) +- .contains(entry("FiveMinuteRate", 4.0)) +- .contains(entry("FifteenMinuteRate", 5.0)) +- .contains(entry("RateUnit", "events/second")); ++final class JmxReporterTest { ++ private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ++ private final String name = randomUUID().toString().replaceAll("[{\\-}]", ""); ++ private final MetricRegistry registry = new MetricRegistry(); ++ ++ private final JmxReporter reporter = ++ JmxReporter.forRegistry(registry) ++ .registerWith(mBeanServer) ++ .inDomain(name) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .convertRatesTo(TimeUnit.SECONDS) ++ .filter(MetricFilter.ALL) ++ .build(); ++ ++ private final Gauge gauge = mock(); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); ++ private final ObjectNameFactory mockObjectNameFactory = mock(); ++ private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ when(gauge.getValue()).thenReturn(1); ++ ++ when(counter.getCount()).thenReturn(100L); ++ ++ when(histogram.getCount()).thenReturn(1L); ++ when(histogram.getSum()).thenReturn(12L); ++ ++ final Snapshot hSnapshot = mock(); ++ when(hSnapshot.getMax()).thenReturn(2L); ++ when(hSnapshot.getMean()).thenReturn(3.0); ++ when(hSnapshot.getMin()).thenReturn(4L); ++ when(hSnapshot.getStdDev()).thenReturn(5.0); ++ when(hSnapshot.getMedian()).thenReturn(6.0); ++ when(hSnapshot.get75thPercentile()).thenReturn(7.0); ++ when(hSnapshot.get95thPercentile()).thenReturn(8.0); ++ when(hSnapshot.get98thPercentile()).thenReturn(9.0); ++ when(hSnapshot.get99thPercentile()).thenReturn(10.0); ++ when(hSnapshot.get999thPercentile()).thenReturn(11.0); ++ when(hSnapshot.size()).thenReturn(1); ++ ++ when(histogram.getSnapshot()).thenReturn(hSnapshot); ++ ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getSum()).thenReturn(6L); ++ when(meter.getMeanRate()).thenReturn(2.0); ++ when(meter.getOneMinuteRate()).thenReturn(3.0); ++ when(meter.getFiveMinuteRate()).thenReturn(4.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ when(timer.getCount()).thenReturn(1L); ++ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); ++ when(timer.getMeanRate()).thenReturn(2.0); ++ when(timer.getOneMinuteRate()).thenReturn(3.0); ++ when(timer.getFiveMinuteRate()).thenReturn(4.0); ++ when(timer.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ final Snapshot tSnapshot = mock(); ++ when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); ++ when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); ++ when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ++ when(tSnapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); ++ when(tSnapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); ++ when(tSnapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); ++ when(tSnapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); ++ when(tSnapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); ++ when(tSnapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); ++ when(tSnapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); ++ when(tSnapshot.size()).thenReturn(1); ++ ++ when(timer.getSnapshot()).thenReturn(tSnapshot); ++ ++ registry.register(MetricName.build("gauge"), gauge); ++ registry.register(MetricName.build("test", "counter"), counter); ++ registry.register(MetricName.build("test", "histogram"), histogram); ++ registry.register(MetricName.build("test", "meter"), meter); ++ registry.register(MetricName.build("test", "another", "timer"), timer); ++ ++ reporter.start(); ++ } ++ ++ @AfterEach ++ void tearDown() { ++ reporter.stop(); ++ } ++ ++ @Test ++ void registersMBeansForMetricObjectsUsingProvidedObjectNameFactory() throws Exception { ++ ObjectName n = new ObjectName(name + ":name=dummy"); ++ try { ++ String widgetName = "something"; ++ when(mockObjectNameFactory.createName( ++ any(String.class), any(String.class), any(MetricName.class))) ++ .thenReturn(n); ++ JmxReporter reporter = ++ JmxReporter.forRegistry(registry) ++ .registerWith(mBeanServer) ++ .inDomain(name) ++ .createsObjectNamesWith(mockObjectNameFactory) ++ .build(); ++ registry.registerGauge(widgetName, () -> 1); ++ reporter.start(); ++ verify(mockObjectNameFactory) ++ .createName(eq("gauges"), any(String.class), eq(MetricName.build("something"))); ++ // verifyNoMoreInteractions(mockObjectNameFactory); ++ } finally { ++ reporter.stop(); ++ if (mBeanServer.isRegistered(n)) { ++ mBeanServer.unregisterMBean(n); ++ } + } ++ } ++ ++ @Test ++ void registersMBeansForGauges() throws Exception { ++ final AttributeList attributes = getAttributes("gauges", "gauge", "Value", "Number"); ++ ++ assertThat(values(attributes)).contains(entry("Value", 1), entry("Number", 1)); ++ } ++ ++ @Test ++ void registersMBeansForCounters() throws Exception { ++ final AttributeList attributes = getAttributes("counters", "test.counter", "Count"); ++ ++ assertThat(values(attributes)).contains(entry("Count", 100L)); ++ } ++ ++ @Test ++ void registersMBeansForHistograms() throws Exception { ++ final AttributeList attributes = ++ getAttributes( ++ "histograms", ++ "test.histogram", ++ "Count", ++ "Sum", ++ "Max", ++ "Mean", ++ "Min", ++ "StdDev", ++ "50thPercentile", ++ "75thPercentile", ++ "95thPercentile", ++ "98thPercentile", ++ "99thPercentile", ++ "999thPercentile", ++ "SnapshotSize"); ++ ++ assertThat(values(attributes)) ++ .contains(entry("Count", 1L)) ++ .contains(entry("Sum", 12L)) ++ .contains(entry("Max", 2L)) ++ .contains(entry("Mean", 3.0)) ++ .contains(entry("Min", 4L)) ++ .contains(entry("StdDev", 5.0)) ++ .contains(entry("50thPercentile", 6.0)) ++ .contains(entry("75thPercentile", 7.0)) ++ .contains(entry("95thPercentile", 8.0)) ++ .contains(entry("98thPercentile", 9.0)) ++ .contains(entry("99thPercentile", 10.0)) ++ .contains(entry("999thPercentile", 11.0)) ++ .contains(entry("SnapshotSize", 1L)); ++ } ++ ++ @Test ++ void registersMBeansForMeters() throws Exception { ++ final AttributeList attributes = ++ getAttributes( ++ "meters", ++ "test.meter", ++ "Count", ++ "Sum", ++ "MeanRate", ++ "OneMinuteRate", ++ "FiveMinuteRate", ++ "FifteenMinuteRate", ++ "RateUnit"); ++ ++ assertThat(values(attributes)) ++ .contains(entry("Count", 1L)) ++ .contains(entry("Sum", 6.0)) ++ .contains(entry("MeanRate", 2.0)) ++ .contains(entry("OneMinuteRate", 3.0)) ++ .contains(entry("FiveMinuteRate", 4.0)) ++ .contains(entry("FifteenMinuteRate", 5.0)) ++ .contains(entry("RateUnit", "events/second")); ++ } ++ ++ @Test ++ void registersMBeansForTimers() throws Exception { ++ final AttributeList attributes = ++ getAttributes( ++ "timers", ++ "test.another.timer", ++ "Count", ++ "Sum", ++ "MeanRate", ++ "OneMinuteRate", ++ "FiveMinuteRate", ++ "FifteenMinuteRate", ++ "Max", ++ "Mean", ++ "Min", ++ "StdDev", ++ "50thPercentile", ++ "75thPercentile", ++ "95thPercentile", ++ "98thPercentile", ++ "99thPercentile", ++ "999thPercentile", ++ "RateUnit", ++ "DurationUnit"); ++ ++ assertThat(values(attributes)) ++ .contains(entry("Count", 1L)) ++ .contains(entry("Sum", 6.0)) ++ .contains(entry("MeanRate", 2.0)) ++ .contains(entry("OneMinuteRate", 3.0)) ++ .contains(entry("FiveMinuteRate", 4.0)) ++ .contains(entry("FifteenMinuteRate", 5.0)) ++ .contains(entry("Max", 100.0)) ++ .contains(entry("Mean", 200.0)) ++ .contains(entry("Min", 300.0)) ++ .contains(entry("StdDev", 400.0)) ++ .contains(entry("50thPercentile", 500.0)) ++ .contains(entry("75thPercentile", 600.0)) ++ .contains(entry("95thPercentile", 700.0)) ++ .contains(entry("98thPercentile", 800.0)) ++ .contains(entry("99thPercentile", 900.0)) ++ .contains(entry("999thPercentile", 1000.0)) ++ .contains(entry("RateUnit", "events/second")) ++ .contains(entry("DurationUnit", "milliseconds")); ++ } ++ ++ @Test ++ void cleansUpAfterItselfWhenStopped() throws Exception { ++ reporter.stop(); ++ ++ try { ++ getAttributes("gauges", "gauge", "Value", "Number"); ++ failBecauseExceptionWasNotThrown(InstanceNotFoundException.class); ++ } catch (InstanceNotFoundException e) { + +- @Test +- void registersMBeansForTimers() throws Exception { +- final AttributeList attributes = getAttributes("timers", "test.another.timer", +- "Count", +- "Sum", +- "MeanRate", +- "OneMinuteRate", +- "FiveMinuteRate", +- "FifteenMinuteRate", +- "Max", +- "Mean", +- "Min", +- "StdDev", +- "50thPercentile", +- "75thPercentile", +- "95thPercentile", +- "98thPercentile", +- "99thPercentile", +- "999thPercentile", +- "RateUnit", +- "DurationUnit"); +- +- assertThat(values(attributes)) +- .contains(entry("Count", 1L)) +- .contains(entry("Sum", 6.0)) +- .contains(entry("MeanRate", 2.0)) +- .contains(entry("OneMinuteRate", 3.0)) +- .contains(entry("FiveMinuteRate", 4.0)) +- .contains(entry("FifteenMinuteRate", 5.0)) +- .contains(entry("Max", 100.0)) +- .contains(entry("Mean", 200.0)) +- .contains(entry("Min", 300.0)) +- .contains(entry("StdDev", 400.0)) +- .contains(entry("50thPercentile", 500.0)) +- .contains(entry("75thPercentile", 600.0)) +- .contains(entry("95thPercentile", 700.0)) +- .contains(entry("98thPercentile", 800.0)) +- .contains(entry("99thPercentile", 900.0)) +- .contains(entry("999thPercentile", 1000.0)) +- .contains(entry("RateUnit", "events/second")) +- .contains(entry("DurationUnit", "milliseconds")); + } ++ } + +- @Test +- void cleansUpAfterItselfWhenStopped() throws Exception { +- reporter.stop(); +- +- try { +- getAttributes("gauges", "gauge", "Value", "Number"); +- failBecauseExceptionWasNotThrown(InstanceNotFoundException.class); +- } catch (InstanceNotFoundException e) { +- +- } +- } ++ @Test ++ void objectNameModifyingMBeanServer() throws Exception { ++ MBeanServer mockedMBeanServer = mock(); + +- @Test +- void objectNameModifyingMBeanServer() throws Exception { +- MBeanServer mockedMBeanServer = mock(MBeanServer.class); ++ // overwrite the objectName ++ when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))) ++ .thenReturn(new ObjectInstance("DOMAIN:key=value", "className")); + +- // overwrite the objectName +- when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))).thenReturn(new ObjectInstance("DOMAIN:key=value", "className")); +- +- MetricRegistry testRegistry = new MetricRegistry(); +- JmxReporter testJmxReporter = JmxReporter.forRegistry(testRegistry) +- .registerWith(mockedMBeanServer) +- .inDomain(name) +- .build(); ++ MetricRegistry testRegistry = new MetricRegistry(); ++ JmxReporter testJmxReporter = ++ JmxReporter.forRegistry(testRegistry) ++ .registerWith(mockedMBeanServer) ++ .inDomain(name) ++ .build(); + +- testJmxReporter.start(); ++ testJmxReporter.start(); + +- // should trigger a registerMBean +- testRegistry.timer("test"); ++ // should trigger a registerMBean ++ testRegistry.timer("test"); + +- // should trigger an unregisterMBean with the overwritten objectName = "DOMAIN:key=value" +- testJmxReporter.stop(); ++ // should trigger an unregisterMBean with the overwritten objectName = "DOMAIN:key=value" ++ testJmxReporter.stop(); + +- verify(mockedMBeanServer).unregisterMBean(new ObjectName("DOMAIN:key=value")); ++ verify(mockedMBeanServer).unregisterMBean(new ObjectName("DOMAIN:key=value")); ++ } + +- } ++ @Test ++ void jmxMetricNameWithAsterisk() { ++ MetricRegistry metricRegistry = new MetricRegistry(); ++ JmxReporter.forRegistry(metricRegistry).build().start(); ++ metricRegistry.counter("test*"); ++ } + +- @Test +- void testJmxMetricNameWithAsterisk() { +- MetricRegistry metricRegistry = new MetricRegistry(); +- JmxReporter.forRegistry(metricRegistry).build().start(); +- metricRegistry.counter("test*"); +- } +- +- private AttributeList getAttributes(String type, String name, String... attributeNames) throws JMException { +- ObjectName n = concreteObjectNameFactory.createName(type, this.name, MetricName.build(name)); +- return mBeanServer.getAttributes(n, attributeNames); +- } ++ private AttributeList getAttributes(String type, String name, String... attributeNames) ++ throws JMException { ++ ObjectName n = concreteObjectNameFactory.createName(type, this.name, MetricName.build(name)); ++ return mBeanServer.getAttributes(n, attributeNames); ++ } + +- private SortedMap values(AttributeList attributes) { +- final SortedMap values = new TreeMap<>(); +- for (Object o : attributes) { +- final Attribute attribute = (Attribute) o; +- values.put(attribute.getName(), attribute.getValue()); +- } +- return values; ++ private SortedMap values(AttributeList attributes) { ++ final SortedMap values = new TreeMap<>(); ++ for (Object o : attributes) { ++ final Attribute attribute = (Attribute) o; ++ values.put(attribute.getName(), attribute.getValue()); + } ++ return values; ++ } + } +--- a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java ++++ b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java +@@ -6,79 +6,80 @@ import com.fasterxml.jackson.databind.Module; + import com.fasterxml.jackson.databind.SerializerProvider; + import com.fasterxml.jackson.databind.module.SimpleSerializers; + import com.fasterxml.jackson.databind.ser.std.StdSerializer; ++import com.google.common.collect.ImmutableList; + import io.dropwizard.metrics5.health.HealthCheck; +- + import java.io.IOException; +-import java.util.Collections; + import java.util.Map; + + public class HealthCheckModule extends Module { +- private static class HealthCheckResultSerializer extends StdSerializer { +- +- private static final long serialVersionUID = 1L; +- +- private HealthCheckResultSerializer() { +- super(HealthCheck.Result.class); +- } +- +- @Override +- public void serialize(HealthCheck.Result result, +- JsonGenerator json, +- SerializerProvider provider) throws IOException { +- json.writeStartObject(); +- json.writeBooleanField("healthy", result.isHealthy()); ++ private static class HealthCheckResultSerializer extends StdSerializer { + +- final String message = result.getMessage(); +- if (message != null) { +- json.writeStringField("message", message); +- } ++ private static final long serialVersionUID = 1L; + +- serializeThrowable(json, result.getError(), "error"); +- json.writeNumberField("duration", result.getDuration()); +- +- Map details = result.getDetails(); +- if (details != null && !details.isEmpty()) { +- for (Map.Entry e : details.entrySet()) { +- json.writeObjectField(e.getKey(), e.getValue()); +- } +- } ++ private HealthCheckResultSerializer() { ++ super(HealthCheck.Result.class); ++ } + +- json.writeStringField("timestamp", result.getTimestamp()); +- json.writeEndObject(); ++ @Override ++ public void serialize( ++ HealthCheck.Result result, JsonGenerator json, SerializerProvider provider) ++ throws IOException { ++ json.writeStartObject(); ++ json.writeBooleanField("healthy", result.isHealthy()); ++ ++ final String message = result.getMessage(); ++ if (message != null) { ++ json.writeStringField("message", message); ++ } ++ ++ serializeThrowable(json, result.getError(), "error"); ++ json.writeNumberField("duration", result.getDuration()); ++ ++ Map details = result.getDetails(); ++ if (details != null && !details.isEmpty()) { ++ for (Map.Entry e : details.entrySet()) { ++ json.writeObjectField(e.getKey(), e.getValue()); + } ++ } + +- private void serializeThrowable(JsonGenerator json, Throwable error, String name) throws IOException { +- if (error != null) { +- json.writeObjectFieldStart(name); +- json.writeStringField("type", error.getClass().getTypeName()); +- json.writeStringField("message", error.getMessage()); +- json.writeArrayFieldStart("stack"); +- for (StackTraceElement element : error.getStackTrace()) { +- json.writeString(element.toString()); +- } +- json.writeEndArray(); +- +- if (error.getCause() != null) { +- serializeThrowable(json, error.getCause(), "cause"); +- } +- +- json.writeEndObject(); +- } +- } ++ json.writeStringField("timestamp", result.getTimestamp()); ++ json.writeEndObject(); + } + +- @Override +- public String getModuleName() { +- return "healthchecks"; +- } ++ private void serializeThrowable(JsonGenerator json, Throwable error, String name) ++ throws IOException { ++ if (error != null) { ++ json.writeObjectFieldStart(name); ++ json.writeStringField("type", error.getClass().getTypeName()); ++ json.writeStringField("message", error.getMessage()); ++ json.writeArrayFieldStart("stack"); ++ for (StackTraceElement element : error.getStackTrace()) { ++ json.writeString(element.toString()); ++ } ++ json.writeEndArray(); + +- @Override +- public Version version() { +- return MetricsModule.VERSION; +- } ++ if (error.getCause() != null) { ++ serializeThrowable(json, error.getCause(), "cause"); ++ } + +- @Override +- public void setupModule(SetupContext context) { +- context.addSerializers(new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer()))); ++ json.writeEndObject(); ++ } + } ++ } ++ ++ @Override ++ public String getModuleName() { ++ return "healthchecks"; ++ } ++ ++ @Override ++ public Version version() { ++ return MetricsModule.VERSION; ++ } ++ ++ @Override ++ public void setupModule(SetupContext context) { ++ context.addSerializers( ++ new SimpleSerializers(ImmutableList.of(new HealthCheckResultSerializer()))); ++ } + } +--- a/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java ++++ b/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java +@@ -14,248 +14,241 @@ import io.dropwizard.metrics5.MetricFilter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +- + import java.io.IOException; + import java.util.Arrays; + import java.util.Locale; + import java.util.concurrent.TimeUnit; + + public class MetricsModule extends Module { +- static final Version VERSION = new Version(5, 0, 0, "", "io.dropwizard.metrics5", "metrics-json"); +- +- @SuppressWarnings("rawtypes") +- private static class GaugeSerializer extends StdSerializer { ++ static final Version VERSION = new Version(5, 0, 0, "", "io.dropwizard.metrics5", "metrics-json"); + +- private static final long serialVersionUID = 1L; ++ @SuppressWarnings("rawtypes") ++ private static class GaugeSerializer extends StdSerializer { + +- private GaugeSerializer() { +- super(Gauge.class); +- } ++ private static final long serialVersionUID = 1L; + +- @Override +- public void serialize(Gauge gauge, +- JsonGenerator json, +- SerializerProvider provider) throws IOException { +- json.writeStartObject(); +- final Object value; +- try { +- value = gauge.getValue(); +- json.writeObjectField("value", value); +- } catch (RuntimeException e) { +- json.writeObjectField("error", e.toString()); +- } +- json.writeEndObject(); +- } ++ private GaugeSerializer() { ++ super(Gauge.class); + } + +- private static class CounterSerializer extends StdSerializer { ++ @Override ++ public void serialize(Gauge gauge, JsonGenerator json, SerializerProvider provider) ++ throws IOException { ++ json.writeStartObject(); ++ final Object value; ++ try { ++ value = gauge.getValue(); ++ json.writeObjectField("value", value); ++ } catch (RuntimeException e) { ++ json.writeObjectField("error", e.toString()); ++ } ++ json.writeEndObject(); ++ } ++ } + +- private static final long serialVersionUID = 1L; ++ private static class CounterSerializer extends StdSerializer { + +- private CounterSerializer() { +- super(Counter.class); +- } ++ private static final long serialVersionUID = 1L; + +- @Override +- public void serialize(Counter counter, +- JsonGenerator json, +- SerializerProvider provider) throws IOException { +- json.writeStartObject(); +- json.writeNumberField("count", counter.getCount()); +- json.writeEndObject(); +- } ++ private CounterSerializer() { ++ super(Counter.class); + } + +- private static class HistogramSerializer extends StdSerializer { ++ @Override ++ public void serialize(Counter counter, JsonGenerator json, SerializerProvider provider) ++ throws IOException { ++ json.writeStartObject(); ++ json.writeNumberField("count", counter.getCount()); ++ json.writeEndObject(); ++ } ++ } + +- private static final long serialVersionUID = 1L; ++ private static class HistogramSerializer extends StdSerializer { + +- private final boolean showSamples; ++ private static final long serialVersionUID = 1L; + +- private HistogramSerializer(boolean showSamples) { +- super(Histogram.class); +- this.showSamples = showSamples; +- } ++ private final boolean showSamples; + +- @Override +- public void serialize(Histogram histogram, +- JsonGenerator json, +- SerializerProvider provider) throws IOException { +- json.writeStartObject(); +- final Snapshot snapshot = histogram.getSnapshot(); +- json.writeNumberField("count", histogram.getCount()); +- json.writeNumberField("max", snapshot.getMax()); +- json.writeNumberField("mean", snapshot.getMean()); +- json.writeNumberField("min", snapshot.getMin()); +- json.writeNumberField("p50", snapshot.getMedian()); +- json.writeNumberField("p75", snapshot.get75thPercentile()); +- json.writeNumberField("p95", snapshot.get95thPercentile()); +- json.writeNumberField("p98", snapshot.get98thPercentile()); +- json.writeNumberField("p99", snapshot.get99thPercentile()); +- json.writeNumberField("p999", snapshot.get999thPercentile()); +- +- if (showSamples) { +- json.writeObjectField("values", snapshot.getValues()); +- } +- +- json.writeNumberField("stddev", snapshot.getStdDev()); +- json.writeEndObject(); +- } ++ private HistogramSerializer(boolean showSamples) { ++ super(Histogram.class); ++ this.showSamples = showSamples; + } + +- private static class MeterSerializer extends StdSerializer { ++ @Override ++ public void serialize(Histogram histogram, JsonGenerator json, SerializerProvider provider) ++ throws IOException { ++ json.writeStartObject(); ++ final Snapshot snapshot = histogram.getSnapshot(); ++ json.writeNumberField("count", histogram.getCount()); ++ json.writeNumberField("max", snapshot.getMax()); ++ json.writeNumberField("mean", snapshot.getMean()); ++ json.writeNumberField("min", snapshot.getMin()); ++ json.writeNumberField("p50", snapshot.getMedian()); ++ json.writeNumberField("p75", snapshot.get75thPercentile()); ++ json.writeNumberField("p95", snapshot.get95thPercentile()); ++ json.writeNumberField("p98", snapshot.get98thPercentile()); ++ json.writeNumberField("p99", snapshot.get99thPercentile()); ++ json.writeNumberField("p999", snapshot.get999thPercentile()); ++ ++ if (showSamples) { ++ json.writeObjectField("values", snapshot.getValues()); ++ } ++ ++ json.writeNumberField("stddev", snapshot.getStdDev()); ++ json.writeEndObject(); ++ } ++ } + +- private static final long serialVersionUID = 1L; ++ private static class MeterSerializer extends StdSerializer { + +- private final String rateUnit; +- private final double rateFactor; ++ private static final long serialVersionUID = 1L; + +- public MeterSerializer(TimeUnit rateUnit) { +- super(Meter.class); +- this.rateFactor = rateUnit.toSeconds(1); +- this.rateUnit = calculateRateUnit(rateUnit, "events"); +- } ++ private final String rateUnit; ++ private final double rateFactor; + +- @Override +- public void serialize(Meter meter, +- JsonGenerator json, +- SerializerProvider provider) throws IOException { +- json.writeStartObject(); +- json.writeNumberField("count", meter.getCount()); +- json.writeNumberField("m15_rate", meter.getFifteenMinuteRate() * rateFactor); +- json.writeNumberField("m1_rate", meter.getOneMinuteRate() * rateFactor); +- json.writeNumberField("m5_rate", meter.getFiveMinuteRate() * rateFactor); +- json.writeNumberField("mean_rate", meter.getMeanRate() * rateFactor); +- json.writeStringField("units", rateUnit); +- json.writeEndObject(); +- } ++ public MeterSerializer(TimeUnit rateUnit) { ++ super(Meter.class); ++ this.rateFactor = rateUnit.toSeconds(1); ++ this.rateUnit = calculateRateUnit(rateUnit, "events"); + } + +- private static class TimerSerializer extends StdSerializer { +- +- private static final long serialVersionUID = 1L; +- +- private final String rateUnit; +- private final double rateFactor; +- private final String durationUnit; +- private final double durationFactor; +- private final boolean showSamples; +- +- private TimerSerializer(TimeUnit rateUnit, +- TimeUnit durationUnit, +- boolean showSamples) { +- super(Timer.class); +- this.rateUnit = calculateRateUnit(rateUnit, "calls"); +- this.rateFactor = rateUnit.toSeconds(1); +- this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); +- this.durationFactor = 1.0 / durationUnit.toNanos(1); +- this.showSamples = showSamples; +- } +- +- @Override +- public void serialize(Timer timer, +- JsonGenerator json, +- SerializerProvider provider) throws IOException { +- json.writeStartObject(); +- final Snapshot snapshot = timer.getSnapshot(); +- json.writeNumberField("count", timer.getCount()); +- json.writeNumberField("max", snapshot.getMax() * durationFactor); +- json.writeNumberField("mean", snapshot.getMean() * durationFactor); +- json.writeNumberField("min", snapshot.getMin() * durationFactor); +- +- json.writeNumberField("p50", snapshot.getMedian() * durationFactor); +- json.writeNumberField("p75", snapshot.get75thPercentile() * durationFactor); +- json.writeNumberField("p95", snapshot.get95thPercentile() * durationFactor); +- json.writeNumberField("p98", snapshot.get98thPercentile() * durationFactor); +- json.writeNumberField("p99", snapshot.get99thPercentile() * durationFactor); +- json.writeNumberField("p999", snapshot.get999thPercentile() * durationFactor); +- +- if (showSamples) { +- final long[] values = snapshot.getValues(); +- final double[] scaledValues = new double[values.length]; +- for (int i = 0; i < values.length; i++) { +- scaledValues[i] = values[i] * durationFactor; +- } +- json.writeObjectField("values", scaledValues); +- } +- +- json.writeNumberField("stddev", snapshot.getStdDev() * durationFactor); +- json.writeNumberField("m15_rate", timer.getFifteenMinuteRate() * rateFactor); +- json.writeNumberField("m1_rate", timer.getOneMinuteRate() * rateFactor); +- json.writeNumberField("m5_rate", timer.getFiveMinuteRate() * rateFactor); +- json.writeNumberField("mean_rate", timer.getMeanRate() * rateFactor); +- json.writeStringField("duration_units", durationUnit); +- json.writeStringField("rate_units", rateUnit); +- json.writeEndObject(); +- } ++ @Override ++ public void serialize(Meter meter, JsonGenerator json, SerializerProvider provider) ++ throws IOException { ++ json.writeStartObject(); ++ json.writeNumberField("count", meter.getCount()); ++ json.writeNumberField("m15_rate", meter.getFifteenMinuteRate() * rateFactor); ++ json.writeNumberField("m1_rate", meter.getOneMinuteRate() * rateFactor); ++ json.writeNumberField("m5_rate", meter.getFiveMinuteRate() * rateFactor); ++ json.writeNumberField("mean_rate", meter.getMeanRate() * rateFactor); ++ json.writeStringField("units", rateUnit); ++ json.writeEndObject(); + } ++ } + +- private static class MetricRegistrySerializer extends StdSerializer { ++ private static class TimerSerializer extends StdSerializer { + +- private static final long serialVersionUID = 1L; ++ private static final long serialVersionUID = 1L; + +- private final MetricFilter filter; ++ private final String rateUnit; ++ private final double rateFactor; ++ private final String durationUnit; ++ private final double durationFactor; ++ private final boolean showSamples; + +- private MetricRegistrySerializer(MetricFilter filter) { +- super(MetricRegistry.class); +- this.filter = filter; +- } ++ private TimerSerializer(TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples) { ++ super(Timer.class); ++ this.rateUnit = calculateRateUnit(rateUnit, "calls"); ++ this.rateFactor = rateUnit.toSeconds(1); ++ this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); ++ this.durationFactor = 1.0 / durationUnit.toNanos(1); ++ this.showSamples = showSamples; ++ } + +- @Override +- public void serialize(MetricRegistry registry, +- JsonGenerator json, +- SerializerProvider provider) throws IOException { +- json.writeStartObject(); +- json.writeStringField("version", VERSION.toString()); +- json.writeObjectField("gauges", registry.getGauges(filter)); +- json.writeObjectField("counters", registry.getCounters(filter)); +- json.writeObjectField("histograms", registry.getHistograms(filter)); +- json.writeObjectField("meters", registry.getMeters(filter)); +- json.writeObjectField("timers", registry.getTimers(filter)); +- json.writeEndObject(); ++ @Override ++ public void serialize(Timer timer, JsonGenerator json, SerializerProvider provider) ++ throws IOException { ++ json.writeStartObject(); ++ final Snapshot snapshot = timer.getSnapshot(); ++ json.writeNumberField("count", timer.getCount()); ++ json.writeNumberField("max", snapshot.getMax() * durationFactor); ++ json.writeNumberField("mean", snapshot.getMean() * durationFactor); ++ json.writeNumberField("min", snapshot.getMin() * durationFactor); ++ ++ json.writeNumberField("p50", snapshot.getMedian() * durationFactor); ++ json.writeNumberField("p75", snapshot.get75thPercentile() * durationFactor); ++ json.writeNumberField("p95", snapshot.get95thPercentile() * durationFactor); ++ json.writeNumberField("p98", snapshot.get98thPercentile() * durationFactor); ++ json.writeNumberField("p99", snapshot.get99thPercentile() * durationFactor); ++ json.writeNumberField("p999", snapshot.get999thPercentile() * durationFactor); ++ ++ if (showSamples) { ++ final long[] values = snapshot.getValues(); ++ final double[] scaledValues = new double[values.length]; ++ for (int i = 0; i < values.length; i++) { ++ scaledValues[i] = values[i] * durationFactor; + } ++ json.writeObjectField("values", scaledValues); ++ } ++ ++ json.writeNumberField("stddev", snapshot.getStdDev() * durationFactor); ++ json.writeNumberField("m15_rate", timer.getFifteenMinuteRate() * rateFactor); ++ json.writeNumberField("m1_rate", timer.getOneMinuteRate() * rateFactor); ++ json.writeNumberField("m5_rate", timer.getFiveMinuteRate() * rateFactor); ++ json.writeNumberField("mean_rate", timer.getMeanRate() * rateFactor); ++ json.writeStringField("duration_units", durationUnit); ++ json.writeStringField("rate_units", rateUnit); ++ json.writeEndObject(); + } ++ } + +- protected final TimeUnit rateUnit; +- protected final TimeUnit durationUnit; +- protected final boolean showSamples; +- protected final MetricFilter filter; ++ private static class MetricRegistrySerializer extends StdSerializer { + +- public MetricsModule(TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples) { +- this(rateUnit, durationUnit, showSamples, MetricFilter.ALL); +- } ++ private static final long serialVersionUID = 1L; + +- public MetricsModule(TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples, MetricFilter filter) { +- this.rateUnit = rateUnit; +- this.durationUnit = durationUnit; +- this.showSamples = showSamples; +- this.filter = filter; +- } ++ private final MetricFilter filter; + +- @Override +- public String getModuleName() { +- return "metrics"; ++ private MetricRegistrySerializer(MetricFilter filter) { ++ super(MetricRegistry.class); ++ this.filter = filter; + } + + @Override +- public Version version() { +- return VERSION; ++ public void serialize(MetricRegistry registry, JsonGenerator json, SerializerProvider provider) ++ throws IOException { ++ json.writeStartObject(); ++ json.writeStringField("version", VERSION.toString()); ++ json.writeObjectField("gauges", registry.getGauges(filter)); ++ json.writeObjectField("counters", registry.getCounters(filter)); ++ json.writeObjectField("histograms", registry.getHistograms(filter)); ++ json.writeObjectField("meters", registry.getMeters(filter)); ++ json.writeObjectField("timers", registry.getTimers(filter)); ++ json.writeEndObject(); + } +- +- @Override +- public void setupModule(SetupContext context) { +- context.addSerializers(new SimpleSerializers(Arrays.asList( ++ } ++ ++ protected final TimeUnit rateUnit; ++ protected final TimeUnit durationUnit; ++ protected final boolean showSamples; ++ protected final MetricFilter filter; ++ ++ public MetricsModule(TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples) { ++ this(rateUnit, durationUnit, showSamples, MetricFilter.ALL); ++ } ++ ++ public MetricsModule( ++ TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples, MetricFilter filter) { ++ this.rateUnit = rateUnit; ++ this.durationUnit = durationUnit; ++ this.showSamples = showSamples; ++ this.filter = filter; ++ } ++ ++ @Override ++ public String getModuleName() { ++ return "metrics"; ++ } ++ ++ @Override ++ public Version version() { ++ return VERSION; ++ } ++ ++ @Override ++ public void setupModule(SetupContext context) { ++ context.addSerializers( ++ new SimpleSerializers( ++ Arrays.asList( + new GaugeSerializer(), + new CounterSerializer(), + new HistogramSerializer(showSamples), + new MeterSerializer(rateUnit), + new TimerSerializer(rateUnit, durationUnit, showSamples), +- new MetricRegistrySerializer(filter) +- ))); +- } ++ new MetricRegistrySerializer(filter)))); ++ } + +- private static String calculateRateUnit(TimeUnit unit, String name) { +- final String s = unit.toString().toLowerCase(Locale.US); +- return name + '/' + s.substring(0, s.length() - 1); +- } ++ private static String calculateRateUnit(TimeUnit unit, String name) { ++ final String s = unit.toString().toLowerCase(Locale.US); ++ return name + '/' + s.substring(0, s.length() - 1); ++ } + } +--- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java ++++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java +@@ -1,138 +1,95 @@ + package io.dropwizard.metrics5.json; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import com.fasterxml.jackson.databind.ObjectMapper; + import io.dropwizard.metrics5.health.HealthCheck; +-import org.junit.jupiter.api.Test; +- + import java.math.BigDecimal; + import java.math.BigInteger; + import java.util.LinkedHashMap; + import java.util.Map; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class HealthCheckModuleTest { +- private final ObjectMapper mapper = new ObjectMapper().registerModule(new HealthCheckModule()); ++final class HealthCheckModuleTest { ++ private final ObjectMapper mapper = new ObjectMapper().registerModule(new HealthCheckModule()); + +- @Test +- void serializesAHealthyResult() throws Exception { +- HealthCheck.Result result = HealthCheck.Result.healthy(); +- assertThat(mapper.writeValueAsString(result)) +- .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); +- } ++ @Test ++ void serializesAHealthyResult() throws Exception { ++ HealthCheck.Result result = HealthCheck.Result.healthy(); ++ assertThat(mapper.writeValueAsString(result)) ++ .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp()); ++ } + +- @Test +- void serializesAHealthyResultWithAMessage() throws Exception { +- HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); +- assertThat(mapper.writeValueAsString(result)) +- .isEqualTo("{" + +- "\"healthy\":true," + +- "\"message\":\"yay for me\"," + +- "\"duration\":0," + +- "\"timestamp\":\"" + result.getTimestamp() + "\"" + +- "}"); +- } ++ @Test ++ void serializesAHealthyResultWithAMessage() throws Exception { ++ HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); ++ assertThat(mapper.writeValueAsString(result)) ++ .isEqualTo( ++ "{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); ++ } + +- @Test +- void serializesAnUnhealthyResult() throws Exception { +- HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); +- assertThat(mapper.writeValueAsString(result)) +- .isEqualTo("{" + +- "\"healthy\":false," + +- "\"message\":\"boo\"," + +- "\"duration\":0," + +- "\"timestamp\":\"" + result.getTimestamp() + "\"" + +- "}"); +- } ++ @Test ++ void serializesAnUnhealthyResult() throws Exception { ++ HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); ++ assertThat(mapper.writeValueAsString(result)) ++ .isEqualTo( ++ "{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); ++ } + +- @Test +- void serializesAnUnhealthyResultWithAnException() throws Exception { +- final RuntimeException e = new RuntimeException("oh no"); +- e.setStackTrace(new StackTraceElement[]{ +- new StackTraceElement("Blah", "bloo", "Blah.java", 100) +- }); ++ @Test ++ void serializesAnUnhealthyResultWithAnException() throws Exception { ++ final RuntimeException e = new RuntimeException("oh no"); ++ e.setStackTrace( ++ new StackTraceElement[] {new StackTraceElement("Blah", "bloo", "Blah.java", 100)}); + +- HealthCheck.Result result = HealthCheck.Result.unhealthy(e); +- assertThat(mapper.writeValueAsString(result)) +- .isEqualTo("{" + +- "\"healthy\":false," + +- "\"message\":\"oh no\"," + +- "\"error\":{" + +- "\"type\":\"java.lang.RuntimeException\"," + +- "\"message\":\"oh no\"," + +- "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" + +- "}," + +- "\"duration\":0," + +- "\"timestamp\":\"" + result.getTimestamp() + "\"" + +- "}"); +- } ++ HealthCheck.Result result = HealthCheck.Result.unhealthy(e); ++ assertThat(mapper.writeValueAsString(result)) ++ .isEqualTo( ++ "{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); ++ } + +- @Test +- void serializesAnUnhealthyResultWithNestedExceptions() throws Exception { +- final RuntimeException a = new RuntimeException("oh no"); +- a.setStackTrace(new StackTraceElement[]{ +- new StackTraceElement("Blah", "bloo", "Blah.java", 100) +- }); ++ @Test ++ void serializesAnUnhealthyResultWithNestedExceptions() throws Exception { ++ final RuntimeException a = new RuntimeException("oh no"); ++ a.setStackTrace( ++ new StackTraceElement[] {new StackTraceElement("Blah", "bloo", "Blah.java", 100)}); + +- final RuntimeException b = new RuntimeException("oh well", a); +- b.setStackTrace(new StackTraceElement[]{ +- new StackTraceElement("Blah", "blee", "Blah.java", 150) +- }); ++ final RuntimeException b = new RuntimeException("oh well", a); ++ b.setStackTrace( ++ new StackTraceElement[] {new StackTraceElement("Blah", "blee", "Blah.java", 150)}); + +- HealthCheck.Result result = HealthCheck.Result.unhealthy(b); +- assertThat(mapper.writeValueAsString(result)) +- .isEqualTo("{" + +- "\"healthy\":false," + +- "\"message\":\"oh well\"," + +- "\"error\":{" + +- "\"type\":\"java.lang.RuntimeException\"," + +- "\"message\":\"oh well\"," + +- "\"stack\":[\"Blah.blee(Blah.java:150)\"]," + +- "\"cause\":{" + +- "\"type\":\"java.lang.RuntimeException\"," + +- "\"message\":\"oh no\"," + +- "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" + +- "}" + +- "}," + +- "\"duration\":0," + +- "\"timestamp\":\"" + result.getTimestamp() + "\"" + +- "}"); +- } ++ HealthCheck.Result result = HealthCheck.Result.unhealthy(b); ++ assertThat(mapper.writeValueAsString(result)) ++ .isEqualTo( ++ "{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); ++ } + +- @Test +- void serializeResultWithDetail() throws Exception { +- Map complex = new LinkedHashMap<>(); +- complex.put("field", "value"); ++ @Test ++ void serializeResultWithDetail() throws Exception { ++ Map complex = new LinkedHashMap<>(); ++ complex.put("field", "value"); + +- HealthCheck.Result result = HealthCheck.Result.builder() +- .healthy() +- .withDetail("boolean", true) +- .withDetail("integer", 1) +- .withDetail("long", 2L) +- .withDetail("float", 3.546F) +- .withDetail("double", 4.567D) +- .withDetail("BigInteger", new BigInteger("12345")) +- .withDetail("BigDecimal", new BigDecimal("12345.56789")) +- .withDetail("String", "string") +- .withDetail("complex", complex) +- .build(); ++ HealthCheck.Result result = ++ HealthCheck.Result.builder() ++ .healthy() ++ .withDetail("boolean", true) ++ .withDetail("integer", 1) ++ .withDetail("long", 2L) ++ .withDetail("float", 3.546F) ++ .withDetail("double", 4.567D) ++ .withDetail("BigInteger", new BigInteger("12345")) ++ .withDetail("BigDecimal", new BigDecimal("12345.56789")) ++ .withDetail("String", "string") ++ .withDetail("complex", complex) ++ .build(); + +- assertThat(mapper.writeValueAsString(result)) +- .isEqualTo("{" + +- "\"healthy\":true," + +- "\"duration\":0," + +- "\"boolean\":true," + +- "\"integer\":1," + +- "\"long\":2," + +- "\"float\":3.546," + +- "\"double\":4.567," + +- "\"BigInteger\":12345," + +- "\"BigDecimal\":12345.56789," + +- "\"String\":\"string\"," + +- "\"complex\":{" + +- "\"field\":\"value\"" + +- "}," + +- "\"timestamp\":\"" + result.getTimestamp() + "\"" + +- "}"); +- } ++ assertThat(mapper.writeValueAsString(result)) ++ .isEqualTo( ++ "{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", ++ result.getTimestamp()); ++ } + } +--- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java ++++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.json; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import com.fasterxml.jackson.databind.ObjectMapper; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -9,202 +13,210 @@ import io.dropwizard.metrics5.MetricFilter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +-import org.junit.jupiter.api.Test; +- + import java.util.concurrent.TimeUnit; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-class MetricsModuleTest { +- private final ObjectMapper mapper = new ObjectMapper().registerModule( +- new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, false, MetricFilter.ALL)); ++final class MetricsModuleTest { ++ private final ObjectMapper mapper = ++ new ObjectMapper() ++ .registerModule( ++ new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, false, MetricFilter.ALL)); + +- @Test +- void serializesGauges() throws Exception { +- final Gauge gauge = () -> 100; ++ @Test ++ void serializesGauges() throws Exception { ++ final Gauge gauge = () -> 100; + +- assertThat(mapper.writeValueAsString(gauge)) +- .isEqualTo("{\"value\":100}"); +- } ++ assertThat(mapper.writeValueAsString(gauge)).isEqualTo("{\"value\":100}"); ++ } + +- @Test +- void serializesGaugesThatThrowExceptions() throws Exception { +- final Gauge gauge = () -> { +- throw new IllegalArgumentException("poops"); ++ @Test ++ void serializesGaugesThatThrowExceptions() throws Exception { ++ final Gauge gauge = ++ () -> { ++ throw new IllegalArgumentException("poops"); + }; + +- assertThat(mapper.writeValueAsString(gauge)) +- .isEqualTo("{\"error\":\"java.lang.IllegalArgumentException: poops\"}"); +- } +- +- @Test +- void serializesCounters() throws Exception { +- final Counter counter = mock(Counter.class); +- when(counter.getCount()).thenReturn(100L); +- +- assertThat(mapper.writeValueAsString(counter)) +- .isEqualTo("{\"count\":100}"); +- } +- +- @Test +- void serializesHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); +- when(histogram.getCount()).thenReturn(1L); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(2L); +- when(snapshot.getMean()).thenReturn(3.0); +- when(snapshot.getMin()).thenReturn(4L); +- when(snapshot.getStdDev()).thenReturn(5.0); +- when(snapshot.getMedian()).thenReturn(6.0); +- when(snapshot.get75thPercentile()).thenReturn(7.0); +- when(snapshot.get95thPercentile()).thenReturn(8.0); +- when(snapshot.get98thPercentile()).thenReturn(9.0); +- when(snapshot.get99thPercentile()).thenReturn(10.0); +- when(snapshot.get999thPercentile()).thenReturn(11.0); +- when(snapshot.getValues()).thenReturn(new long[]{1, 2, 3}); +- +- when(histogram.getSnapshot()).thenReturn(snapshot); +- +- assertThat(mapper.writeValueAsString(histogram)) +- .isEqualTo("{" + +- "\"count\":1," + +- "\"max\":2," + +- "\"mean\":3.0," + +- "\"min\":4," + +- "\"p50\":6.0," + +- "\"p75\":7.0," + +- "\"p95\":8.0," + +- "\"p98\":9.0," + +- "\"p99\":10.0," + +- "\"p999\":11.0," + +- "\"stddev\":5.0}"); +- +- final ObjectMapper fullMapper = new ObjectMapper().registerModule( ++ assertThat(mapper.writeValueAsString(gauge)) ++ .isEqualTo("{\"error\":\"java.lang.IllegalArgumentException: poops\"}"); ++ } ++ ++ @Test ++ void serializesCounters() throws Exception { ++ final Counter counter = mock(); ++ when(counter.getCount()).thenReturn(100L); ++ ++ assertThat(mapper.writeValueAsString(counter)).isEqualTo("{\"count\":100}"); ++ } ++ ++ @Test ++ void serializesHistograms() throws Exception { ++ final Histogram histogram = mock(); ++ when(histogram.getCount()).thenReturn(1L); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(2L); ++ when(snapshot.getMean()).thenReturn(3.0); ++ when(snapshot.getMin()).thenReturn(4L); ++ when(snapshot.getStdDev()).thenReturn(5.0); ++ when(snapshot.getMedian()).thenReturn(6.0); ++ when(snapshot.get75thPercentile()).thenReturn(7.0); ++ when(snapshot.get95thPercentile()).thenReturn(8.0); ++ when(snapshot.get98thPercentile()).thenReturn(9.0); ++ when(snapshot.get99thPercentile()).thenReturn(10.0); ++ when(snapshot.get999thPercentile()).thenReturn(11.0); ++ when(snapshot.getValues()).thenReturn(new long[] {1, 2, 3}); ++ ++ when(histogram.getSnapshot()).thenReturn(snapshot); ++ ++ assertThat(mapper.writeValueAsString(histogram)) ++ .isEqualTo( ++ "{" ++ + "\"count\":1," ++ + "\"max\":2," ++ + "\"mean\":3.0," ++ + "\"min\":4," ++ + "\"p50\":6.0," ++ + "\"p75\":7.0," ++ + "\"p95\":8.0," ++ + "\"p98\":9.0," ++ + "\"p99\":10.0," ++ + "\"p999\":11.0," ++ + "\"stddev\":5.0}"); ++ ++ final ObjectMapper fullMapper = ++ new ObjectMapper() ++ .registerModule( + new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true, MetricFilter.ALL)); + +- assertThat(fullMapper.writeValueAsString(histogram)) +- .isEqualTo("{" + +- "\"count\":1," + +- "\"max\":2," + +- "\"mean\":3.0," + +- "\"min\":4," + +- "\"p50\":6.0," + +- "\"p75\":7.0," + +- "\"p95\":8.0," + +- "\"p98\":9.0," + +- "\"p99\":10.0," + +- "\"p999\":11.0," + +- "\"values\":[1,2,3]," + +- "\"stddev\":5.0}"); +- } +- +- @Test +- void serializesMeters() throws Exception { +- final Meter meter = mock(Meter.class); +- when(meter.getCount()).thenReturn(1L); +- when(meter.getMeanRate()).thenReturn(2.0); +- when(meter.getOneMinuteRate()).thenReturn(5.0); +- when(meter.getFiveMinuteRate()).thenReturn(4.0); +- when(meter.getFifteenMinuteRate()).thenReturn(3.0); +- +- assertThat(mapper.writeValueAsString(meter)) +- .isEqualTo("{" + +- "\"count\":1," + +- "\"m15_rate\":3.0," + +- "\"m1_rate\":5.0," + +- "\"m5_rate\":4.0," + +- "\"mean_rate\":2.0," + +- "\"units\":\"events/second\"}"); +- } +- +- @Test +- void serializesTimers() throws Exception { +- final Timer timer = mock(Timer.class); +- when(timer.getCount()).thenReturn(1L); +- when(timer.getMeanRate()).thenReturn(2.0); +- when(timer.getOneMinuteRate()).thenReturn(3.0); +- when(timer.getFiveMinuteRate()).thenReturn(4.0); +- when(timer.getFifteenMinuteRate()).thenReturn(5.0); +- +- final Snapshot snapshot = mock(Snapshot.class); +- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); +- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); +- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); +- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); +- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); +- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); +- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); +- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); +- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); +- +- when(snapshot.getValues()).thenReturn(new long[]{ +- TimeUnit.MILLISECONDS.toNanos(1), +- TimeUnit.MILLISECONDS.toNanos(2), +- TimeUnit.MILLISECONDS.toNanos(3) +- }); +- +- when(timer.getSnapshot()).thenReturn(snapshot); +- +- assertThat(mapper.writeValueAsString(timer)) +- .isEqualTo("{" + +- "\"count\":1," + +- "\"max\":100.0," + +- "\"mean\":200.0," + +- "\"min\":300.0," + +- "\"p50\":500.0," + +- "\"p75\":600.0," + +- "\"p95\":700.0," + +- "\"p98\":800.0," + +- "\"p99\":900.0," + +- "\"p999\":1000.0," + +- "\"stddev\":400.0," + +- "\"m15_rate\":5.0," + +- "\"m1_rate\":3.0," + +- "\"m5_rate\":4.0," + +- "\"mean_rate\":2.0," + +- "\"duration_units\":\"milliseconds\"," + +- "\"rate_units\":\"calls/second\"}"); +- +- final ObjectMapper fullMapper = new ObjectMapper().registerModule( ++ assertThat(fullMapper.writeValueAsString(histogram)) ++ .isEqualTo( ++ "{" ++ + "\"count\":1," ++ + "\"max\":2," ++ + "\"mean\":3.0," ++ + "\"min\":4," ++ + "\"p50\":6.0," ++ + "\"p75\":7.0," ++ + "\"p95\":8.0," ++ + "\"p98\":9.0," ++ + "\"p99\":10.0," ++ + "\"p999\":11.0," ++ + "\"values\":[1,2,3]," ++ + "\"stddev\":5.0}"); ++ } ++ ++ @Test ++ void serializesMeters() throws Exception { ++ final Meter meter = mock(); ++ when(meter.getCount()).thenReturn(1L); ++ when(meter.getMeanRate()).thenReturn(2.0); ++ when(meter.getOneMinuteRate()).thenReturn(5.0); ++ when(meter.getFiveMinuteRate()).thenReturn(4.0); ++ when(meter.getFifteenMinuteRate()).thenReturn(3.0); ++ ++ assertThat(mapper.writeValueAsString(meter)) ++ .isEqualTo( ++ "{" ++ + "\"count\":1," ++ + "\"m15_rate\":3.0," ++ + "\"m1_rate\":5.0," ++ + "\"m5_rate\":4.0," ++ + "\"mean_rate\":2.0," ++ + "\"units\":\"events/second\"}"); ++ } ++ ++ @Test ++ void serializesTimers() throws Exception { ++ final Timer timer = mock(); ++ when(timer.getCount()).thenReturn(1L); ++ when(timer.getMeanRate()).thenReturn(2.0); ++ when(timer.getOneMinuteRate()).thenReturn(3.0); ++ when(timer.getFiveMinuteRate()).thenReturn(4.0); ++ when(timer.getFifteenMinuteRate()).thenReturn(5.0); ++ ++ final Snapshot snapshot = mock(); ++ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); ++ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); ++ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); ++ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); ++ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); ++ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); ++ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); ++ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); ++ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); ++ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); ++ ++ when(snapshot.getValues()) ++ .thenReturn( ++ new long[] { ++ TimeUnit.MILLISECONDS.toNanos(1), ++ TimeUnit.MILLISECONDS.toNanos(2), ++ TimeUnit.MILLISECONDS.toNanos(3) ++ }); ++ ++ when(timer.getSnapshot()).thenReturn(snapshot); ++ ++ assertThat(mapper.writeValueAsString(timer)) ++ .isEqualTo( ++ "{" ++ + "\"count\":1," ++ + "\"max\":100.0," ++ + "\"mean\":200.0," ++ + "\"min\":300.0," ++ + "\"p50\":500.0," ++ + "\"p75\":600.0," ++ + "\"p95\":700.0," ++ + "\"p98\":800.0," ++ + "\"p99\":900.0," ++ + "\"p999\":1000.0," ++ + "\"stddev\":400.0," ++ + "\"m15_rate\":5.0," ++ + "\"m1_rate\":3.0," ++ + "\"m5_rate\":4.0," ++ + "\"mean_rate\":2.0," ++ + "\"duration_units\":\"milliseconds\"," ++ + "\"rate_units\":\"calls/second\"}"); ++ ++ final ObjectMapper fullMapper = ++ new ObjectMapper() ++ .registerModule( + new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true, MetricFilter.ALL)); + +- assertThat(fullMapper.writeValueAsString(timer)) +- .isEqualTo("{" + +- "\"count\":1," + +- "\"max\":100.0," + +- "\"mean\":200.0," + +- "\"min\":300.0," + +- "\"p50\":500.0," + +- "\"p75\":600.0," + +- "\"p95\":700.0," + +- "\"p98\":800.0," + +- "\"p99\":900.0," + +- "\"p999\":1000.0," + +- "\"values\":[1.0,2.0,3.0]," + +- "\"stddev\":400.0," + +- "\"m15_rate\":5.0," + +- "\"m1_rate\":3.0," + +- "\"m5_rate\":4.0," + +- "\"mean_rate\":2.0," + +- "\"duration_units\":\"milliseconds\"," + +- "\"rate_units\":\"calls/second\"}"); +- } +- +- @Test +- void serializesMetricRegistries() throws Exception { +- final MetricRegistry registry = new MetricRegistry(); +- +- assertThat(mapper.writeValueAsString(registry)) +- .isEqualTo("{" + +- "\"version\":\"5.0.0\"," + +- "\"gauges\":{}," + +- "\"counters\":{}," + +- "\"histograms\":{}," + +- "\"meters\":{}," + +- "\"timers\":{}}"); +- } ++ assertThat(fullMapper.writeValueAsString(timer)) ++ .isEqualTo( ++ "{" ++ + "\"count\":1," ++ + "\"max\":100.0," ++ + "\"mean\":200.0," ++ + "\"min\":300.0," ++ + "\"p50\":500.0," ++ + "\"p75\":600.0," ++ + "\"p95\":700.0," ++ + "\"p98\":800.0," ++ + "\"p99\":900.0," ++ + "\"p999\":1000.0," ++ + "\"values\":[1.0,2.0,3.0]," ++ + "\"stddev\":400.0," ++ + "\"m15_rate\":5.0," ++ + "\"m1_rate\":3.0," ++ + "\"m5_rate\":4.0," ++ + "\"mean_rate\":2.0," ++ + "\"duration_units\":\"milliseconds\"," ++ + "\"rate_units\":\"calls/second\"}"); ++ } ++ ++ @Test ++ void serializesMetricRegistries() throws Exception { ++ final MetricRegistry registry = new MetricRegistry(); ++ ++ assertThat(mapper.writeValueAsString(registry)) ++ .isEqualTo( ++ "{" ++ + "\"version\":\"5.0.0\"," ++ + "\"gauges\":{}," ++ + "\"counters\":{}," ++ + "\"histograms\":{}," ++ + "\"meters\":{}," ++ + "\"timers\":{}}"); ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java +@@ -1,52 +1,53 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricSet; +-import org.slf4j.Logger; +-import org.slf4j.LoggerFactory; +- ++import java.util.HashMap; ++import java.util.Map; + import javax.management.JMException; + import javax.management.MBeanServer; + import javax.management.ObjectName; +-import java.util.Collections; +-import java.util.HashMap; +-import java.util.Map; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; + + /** + * A set of gauges for the count, usage, and capacity of the JVM's direct and mapped buffer pools. +- *

    +- * These JMX objects are only available on Java 7 and above. ++ * ++ *

    These JMX objects are only available on Java 7 and above. + */ + public class BufferPoolMetricSet implements MetricSet { +- private static final Logger LOGGER = LoggerFactory.getLogger(BufferPoolMetricSet.class); +- private static final String[] ATTRIBUTES = {"Count", "MemoryUsed", "TotalCapacity"}; +- private static final String[] NAMES = {"count", "used", "capacity"}; +- private static final String[] POOLS = {"direct", "mapped"}; ++ private static final Logger LOG = LoggerFactory.getLogger(BufferPoolMetricSet.class); ++ private static final String[] ATTRIBUTES = {"Count", "MemoryUsed", "TotalCapacity"}; ++ private static final String[] NAMES = {"count", "used", "capacity"}; ++ private static final String[] POOLS = {"direct", "mapped"}; + +- private final MBeanServer mBeanServer; ++ private final MBeanServer mBeanServer; + +- public BufferPoolMetricSet(MBeanServer mBeanServer) { +- this.mBeanServer = mBeanServer; +- } ++ public BufferPoolMetricSet(MBeanServer mBeanServer) { ++ this.mBeanServer = mBeanServer; ++ } + +- @Override +- public Map getMetrics() { +- final Map gauges = new HashMap<>(); +- for (String pool : POOLS) { +- for (int i = 0; i < ATTRIBUTES.length; i++) { +- final String attribute = ATTRIBUTES[i]; +- final String name = NAMES[i]; +- try { +- final ObjectName on = new ObjectName("java.nio:type=BufferPool,name=" + pool); +- mBeanServer.getMBeanInfo(on); +- gauges.put(MetricRegistry.name(pool, name), new JmxAttributeGauge(mBeanServer, on, attribute)); +- } catch (JMException ignored) { +- LOGGER.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); +- } +- } ++ @Override ++ public Map getMetrics() { ++ final Map gauges = new HashMap<>(); ++ for (String pool : POOLS) { ++ for (int i = 0; i < ATTRIBUTES.length; i++) { ++ final String attribute = ATTRIBUTES[i]; ++ final String name = NAMES[i]; ++ try { ++ final ObjectName on = new ObjectName("java.nio:type=BufferPool,name=" + pool); ++ mBeanServer.getMBeanInfo(on); ++ gauges.put( ++ MetricRegistry.name(pool, name), new JmxAttributeGauge(mBeanServer, on, attribute)); ++ } catch (JMException ignored) { ++ LOG.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); + } +- return Collections.unmodifiableMap(gauges); ++ } + } ++ return unmodifiableMap(gauges); ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/CachedThreadStatesGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/CachedThreadStatesGaugeSet.java +@@ -1,54 +1,55 @@ + package io.dropwizard.metrics5.jvm; + + import io.dropwizard.metrics5.CachedGauge; +- + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; + import java.util.concurrent.TimeUnit; + + /** +- * A variation of ThreadStatesGaugeSet that caches the ThreadInfo[] objects for +- * a given interval. ++ * A variation of ThreadStatesGaugeSet that caches the ThreadInfo[] objects for a given interval. + */ + public class CachedThreadStatesGaugeSet extends ThreadStatesGaugeSet { + +- private final CachedGauge threadInfo; +- +- /** +- * Creates a new set of gauges using the given MXBean and detector. +- * Caches the information for the given interval and time unit. +- * +- * @param threadMXBean a thread MXBean +- * @param deadlockDetector a deadlock detector +- * @param interval cache interval +- * @param unit cache interval time unit +- */ +- public CachedThreadStatesGaugeSet(final ThreadMXBean threadMXBean, ThreadDeadlockDetector deadlockDetector, +- long interval, TimeUnit unit) { +- super(threadMXBean, deadlockDetector); +- threadInfo = new CachedGauge(interval, unit) { +- @Override +- protected ThreadInfo[] loadValue() { +- return CachedThreadStatesGaugeSet.super.getThreadInfo(); +- } ++ private final CachedGauge threadInfo; ++ ++ /** ++ * Creates a new set of gauges using the given MXBean and detector. Caches the information for the ++ * given interval and time unit. ++ * ++ * @param threadMXBean a thread MXBean ++ * @param deadlockDetector a deadlock detector ++ * @param interval cache interval ++ * @param unit cache interval time unit ++ */ ++ public CachedThreadStatesGaugeSet( ++ final ThreadMXBean threadMXBean, ++ ThreadDeadlockDetector deadlockDetector, ++ long interval, ++ TimeUnit unit) { ++ super(threadMXBean, deadlockDetector); ++ threadInfo = ++ new CachedGauge(interval, unit) { ++ @Override ++ protected ThreadInfo[] loadValue() { ++ return CachedThreadStatesGaugeSet.super.getThreadInfo(); ++ } + }; +- } +- +- /** +- * Creates a new set of gauges using the default MXBeans. +- * Caches the information for the given interval and time unit. +- * +- * @param interval cache interval +- * @param unit cache interval time unit +- */ +- public CachedThreadStatesGaugeSet(long interval, TimeUnit unit) { +- this(ManagementFactory.getThreadMXBean(), new ThreadDeadlockDetector(), interval, unit); +- } +- +- @Override +- ThreadInfo[] getThreadInfo() { +- return threadInfo.getValue(); +- } +- ++ } ++ ++ /** ++ * Creates a new set of gauges using the default MXBeans. Caches the information for the given ++ * interval and time unit. ++ * ++ * @param interval cache interval ++ * @param unit cache interval time unit ++ */ ++ public CachedThreadStatesGaugeSet(long interval, TimeUnit unit) { ++ this(ManagementFactory.getThreadMXBean(), new ThreadDeadlockDetector(), interval, unit); ++ } ++ ++ @Override ++ ThreadInfo[] getThreadInfo() { ++ return threadInfo.getValue(); ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSet.java +@@ -4,33 +4,30 @@ import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricSet; +- + import java.lang.management.ClassLoadingMXBean; + import java.lang.management.ManagementFactory; + import java.util.HashMap; + import java.util.Map; + +-/** +- * A set of gauges for JVM classloader usage. +- */ ++/** A set of gauges for JVM classloader usage. */ + public class ClassLoadingGaugeSet implements MetricSet { + +- private final ClassLoadingMXBean mxBean; ++ private final ClassLoadingMXBean mxBean; + +- public ClassLoadingGaugeSet() { +- this(ManagementFactory.getClassLoadingMXBean()); +- } ++ public ClassLoadingGaugeSet() { ++ this(ManagementFactory.getClassLoadingMXBean()); ++ } + +- public ClassLoadingGaugeSet(ClassLoadingMXBean mxBean) { +- this.mxBean = mxBean; +- } ++ public ClassLoadingGaugeSet(ClassLoadingMXBean mxBean) { ++ this.mxBean = mxBean; ++ } + +- @Override +- public Map getMetrics() { +- final Map gauges = new HashMap<>(); +- gauges.put(MetricName.build("loaded"), (Gauge) mxBean::getTotalLoadedClassCount); +- gauges.put(MetricName.build("unloaded"), (Gauge) mxBean::getUnloadedClassCount); ++ @Override ++ public Map getMetrics() { ++ final Map gauges = new HashMap<>(); ++ gauges.put(MetricName.build("loaded"), (Gauge) mxBean::getTotalLoadedClassCount); ++ gauges.put(MetricName.build("unloaded"), (Gauge) mxBean::getUnloadedClassCount); + +- return gauges; +- } ++ return gauges; ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/CpuTimeClock.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/CpuTimeClock.java +@@ -1,19 +1,16 @@ + package io.dropwizard.metrics5.jvm; + + import io.dropwizard.metrics5.Clock; +- + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadMXBean; + +-/** +- * A clock implementation which returns the current thread's CPU time. +- */ ++/** A clock implementation which returns the current thread's CPU time. */ + public class CpuTimeClock extends Clock { + +- private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); ++ private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); + +- @Override +- public long getTick() { +- return THREAD_MX_BEAN.getCurrentThreadCpuTime(); +- } ++ @Override ++ public long getTick() { ++ return THREAD_MX_BEAN.getCurrentThreadCpuTime(); ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGauge.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGauge.java +@@ -1,50 +1,47 @@ + package io.dropwizard.metrics5.jvm; + + import io.dropwizard.metrics5.RatioGauge; +- + import java.lang.management.ManagementFactory; + import java.lang.management.OperatingSystemMXBean; + +-/** +- * A gauge for the ratio of used to total file descriptors. +- */ ++/** A gauge for the ratio of used to total file descriptors. */ + public class FileDescriptorRatioGauge extends RatioGauge { +- private static boolean unixOperatingSystemMXBeanExists = false; +- +- private final OperatingSystemMXBean os; +- +- static { +- try { +- Class.forName("com.sun.management.UnixOperatingSystemMXBean"); +- unixOperatingSystemMXBeanExists = true; +- } catch (ClassNotFoundException e) { +- // do nothing +- } +- } ++ private static boolean unixOperatingSystemMXBeanExists = false; + +- /** +- * Creates a new gauge using the platform OS bean. +- */ +- public FileDescriptorRatioGauge() { +- this(ManagementFactory.getOperatingSystemMXBean()); +- } ++ private final OperatingSystemMXBean os; + +- /** +- * Creates a new gauge using the given OS bean. +- * +- * @param os an {@link OperatingSystemMXBean} +- */ +- public FileDescriptorRatioGauge(OperatingSystemMXBean os) { +- this.os = os; ++ static { ++ try { ++ Class.forName("com.sun.management.UnixOperatingSystemMXBean"); ++ unixOperatingSystemMXBeanExists = true; ++ } catch (ClassNotFoundException e) { ++ // do nothing + } +- +- @Override +- protected Ratio getRatio() { +- if (unixOperatingSystemMXBeanExists && os instanceof com.sun.management.UnixOperatingSystemMXBean) { +- final com.sun.management.UnixOperatingSystemMXBean unixOs = (com.sun.management.UnixOperatingSystemMXBean) os; +- return Ratio.of(unixOs.getOpenFileDescriptorCount(), unixOs.getMaxFileDescriptorCount()); +- } else { +- return Ratio.of(Double.NaN, Double.NaN); +- } ++ } ++ ++ /** Creates a new gauge using the platform OS bean. */ ++ public FileDescriptorRatioGauge() { ++ this(ManagementFactory.getOperatingSystemMXBean()); ++ } ++ ++ /** ++ * Creates a new gauge using the given OS bean. ++ * ++ * @param os an {@link OperatingSystemMXBean} ++ */ ++ public FileDescriptorRatioGauge(OperatingSystemMXBean os) { ++ this.os = os; ++ } ++ ++ @Override ++ protected Ratio getRatio() { ++ if (unixOperatingSystemMXBeanExists ++ && os instanceof com.sun.management.UnixOperatingSystemMXBean) { ++ final com.sun.management.UnixOperatingSystemMXBean unixOs = ++ (com.sun.management.UnixOperatingSystemMXBean) os; ++ return Ratio.of(unixOs.getOpenFileDescriptorCount(), unixOs.getMaxFileDescriptorCount()); ++ } else { ++ return Ratio.of(Double.NaN, Double.NaN); + } ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java +@@ -1,53 +1,49 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricSet; +- + import java.lang.management.GarbageCollectorMXBean; + import java.lang.management.ManagementFactory; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; + import java.util.regex.Pattern; + +-/** +- * A set of gauges for the counts and elapsed times of garbage collections. +- */ ++/** A set of gauges for the counts and elapsed times of garbage collections. */ + public class GarbageCollectorMetricSet implements MetricSet { +- private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); ++ private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); + +- private final List garbageCollectors; ++ private final List garbageCollectors; + +- /** +- * Creates a new set of gauges for all discoverable garbage collectors. +- */ +- public GarbageCollectorMetricSet() { +- this(ManagementFactory.getGarbageCollectorMXBeans()); +- } ++ /** Creates a new set of gauges for all discoverable garbage collectors. */ ++ public GarbageCollectorMetricSet() { ++ this(ManagementFactory.getGarbageCollectorMXBeans()); ++ } + +- /** +- * Creates a new set of gauges for the given collection of garbage collectors. +- * +- * @param garbageCollectors the garbage collectors +- */ +- public GarbageCollectorMetricSet(Collection garbageCollectors) { +- this.garbageCollectors = new ArrayList<>(garbageCollectors); +- } ++ /** ++ * Creates a new set of gauges for the given collection of garbage collectors. ++ * ++ * @param garbageCollectors the garbage collectors ++ */ ++ public GarbageCollectorMetricSet(Collection garbageCollectors) { ++ this.garbageCollectors = new ArrayList<>(garbageCollectors); ++ } + +- @Override +- public Map getMetrics() { +- final Map gauges = new HashMap<>(); +- for (final GarbageCollectorMXBean gc : garbageCollectors) { +- final String name = WHITESPACE.matcher(gc.getName()).replaceAll("-"); +- gauges.put(MetricRegistry.name(name, "count"), (Gauge) gc::getCollectionCount); +- gauges.put(MetricRegistry.name(name, "time"), (Gauge) gc::getCollectionTime); +- } +- return Collections.unmodifiableMap(gauges); ++ @Override ++ public Map getMetrics() { ++ final Map gauges = new HashMap<>(); ++ for (final GarbageCollectorMXBean gc : garbageCollectors) { ++ final String name = WHITESPACE.matcher(gc.getName()).replaceAll("-"); ++ gauges.put(MetricRegistry.name(name, "count"), (Gauge) gc::getCollectionCount); ++ gauges.put(MetricRegistry.name(name, "time"), (Gauge) gc::getCollectionTime); + } ++ return unmodifiableMap(gauges); ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JmxAttributeGauge.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JmxAttributeGauge.java +@@ -1,61 +1,62 @@ + package io.dropwizard.metrics5.jvm; + + import io.dropwizard.metrics5.Gauge; +- +-import javax.management.JMException; +-import javax.management.MBeanServerConnection; +-import javax.management.ObjectName; + import java.io.IOException; + import java.lang.management.ManagementFactory; + import java.util.Set; ++import javax.management.JMException; ++import javax.management.MBeanServerConnection; ++import javax.management.ObjectName; + + /** +- * A {@link Gauge} implementation which queries an {@link MBeanServerConnection} for an attribute of an object. ++ * A {@link Gauge} implementation which queries an {@link MBeanServerConnection} for an attribute of ++ * an object. + */ + public class JmxAttributeGauge implements Gauge { +- private final MBeanServerConnection mBeanServerConn; +- private final ObjectName objectName; +- private final String attributeName; ++ private final MBeanServerConnection mBeanServerConn; ++ private final ObjectName objectName; ++ private final String attributeName; + +- /** +- * Creates a new JmxAttributeGauge. +- * +- * @param objectName the name of the object +- * @param attributeName the name of the object's attribute +- */ +- public JmxAttributeGauge(ObjectName objectName, String attributeName) { +- this(ManagementFactory.getPlatformMBeanServer(), objectName, attributeName); +- } ++ /** ++ * Creates a new JmxAttributeGauge. ++ * ++ * @param objectName the name of the object ++ * @param attributeName the name of the object's attribute ++ */ ++ public JmxAttributeGauge(ObjectName objectName, String attributeName) { ++ this(ManagementFactory.getPlatformMBeanServer(), objectName, attributeName); ++ } + +- /** +- * Creates a new JmxAttributeGauge. +- * +- * @param mBeanServerConn the {@link MBeanServerConnection} +- * @param objectName the name of the object +- * @param attributeName the name of the object's attribute +- */ +- public JmxAttributeGauge(MBeanServerConnection mBeanServerConn, ObjectName objectName, String attributeName) { +- this.mBeanServerConn = mBeanServerConn; +- this.objectName = objectName; +- this.attributeName = attributeName; +- } ++ /** ++ * Creates a new JmxAttributeGauge. ++ * ++ * @param mBeanServerConn the {@link MBeanServerConnection} ++ * @param objectName the name of the object ++ * @param attributeName the name of the object's attribute ++ */ ++ public JmxAttributeGauge( ++ MBeanServerConnection mBeanServerConn, ObjectName objectName, String attributeName) { ++ this.mBeanServerConn = mBeanServerConn; ++ this.objectName = objectName; ++ this.attributeName = attributeName; ++ } + +- @Override +- public Object getValue() { +- try { +- return mBeanServerConn.getAttribute(getObjectName(), attributeName); +- } catch (IOException | JMException e) { +- return null; +- } ++ @Override ++ public Object getValue() { ++ try { ++ return mBeanServerConn.getAttribute(getObjectName(), attributeName); ++ } catch (IOException | JMException e) { ++ return null; + } ++ } + +- private ObjectName getObjectName() throws IOException { +- if (objectName.isPattern()) { +- Set foundNames = mBeanServerConn.queryNames(objectName, null); +- if (foundNames.size() == 1) { +- return foundNames.iterator().next(); +- } +- } +- return objectName; ++ private ObjectName getObjectName() throws IOException { ++ if (objectName.isPattern()) { ++ Set foundNames = mBeanServerConn.queryNames(objectName, null); ++ if (foundNames.size() == 1) { ++ return foundNames.iterator().next(); ++ } + } ++ return objectName; ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java +@@ -1,52 +1,53 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricSet; +- + import java.lang.management.ManagementFactory; + import java.lang.management.RuntimeMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Locale; + import java.util.Map; + +-/** +- * A set of gauges for the JVM name, vendor, and uptime. +- */ ++/** A set of gauges for the JVM name, vendor, and uptime. */ + public class JvmAttributeGaugeSet implements MetricSet { +- private final RuntimeMXBean runtime; +- +- /** +- * Creates a new set of gauges. +- */ +- public JvmAttributeGaugeSet() { +- this(ManagementFactory.getRuntimeMXBean()); +- } +- +- /** +- * Creates a new set of gauges with the given {@link RuntimeMXBean}. +- * +- * @param runtime JVM management interface with access to system properties +- */ +- public JvmAttributeGaugeSet(RuntimeMXBean runtime) { +- this.runtime = runtime; +- } +- +- @Override +- public Map getMetrics() { +- final Map gauges = new HashMap<>(); +- +- gauges.put(MetricName.build("name"), (Gauge) runtime::getName); +- gauges.put(MetricName.build("vendor"), (Gauge) () -> String.format(Locale.US, +- "%s %s %s (%s)", +- runtime.getVmVendor(), +- runtime.getVmName(), +- runtime.getVmVersion(), +- runtime.getSpecVersion())); +- gauges.put(MetricName.build("uptime"), (Gauge) runtime::getUptime); +- +- return Collections.unmodifiableMap(gauges); +- } ++ private final RuntimeMXBean runtime; ++ ++ /** Creates a new set of gauges. */ ++ public JvmAttributeGaugeSet() { ++ this(ManagementFactory.getRuntimeMXBean()); ++ } ++ ++ /** ++ * Creates a new set of gauges with the given {@link RuntimeMXBean}. ++ * ++ * @param runtime JVM management interface with access to system properties ++ */ ++ public JvmAttributeGaugeSet(RuntimeMXBean runtime) { ++ this.runtime = runtime; ++ } ++ ++ @Override ++ public Map getMetrics() { ++ final Map gauges = new HashMap<>(); ++ ++ gauges.put(MetricName.build("name"), (Gauge) runtime::getName); ++ gauges.put( ++ MetricName.build("vendor"), ++ (Gauge) ++ () -> ++ String.format( ++ Locale.US, ++ "%s %s %s (%s)", ++ runtime.getVmVendor(), ++ runtime.getVmName(), ++ runtime.getVmVersion(), ++ runtime.getSpecVersion())); ++ gauges.put(MetricName.build("uptime"), (Gauge) runtime::getUptime); ++ ++ return unmodifiableMap(gauges); ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java +@@ -1,19 +1,19 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricSet; + import io.dropwizard.metrics5.RatioGauge; +- + import java.lang.management.ManagementFactory; + import java.lang.management.MemoryMXBean; + import java.lang.management.MemoryPoolMXBean; + import java.lang.management.MemoryUsage; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -24,83 +24,122 @@ import java.util.regex.Pattern; + * GC-specific memory pools. + */ + public class MemoryUsageGaugeSet implements MetricSet { +- private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); +- +- private final MemoryMXBean mxBean; +- private final List memoryPools; +- +- public MemoryUsageGaugeSet() { +- this(ManagementFactory.getMemoryMXBean(), ManagementFactory.getMemoryPoolMXBeans()); +- } +- +- public MemoryUsageGaugeSet(MemoryMXBean mxBean, +- Collection memoryPools) { +- this.mxBean = mxBean; +- this.memoryPools = new ArrayList<>(memoryPools); +- } ++ private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); ++ ++ private final MemoryMXBean mxBean; ++ private final List memoryPools; ++ ++ public MemoryUsageGaugeSet() { ++ this(ManagementFactory.getMemoryMXBean(), ManagementFactory.getMemoryPoolMXBeans()); ++ } ++ ++ public MemoryUsageGaugeSet(MemoryMXBean mxBean, Collection memoryPools) { ++ this.mxBean = mxBean; ++ this.memoryPools = new ArrayList<>(memoryPools); ++ } ++ ++ @Override ++ public Map getMetrics() { ++ final Map gauges = new HashMap<>(); ++ ++ gauges.put( ++ MetricName.build("total.init"), ++ (Gauge) ++ () -> mxBean.getHeapMemoryUsage().getInit() + mxBean.getNonHeapMemoryUsage().getInit()); ++ gauges.put( ++ MetricName.build("total.used"), ++ (Gauge) ++ () -> mxBean.getHeapMemoryUsage().getUsed() + mxBean.getNonHeapMemoryUsage().getUsed()); ++ gauges.put( ++ MetricName.build("total.max"), ++ (Gauge) ++ () -> ++ mxBean.getNonHeapMemoryUsage().getMax() == -1 ++ ? -1 ++ : mxBean.getHeapMemoryUsage().getMax() ++ + mxBean.getNonHeapMemoryUsage().getMax()); ++ gauges.put( ++ MetricName.build("total.committed"), ++ (Gauge) ++ () -> ++ mxBean.getHeapMemoryUsage().getCommitted() ++ + mxBean.getNonHeapMemoryUsage().getCommitted()); ++ ++ gauges.put( ++ MetricName.build("heap.init"), (Gauge) () -> mxBean.getHeapMemoryUsage().getInit()); ++ gauges.put( ++ MetricName.build("heap.used"), (Gauge) () -> mxBean.getHeapMemoryUsage().getUsed()); ++ gauges.put( ++ MetricName.build("heap.max"), (Gauge) () -> mxBean.getHeapMemoryUsage().getMax()); ++ gauges.put( ++ MetricName.build("heap.committed"), ++ (Gauge) () -> mxBean.getHeapMemoryUsage().getCommitted()); ++ gauges.put( ++ MetricName.build("heap.usage"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ final MemoryUsage usage = mxBean.getHeapMemoryUsage(); ++ return Ratio.of(usage.getUsed(), usage.getMax()); ++ } ++ }); + +- @Override +- public Map getMetrics() { +- final Map gauges = new HashMap<>(); +- +- gauges.put(MetricName.build("total.init"), (Gauge) () -> mxBean.getHeapMemoryUsage().getInit() + +- mxBean.getNonHeapMemoryUsage().getInit()); +- gauges.put(MetricName.build("total.used"), (Gauge) () -> mxBean.getHeapMemoryUsage().getUsed() + +- mxBean.getNonHeapMemoryUsage().getUsed()); +- gauges.put(MetricName.build("total.max"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getMax() == -1 ? +- -1 : mxBean.getHeapMemoryUsage().getMax() + mxBean.getNonHeapMemoryUsage().getMax()); +- gauges.put(MetricName.build("total.committed"), (Gauge) () -> mxBean.getHeapMemoryUsage().getCommitted() + +- mxBean.getNonHeapMemoryUsage().getCommitted()); +- +- gauges.put(MetricName.build("heap.init"), (Gauge) () -> mxBean.getHeapMemoryUsage().getInit()); +- gauges.put(MetricName.build("heap.used"), (Gauge) () -> mxBean.getHeapMemoryUsage().getUsed()); +- gauges.put(MetricName.build("heap.max"), (Gauge) () -> mxBean.getHeapMemoryUsage().getMax()); +- gauges.put(MetricName.build("heap.committed"), (Gauge) () -> mxBean.getHeapMemoryUsage().getCommitted()); +- gauges.put(MetricName.build("heap.usage"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- final MemoryUsage usage = mxBean.getHeapMemoryUsage(); +- return Ratio.of(usage.getUsed(), usage.getMax()); +- } ++ gauges.put( ++ MetricName.build("non-heap.init"), ++ (Gauge) () -> mxBean.getNonHeapMemoryUsage().getInit()); ++ gauges.put( ++ MetricName.build("non-heap.used"), ++ (Gauge) () -> mxBean.getNonHeapMemoryUsage().getUsed()); ++ gauges.put( ++ MetricName.build("non-heap.max"), ++ (Gauge) () -> mxBean.getNonHeapMemoryUsage().getMax()); ++ gauges.put( ++ MetricName.build("non-heap.committed"), ++ (Gauge) () -> mxBean.getNonHeapMemoryUsage().getCommitted()); ++ gauges.put( ++ MetricName.build("non-heap.usage"), ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ final MemoryUsage usage = mxBean.getNonHeapMemoryUsage(); ++ return Ratio.of( ++ usage.getUsed(), usage.getMax() == -1 ? usage.getCommitted() : usage.getMax()); ++ } + }); + +- gauges.put(MetricName.build("non-heap.init"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getInit()); +- gauges.put(MetricName.build("non-heap.used"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getUsed()); +- gauges.put(MetricName.build("non-heap.max"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getMax()); +- gauges.put(MetricName.build("non-heap.committed"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getCommitted()); +- gauges.put(MetricName.build("non-heap.usage"), new RatioGauge() { ++ for (final MemoryPoolMXBean pool : memoryPools) { ++ final String poolName = "pools." + WHITESPACE.matcher(pool.getName()).replaceAll("-"); ++ ++ gauges.put( ++ MetricRegistry.name(poolName, "usage"), ++ new RatioGauge() { + @Override + protected Ratio getRatio() { +- final MemoryUsage usage = mxBean.getNonHeapMemoryUsage(); +- return Ratio.of(usage.getUsed(), usage.getMax() == -1 ? usage.getCommitted() : usage.getMax()); ++ MemoryUsage usage = pool.getUsage(); ++ return Ratio.of( ++ usage.getUsed(), usage.getMax() == -1 ? usage.getCommitted() : usage.getMax()); + } +- }); +- +- for (final MemoryPoolMXBean pool : memoryPools) { +- final String poolName = "pools." + WHITESPACE.matcher(pool.getName()).replaceAll("-"); +- +- gauges.put(MetricRegistry.name(poolName, "usage"), new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- MemoryUsage usage = pool.getUsage(); +- return Ratio.of(usage.getUsed(), +- usage.getMax() == -1 ? usage.getCommitted() : usage.getMax()); +- } +- }); +- +- gauges.put(MetricRegistry.name(poolName, "max"), (Gauge) () -> pool.getUsage().getMax()); +- gauges.put(MetricRegistry.name(poolName, "used"), (Gauge) () -> pool.getUsage().getUsed()); +- gauges.put(MetricRegistry.name(poolName, "committed"), (Gauge) () -> pool.getUsage().getCommitted()); +- +- // Only register GC usage metrics if the memory pool supports usage statistics. +- if (pool.getCollectionUsage() != null) { +- gauges.put(MetricRegistry.name(poolName, "used-after-gc"), (Gauge) () -> +- pool.getCollectionUsage().getUsed()); +- } +- +- gauges.put(MetricRegistry.name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); +- } +- +- return Collections.unmodifiableMap(gauges); ++ }); ++ ++ gauges.put( ++ MetricRegistry.name(poolName, "max"), (Gauge) () -> pool.getUsage().getMax()); ++ gauges.put( ++ MetricRegistry.name(poolName, "used"), (Gauge) () -> pool.getUsage().getUsed()); ++ gauges.put( ++ MetricRegistry.name(poolName, "committed"), ++ (Gauge) () -> pool.getUsage().getCommitted()); ++ ++ // Only register GC usage metrics if the memory pool supports usage statistics. ++ if (pool.getCollectionUsage() != null) { ++ gauges.put( ++ MetricRegistry.name(poolName, "used-after-gc"), ++ (Gauge) () -> pool.getCollectionUsage().getUsed()); ++ } ++ ++ gauges.put( ++ MetricRegistry.name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); + } ++ ++ return unmodifiableMap(gauges); ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java +@@ -1,65 +1,57 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableSet; ++ ++import com.google.common.collect.ImmutableSet; + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashSet; + import java.util.Set; + +-/** +- * A utility class for detecting deadlocked threads. +- */ ++/** A utility class for detecting deadlocked threads. */ + public class ThreadDeadlockDetector { +- private static final int MAX_STACK_TRACE_DEPTH = 100; ++ private static final int MAX_STACK_TRACE_DEPTH = 100; + +- private final ThreadMXBean threads; ++ private final ThreadMXBean threads; + +- /** +- * Creates a new detector. +- */ +- public ThreadDeadlockDetector() { +- this(ManagementFactory.getThreadMXBean()); +- } ++ /** Creates a new detector. */ ++ public ThreadDeadlockDetector() { ++ this(ManagementFactory.getThreadMXBean()); ++ } + +- /** +- * Creates a new detector using the given {@link ThreadMXBean}. +- * +- * @param threads a {@link ThreadMXBean} +- */ +- public ThreadDeadlockDetector(ThreadMXBean threads) { +- this.threads = threads; +- } ++ /** ++ * Creates a new detector using the given {@link ThreadMXBean}. ++ * ++ * @param threads a {@link ThreadMXBean} ++ */ ++ public ThreadDeadlockDetector(ThreadMXBean threads) { ++ this.threads = threads; ++ } + +- /** +- * Returns a set of diagnostic stack traces for any deadlocked threads. If no threads are +- * deadlocked, returns an empty set. +- * +- * @return stack traces for deadlocked threads or an empty set +- */ +- public Set getDeadlockedThreads() { +- final long[] ids = threads.findDeadlockedThreads(); +- if (ids != null) { +- final Set deadlocks = new HashSet<>(); +- for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { +- final StringBuilder stackTrace = new StringBuilder(); +- for (StackTraceElement element : info.getStackTrace()) { +- stackTrace.append("\t at ") +- .append(element.toString()) +- .append(String.format("%n")); +- } +- +- deadlocks.add( +- String.format("%s locked on %s (owned by %s):%n%s", +- info.getThreadName(), +- info.getLockName(), +- info.getLockOwnerName(), +- stackTrace.toString() +- ) +- ); +- } +- return Collections.unmodifiableSet(deadlocks); ++ /** ++ * Returns a set of diagnostic stack traces for any deadlocked threads. If no threads are ++ * deadlocked, returns an empty set. ++ * ++ * @return stack traces for deadlocked threads or an empty set ++ */ ++ public Set getDeadlockedThreads() { ++ final long[] ids = threads.findDeadlockedThreads(); ++ if (ids != null) { ++ final Set deadlocks = new HashSet<>(); ++ for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { ++ final StringBuilder stackTrace = new StringBuilder(); ++ for (StackTraceElement element : info.getStackTrace()) { ++ stackTrace.append("\t at ").append(element).append(String.format("%n")); + } +- return Collections.emptySet(); ++ ++ deadlocks.add( ++ String.format( ++ "%s locked on %s (owned by %s):%n%s", ++ info.getThreadName(), info.getLockName(), info.getLockOwnerName(), stackTrace)); ++ } ++ return unmodifiableSet(deadlocks); + } ++ return ImmutableSet.of(); ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDump.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDump.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.nio.charset.StandardCharsets.UTF_8; ++ + import java.io.OutputStream; + import java.io.OutputStreamWriter; + import java.io.PrintWriter; +@@ -8,106 +10,98 @@ import java.lang.management.MonitorInfo; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; + +-import static java.nio.charset.StandardCharsets.UTF_8; +- +- +-/** +- * A convenience class for getting a thread dump. +- */ ++/** A convenience class for getting a thread dump. */ + public class ThreadDump { + +- private final ThreadMXBean threadMXBean; +- +- public ThreadDump(ThreadMXBean threadMXBean) { +- this.threadMXBean = threadMXBean; +- } +- +- /** +- * Dumps all of the threads' current information, including synchronization, to an output stream. +- * +- * @param out an output stream +- */ +- public void dump(OutputStream out) { +- dump(true, true, out); +- } +- +- /** +- * Dumps all of the threads' current information, optionally including synchronization, to an output stream. +- * +- * Having control over including synchronization info allows using this method (and its wrappers, i.e. +- * ThreadDumpServlet) in environments where getting object monitor and/or ownable synchronizer usage is not +- * supported. It can also speed things up. +- * +- * See {@link ThreadMXBean#dumpAllThreads(boolean, boolean)} +- * +- * @param lockedMonitors dump all locked monitors if true +- * @param lockedSynchronizers dump all locked ownable synchronizers if true +- * @param out an output stream +- */ +- public void dump(boolean lockedMonitors, boolean lockedSynchronizers, OutputStream out) { +- final ThreadInfo[] threads = this.threadMXBean.dumpAllThreads(lockedMonitors, lockedSynchronizers); +- final PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, UTF_8)); +- +- for (int ti = threads.length - 1; ti >= 0; ti--) { +- final ThreadInfo t = threads[ti]; +- writer.printf("\"%s\" id=%d state=%s", +- t.getThreadName(), +- t.getThreadId(), +- t.getThreadState()); +- final LockInfo lock = t.getLockInfo(); +- if (lock != null && t.getThreadState() != Thread.State.BLOCKED) { +- writer.printf("%n - waiting on <0x%08x> (a %s)", +- lock.getIdentityHashCode(), +- lock.getClassName()); +- writer.printf("%n - locked <0x%08x> (a %s)", +- lock.getIdentityHashCode(), +- lock.getClassName()); +- } else if (lock != null && t.getThreadState() == Thread.State.BLOCKED) { +- writer.printf("%n - waiting to lock <0x%08x> (a %s)", +- lock.getIdentityHashCode(), +- lock.getClassName()); +- } +- +- if (t.isSuspended()) { +- writer.print(" (suspended)"); +- } +- +- if (t.isInNative()) { +- writer.print(" (running in native)"); +- } +- +- writer.println(); +- if (t.getLockOwnerName() != null) { +- writer.printf(" owned by %s id=%d%n", t.getLockOwnerName(), t.getLockOwnerId()); +- } +- +- final StackTraceElement[] elements = t.getStackTrace(); +- final MonitorInfo[] monitors = t.getLockedMonitors(); +- +- for (int i = 0; i < elements.length; i++) { +- final StackTraceElement element = elements[i]; +- writer.printf(" at %s%n", element); +- for (int j = 1; j < monitors.length; j++) { +- final MonitorInfo monitor = monitors[j]; +- if (monitor.getLockedStackDepth() == i) { +- writer.printf(" - locked %s%n", monitor); +- } +- } +- } +- writer.println(); +- +- final LockInfo[] locks = t.getLockedSynchronizers(); +- if (locks.length > 0) { +- writer.printf(" Locked synchronizers: count = %d%n", locks.length); +- for (LockInfo l : locks) { +- writer.printf(" - %s%n", l); +- } +- writer.println(); +- } ++ private final ThreadMXBean threadMXBean; ++ ++ public ThreadDump(ThreadMXBean threadMXBean) { ++ this.threadMXBean = threadMXBean; ++ } ++ ++ /** ++ * Dumps all of the threads' current information, including synchronization, to an output stream. ++ * ++ * @param out an output stream ++ */ ++ public void dump(OutputStream out) { ++ dump(true, true, out); ++ } ++ ++ /** ++ * Dumps all of the threads' current information, optionally including synchronization, to an ++ * output stream. ++ * ++ *

    Having control over including synchronization info allows using this method (and its ++ * wrappers, i.e. ThreadDumpServlet) in environments where getting object monitor and/or ownable ++ * synchronizer usage is not supported. It can also speed things up. ++ * ++ *

    See {@link ThreadMXBean#dumpAllThreads(boolean, boolean)} ++ * ++ * @param lockedMonitors dump all locked monitors if true ++ * @param lockedSynchronizers dump all locked ownable synchronizers if true ++ * @param out an output stream ++ */ ++ public void dump(boolean lockedMonitors, boolean lockedSynchronizers, OutputStream out) { ++ final ThreadInfo[] threads = ++ this.threadMXBean.dumpAllThreads(lockedMonitors, lockedSynchronizers); ++ final PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, UTF_8)); ++ ++ for (int ti = threads.length - 1; ti >= 0; ti--) { ++ final ThreadInfo t = threads[ti]; ++ writer.printf( ++ "\"%s\" id=%d state=%s", t.getThreadName(), t.getThreadId(), t.getThreadState()); ++ final LockInfo lock = t.getLockInfo(); ++ if (lock != null && t.getThreadState() != Thread.State.BLOCKED) { ++ writer.printf( ++ "%n - waiting on <0x%08x> (a %s)", lock.getIdentityHashCode(), lock.getClassName()); ++ writer.printf( ++ "%n - locked <0x%08x> (a %s)", lock.getIdentityHashCode(), lock.getClassName()); ++ } else if (lock != null && t.getThreadState() == Thread.State.BLOCKED) { ++ writer.printf( ++ "%n - waiting to lock <0x%08x> (a %s)", ++ lock.getIdentityHashCode(), lock.getClassName()); ++ } ++ ++ if (t.isSuspended()) { ++ writer.print(" (suspended)"); ++ } ++ ++ if (t.isInNative()) { ++ writer.print(" (running in native)"); ++ } ++ ++ writer.println(); ++ if (t.getLockOwnerName() != null) { ++ writer.printf(" owned by %s id=%d%n", t.getLockOwnerName(), t.getLockOwnerId()); ++ } ++ ++ final StackTraceElement[] elements = t.getStackTrace(); ++ final MonitorInfo[] monitors = t.getLockedMonitors(); ++ ++ for (int i = 0; i < elements.length; i++) { ++ final StackTraceElement element = elements[i]; ++ writer.printf(" at %s%n", element); ++ for (int j = 1; j < monitors.length; j++) { ++ final MonitorInfo monitor = monitors[j]; ++ if (monitor.getLockedStackDepth() == i) { ++ writer.printf(" - locked %s%n", monitor); ++ } ++ } ++ } ++ writer.println(); ++ ++ final LockInfo[] locks = t.getLockedSynchronizers(); ++ if (locks.length > 0) { ++ writer.printf(" Locked synchronizers: count = %d%n", locks.length); ++ for (LockInfo l : locks) { ++ writer.printf(" - %s%n", l); + } +- + writer.println(); +- writer.flush(); ++ } + } + ++ writer.println(); ++ writer.flush(); ++ } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java +@@ -1,81 +1,80 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricSet; +- + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + import java.util.Set; + +-/** +- * A set of gauges for the number of threads in their various states and deadlock detection. +- */ ++/** A set of gauges for the number of threads in their various states and deadlock detection. */ + public class ThreadStatesGaugeSet implements MetricSet { + +- // do not compute stack traces. +- private final static int STACK_TRACE_DEPTH = 0; +- +- private final ThreadMXBean threads; +- private final ThreadDeadlockDetector deadlockDetector; +- +- /** +- * Creates a new set of gauges using the default MXBeans. +- */ +- public ThreadStatesGaugeSet() { +- this(ManagementFactory.getThreadMXBean(), new ThreadDeadlockDetector()); +- } ++ // do not compute stack traces. ++ private static final int STACK_TRACE_DEPTH = 0; + +- /** +- * Creates a new set of gauges using the given MXBean and detector. +- * +- * @param threads a thread MXBean +- * @param deadlockDetector a deadlock detector +- */ +- public ThreadStatesGaugeSet(ThreadMXBean threads, +- ThreadDeadlockDetector deadlockDetector) { +- this.threads = threads; +- this.deadlockDetector = deadlockDetector; +- } ++ private final ThreadMXBean threads; ++ private final ThreadDeadlockDetector deadlockDetector; + +- @Override +- public Map getMetrics() { +- final Map gauges = new HashMap<>(); ++ /** Creates a new set of gauges using the default MXBeans. */ ++ public ThreadStatesGaugeSet() { ++ this(ManagementFactory.getThreadMXBean(), new ThreadDeadlockDetector()); ++ } + +- for (final Thread.State state : Thread.State.values()) { +- gauges.put(MetricRegistry.name(state.toString().toLowerCase(), "count"), +- (Gauge) () -> getThreadCount(state)); +- } ++ /** ++ * Creates a new set of gauges using the given MXBean and detector. ++ * ++ * @param threads a thread MXBean ++ * @param deadlockDetector a deadlock detector ++ */ ++ public ThreadStatesGaugeSet(ThreadMXBean threads, ThreadDeadlockDetector deadlockDetector) { ++ this.threads = threads; ++ this.deadlockDetector = deadlockDetector; ++ } + +- gauges.put(MetricName.build("count"), (Gauge) threads::getThreadCount); +- gauges.put(MetricName.build("daemon.count"), (Gauge) threads::getDaemonThreadCount); +- gauges.put(MetricName.build("peak.count"), (Gauge) threads::getPeakThreadCount); +- gauges.put(MetricName.build("total_started.count"), (Gauge) threads::getTotalStartedThreadCount); +- gauges.put(MetricName.build("deadlock.count"), (Gauge) () -> deadlockDetector.getDeadlockedThreads().size()); +- gauges.put(MetricName.build("deadlocks"), (Gauge>) deadlockDetector::getDeadlockedThreads); ++ @Override ++ public Map getMetrics() { ++ final Map gauges = new HashMap<>(); + +- return Collections.unmodifiableMap(gauges); ++ for (final Thread.State state : Thread.State.values()) { ++ gauges.put( ++ MetricRegistry.name(state.toString().toLowerCase(), "count"), ++ (Gauge) () -> getThreadCount(state)); + } + +- private int getThreadCount(Thread.State state) { +- final ThreadInfo[] allThreads = getThreadInfo(); +- int count = 0; +- for (ThreadInfo info : allThreads) { +- if (info != null && info.getThreadState() == state) { +- count++; +- } +- } +- return count; +- } ++ gauges.put(MetricName.build("count"), (Gauge) threads::getThreadCount); ++ gauges.put(MetricName.build("daemon.count"), (Gauge) threads::getDaemonThreadCount); ++ gauges.put(MetricName.build("peak.count"), (Gauge) threads::getPeakThreadCount); ++ gauges.put( ++ MetricName.build("total_started.count"), (Gauge) threads::getTotalStartedThreadCount); ++ gauges.put( ++ MetricName.build("deadlock.count"), ++ (Gauge) () -> deadlockDetector.getDeadlockedThreads().size()); ++ gauges.put( ++ MetricName.build("deadlocks"), (Gauge>) deadlockDetector::getDeadlockedThreads); ++ ++ return unmodifiableMap(gauges); ++ } + +- ThreadInfo[] getThreadInfo() { +- return threads.getThreadInfo(threads.getAllThreadIds(), STACK_TRACE_DEPTH); ++ private int getThreadCount(Thread.State state) { ++ final ThreadInfo[] allThreads = getThreadInfo(); ++ int count = 0; ++ for (ThreadInfo info : allThreads) { ++ if (info != null && info.getThreadState() == state) { ++ count++; ++ } + } ++ return count; ++ } + ++ ThreadInfo[] getThreadInfo() { ++ return threads.getThreadInfo(threads.getAllThreadIds(), STACK_TRACE_DEPTH); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java +@@ -1,121 +1,107 @@ + package io.dropwizard.metrics5.jvm; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricName; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- + import javax.management.InstanceNotFoundException; + import javax.management.MBeanServer; + import javax.management.ObjectName; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("rawtypes") +-class BufferPoolMetricSetTest { +- +- private static final MetricName DIRECT = MetricName.build("direct"); +- private static final MetricName MAPPED = MetricName.build("mapped"); +- private static final MetricName DIRECT_COUNT = DIRECT.resolve("count"); +- private static final MetricName DIRECT_CAPACITY = DIRECT.resolve("capacity"); +- private static final MetricName DIRECT_USED = DIRECT.resolve("used"); +- private static final MetricName MAPPED_COUNT = MAPPED.resolve("count"); +- private static final MetricName MAPPED_CAPACITY = MAPPED.resolve("capacity"); +- private static final MetricName MAPPED_USED = MAPPED.resolve("used"); ++final class BufferPoolMetricSetTest { + +- private final MBeanServer mBeanServer = mock(MBeanServer.class); +- private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); ++ private static final MetricName DIRECT = MetricName.build("direct"); ++ private static final MetricName MAPPED = MetricName.build("mapped"); ++ private static final MetricName DIRECT_COUNT = DIRECT.resolve("count"); ++ private static final MetricName DIRECT_CAPACITY = DIRECT.resolve("capacity"); ++ private static final MetricName DIRECT_USED = DIRECT.resolve("used"); ++ private static final MetricName MAPPED_COUNT = MAPPED.resolve("count"); ++ private static final MetricName MAPPED_CAPACITY = MAPPED.resolve("capacity"); ++ private static final MetricName MAPPED_USED = MAPPED.resolve("used"); + +- private ObjectName mapped; +- private ObjectName direct; ++ private final MBeanServer mBeanServer = mock(); ++ private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); + +- @BeforeEach +- void setUp() throws Exception { +- this.mapped = new ObjectName("java.nio:type=BufferPool,name=mapped"); +- this.direct = new ObjectName("java.nio:type=BufferPool,name=direct"); ++ private ObjectName mapped; ++ private ObjectName direct; + +- } ++ @BeforeEach ++ void setUp() throws Exception { ++ this.mapped = new ObjectName("java.nio:type=BufferPool,name=mapped"); ++ this.direct = new ObjectName("java.nio:type=BufferPool,name=direct"); ++ } + +- @Test +- void includesGaugesForDirectAndMappedPools() { +- assertThat(buffers.getMetrics().keySet()) +- .containsOnly(DIRECT_COUNT, +- DIRECT_USED, +- DIRECT_CAPACITY, +- MAPPED_COUNT, +- MAPPED_USED, +- MAPPED_CAPACITY); +- } ++ @Test ++ void includesGaugesForDirectAndMappedPools() { ++ assertThat(buffers.getMetrics().keySet()) ++ .containsOnly( ++ DIRECT_COUNT, DIRECT_USED, DIRECT_CAPACITY, MAPPED_COUNT, MAPPED_USED, MAPPED_CAPACITY); ++ } + +- @Test +- void ignoresGaugesForObjectsWhichCannotBeFound() throws Exception { +- when(mBeanServer.getMBeanInfo(mapped)).thenThrow(new InstanceNotFoundException()); ++ @Test ++ void ignoresGaugesForObjectsWhichCannotBeFound() throws Exception { ++ when(mBeanServer.getMBeanInfo(mapped)).thenThrow(new InstanceNotFoundException()); + +- assertThat(buffers.getMetrics().keySet()) +- .containsOnly(DIRECT_COUNT, +- DIRECT_USED, +- DIRECT_CAPACITY); +- } ++ assertThat(buffers.getMetrics().keySet()) ++ .containsOnly(DIRECT_COUNT, DIRECT_USED, DIRECT_CAPACITY); ++ } + +- @Test +- void includesAGaugeForDirectCount() throws Exception { +- final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_COUNT); ++ @Test ++ void includesAGaugeForDirectCount() throws Exception { ++ final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_COUNT); + +- when(mBeanServer.getAttribute(direct, "Count")).thenReturn(100); ++ when(mBeanServer.getAttribute(direct, "Count")).thenReturn(100); + +- assertThat(gauge.getValue()) +- .isEqualTo(100); +- } ++ assertThat(gauge.getValue()).isEqualTo(100); ++ } + +- @Test +- void includesAGaugeForDirectMemoryUsed() throws Exception { +- final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_USED); ++ @Test ++ void includesAGaugeForDirectMemoryUsed() throws Exception { ++ final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_USED); + +- when(mBeanServer.getAttribute(direct, "MemoryUsed")).thenReturn(100); ++ when(mBeanServer.getAttribute(direct, "MemoryUsed")).thenReturn(100); + +- assertThat(gauge.getValue()) +- .isEqualTo(100); +- } ++ assertThat(gauge.getValue()).isEqualTo(100); ++ } + +- @Test +- void includesAGaugeForDirectCapacity() throws Exception { +- final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_CAPACITY); ++ @Test ++ void includesAGaugeForDirectCapacity() throws Exception { ++ final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_CAPACITY); + +- when(mBeanServer.getAttribute(direct, "TotalCapacity")).thenReturn(100); ++ when(mBeanServer.getAttribute(direct, "TotalCapacity")).thenReturn(100); + +- assertThat(gauge.getValue()) +- .isEqualTo(100); +- } ++ assertThat(gauge.getValue()).isEqualTo(100); ++ } + +- @Test +- void includesAGaugeForMappedCount() throws Exception { +- final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_COUNT); ++ @Test ++ void includesAGaugeForMappedCount() throws Exception { ++ final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_COUNT); + +- when(mBeanServer.getAttribute(mapped, "Count")).thenReturn(100); ++ when(mBeanServer.getAttribute(mapped, "Count")).thenReturn(100); + +- assertThat(gauge.getValue()) +- .isEqualTo(100); +- } ++ assertThat(gauge.getValue()).isEqualTo(100); ++ } + +- @Test +- void includesAGaugeForMappedMemoryUsed() throws Exception { +- final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_USED); ++ @Test ++ void includesAGaugeForMappedMemoryUsed() throws Exception { ++ final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_USED); + +- when(mBeanServer.getAttribute(mapped, "MemoryUsed")).thenReturn(100); ++ when(mBeanServer.getAttribute(mapped, "MemoryUsed")).thenReturn(100); + +- assertThat(gauge.getValue()) +- .isEqualTo(100); +- } ++ assertThat(gauge.getValue()).isEqualTo(100); ++ } + +- @Test +- void includesAGaugeForMappedCapacity() throws Exception { +- final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_CAPACITY); ++ @Test ++ void includesAGaugeForMappedCapacity() throws Exception { ++ final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_CAPACITY); + +- when(mBeanServer.getAttribute(mapped, "TotalCapacity")).thenReturn(100); ++ when(mBeanServer.getAttribute(mapped, "TotalCapacity")).thenReturn(100); + +- assertThat(gauge.getValue()) +- .isEqualTo(100); +- } ++ assertThat(gauge.getValue()).isEqualTo(100); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java +@@ -1,38 +1,36 @@ + package io.dropwizard.metrics5.jvm; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricName; ++import java.lang.management.ClassLoadingMXBean; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.lang.management.ClassLoadingMXBean; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- + @SuppressWarnings("rawtypes") +-class ClassLoadingGaugeSetTest { +- +- private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); +- private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); +- +- @BeforeEach +- void setUp() { +- when(cl.getTotalLoadedClassCount()).thenReturn(2L); +- when(cl.getUnloadedClassCount()).thenReturn(1L); +- } +- +- @Test +- void loadedGauge() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("loaded")); +- assertThat(gauge.getValue()).isEqualTo(2L); +- } +- +- @Test +- void unLoadedGauge() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("unloaded")); +- assertThat(gauge.getValue()).isEqualTo(1L); +- } +- ++final class ClassLoadingGaugeSetTest { ++ ++ private final ClassLoadingMXBean cl = mock(); ++ private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); ++ ++ @BeforeEach ++ void setUp() { ++ when(cl.getTotalLoadedClassCount()).thenReturn(2L); ++ when(cl.getUnloadedClassCount()).thenReturn(1L); ++ } ++ ++ @Test ++ void loadedGauge() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("loaded")); ++ assertThat(gauge.getValue()).isEqualTo(2L); ++ } ++ ++ @Test ++ void unLoadedGauge() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("unloaded")); ++ assertThat(gauge.getValue()).isEqualTo(1L); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java +@@ -1,24 +1,23 @@ + package io.dropwizard.metrics5.jvm; + +-import org.junit.jupiter.api.Test; +- +-import java.lang.management.ManagementFactory; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.offset; + +-class CpuTimeClockTest { ++import java.lang.management.ManagementFactory; ++import org.junit.jupiter.api.Test; ++ ++final class CpuTimeClockTest { + +- @Test +- void cpuTimeClock() { +- final CpuTimeClock clock = new CpuTimeClock(); ++ @Test ++ void cpuTimeClock() { ++ final CpuTimeClock clock = new CpuTimeClock(); + +- final long clockTime = clock.getTime(); +- final long systemTime = System.currentTimeMillis(); +- assertThat((double) clockTime).isEqualTo(systemTime, offset(200.0)); ++ final long clockTime = clock.getTime(); ++ final long systemTime = System.currentTimeMillis(); ++ assertThat((double) clockTime).isCloseTo(systemTime, offset(200.0)); + +- final long clockTick = clock.getTick(); +- final long systemTick = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(); +- assertThat((double) clockTick).isEqualTo(systemTick, offset(1000000.0)); +- } +-} +\ No newline at end of file ++ final long clockTick = clock.getTick(); ++ final long systemTick = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(); ++ assertThat((double) clockTick).isCloseTo(systemTick, offset(1000000.0)); ++ } ++} +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java +@@ -1,48 +1,43 @@ + package io.dropwizard.metrics5.jvm; + +-import com.sun.management.UnixOperatingSystemMXBean; +-import org.assertj.core.api.Assertions; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import java.lang.management.ManagementFactory; +-import java.lang.management.OperatingSystemMXBean; +- ++import static org.assertj.core.api.Assertions.assertThat; + import static org.junit.jupiter.api.Assumptions.assumeTrue; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + ++import com.sun.management.UnixOperatingSystemMXBean; ++import java.lang.management.ManagementFactory; ++import java.lang.management.OperatingSystemMXBean; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; ++ + @SuppressWarnings("UnusedDeclaration") +-class FileDescriptorRatioGaugeTest { +- private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); +- +- private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); +- +- @BeforeEach +- void setUp() throws Exception { +- when(os.getOpenFileDescriptorCount()).thenReturn(10L); +- when(os.getMaxFileDescriptorCount()).thenReturn(100L); +- } +- +- @Test +- void calculatesTheRatioOfUsedToTotalFileDescriptors() { +- Assertions.assertThat(gauge.getValue()) +- .isEqualTo(0.1); +- } +- +- @Test +- void validateFileDescriptorRatioPresenceOnNixPlatforms() { +- OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); +- assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); +- +- Assertions.assertThat(new FileDescriptorRatioGauge().getValue()) +- .isGreaterThanOrEqualTo(0.0) +- .isLessThanOrEqualTo(1.0); +- } +- +- @Test +- void returnsNaNWhenTheInformationIsUnavailable() { +- Assertions.assertThat(new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()) +- .isNaN(); +- } ++final class FileDescriptorRatioGaugeTest { ++ private final UnixOperatingSystemMXBean os = mock(); ++ ++ private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ when(os.getOpenFileDescriptorCount()).thenReturn(10L); ++ when(os.getMaxFileDescriptorCount()).thenReturn(100L); ++ } ++ ++ @Test ++ void calculatesTheRatioOfUsedToTotalFileDescriptors() { ++ assertThat(gauge.getValue()).isEqualTo(0.1); ++ } ++ ++ @Test ++ void validateFileDescriptorRatioPresenceOnNixPlatforms() { ++ OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); ++ assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); ++ ++ assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative().isLessThanOrEqualTo(1.0); ++ } ++ ++ @Test ++ void returnsNaNWhenTheInformationIsUnavailable() { ++ assertThat(new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()).isNaN(); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java +@@ -1,55 +1,51 @@ + package io.dropwizard.metrics5.jvm; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ ++import com.google.common.collect.ImmutableList; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricName; ++import java.lang.management.GarbageCollectorMXBean; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.lang.management.GarbageCollectorMXBean; +-import java.util.Collections; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- + @SuppressWarnings("unchecked") +-class GarbageCollectorMetricSetTest { +- private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); +- private final GarbageCollectorMetricSet metrics = new GarbageCollectorMetricSet(Collections.singletonList(gc)); +- +- private static final MetricName PS_OLDGEN_TIME = MetricName.build("PS-OldGen.time"); +- private static final MetricName PS_OLDGEN_COUNT = MetricName.build("PS-OldGen.count"); +- +- @BeforeEach +- void setUp() { +- when(gc.getName()).thenReturn("PS OldGen"); +- when(gc.getCollectionCount()).thenReturn(1L); +- when(gc.getCollectionTime()).thenReturn(2L); +- } +- +- @Test +- void hasGaugesForGcCountsAndElapsedTimes() { +- assertThat(metrics.getMetrics().keySet()) +- .containsOnly(PS_OLDGEN_TIME, PS_OLDGEN_COUNT); +- } +- +- @Test +- void hasAGaugeForGcCounts() { +- final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_COUNT); +- assertThat(gauge.getValue()) +- .isEqualTo(1L); +- } +- +- @Test +- void hasAGaugeForGcTimes() { +- final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_TIME); +- assertThat(gauge.getValue()) +- .isEqualTo(2L); +- } +- +- @Test +- void autoDiscoversGCs() { +- assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()) +- .isNotEmpty(); +- } ++final class GarbageCollectorMetricSetTest { ++ private final GarbageCollectorMXBean gc = mock(); ++ private final GarbageCollectorMetricSet metrics = ++ new GarbageCollectorMetricSet(ImmutableList.of(gc)); ++ ++ private static final MetricName PS_OLDGEN_TIME = MetricName.build("PS-OldGen.time"); ++ private static final MetricName PS_OLDGEN_COUNT = MetricName.build("PS-OldGen.count"); ++ ++ @BeforeEach ++ void setUp() { ++ when(gc.getName()).thenReturn("PS OldGen"); ++ when(gc.getCollectionCount()).thenReturn(1L); ++ when(gc.getCollectionTime()).thenReturn(2L); ++ } ++ ++ @Test ++ void hasGaugesForGcCountsAndElapsedTimes() { ++ assertThat(metrics.getMetrics().keySet()).containsOnly(PS_OLDGEN_TIME, PS_OLDGEN_COUNT); ++ } ++ ++ @Test ++ void hasAGaugeForGcCounts() { ++ final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_COUNT); ++ assertThat(gauge.getValue()).isEqualTo(1L); ++ } ++ ++ @Test ++ void hasAGaugeForGcTimes() { ++ final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_TIME); ++ assertThat(gauge.getValue()).isEqualTo(2L); ++ } ++ ++ @Test ++ void autoDiscoversGCs() { ++ assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty(); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java +@@ -5,95 +5,92 @@ import static org.assertj.core.api.Assertions.assertThat; + import java.lang.management.ManagementFactory; + import java.util.ArrayList; + import java.util.List; +- + import javax.management.JMException; + import javax.management.MBeanServer; + import javax.management.ObjectInstance; + import javax.management.ObjectName; +- + import org.junit.jupiter.api.AfterAll; + import org.junit.jupiter.api.BeforeAll; + import org.junit.jupiter.api.Test; + +-class JmxAttributeGaugeTest { +- +- private static MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); +- +- private static List registeredMBeans = new ArrayList<>(); +- +- public interface JmxTestMBean { +- Long getValue(); +- } +- +- private static class JmxTest implements JmxTestMBean { +- @Override +- public Long getValue() { +- return Long.MAX_VALUE; +- } +- } +- +- @BeforeAll +- static void setUp() throws Exception { +- registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test1")); +- registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test2")); +- } +- +- @AfterAll +- static void tearDown() { +- for (ObjectName objectName : registeredMBeans) { +- try { +- mBeanServer.unregisterMBean(objectName); +- } catch (Exception e) { +- // ignore +- } +- } +- } +- +- @Test +- void returnsJmxAttribute() throws Exception { +- ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); +- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); +- +- assertThat(gauge.getValue()).isInstanceOf(Integer.class); +- assertThat((Integer) gauge.getValue()).isGreaterThan(0); +- } +- +- @Test +- void returnsNullIfAttributeDoesNotExist() throws Exception { +- ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); +- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "DoesNotExist"); +- +- assertThat(gauge.getValue()).isNull(); +- } +- +- @Test +- void returnsNullIfMBeanNotFound() throws Exception { +- ObjectName objectName = new ObjectName("foo.bar:type=NoSuchMBean"); +- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); +- +- assertThat(gauge.getValue()).isNull(); +- } ++final class JmxAttributeGaugeTest { + +- @Test +- void returnsAttributeForObjectNamePattern() throws Exception { +- ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:name=test1,*"); +- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); ++ private static MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + +- assertThat(gauge.getValue()).isInstanceOf(Long.class); +- assertThat((Long) gauge.getValue()).isEqualTo(Long.MAX_VALUE); +- } ++ private static List registeredMBeans = new ArrayList<>(); + +- @Test +- void returnsNullIfObjectNamePatternAmbiguous() throws Exception { +- ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:type=test,*"); +- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); ++ public interface JmxTestMBean { ++ Long getValue(); ++ } + +- assertThat(gauge.getValue()).isNull(); ++ private static class JmxTest implements JmxTestMBean { ++ @Override ++ public Long getValue() { ++ return Long.MAX_VALUE; + } +- +- private static void registerMBean(ObjectName objectName) throws JMException { +- ObjectInstance objectInstance = mBeanServer.registerMBean(new JmxTest(), objectName); +- registeredMBeans.add(objectInstance.getObjectName()); ++ } ++ ++ @BeforeAll ++ static void setUp() throws Exception { ++ registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test1")); ++ registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test2")); ++ } ++ ++ @AfterAll ++ static void tearDown() { ++ for (ObjectName objectName : registeredMBeans) { ++ try { ++ mBeanServer.unregisterMBean(objectName); ++ } catch (Exception e) { ++ // ignore ++ } + } +- ++ } ++ ++ @Test ++ void returnsJmxAttribute() throws Exception { ++ ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); ++ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); ++ ++ assertThat(gauge.getValue()).isInstanceOf(Integer.class); ++ assertThat((Integer) gauge.getValue()).isPositive(); ++ } ++ ++ @Test ++ void returnsNullIfAttributeDoesNotExist() throws Exception { ++ ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); ++ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "DoesNotExist"); ++ ++ assertThat(gauge.getValue()).isNull(); ++ } ++ ++ @Test ++ void returnsNullIfMBeanNotFound() throws Exception { ++ ObjectName objectName = new ObjectName("foo.bar:type=NoSuchMBean"); ++ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); ++ ++ assertThat(gauge.getValue()).isNull(); ++ } ++ ++ @Test ++ void returnsAttributeForObjectNamePattern() throws Exception { ++ ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:name=test1,*"); ++ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); ++ ++ assertThat(gauge.getValue()).isInstanceOf(Long.class); ++ assertThat((Long) gauge.getValue()).isEqualTo(Long.MAX_VALUE); ++ } ++ ++ @Test ++ void returnsNullIfObjectNamePatternAmbiguous() throws Exception { ++ ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:type=test,*"); ++ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); ++ ++ assertThat(gauge.getValue()).isNull(); ++ } ++ ++ private static void registerMBean(ObjectName objectName) throws JMException { ++ ObjectInstance objectInstance = mBeanServer.registerMBean(new JmxTest(), objectName); ++ registeredMBeans.add(objectInstance.getObjectName()); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java +@@ -1,68 +1,65 @@ + package io.dropwizard.metrics5.jvm; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricName; ++import java.lang.management.RuntimeMXBean; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.lang.management.RuntimeMXBean; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- + @SuppressWarnings("unchecked") +-class JvmAttributeGaugeSetTest { +- private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); +- private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); ++final class JvmAttributeGaugeSetTest { ++ private final RuntimeMXBean runtime = mock(); ++ private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); + +- @BeforeEach +- void setUp() { +- when(runtime.getName()).thenReturn("9928@example.com"); ++ @BeforeEach ++ void setUp() { ++ when(runtime.getName()).thenReturn("9928@example.com"); + +- when(runtime.getVmVendor()).thenReturn("Oracle Corporation"); +- when(runtime.getVmName()).thenReturn("Java HotSpot(TM) 64-Bit Server VM"); +- when(runtime.getVmVersion()).thenReturn("23.7-b01"); +- when(runtime.getSpecVersion()).thenReturn("1.7"); +- when(runtime.getUptime()).thenReturn(100L); +- } ++ when(runtime.getVmVendor()).thenReturn("Oracle Corporation"); ++ when(runtime.getVmName()).thenReturn("Java HotSpot(TM) 64-Bit Server VM"); ++ when(runtime.getVmVersion()).thenReturn("23.7-b01"); ++ when(runtime.getSpecVersion()).thenReturn("1.7"); ++ when(runtime.getUptime()).thenReturn(100L); ++ } + +- @Test +- void hasASetOfGauges() { +- assertThat(gauges.getMetrics().keySet()) +- .containsOnly(MetricName.build("vendor"), +- MetricName.build("name"), +- MetricName.build("uptime")); +- } ++ @Test ++ void hasASetOfGauges() { ++ assertThat(gauges.getMetrics().keySet()) ++ .containsOnly( ++ MetricName.build("vendor"), MetricName.build("name"), MetricName.build("uptime")); ++ } + +- @Test +- void hasAGaugeForTheJVMName() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("name")); ++ @Test ++ void hasAGaugeForTheJVMName() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("name")); + +- assertThat(gauge.getValue()) +- .isEqualTo("9928@example.com"); +- } ++ assertThat(gauge.getValue()).isEqualTo("9928@example.com"); ++ } + +- @Test +- void hasAGaugeForTheJVMVendor() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("vendor")); ++ @Test ++ void hasAGaugeForTheJVMVendor() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("vendor")); + +- assertThat(gauge.getValue()) +- .isEqualTo("Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 23.7-b01 (1.7)"); +- } ++ assertThat(gauge.getValue()) ++ .isEqualTo("Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 23.7-b01 (1.7)"); ++ } + +- @Test +- void hasAGaugeForTheJVMUptime() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("uptime")); ++ @Test ++ void hasAGaugeForTheJVMUptime() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("uptime")); + +- assertThat(gauge.getValue()) +- .isEqualTo(100L); +- } ++ assertThat(gauge.getValue()).isEqualTo(100L); ++ } + +- @Test +- void autoDiscoversTheRuntimeBean() { +- final Gauge gauge = (Gauge) new JvmAttributeGaugeSet().getMetrics().get(MetricName.build("uptime")); ++ @Test ++ void autoDiscoversTheRuntimeBean() { ++ final Gauge gauge = ++ (Gauge) new JvmAttributeGaugeSet().getMetrics().get(MetricName.build("uptime")); + +- assertThat(gauge.getValue()).isPositive(); +- } ++ assertThat(gauge.getValue()).isPositive(); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java +@@ -1,325 +1,301 @@ + package io.dropwizard.metrics5.jvm; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricName; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- + import java.lang.management.MemoryMXBean; + import java.lang.management.MemoryPoolMXBean; + import java.lang.management.MemoryUsage; + import java.util.Arrays; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("rawtypes") +-class MemoryUsageGaugeSetTest { +- private final MemoryUsage heap = mock(MemoryUsage.class); +- private final MemoryUsage nonHeap = mock(MemoryUsage.class); +- private final MemoryUsage pool = mock(MemoryUsage.class); +- private final MemoryUsage weirdPool = mock(MemoryUsage.class); +- private final MemoryUsage weirdCollection = mock(MemoryUsage.class); +- private final MemoryMXBean mxBean = mock(MemoryMXBean.class); +- private final MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); +- private final MemoryPoolMXBean weirdMemoryPool = mock(MemoryPoolMXBean.class); +- +- private final MemoryUsageGaugeSet gauges = new MemoryUsageGaugeSet(mxBean, +- Arrays.asList(memoryPool, +- weirdMemoryPool)); +- +- private static final MetricName TOTAL = MetricName.build("total"); +- private static final MetricName HEAP = MetricName.build("heap"); +- private static final MetricName NON_HEAP = MetricName.build("non-heap"); +- private static final MetricName POOLS = MetricName.build("pools"); +- +- private static final MetricName TOTAL_MAX = TOTAL.resolve("max"); +- private static final MetricName TOTAL_INIT = TOTAL.resolve("init"); +- private static final MetricName TOTAL_USED = TOTAL.resolve("used"); +- private static final MetricName TOTAL_COMMITTED = TOTAL.resolve("committed"); +- private static final MetricName POOLS_BIG_POOL_USAGE = POOLS.resolve("Big-Pool.usage"); +- private static final MetricName POOLS_BIG_POOL_USED = POOLS.resolve("Big-Pool.used"); +- private static final MetricName POOLS_BIG_POOL_INIT = POOLS.resolve("Big-Pool.init"); +- private static final MetricName POOLS_BIG_POOL_COMMITED = POOLS.resolve("Big-Pool.committed"); +- private static final MetricName POOLS_BIG_POOL_MAX = POOLS.resolve("Big-Pool.max"); +- private static final MetricName POOLS_WEIRD_POOL_USAGE = POOLS.resolve("Weird-Pool.usage"); +- private static final MetricName POOLS_WEIRD_POOL_INIT = POOLS.resolve("Weird-Pool.init"); +- private static final MetricName POOLS_WEIRD_POOL_MAX = POOLS.resolve("Weird-Pool.max"); +- private static final MetricName POOLS_WEIRD_POOL_USED = POOLS.resolve("Weird-Pool.used"); +- private static final MetricName POOLS_WEIRD_POOL_USED_AFTER_GC = POOLS.resolve("Weird-Pool.used-after-gc"); +- private static final MetricName POOLS_WEIRD_POOL_COMMITTED = POOLS.resolve("Weird-Pool.committed"); +- private static final MetricName HEAP_INIT = HEAP.resolve("init"); +- private static final MetricName HEAP_COMMITTED = HEAP.resolve("committed"); +- private static final MetricName HEAP_USAGE = HEAP.resolve("usage"); +- private static final MetricName HEAP_USED = HEAP.resolve("used"); +- private static final MetricName HEAP_MAX = HEAP.resolve("max"); +- private static final MetricName NON_HEAP_USAGE = NON_HEAP.resolve("usage"); +- private static final MetricName NON_HEAP_MAX = NON_HEAP.resolve("max"); +- private static final MetricName NON_HEAP_USED = NON_HEAP.resolve("used"); +- private static final MetricName NON_HEAP_INIT = NON_HEAP.resolve("init"); +- private static final MetricName NON_HEAP_COMMITTED = NON_HEAP.resolve("committed"); +- +- @BeforeEach +- void setUp() { +- when(heap.getCommitted()).thenReturn(10L); +- when(heap.getInit()).thenReturn(20L); +- when(heap.getUsed()).thenReturn(30L); +- when(heap.getMax()).thenReturn(40L); +- +- when(nonHeap.getCommitted()).thenReturn(1L); +- when(nonHeap.getInit()).thenReturn(2L); +- when(nonHeap.getUsed()).thenReturn(3L); +- when(nonHeap.getMax()).thenReturn(4L); +- +- when(pool.getCommitted()).thenReturn(100L); +- when(pool.getInit()).thenReturn(200L); +- when(pool.getUsed()).thenReturn(300L); +- when(pool.getMax()).thenReturn(400L); +- +- when(weirdPool.getCommitted()).thenReturn(100L); +- when(weirdPool.getInit()).thenReturn(200L); +- when(weirdPool.getUsed()).thenReturn(300L); +- when(weirdPool.getMax()).thenReturn(-1L); +- +- when(weirdCollection.getUsed()).thenReturn(290L); +- +- when(mxBean.getHeapMemoryUsage()).thenReturn(heap); +- when(mxBean.getNonHeapMemoryUsage()).thenReturn(nonHeap); +- +- when(memoryPool.getUsage()).thenReturn(pool); +- // Mock that "Big Pool" is a non-collected pool therefore doesn't +- // have collection usage statistics. +- when(memoryPool.getCollectionUsage()).thenReturn(null); +- when(memoryPool.getName()).thenReturn("Big Pool"); +- +- when(weirdMemoryPool.getUsage()).thenReturn(weirdPool); +- when(weirdMemoryPool.getCollectionUsage()).thenReturn(weirdCollection); +- when(weirdMemoryPool.getName()).thenReturn("Weird Pool"); +- } +- +- @Test +- void hasASetOfGauges() { +- assertThat(gauges.getMetrics().keySet()) +- .containsOnly( +- TOTAL_MAX, +- TOTAL_INIT, +- TOTAL_USED, +- TOTAL_COMMITTED, +- HEAP_INIT, +- HEAP_COMMITTED, +- HEAP_USAGE, +- HEAP_USED, +- HEAP_MAX, +- NON_HEAP_USAGE, +- NON_HEAP_MAX, +- NON_HEAP_USED, +- NON_HEAP_INIT, +- NON_HEAP_COMMITTED, +- POOLS_BIG_POOL_INIT, +- POOLS_BIG_POOL_COMMITED, +- POOLS_BIG_POOL_USED, +- POOLS_BIG_POOL_USAGE, +- POOLS_BIG_POOL_MAX, +- // skip in non-collected pools - "pools.Big-Pool.used-after-gc", +- POOLS_WEIRD_POOL_USAGE, +- POOLS_WEIRD_POOL_USED, +- POOLS_WEIRD_POOL_INIT, +- POOLS_WEIRD_POOL_MAX, +- POOLS_WEIRD_POOL_COMMITTED, +- POOLS_WEIRD_POOL_USED_AFTER_GC); +- } +- +- @Test +- void hasAGaugeForTotalCommitted() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_COMMITTED); +- +- assertThat(gauge.getValue()) +- .isEqualTo(11L); +- } +- +- @Test +- void hasAGaugeForTotalInit() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_INIT); +- +- assertThat(gauge.getValue()) +- .isEqualTo(22L); +- } +- +- @Test +- void hasAGaugeForTotalUsed() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_USED); +- +- assertThat(gauge.getValue()) +- .isEqualTo(33L); +- } +- +- @Test +- void hasAGaugeForTotalMax() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); +- +- assertThat(gauge.getValue()) +- .isEqualTo(44L); +- } +- +- @Test +- public void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { +- when(nonHeap.getMax()).thenReturn(-1L); +- +- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); +- +- assertThat(gauge.getValue()) +- .isEqualTo(-1L); +- } +- +- @Test +- void hasAGaugeForHeapCommitted() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_COMMITTED); +- +- assertThat(gauge.getValue()) +- .isEqualTo(10L); +- } +- +- @Test +- void hasAGaugeForHeapInit() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_INIT); +- +- assertThat(gauge.getValue()) +- .isEqualTo(20L); +- } +- +- @Test +- void hasAGaugeForHeapUsed() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USED); +- +- assertThat(gauge.getValue()) +- .isEqualTo(30L); +- } +- +- @Test +- void hasAGaugeForHeapMax() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_MAX); +- +- assertThat(gauge.getValue()) +- .isEqualTo(40L); +- } +- +- @Test +- void hasAGaugeForHeapUsage() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USAGE); +- +- assertThat(gauge.getValue()) +- .isEqualTo(0.75); +- } +- +- @Test +- void hasAGaugeForNonHeapCommitted() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_COMMITTED); +- +- assertThat(gauge.getValue()) +- .isEqualTo(1L); +- } +- +- @Test +- void hasAGaugeForNonHeapInit() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_INIT); +- +- assertThat(gauge.getValue()) +- .isEqualTo(2L); +- } ++final class MemoryUsageGaugeSetTest { ++ private final MemoryUsage heap = mock(); ++ private final MemoryUsage nonHeap = mock(); ++ private final MemoryUsage pool = mock(); ++ private final MemoryUsage weirdPool = mock(); ++ private final MemoryUsage weirdCollection = mock(); ++ private final MemoryMXBean mxBean = mock(); ++ private final MemoryPoolMXBean memoryPool = mock(); ++ private final MemoryPoolMXBean weirdMemoryPool = mock(); ++ ++ private final MemoryUsageGaugeSet gauges = ++ new MemoryUsageGaugeSet(mxBean, Arrays.asList(memoryPool, weirdMemoryPool)); ++ ++ private static final MetricName TOTAL = MetricName.build("total"); ++ private static final MetricName HEAP = MetricName.build("heap"); ++ private static final MetricName NON_HEAP = MetricName.build("non-heap"); ++ private static final MetricName POOLS = MetricName.build("pools"); ++ ++ private static final MetricName TOTAL_MAX = TOTAL.resolve("max"); ++ private static final MetricName TOTAL_INIT = TOTAL.resolve("init"); ++ private static final MetricName TOTAL_USED = TOTAL.resolve("used"); ++ private static final MetricName TOTAL_COMMITTED = TOTAL.resolve("committed"); ++ private static final MetricName POOLS_BIG_POOL_USAGE = POOLS.resolve("Big-Pool.usage"); ++ private static final MetricName POOLS_BIG_POOL_USED = POOLS.resolve("Big-Pool.used"); ++ private static final MetricName POOLS_BIG_POOL_INIT = POOLS.resolve("Big-Pool.init"); ++ private static final MetricName POOLS_BIG_POOL_COMMITED = POOLS.resolve("Big-Pool.committed"); ++ private static final MetricName POOLS_BIG_POOL_MAX = POOLS.resolve("Big-Pool.max"); ++ private static final MetricName POOLS_WEIRD_POOL_USAGE = POOLS.resolve("Weird-Pool.usage"); ++ private static final MetricName POOLS_WEIRD_POOL_INIT = POOLS.resolve("Weird-Pool.init"); ++ private static final MetricName POOLS_WEIRD_POOL_MAX = POOLS.resolve("Weird-Pool.max"); ++ private static final MetricName POOLS_WEIRD_POOL_USED = POOLS.resolve("Weird-Pool.used"); ++ private static final MetricName POOLS_WEIRD_POOL_USED_AFTER_GC = ++ POOLS.resolve("Weird-Pool.used-after-gc"); ++ private static final MetricName POOLS_WEIRD_POOL_COMMITTED = ++ POOLS.resolve("Weird-Pool.committed"); ++ private static final MetricName HEAP_INIT = HEAP.resolve("init"); ++ private static final MetricName HEAP_COMMITTED = HEAP.resolve("committed"); ++ private static final MetricName HEAP_USAGE = HEAP.resolve("usage"); ++ private static final MetricName HEAP_USED = HEAP.resolve("used"); ++ private static final MetricName HEAP_MAX = HEAP.resolve("max"); ++ private static final MetricName NON_HEAP_USAGE = NON_HEAP.resolve("usage"); ++ private static final MetricName NON_HEAP_MAX = NON_HEAP.resolve("max"); ++ private static final MetricName NON_HEAP_USED = NON_HEAP.resolve("used"); ++ private static final MetricName NON_HEAP_INIT = NON_HEAP.resolve("init"); ++ private static final MetricName NON_HEAP_COMMITTED = NON_HEAP.resolve("committed"); ++ ++ @BeforeEach ++ void setUp() { ++ when(heap.getCommitted()).thenReturn(10L); ++ when(heap.getInit()).thenReturn(20L); ++ when(heap.getUsed()).thenReturn(30L); ++ when(heap.getMax()).thenReturn(40L); ++ ++ when(nonHeap.getCommitted()).thenReturn(1L); ++ when(nonHeap.getInit()).thenReturn(2L); ++ when(nonHeap.getUsed()).thenReturn(3L); ++ when(nonHeap.getMax()).thenReturn(4L); ++ ++ when(pool.getCommitted()).thenReturn(100L); ++ when(pool.getInit()).thenReturn(200L); ++ when(pool.getUsed()).thenReturn(300L); ++ when(pool.getMax()).thenReturn(400L); ++ ++ when(weirdPool.getCommitted()).thenReturn(100L); ++ when(weirdPool.getInit()).thenReturn(200L); ++ when(weirdPool.getUsed()).thenReturn(300L); ++ when(weirdPool.getMax()).thenReturn(-1L); ++ ++ when(weirdCollection.getUsed()).thenReturn(290L); ++ ++ when(mxBean.getHeapMemoryUsage()).thenReturn(heap); ++ when(mxBean.getNonHeapMemoryUsage()).thenReturn(nonHeap); ++ ++ when(memoryPool.getUsage()).thenReturn(pool); ++ // Mock that "Big Pool" is a non-collected pool therefore doesn't ++ // have collection usage statistics. ++ when(memoryPool.getCollectionUsage()).thenReturn(null); ++ when(memoryPool.getName()).thenReturn("Big Pool"); ++ ++ when(weirdMemoryPool.getUsage()).thenReturn(weirdPool); ++ when(weirdMemoryPool.getCollectionUsage()).thenReturn(weirdCollection); ++ when(weirdMemoryPool.getName()).thenReturn("Weird Pool"); ++ } ++ ++ @Test ++ void hasASetOfGauges() { ++ assertThat(gauges.getMetrics().keySet()) ++ .containsOnly( ++ TOTAL_MAX, ++ TOTAL_INIT, ++ TOTAL_USED, ++ TOTAL_COMMITTED, ++ HEAP_INIT, ++ HEAP_COMMITTED, ++ HEAP_USAGE, ++ HEAP_USED, ++ HEAP_MAX, ++ NON_HEAP_USAGE, ++ NON_HEAP_MAX, ++ NON_HEAP_USED, ++ NON_HEAP_INIT, ++ NON_HEAP_COMMITTED, ++ POOLS_BIG_POOL_INIT, ++ POOLS_BIG_POOL_COMMITED, ++ POOLS_BIG_POOL_USED, ++ POOLS_BIG_POOL_USAGE, ++ POOLS_BIG_POOL_MAX, ++ // skip in non-collected pools - "pools.Big-Pool.used-after-gc", ++ POOLS_WEIRD_POOL_USAGE, ++ POOLS_WEIRD_POOL_USED, ++ POOLS_WEIRD_POOL_INIT, ++ POOLS_WEIRD_POOL_MAX, ++ POOLS_WEIRD_POOL_COMMITTED, ++ POOLS_WEIRD_POOL_USED_AFTER_GC); ++ } ++ ++ @Test ++ void hasAGaugeForTotalCommitted() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_COMMITTED); ++ ++ assertThat(gauge.getValue()).isEqualTo(11L); ++ } ++ ++ @Test ++ void hasAGaugeForTotalInit() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_INIT); ++ ++ assertThat(gauge.getValue()).isEqualTo(22L); ++ } ++ ++ @Test ++ void hasAGaugeForTotalUsed() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_USED); ++ ++ assertThat(gauge.getValue()).isEqualTo(33L); ++ } ++ ++ @Test ++ void hasAGaugeForTotalMax() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); ++ ++ assertThat(gauge.getValue()).isEqualTo(44L); ++ } ++ ++ @Test ++ void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { ++ when(nonHeap.getMax()).thenReturn(-1L); ++ ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); ++ ++ assertThat(gauge.getValue()).isEqualTo(-1L); ++ } ++ ++ @Test ++ void hasAGaugeForHeapCommitted() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_COMMITTED); ++ ++ assertThat(gauge.getValue()).isEqualTo(10L); ++ } ++ ++ @Test ++ void hasAGaugeForHeapInit() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_INIT); ++ ++ assertThat(gauge.getValue()).isEqualTo(20L); ++ } ++ ++ @Test ++ void hasAGaugeForHeapUsed() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USED); ++ ++ assertThat(gauge.getValue()).isEqualTo(30L); ++ } ++ ++ @Test ++ void hasAGaugeForHeapMax() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_MAX); ++ ++ assertThat(gauge.getValue()).isEqualTo(40L); ++ } ++ ++ @Test ++ void hasAGaugeForHeapUsage() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USAGE); ++ ++ assertThat(gauge.getValue()).isEqualTo(0.75); ++ } ++ ++ @Test ++ void hasAGaugeForNonHeapCommitted() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_COMMITTED); ++ ++ assertThat(gauge.getValue()).isEqualTo(1L); ++ } ++ ++ @Test ++ void hasAGaugeForNonHeapInit() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_INIT); ++ ++ assertThat(gauge.getValue()).isEqualTo(2L); ++ } ++ ++ @Test ++ void hasAGaugeForNonHeapUsed() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USED); ++ ++ assertThat(gauge.getValue()).isEqualTo(3L); ++ } ++ ++ @Test ++ void hasAGaugeForNonHeapMax() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_MAX); ++ ++ assertThat(gauge.getValue()).isEqualTo(4L); ++ } ++ ++ @Test ++ void hasAGaugeForNonHeapUsage() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); ++ ++ assertThat(gauge.getValue()).isEqualTo(0.75); ++ } ++ ++ @Test ++ void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { ++ when(nonHeap.getMax()).thenReturn(-1L); ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); ++ ++ assertThat(gauge.getValue()).isEqualTo(3.0); ++ } ++ ++ @Test ++ void hasAGaugeForMemoryPoolUsage() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_BIG_POOL_USAGE); ++ ++ assertThat(gauge.getValue()).isEqualTo(0.75); ++ } ++ ++ @Test ++ void hasAGaugeForWeirdMemoryPoolInit() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_INIT); ++ ++ assertThat(gauge.getValue()).isEqualTo(200L); ++ } ++ ++ @Test ++ void hasAGaugeForWeirdMemoryPoolCommitted() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_COMMITTED); + +- @Test +- void hasAGaugeForNonHeapUsed() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USED); ++ assertThat(gauge.getValue()).isEqualTo(100L); ++ } + +- assertThat(gauge.getValue()) +- .isEqualTo(3L); +- } ++ @Test ++ void hasAGaugeForWeirdMemoryPoolUsed() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED); + +- @Test +- void hasAGaugeForNonHeapMax() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_MAX); ++ assertThat(gauge.getValue()).isEqualTo(300L); ++ } + +- assertThat(gauge.getValue()) +- .isEqualTo(4L); +- } ++ @Test ++ void hasAGaugeForWeirdMemoryPoolUsage() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USAGE); + +- @Test +- void hasAGaugeForNonHeapUsage() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); ++ assertThat(gauge.getValue()).isEqualTo(3.0); ++ } + +- assertThat(gauge.getValue()) +- .isEqualTo(0.75); +- } ++ @Test ++ void hasAGaugeForWeirdMemoryPoolMax() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_MAX); + +- @Test +- public void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { +- when(nonHeap.getMax()).thenReturn(-1L); +- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); ++ assertThat(gauge.getValue()).isEqualTo(-1L); ++ } + +- assertThat(gauge.getValue()) +- .isEqualTo(3.0); +- } ++ @Test ++ void hasAGaugeForWeirdCollectionPoolUsed() { ++ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED_AFTER_GC); + +- @Test +- void hasAGaugeForMemoryPoolUsage() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_BIG_POOL_USAGE); ++ assertThat(gauge.getValue()).isEqualTo(290L); ++ } + +- assertThat(gauge.getValue()) +- .isEqualTo(0.75); +- } +- +- @Test +- void hasAGaugeForWeirdMemoryPoolInit() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_INIT); +- +- assertThat(gauge.getValue()) +- .isEqualTo(200L); +- } +- +- @Test +- void hasAGaugeForWeirdMemoryPoolCommitted() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_COMMITTED); +- +- assertThat(gauge.getValue()) +- .isEqualTo(100L); +- } +- +- @Test +- void hasAGaugeForWeirdMemoryPoolUsed() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED); +- +- assertThat(gauge.getValue()) +- .isEqualTo(300L); +- } +- +- @Test +- void hasAGaugeForWeirdMemoryPoolUsage() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USAGE); +- +- assertThat(gauge.getValue()) +- .isEqualTo(3.0); +- } +- +- @Test +- void hasAGaugeForWeirdMemoryPoolMax() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_MAX); +- +- assertThat(gauge.getValue()) +- .isEqualTo(-1L); +- } +- +- @Test +- void hasAGaugeForWeirdCollectionPoolUsed() { +- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED_AFTER_GC); +- +- assertThat(gauge.getValue()) +- .isEqualTo(290L); +- } +- +- @Test +- void autoDetectsMemoryUsageBeanAndMemoryPools() { +- assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()) +- .isNotEmpty(); +- } ++ @Test ++ void autoDetectsMemoryUsageBeanAndMemoryPools() { ++ assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty(); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java +@@ -1,68 +1,71 @@ + package io.dropwizard.metrics5.jvm; + +-import org.junit.jupiter.api.Test; +- +-import java.lang.management.ThreadInfo; +-import java.lang.management.ThreadMXBean; +-import java.util.Locale; +- + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.ArgumentMatchers.anyInt; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + +-class ThreadDeadlockDetectorTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); +- private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); ++import java.lang.management.ThreadInfo; ++import java.lang.management.ThreadMXBean; ++import java.util.Locale; ++import org.junit.jupiter.api.Test; ++ ++final class ThreadDeadlockDetectorTest { ++ private final ThreadMXBean threads = mock(); ++ private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); + +- @Test +- void returnsAnEmptySetIfNoThreadsAreDeadlocked() { +- when(threads.findDeadlockedThreads()).thenReturn(null); ++ @Test ++ void returnsAnEmptySetIfNoThreadsAreDeadlocked() { ++ when(threads.findDeadlockedThreads()).thenReturn(null); + +- assertThat(detector.getDeadlockedThreads()) +- .isEmpty(); +- } ++ assertThat(detector.getDeadlockedThreads()).isEmpty(); ++ } + +- @Test +- void returnsASetOfThreadsIfAnyAreDeadlocked() { +- final ThreadInfo thread1 = mock(ThreadInfo.class); +- when(thread1.getThreadName()).thenReturn("thread1"); +- when(thread1.getLockName()).thenReturn("lock2"); +- when(thread1.getLockOwnerName()).thenReturn("thread2"); +- when(thread1.getStackTrace()).thenReturn(new StackTraceElement[]{ +- new StackTraceElement("Blah", "bloo", "Blah.java", 150), +- new StackTraceElement("Blah", "blee", "Blah.java", 100) +- }); ++ @Test ++ void returnsASetOfThreadsIfAnyAreDeadlocked() { ++ final ThreadInfo thread1 = mock(); ++ when(thread1.getThreadName()).thenReturn("thread1"); ++ when(thread1.getLockName()).thenReturn("lock2"); ++ when(thread1.getLockOwnerName()).thenReturn("thread2"); ++ when(thread1.getStackTrace()) ++ .thenReturn( ++ new StackTraceElement[] { ++ new StackTraceElement("Blah", "bloo", "Blah.java", 150), ++ new StackTraceElement("Blah", "blee", "Blah.java", 100) ++ }); + +- final ThreadInfo thread2 = mock(ThreadInfo.class); +- when(thread2.getThreadName()).thenReturn("thread2"); +- when(thread2.getLockName()).thenReturn("lock1"); +- when(thread2.getLockOwnerName()).thenReturn("thread1"); +- when(thread2.getStackTrace()).thenReturn(new StackTraceElement[]{ +- new StackTraceElement("Blah", "blee", "Blah.java", 100), +- new StackTraceElement("Blah", "bloo", "Blah.java", 150) +- }); ++ final ThreadInfo thread2 = mock(); ++ when(thread2.getThreadName()).thenReturn("thread2"); ++ when(thread2.getLockName()).thenReturn("lock1"); ++ when(thread2.getLockOwnerName()).thenReturn("thread1"); ++ when(thread2.getStackTrace()) ++ .thenReturn( ++ new StackTraceElement[] { ++ new StackTraceElement("Blah", "blee", "Blah.java", 100), ++ new StackTraceElement("Blah", "bloo", "Blah.java", 150) ++ }); + +- final long[] ids = {1, 2}; +- when(threads.findDeadlockedThreads()).thenReturn(ids); +- when(threads.getThreadInfo(eq(ids), anyInt())) +- .thenReturn(new ThreadInfo[]{thread1, thread2}); ++ final long[] ids = {1, 2}; ++ when(threads.findDeadlockedThreads()).thenReturn(ids); ++ when(threads.getThreadInfo(eq(ids), anyInt())).thenReturn(new ThreadInfo[] {thread1, thread2}); + +- assertThat(detector.getDeadlockedThreads()) +- .containsOnly(String.format(Locale.US, +- "thread1 locked on lock2 (owned by thread2):%n" + +- "\t at Blah.bloo(Blah.java:150)%n" + +- "\t at Blah.blee(Blah.java:100)%n"), +- String.format(Locale.US, +- "thread2 locked on lock1 (owned by thread1):%n" + +- "\t at Blah.blee(Blah.java:100)%n" + +- "\t at Blah.bloo(Blah.java:150)%n")); +- } ++ assertThat(detector.getDeadlockedThreads()) ++ .containsOnly( ++ String.format( ++ Locale.US, ++ "thread1 locked on lock2 (owned by thread2):%n" ++ + "\t at Blah.bloo(Blah.java:150)%n" ++ + "\t at Blah.blee(Blah.java:100)%n"), ++ String.format( ++ Locale.US, ++ "thread2 locked on lock1 (owned by thread1):%n" ++ + "\t at Blah.blee(Blah.java:100)%n" ++ + "\t at Blah.bloo(Blah.java:150)%n")); ++ } + +- @Test +- void autoDiscoversTheThreadMXBean() { +- assertThat(new ThreadDeadlockDetector().getDeadlockedThreads()) +- .isNotNull(); +- } ++ @Test ++ void autoDiscoversTheThreadMXBean() { ++ assertThat(new ThreadDeadlockDetector().getDeadlockedThreads()).isNotNull(); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java +@@ -1,51 +1,50 @@ + package io.dropwizard.metrics5.jvm; + +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; + + import java.io.ByteArrayOutputStream; + import java.lang.management.LockInfo; + import java.lang.management.MonitorInfo; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + + // TODO: 3/12/13 -- improve test coverage for ThreadDump + +-class ThreadDumpTest { +- private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); +- private final ThreadDump threadDump = new ThreadDump(threadMXBean); +- +- private final ThreadInfo runnable = mock(ThreadInfo.class); +- +- @BeforeEach +- void setUp() { +- final StackTraceElement rLine1 = new StackTraceElement("Blah", "blee", "Blah.java", 100); +- +- when(runnable.getThreadName()).thenReturn("runnable"); +- when(runnable.getThreadId()).thenReturn(100L); +- when(runnable.getThreadState()).thenReturn(Thread.State.RUNNABLE); +- when(runnable.getStackTrace()).thenReturn(new StackTraceElement[]{rLine1}); +- when(runnable.getLockedMonitors()).thenReturn(new MonitorInfo[]{}); +- when(runnable.getLockedSynchronizers()).thenReturn(new LockInfo[]{}); +- +- when(threadMXBean.dumpAllThreads(true, true)).thenReturn(new ThreadInfo[]{ +- runnable +- }); +- } +- +- @Test +- void dumpsAllThreads() { +- final ByteArrayOutputStream output = new ByteArrayOutputStream(); +- threadDump.dump(output); +- +- assertThat(output.toString()) +- .isEqualTo(String.format("\"runnable\" id=100 state=RUNNABLE%n" + +- " at Blah.blee(Blah.java:100)%n" + +- "%n" + +- "%n")); +- } ++final class ThreadDumpTest { ++ private final ThreadMXBean threadMXBean = mock(); ++ private final ThreadDump threadDump = new ThreadDump(threadMXBean); ++ ++ private final ThreadInfo runnable = mock(); ++ ++ @BeforeEach ++ void setUp() { ++ final StackTraceElement rLine1 = new StackTraceElement("Blah", "blee", "Blah.java", 100); ++ ++ when(runnable.getThreadName()).thenReturn("runnable"); ++ when(runnable.getThreadId()).thenReturn(100L); ++ when(runnable.getThreadState()).thenReturn(Thread.State.RUNNABLE); ++ when(runnable.getStackTrace()).thenReturn(new StackTraceElement[] {rLine1}); ++ when(runnable.getLockedMonitors()).thenReturn(new MonitorInfo[] {}); ++ when(runnable.getLockedSynchronizers()).thenReturn(new LockInfo[] {}); ++ ++ when(threadMXBean.dumpAllThreads(true, true)).thenReturn(new ThreadInfo[] {runnable}); ++ } ++ ++ @Test ++ void dumpsAllThreads() { ++ final ByteArrayOutputStream output = new ByteArrayOutputStream(); ++ threadDump.dump(output); ++ ++ assertThat(output) ++ .hasToString( ++ String.format( ++ "\"runnable\" id=100 state=RUNNABLE%n" ++ + " at Blah.blee(Blah.java:100)%n" ++ + "%n" ++ + "%n")); ++ } + } +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java +@@ -1,151 +1,142 @@ + package io.dropwizard.metrics5.jvm; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricName; +-import org.assertj.core.api.Assertions; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; + import java.util.HashSet; + import java.util.Set; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-class ThreadStatesGaugeSetTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); +- private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); +- private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); +- private final long[] ids = new long[]{1, 2, 3}; +- +- private final ThreadInfo newThread = mock(ThreadInfo.class); +- private final ThreadInfo runnableThread = mock(ThreadInfo.class); +- private final ThreadInfo blockedThread = mock(ThreadInfo.class); +- private final ThreadInfo waitingThread = mock(ThreadInfo.class); +- private final ThreadInfo timedWaitingThread = mock(ThreadInfo.class); +- private final ThreadInfo terminatedThread = mock(ThreadInfo.class); +- +- private final Set deadlocks = new HashSet<>(); +- +- private static final MetricName TERMINATED_COUNT = MetricName.build("terminated.count"); +- private static final MetricName NEW_COUNT = MetricName.build("new.count"); +- private static final MetricName COUNT = MetricName.build("count"); +- private static final MetricName TIMED_WAITING_COUNT = MetricName.build("timed_waiting.count"); +- private static final MetricName DEADLOCKS = MetricName.build("deadlocks"); +- private static final MetricName BLOCKED_COUNT = MetricName.build("blocked.count"); +- private static final MetricName WAITING_COUNT = MetricName.build("waiting.count"); +- private static final MetricName DAEMON_COUNT = MetricName.build("daemon.count"); +- private static final MetricName RUNNABLE_COUNT = MetricName.build("runnable.count"); +- private static final MetricName DEADLOCK_COUNT = MetricName.build("deadlock.count"); +- +- @BeforeEach +- void setUp() { +- deadlocks.add("yay"); +- +- when(newThread.getThreadState()).thenReturn(Thread.State.NEW); +- when(runnableThread.getThreadState()).thenReturn(Thread.State.RUNNABLE); +- when(blockedThread.getThreadState()).thenReturn(Thread.State.BLOCKED); +- when(waitingThread.getThreadState()).thenReturn(Thread.State.WAITING); +- when(timedWaitingThread.getThreadState()).thenReturn(Thread.State.TIMED_WAITING); +- when(terminatedThread.getThreadState()).thenReturn(Thread.State.TERMINATED); +- +- when(threads.getAllThreadIds()).thenReturn(ids); +- when(threads.getThreadInfo(ids, 0)).thenReturn(new ThreadInfo[]{ +- newThread, runnableThread, blockedThread, +- waitingThread, timedWaitingThread, terminatedThread +- }); +- +- when(threads.getThreadCount()).thenReturn(12); +- when(threads.getDaemonThreadCount()).thenReturn(10); +- when(threads.getPeakThreadCount()).thenReturn(30); +- when(threads.getTotalStartedThreadCount()).thenReturn(42L); +- +- when(detector.getDeadlockedThreads()).thenReturn(deadlocks); +- } +- +- @Test +- void hasASetOfGauges() { +- assertThat(gauges.getMetrics().keySet()) +- .containsOnly(TERMINATED_COUNT, +- NEW_COUNT, +- COUNT, +- TIMED_WAITING_COUNT, +- DEADLOCKS, +- BLOCKED_COUNT, +- WAITING_COUNT, +- DAEMON_COUNT, +- RUNNABLE_COUNT, +- DEADLOCK_COUNT, +- MetricName.build("total_started.count"), +- MetricName.build("peak.count")); +- } +- +- @Test +- void hasAGaugeForEachThreadState() { +- Assertions.assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()) +- .isEqualTo(1); +- +- assertThat(((Gauge) gauges.getMetrics().get(RUNNABLE_COUNT)).getValue()) +- .isEqualTo(1); +- +- assertThat(((Gauge) gauges.getMetrics().get(BLOCKED_COUNT)).getValue()) +- .isEqualTo(1); +- +- assertThat(((Gauge) gauges.getMetrics().get(WAITING_COUNT)).getValue()) +- .isEqualTo(1); +- +- assertThat(((Gauge) gauges.getMetrics().get(TIMED_WAITING_COUNT)).getValue()) +- .isEqualTo(1); +- +- assertThat(((Gauge) gauges.getMetrics().get(TERMINATED_COUNT)).getValue()) +- .isEqualTo(1); +- } +- +- @Test +- void hasAGaugeForTheNumberOfThreads() { +- assertThat(((Gauge) gauges.getMetrics().get(COUNT)).getValue()) +- .isEqualTo(12); +- } +- +- @Test +- void hasAGaugeForTheNumberOfDaemonThreads() { +- assertThat(((Gauge) gauges.getMetrics().get(DAEMON_COUNT)).getValue()) +- .isEqualTo(10); +- } +- +- @Test +- void hasAGaugeForAnyDeadlocks() { +- assertThat(((Gauge) gauges.getMetrics().get(DEADLOCKS)).getValue()) +- .isEqualTo(deadlocks); +- } +- +- @Test +- void hasAGaugeForAnyDeadlockCount() { +- assertThat(((Gauge) gauges.getMetrics().get(DEADLOCK_COUNT)).getValue()) +- .isEqualTo(1); +- } +- +- @Test +- void hasAGaugeForPeakThreadCount() { +- assertThat(((Gauge) gauges.getMetrics().get(MetricName.build("peak.count"))).getValue()) +- .isEqualTo(30); +- } +- +- @Test +- void hasAGaugeForTotalStartedThreadsCount() { +- assertThat(((Gauge) gauges.getMetrics().get(MetricName.build("total_started.count"))).getValue()) +- .isEqualTo(42L); +- } +- +- @Test +- void autoDiscoversTheMXBeans() { +- final ThreadStatesGaugeSet set = new ThreadStatesGaugeSet(); +- assertThat(((Gauge) set.getMetrics().get(COUNT)).getValue()) +- .isNotNull(); +- assertThat(((Gauge) set.getMetrics().get(DEADLOCKS)).getValue()) +- .isNotNull(); +- } ++final class ThreadStatesGaugeSetTest { ++ private final ThreadMXBean threads = mock(); ++ private final ThreadDeadlockDetector detector = mock(); ++ private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); ++ private final long[] ids = new long[] {1, 2, 3}; ++ ++ private final ThreadInfo newThread = mock(); ++ private final ThreadInfo runnableThread = mock(); ++ private final ThreadInfo blockedThread = mock(); ++ private final ThreadInfo waitingThread = mock(); ++ private final ThreadInfo timedWaitingThread = mock(); ++ private final ThreadInfo terminatedThread = mock(); ++ ++ private final Set deadlocks = new HashSet<>(); ++ ++ private static final MetricName TERMINATED_COUNT = MetricName.build("terminated.count"); ++ private static final MetricName NEW_COUNT = MetricName.build("new.count"); ++ private static final MetricName COUNT = MetricName.build("count"); ++ private static final MetricName TIMED_WAITING_COUNT = MetricName.build("timed_waiting.count"); ++ private static final MetricName DEADLOCKS = MetricName.build("deadlocks"); ++ private static final MetricName BLOCKED_COUNT = MetricName.build("blocked.count"); ++ private static final MetricName WAITING_COUNT = MetricName.build("waiting.count"); ++ private static final MetricName DAEMON_COUNT = MetricName.build("daemon.count"); ++ private static final MetricName RUNNABLE_COUNT = MetricName.build("runnable.count"); ++ private static final MetricName DEADLOCK_COUNT = MetricName.build("deadlock.count"); ++ ++ @BeforeEach ++ void setUp() { ++ deadlocks.add("yay"); ++ ++ when(newThread.getThreadState()).thenReturn(Thread.State.NEW); ++ when(runnableThread.getThreadState()).thenReturn(Thread.State.RUNNABLE); ++ when(blockedThread.getThreadState()).thenReturn(Thread.State.BLOCKED); ++ when(waitingThread.getThreadState()).thenReturn(Thread.State.WAITING); ++ when(timedWaitingThread.getThreadState()).thenReturn(Thread.State.TIMED_WAITING); ++ when(terminatedThread.getThreadState()).thenReturn(Thread.State.TERMINATED); ++ ++ when(threads.getAllThreadIds()).thenReturn(ids); ++ when(threads.getThreadInfo(ids, 0)) ++ .thenReturn( ++ new ThreadInfo[] { ++ newThread, runnableThread, blockedThread, ++ waitingThread, timedWaitingThread, terminatedThread ++ }); ++ ++ when(threads.getThreadCount()).thenReturn(12); ++ when(threads.getDaemonThreadCount()).thenReturn(10); ++ when(threads.getPeakThreadCount()).thenReturn(30); ++ when(threads.getTotalStartedThreadCount()).thenReturn(42L); ++ ++ when(detector.getDeadlockedThreads()).thenReturn(deadlocks); ++ } ++ ++ @Test ++ void hasASetOfGauges() { ++ assertThat(gauges.getMetrics().keySet()) ++ .containsOnly( ++ TERMINATED_COUNT, ++ NEW_COUNT, ++ COUNT, ++ TIMED_WAITING_COUNT, ++ DEADLOCKS, ++ BLOCKED_COUNT, ++ WAITING_COUNT, ++ DAEMON_COUNT, ++ RUNNABLE_COUNT, ++ DEADLOCK_COUNT, ++ MetricName.build("total_started.count"), ++ MetricName.build("peak.count")); ++ } ++ ++ @Test ++ void hasAGaugeForEachThreadState() { ++ assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1); ++ ++ assertThat(((Gauge) gauges.getMetrics().get(RUNNABLE_COUNT)).getValue()).isEqualTo(1); ++ ++ assertThat(((Gauge) gauges.getMetrics().get(BLOCKED_COUNT)).getValue()).isEqualTo(1); ++ ++ assertThat(((Gauge) gauges.getMetrics().get(WAITING_COUNT)).getValue()).isEqualTo(1); ++ ++ assertThat(((Gauge) gauges.getMetrics().get(TIMED_WAITING_COUNT)).getValue()).isEqualTo(1); ++ ++ assertThat(((Gauge) gauges.getMetrics().get(TERMINATED_COUNT)).getValue()).isEqualTo(1); ++ } ++ ++ @Test ++ void hasAGaugeForTheNumberOfThreads() { ++ assertThat(((Gauge) gauges.getMetrics().get(COUNT)).getValue()).isEqualTo(12); ++ } ++ ++ @Test ++ void hasAGaugeForTheNumberOfDaemonThreads() { ++ assertThat(((Gauge) gauges.getMetrics().get(DAEMON_COUNT)).getValue()).isEqualTo(10); ++ } ++ ++ @Test ++ void hasAGaugeForAnyDeadlocks() { ++ assertThat(((Gauge) gauges.getMetrics().get(DEADLOCKS)).getValue()).isEqualTo(deadlocks); ++ } ++ ++ @Test ++ void hasAGaugeForAnyDeadlockCount() { ++ assertThat(((Gauge) gauges.getMetrics().get(DEADLOCK_COUNT)).getValue()).isEqualTo(1); ++ } ++ ++ @Test ++ void hasAGaugeForPeakThreadCount() { ++ assertThat(((Gauge) gauges.getMetrics().get(MetricName.build("peak.count"))).getValue()) ++ .isEqualTo(30); ++ } ++ ++ @Test ++ void hasAGaugeForTotalStartedThreadsCount() { ++ assertThat( ++ ((Gauge) gauges.getMetrics().get(MetricName.build("total_started.count"))) ++ .getValue()) ++ .isEqualTo(42L); ++ } ++ ++ @Test ++ void autoDiscoversTheMXBeans() { ++ final ThreadStatesGaugeSet set = new ThreadStatesGaugeSet(); ++ assertThat(((Gauge) set.getMetrics().get(COUNT)).getValue()).isNotNull(); ++ assertThat(((Gauge) set.getMetrics().get(DEADLOCKS)).getValue()).isNotNull(); ++ } + } +--- a/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java ++++ b/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java +@@ -6,158 +6,158 @@ import java.util.Objects; + @Deprecated + public abstract class HealthCheck { + +- public static class Result { ++ public static class Result { + +- public static HealthCheck.Result healthy() { +- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy()); +- } +- +- public static HealthCheck.Result healthy(String message) { +- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy(message)); +- } +- +- public static HealthCheck.Result healthy(String message, Object... args) { +- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy(message, args)); +- } +- +- public static HealthCheck.Result unhealthy(String message) { +- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(message)); +- } ++ public static HealthCheck.Result healthy() { ++ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy()); ++ } + +- public static HealthCheck.Result unhealthy(String message, Object... args) { +- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(message, args)); +- } ++ public static HealthCheck.Result healthy(String message) { ++ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy(message)); ++ } + +- public static HealthCheck.Result unhealthy(Throwable error) { +- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(error)); +- } ++ public static HealthCheck.Result healthy(String message, Object... args) { ++ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy(message, args)); ++ } + +- public static HealthCheck.Result of(io.dropwizard.metrics5.health.HealthCheck.Result delegate) { +- return new Result(delegate); +- } ++ public static HealthCheck.Result unhealthy(String message) { ++ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(message)); ++ } + +- public static HealthCheck.ResultBuilder builder() { +- return new HealthCheck.ResultBuilder(); +- } ++ public static HealthCheck.Result unhealthy(String message, Object... args) { ++ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(message, args)); ++ } + +- private final io.dropwizard.metrics5.health.HealthCheck.Result delegate; ++ public static HealthCheck.Result unhealthy(Throwable error) { ++ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(error)); ++ } + +- private Result(io.dropwizard.metrics5.health.HealthCheck.Result delegate) { +- this.delegate = delegate; +- } ++ public static HealthCheck.Result of(io.dropwizard.metrics5.health.HealthCheck.Result delegate) { ++ return new Result(delegate); ++ } + +- private Result(io.dropwizard.metrics5.health.HealthCheck.ResultBuilder builder) { +- this.delegate = builder.build(); +- } ++ public static HealthCheck.ResultBuilder builder() { ++ return new HealthCheck.ResultBuilder(); ++ } + +- public boolean isHealthy() { +- return delegate.isHealthy(); +- } ++ private final io.dropwizard.metrics5.health.HealthCheck.Result delegate; + +- public String getMessage() { +- return delegate.getMessage(); +- } ++ private Result(io.dropwizard.metrics5.health.HealthCheck.Result delegate) { ++ this.delegate = delegate; ++ } + +- public Throwable getError() { +- return delegate.getError(); +- } ++ private Result(io.dropwizard.metrics5.health.HealthCheck.ResultBuilder builder) { ++ this.delegate = builder.build(); ++ } + +- public String getTimestamp() { +- return delegate.getTimestamp(); +- } ++ public boolean isHealthy() { ++ return delegate.isHealthy(); ++ } + +- public Map getDetails() { +- return delegate.getDetails(); +- } ++ public String getMessage() { ++ return delegate.getMessage(); ++ } + +- public io.dropwizard.metrics5.health.HealthCheck.Result getDelegate() { +- return delegate; +- } ++ public Throwable getError() { ++ return delegate.getError(); ++ } + +- @Override +- public boolean equals(Object o) { +- if (o instanceof Result) { +- final Result that = (Result) o; +- return Objects.equals(delegate, that.delegate); +- } +- return false; +- } ++ public String getTimestamp() { ++ return delegate.getTimestamp(); ++ } + +- @Override +- public int hashCode() { +- return Objects.hash(delegate); +- } ++ public Map getDetails() { ++ return delegate.getDetails(); ++ } + +- @Override +- public String toString() { +- return delegate.toString(); +- } ++ public io.dropwizard.metrics5.health.HealthCheck.Result getDelegate() { ++ return delegate; + } + +- public static class ResultBuilder { ++ @Override ++ public boolean equals(Object o) { ++ if (o instanceof Result) { ++ final Result that = (Result) o; ++ return Objects.equals(delegate, that.delegate); ++ } ++ return false; ++ } + +- private io.dropwizard.metrics5.health.HealthCheck.ResultBuilder delegate; ++ @Override ++ public int hashCode() { ++ return Objects.hash(delegate); ++ } + +- protected ResultBuilder() { +- delegate = io.dropwizard.metrics5.health.HealthCheck.Result.builder(); +- } ++ @Override ++ public String toString() { ++ return delegate.toString(); ++ } ++ } + +- public HealthCheck.ResultBuilder healthy() { +- delegate.healthy(); +- return this; +- } ++ public static class ResultBuilder { + +- public HealthCheck.ResultBuilder unhealthy() { +- delegate.unhealthy(); +- return this; +- } ++ private io.dropwizard.metrics5.health.HealthCheck.ResultBuilder delegate; + +- public HealthCheck.ResultBuilder unhealthy(Throwable error) { +- delegate.unhealthy(error); +- return this; +- } ++ protected ResultBuilder() { ++ delegate = io.dropwizard.metrics5.health.HealthCheck.Result.builder(); ++ } + +- public HealthCheck.ResultBuilder withMessage(String message) { +- delegate.withMessage(message); +- return this; +- } ++ public HealthCheck.ResultBuilder healthy() { ++ delegate.healthy(); ++ return this; ++ } + +- public HealthCheck.ResultBuilder withMessage(String message, Object... args) { +- delegate.withMessage(message, args); +- return this; +- } ++ public HealthCheck.ResultBuilder unhealthy() { ++ delegate.unhealthy(); ++ return this; ++ } + +- public HealthCheck.ResultBuilder withDetail(String key, Object data) { +- delegate.withDetail(key, data); +- return this; +- } ++ public HealthCheck.ResultBuilder unhealthy(Throwable error) { ++ delegate.unhealthy(error); ++ return this; ++ } + +- public HealthCheck.Result build() { +- return new HealthCheck.Result(delegate); +- } ++ public HealthCheck.ResultBuilder withMessage(String message) { ++ delegate.withMessage(message); ++ return this; + } + +- protected abstract HealthCheck.Result check() throws Exception; ++ public HealthCheck.ResultBuilder withMessage(String message, Object... args) { ++ delegate.withMessage(message, args); ++ return this; ++ } + +- public HealthCheck.Result execute() { +- try { +- return check(); +- } catch (Exception e) { +- return HealthCheck.Result.unhealthy(e); +- } ++ public HealthCheck.ResultBuilder withDetail(String key, Object data) { ++ delegate.withDetail(key, data); ++ return this; + } + +- public io.dropwizard.metrics5.health.HealthCheck transform() { +- final HealthCheck original = this; +- return () -> original.check().delegate; ++ public HealthCheck.Result build() { ++ return new HealthCheck.Result(delegate); + } ++ } ++ ++ protected abstract HealthCheck.Result check() throws Exception; + +- public static HealthCheck of(io.dropwizard.metrics5.health.HealthCheck delegate) { +- return new HealthCheck() { +- @Override +- protected Result check() throws Exception { +- return new Result(delegate.execute()); +- } +- }; ++ public HealthCheck.Result execute() { ++ try { ++ return check(); ++ } catch (Exception e) { ++ return HealthCheck.Result.unhealthy(e); + } ++ } ++ ++ public io.dropwizard.metrics5.health.HealthCheck transform() { ++ final HealthCheck original = this; ++ return () -> original.check().delegate; ++ } ++ ++ public static HealthCheck of(io.dropwizard.metrics5.health.HealthCheck delegate) { ++ return new HealthCheck() { ++ @Override ++ protected Result check() throws Exception { ++ return new Result(delegate.execute()); ++ } ++ }; ++ } + } +--- a/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckFilter.java ++++ b/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckFilter.java +@@ -3,12 +3,12 @@ package com.codahale.metrics.health; + @Deprecated + public interface HealthCheckFilter { + +- HealthCheckFilter ALL = (name, healthCheck) -> true; ++ HealthCheckFilter ALL = (name, healthCheck) -> true; + +- boolean matches(String name, HealthCheck healthCheck); ++ boolean matches(String name, HealthCheck healthCheck); + +- default io.dropwizard.metrics5.health.HealthCheckFilter transform() { +- final HealthCheckFilter origin = this; +- return (name, healthCheck) -> origin.matches(name, HealthCheck.of(healthCheck)); +- } ++ default io.dropwizard.metrics5.health.HealthCheckFilter transform() { ++ final HealthCheckFilter origin = this; ++ return (name, healthCheck) -> origin.matches(name, HealthCheck.of(healthCheck)); ++ } + } +--- a/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java ++++ b/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java +@@ -11,79 +11,80 @@ import java.util.concurrent.ScheduledExecutorService; + @Deprecated + public class HealthCheckRegistry { + +- private final io.dropwizard.metrics5.health.HealthCheckRegistry delegate; +- +- public HealthCheckRegistry() { +- this(new io.dropwizard.metrics5.health.HealthCheckRegistry()); +- } +- +- public HealthCheckRegistry(int asyncExecutorPoolSize) { +- this(new io.dropwizard.metrics5.health.HealthCheckRegistry(asyncExecutorPoolSize)); +- } +- +- public HealthCheckRegistry(ScheduledExecutorService asyncExecutorService) { +- this(new io.dropwizard.metrics5.health.HealthCheckRegistry(asyncExecutorService)); +- } +- +- private HealthCheckRegistry(io.dropwizard.metrics5.health.HealthCheckRegistry delegate) { +- this.delegate = delegate; +- } +- +- public static HealthCheckRegistry of(io.dropwizard.metrics5.health.HealthCheckRegistry reg) { +- return new HealthCheckRegistry(reg); +- } +- +- public void addListener(HealthCheckRegistryListener listener) { +- delegate.addListener(listener.transform()); +- } +- +- public void removeListener(HealthCheckRegistryListener listener) { +- delegate.removeListener(listener.transform()); +- } +- +- public void register(String name, HealthCheck healthCheck) { +- delegate.register(name, healthCheck.transform()); +- } +- +- public void unregister(String name) { +- delegate.unregister(name); +- } +- +- public SortedSet getNames() { +- return delegate.getNames(); +- } +- +- public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException { +- return HealthCheck.Result.of(delegate.runHealthCheck(name)); +- } +- +- public SortedMap runHealthChecks() { +- return convertHealthChecks(delegate.runHealthChecks()); +- } +- +- public SortedMap runHealthChecks(HealthCheckFilter filter) { +- return convertHealthChecks(delegate.runHealthChecks(filter.transform())); +- } +- +- public SortedMap runHealthChecks(ExecutorService executor) { +- return convertHealthChecks(delegate.runHealthChecks(executor)); +- } +- +- public SortedMap runHealthChecks(ExecutorService executor, +- HealthCheckFilter filter) { +- return convertHealthChecks(delegate.runHealthChecks(executor, filter.transform())); +- } +- +- private SortedMap convertHealthChecks( +- SortedMap originResults) { +- final SortedMap results = new TreeMap<>(); +- for (Map.Entry entry : originResults.entrySet()) { +- results.put(entry.getKey(), HealthCheck.Result.of(entry.getValue())); +- } +- return results; +- } +- +- public void shutdown() { +- delegate.shutdown(); +- } ++ private final io.dropwizard.metrics5.health.HealthCheckRegistry delegate; ++ ++ public HealthCheckRegistry() { ++ this(new io.dropwizard.metrics5.health.HealthCheckRegistry()); ++ } ++ ++ public HealthCheckRegistry(int asyncExecutorPoolSize) { ++ this(new io.dropwizard.metrics5.health.HealthCheckRegistry(asyncExecutorPoolSize)); ++ } ++ ++ public HealthCheckRegistry(ScheduledExecutorService asyncExecutorService) { ++ this(new io.dropwizard.metrics5.health.HealthCheckRegistry(asyncExecutorService)); ++ } ++ ++ private HealthCheckRegistry(io.dropwizard.metrics5.health.HealthCheckRegistry delegate) { ++ this.delegate = delegate; ++ } ++ ++ public static HealthCheckRegistry of(io.dropwizard.metrics5.health.HealthCheckRegistry reg) { ++ return new HealthCheckRegistry(reg); ++ } ++ ++ public void addListener(HealthCheckRegistryListener listener) { ++ delegate.addListener(listener.transform()); ++ } ++ ++ public void removeListener(HealthCheckRegistryListener listener) { ++ delegate.removeListener(listener.transform()); ++ } ++ ++ public void register(String name, HealthCheck healthCheck) { ++ delegate.register(name, healthCheck.transform()); ++ } ++ ++ public void unregister(String name) { ++ delegate.unregister(name); ++ } ++ ++ public SortedSet getNames() { ++ return delegate.getNames(); ++ } ++ ++ public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException { ++ return HealthCheck.Result.of(delegate.runHealthCheck(name)); ++ } ++ ++ public SortedMap runHealthChecks() { ++ return convertHealthChecks(delegate.runHealthChecks()); ++ } ++ ++ public SortedMap runHealthChecks(HealthCheckFilter filter) { ++ return convertHealthChecks(delegate.runHealthChecks(filter.transform())); ++ } ++ ++ public SortedMap runHealthChecks(ExecutorService executor) { ++ return convertHealthChecks(delegate.runHealthChecks(executor)); ++ } ++ ++ public SortedMap runHealthChecks( ++ ExecutorService executor, HealthCheckFilter filter) { ++ return convertHealthChecks(delegate.runHealthChecks(executor, filter.transform())); ++ } ++ ++ private SortedMap convertHealthChecks( ++ SortedMap originResults) { ++ final SortedMap results = new TreeMap<>(); ++ for (Map.Entry entry : ++ originResults.entrySet()) { ++ results.put(entry.getKey(), HealthCheck.Result.of(entry.getValue())); ++ } ++ return results; ++ } ++ ++ public void shutdown() { ++ delegate.shutdown(); ++ } + } +--- a/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistryListener.java ++++ b/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistryListener.java +@@ -6,44 +6,46 @@ import java.util.Objects; + @Deprecated + public interface HealthCheckRegistryListener extends EventListener { + +- void onHealthCheckAdded(String name, HealthCheck healthCheck); ++ void onHealthCheckAdded(String name, HealthCheck healthCheck); + +- void onHealthCheckRemoved(String name, HealthCheck healthCheck); ++ void onHealthCheckRemoved(String name, HealthCheck healthCheck); + +- default io.dropwizard.metrics5.health.HealthCheckRegistryListener transform() { +- return new Adapter(this); ++ default io.dropwizard.metrics5.health.HealthCheckRegistryListener transform() { ++ return new Adapter(this); ++ } ++ ++ class Adapter implements io.dropwizard.metrics5.health.HealthCheckRegistryListener { ++ ++ private final HealthCheckRegistryListener delegate; ++ ++ public Adapter(HealthCheckRegistryListener delegate) { ++ this.delegate = delegate; ++ } ++ ++ @Override ++ public void onHealthCheckAdded( ++ String name, io.dropwizard.metrics5.health.HealthCheck healthCheck) { ++ delegate.onHealthCheckAdded(name, HealthCheck.of(healthCheck)); ++ } ++ ++ @Override ++ public void onHealthCheckRemoved( ++ String name, io.dropwizard.metrics5.health.HealthCheck healthCheck) { ++ delegate.onHealthCheckRemoved(name, HealthCheck.of(healthCheck)); ++ } ++ ++ @Override ++ public boolean equals(Object o) { ++ if (o instanceof Adapter) { ++ final Adapter that = (Adapter) o; ++ return Objects.equals(delegate, that.delegate); ++ } ++ return false; + } + +- class Adapter implements io.dropwizard.metrics5.health.HealthCheckRegistryListener { +- +- private final HealthCheckRegistryListener delegate; +- +- public Adapter(HealthCheckRegistryListener delegate) { +- this.delegate = delegate; +- } +- +- @Override +- public void onHealthCheckAdded(String name, io.dropwizard.metrics5.health.HealthCheck healthCheck) { +- delegate.onHealthCheckAdded(name, HealthCheck.of(healthCheck)); +- } +- +- @Override +- public void onHealthCheckRemoved(String name, io.dropwizard.metrics5.health.HealthCheck healthCheck) { +- delegate.onHealthCheckRemoved(name, HealthCheck.of(healthCheck)); +- } +- +- @Override +- public boolean equals(Object o) { +- if (o instanceof Adapter) { +- final Adapter that = (Adapter) o; +- return Objects.equals(delegate, that.delegate); +- } +- return false; +- } +- +- @Override +- public int hashCode() { +- return Objects.hash(delegate); +- } ++ @Override ++ public int hashCode() { ++ return Objects.hash(delegate); + } ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CachedGauge.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CachedGauge.java +@@ -1,42 +1,43 @@ + package com.codahale.metrics; + +-import java.util.concurrent.TimeUnit; +- + import static java.util.Objects.requireNonNull; + ++import java.util.concurrent.TimeUnit; ++ + @Deprecated + public abstract class CachedGauge implements Gauge { + +- private final io.dropwizard.metrics5.CachedGauge gauge; ++ private final io.dropwizard.metrics5.CachedGauge gauge; + +- public CachedGauge(io.dropwizard.metrics5.CachedGauge gauge) { +- this.gauge = requireNonNull(gauge); +- } ++ public CachedGauge(io.dropwizard.metrics5.CachedGauge gauge) { ++ this.gauge = requireNonNull(gauge); ++ } + +- protected CachedGauge(long timeout, TimeUnit timeoutUnit) { +- final CachedGauge original = this; +- gauge = new io.dropwizard.metrics5.CachedGauge(timeout, timeoutUnit) { +- @Override +- protected T loadValue() { +- return original.loadValue(); +- } ++ protected CachedGauge(long timeout, TimeUnit timeoutUnit) { ++ final CachedGauge original = this; ++ gauge = ++ new io.dropwizard.metrics5.CachedGauge(timeout, timeoutUnit) { ++ @Override ++ protected T loadValue() { ++ return original.loadValue(); ++ } + }; +- } +- +- protected CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit) { +- final CachedGauge original = this; +- gauge = new io.dropwizard.metrics5.CachedGauge(clock.getDelegate(), timeout, timeoutUnit) { +- @Override +- protected T loadValue() { +- return original.loadValue(); +- } ++ } ++ ++ protected CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit) { ++ final CachedGauge original = this; ++ gauge = ++ new io.dropwizard.metrics5.CachedGauge(clock.getDelegate(), timeout, timeoutUnit) { ++ @Override ++ protected T loadValue() { ++ return original.loadValue(); ++ } + }; +- } +- +- protected abstract T loadValue(); ++ } + +- public T getValue() { +- return gauge.getValue(); +- } ++ protected abstract T loadValue(); + ++ public T getValue() { ++ return gauge.getValue(); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Clock.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Clock.java +@@ -3,64 +3,65 @@ package com.codahale.metrics; + @Deprecated + public abstract class Clock { + +- public abstract long getTick(); ++ public abstract long getTick(); + +- public long getTime() { +- return System.currentTimeMillis(); +- } +- +- public io.dropwizard.metrics5.Clock getDelegate() { +- if (this instanceof DelegateClock) { +- return ((DelegateClock) this).delegate; +- } +- final Clock original = this; +- return new io.dropwizard.metrics5.Clock() { +- @Override +- public long getTick() { +- return original.getTick(); +- } ++ public long getTime() { ++ return System.currentTimeMillis(); ++ } + +- @Override +- public long getTime() { +- return original.getTime(); +- } +- }; ++ public io.dropwizard.metrics5.Clock getDelegate() { ++ if (this instanceof DelegateClock) { ++ return ((DelegateClock) this).delegate; + } ++ final Clock original = this; ++ return new io.dropwizard.metrics5.Clock() { ++ @Override ++ public long getTick() { ++ return original.getTick(); ++ } + +- public static Clock of(io.dropwizard.metrics5.Clock delegate) { +- return new DelegateClock(delegate); +- } ++ @Override ++ public long getTime() { ++ return original.getTime(); ++ } ++ }; ++ } + +- public static Clock defaultClock() { +- return of(io.dropwizard.metrics5.Clock.defaultClock()); +- } ++ public static Clock of(io.dropwizard.metrics5.Clock delegate) { ++ return new DelegateClock(delegate); ++ } + +- public static class UserTimeClock extends Clock { ++ public static Clock defaultClock() { ++ return of(io.dropwizard.metrics5.Clock.defaultClock()); ++ } + +- private final io.dropwizard.metrics5.Clock delegate = new io.dropwizard.metrics5.Clock.UserTimeClock(); ++ public static class UserTimeClock extends Clock { + +- @Override +- public long getTick() { +- return delegate.getTick(); +- } ++ private final io.dropwizard.metrics5.Clock delegate = ++ new io.dropwizard.metrics5.Clock.UserTimeClock(); + +- @Override +- public long getTime() { +- return delegate.getTime(); +- } ++ @Override ++ public long getTick() { ++ return delegate.getTick(); + } + +- private static class DelegateClock extends Clock { ++ @Override ++ public long getTime() { ++ return delegate.getTime(); ++ } ++ } + +- private final io.dropwizard.metrics5.Clock delegate; ++ private static class DelegateClock extends Clock { + +- private DelegateClock(io.dropwizard.metrics5.Clock delegate) { +- this.delegate = delegate; +- } ++ private final io.dropwizard.metrics5.Clock delegate; ++ ++ private DelegateClock(io.dropwizard.metrics5.Clock delegate) { ++ this.delegate = delegate; ++ } + +- @Override +- public long getTick() { +- return delegate.getTick(); +- } ++ @Override ++ public long getTick() { ++ return delegate.getTick(); + } ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ConsoleReporter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ConsoleReporter.java +@@ -11,83 +11,91 @@ import java.util.concurrent.TimeUnit; + @Deprecated + public class ConsoleReporter extends ScheduledReporter { + +- public static Builder forRegistry(MetricRegistry registry) { +- return new Builder(registry); ++ public static Builder forRegistry(MetricRegistry registry) { ++ return new Builder(registry); ++ } ++ ++ public static class Builder { ++ ++ private io.dropwizard.metrics5.ConsoleReporter.Builder delegate; ++ ++ private Builder(MetricRegistry metricRegistry) { ++ delegate = io.dropwizard.metrics5.ConsoleReporter.forRegistry(metricRegistry.getDelegate()); ++ } ++ ++ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { ++ delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); ++ return this; ++ } ++ ++ public Builder scheduleOn(ScheduledExecutorService executor) { ++ delegate.scheduleOn(executor); ++ return this; ++ } ++ ++ public Builder outputTo(PrintStream output) { ++ delegate.outputTo(output); ++ return this; ++ } ++ ++ public Builder formattedFor(Locale locale) { ++ delegate.formattedFor(locale); ++ return this; ++ } ++ ++ public Builder withClock(Clock clock) { ++ delegate.withClock(clock.getDelegate()); ++ return this; ++ } ++ ++ public Builder formattedFor(TimeZone timeZone) { ++ delegate.formattedFor(timeZone); ++ return this; ++ } ++ ++ public Builder convertRatesTo(TimeUnit rateUnit) { ++ delegate.convertRatesTo(rateUnit); ++ return this; ++ } ++ ++ public Builder convertDurationsTo(TimeUnit durationUnit) { ++ delegate.convertDurationsTo(durationUnit); ++ return this; + } + +- public static class Builder { +- +- private io.dropwizard.metrics5.ConsoleReporter.Builder delegate; +- +- private Builder(MetricRegistry metricRegistry) { +- delegate = io.dropwizard.metrics5.ConsoleReporter.forRegistry(metricRegistry.getDelegate()); +- } +- +- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { +- delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); +- return this; +- } +- +- public Builder scheduleOn(ScheduledExecutorService executor) { +- delegate.scheduleOn(executor); +- return this; +- } +- +- public Builder outputTo(PrintStream output) { +- delegate.outputTo(output); +- return this; +- } +- +- public Builder formattedFor(Locale locale) { +- delegate.formattedFor(locale); +- return this; +- } +- +- public Builder withClock(Clock clock) { +- delegate.withClock(clock.getDelegate()); +- return this; +- } +- +- public Builder formattedFor(TimeZone timeZone) { +- delegate.formattedFor(timeZone); +- return this; +- } +- +- public Builder convertRatesTo(TimeUnit rateUnit) { +- delegate.convertRatesTo(rateUnit); +- return this; +- } +- +- public Builder convertDurationsTo(TimeUnit durationUnit) { +- delegate.convertDurationsTo(durationUnit); +- return this; +- } +- +- public Builder filter(MetricFilter filter) { +- delegate.filter(filter.transform()); +- return this; +- } +- +- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { +- delegate.disabledMetricAttributes(MetricAttribute.transform(disabledMetricAttributes)); +- return this; +- } +- +- public ConsoleReporter build() { +- return new ConsoleReporter(delegate.build()); +- } ++ public Builder filter(MetricFilter filter) { ++ delegate.filter(filter.transform()); ++ return this; + } + +- private ConsoleReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { +- super(delegate); ++ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { ++ delegate.disabledMetricAttributes(MetricAttribute.transform(disabledMetricAttributes)); ++ return this; + } + +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap gauges, SortedMap counters, +- SortedMap histograms, SortedMap meters, +- SortedMap timers) { +- getDelegate().report(transform(gauges), transform(counters), transform(histograms), transform(meters), +- transform(timers)); ++ public ConsoleReporter build() { ++ return new ConsoleReporter(delegate.build()); + } ++ } ++ ++ private ConsoleReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { ++ super(delegate); ++ } ++ ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ getDelegate() ++ .report( ++ transform(gauges), ++ transform(counters), ++ transform(histograms), ++ transform(meters), ++ transform(timers)); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Counter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Counter.java +@@ -5,40 +5,39 @@ import static java.util.Objects.requireNonNull; + @Deprecated + public class Counter implements Metric, Counting { + +- private final io.dropwizard.metrics5.Counter counter; ++ private final io.dropwizard.metrics5.Counter counter; + +- public Counter() { +- this(new io.dropwizard.metrics5.Counter()); +- } ++ public Counter() { ++ this(new io.dropwizard.metrics5.Counter()); ++ } + +- public Counter(io.dropwizard.metrics5.Counter counter) { +- this.counter = requireNonNull(counter); +- } ++ public Counter(io.dropwizard.metrics5.Counter counter) { ++ this.counter = requireNonNull(counter); ++ } + +- public void inc() { +- counter.inc(); +- } ++ public void inc() { ++ counter.inc(); ++ } + +- public void inc(long n) { +- counter.inc(n); +- } ++ public void inc(long n) { ++ counter.inc(n); ++ } + +- public void dec() { +- counter.dec(); +- } ++ public void dec() { ++ counter.dec(); ++ } + +- public void dec(long n) { +- counter.dec(n); +- } ++ public void dec(long n) { ++ counter.dec(n); ++ } + +- @Override +- public long getCount() { +- return counter.getCount(); +- } +- +- @Override +- public io.dropwizard.metrics5.Counter getDelegate() { +- return counter; +- } ++ @Override ++ public long getCount() { ++ return counter.getCount(); ++ } + ++ @Override ++ public io.dropwizard.metrics5.Counter getDelegate() { ++ return counter; ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Counting.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Counting.java +@@ -3,5 +3,5 @@ package com.codahale.metrics; + @Deprecated + public interface Counting { + +- long getCount(); ++ long getCount(); + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CsvFileProvider.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CsvFileProvider.java +@@ -5,5 +5,5 @@ import java.io.File; + @Deprecated + public interface CsvFileProvider { + +- File getFile(File directory, String metricName); ++ File getFile(File directory, String metricName); + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CsvReporter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CsvReporter.java +@@ -9,80 +9,86 @@ import java.util.concurrent.TimeUnit; + @Deprecated + public class CsvReporter extends ScheduledReporter { + +- public static Builder forRegistry(MetricRegistry registry) { +- return new Builder(registry); +- } +- +- public static class Builder { +- +- private io.dropwizard.metrics5.CsvReporter.Builder delegate; +- +- private Builder(MetricRegistry metricRegistry) { +- delegate = io.dropwizard.metrics5.CsvReporter.forRegistry(metricRegistry.getDelegate()); +- } ++ public static Builder forRegistry(MetricRegistry registry) { ++ return new Builder(registry); ++ } + +- public CsvReporter.Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { +- delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); +- return this; +- } ++ public static class Builder { + ++ private io.dropwizard.metrics5.CsvReporter.Builder delegate; + +- public CsvReporter.Builder scheduleOn(ScheduledExecutorService executor) { +- delegate.scheduleOn(executor); +- return this; +- } +- +- public CsvReporter.Builder formatFor(Locale locale) { +- delegate.formatFor(locale); +- return this; +- } ++ private Builder(MetricRegistry metricRegistry) { ++ delegate = io.dropwizard.metrics5.CsvReporter.forRegistry(metricRegistry.getDelegate()); ++ } + ++ public CsvReporter.Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { ++ delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); ++ return this; ++ } + +- public CsvReporter.Builder convertRatesTo(TimeUnit rateUnit) { +- delegate.convertRatesTo(rateUnit); +- return this; +- } ++ public CsvReporter.Builder scheduleOn(ScheduledExecutorService executor) { ++ delegate.scheduleOn(executor); ++ return this; ++ } + +- public CsvReporter.Builder convertDurationsTo(TimeUnit durationUnit) { +- delegate.convertDurationsTo(durationUnit); +- return this; +- } ++ public CsvReporter.Builder formatFor(Locale locale) { ++ delegate.formatFor(locale); ++ return this; ++ } + +- public CsvReporter.Builder withSeparator(String separator) { +- delegate.withSeparator(separator); +- return this; +- } ++ public CsvReporter.Builder convertRatesTo(TimeUnit rateUnit) { ++ delegate.convertRatesTo(rateUnit); ++ return this; ++ } + +- public CsvReporter.Builder withClock(Clock clock) { +- delegate.withClock(clock.getDelegate()); +- return this; +- } ++ public CsvReporter.Builder convertDurationsTo(TimeUnit durationUnit) { ++ delegate.convertDurationsTo(durationUnit); ++ return this; ++ } + +- public CsvReporter.Builder filter(MetricFilter filter) { +- delegate.filter(filter.transform()); +- return this; +- } ++ public CsvReporter.Builder withSeparator(String separator) { ++ delegate.withSeparator(separator); ++ return this; ++ } + +- public Builder withCsvFileProvider(CsvFileProvider csvFileProvider) { +- delegate.withCsvFileProvider(csvFileProvider::getFile); +- return this; +- } ++ public CsvReporter.Builder withClock(Clock clock) { ++ delegate.withClock(clock.getDelegate()); ++ return this; ++ } + +- public CsvReporter build(File directory) { +- return new CsvReporter(delegate.build(directory)); +- } ++ public CsvReporter.Builder filter(MetricFilter filter) { ++ delegate.filter(filter.transform()); ++ return this; + } +- +- public CsvReporter(io.dropwizard.metrics5.CsvReporter delegate) { +- super(delegate); ++ ++ public Builder withCsvFileProvider(CsvFileProvider csvFileProvider) { ++ delegate.withCsvFileProvider(csvFileProvider::getFile); ++ return this; + } + +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap gauges, SortedMap counters, +- SortedMap histograms, SortedMap meters, +- SortedMap timers) { +- getDelegate().report(transform(gauges), transform(counters), transform(histograms), transform(meters), +- transform(timers)); ++ public CsvReporter build(File directory) { ++ return new CsvReporter(delegate.build(directory)); + } ++ } ++ ++ public CsvReporter(io.dropwizard.metrics5.CsvReporter delegate) { ++ super(delegate); ++ } ++ ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ getDelegate() ++ .report( ++ transform(gauges), ++ transform(counters), ++ transform(histograms), ++ transform(meters), ++ transform(timers)); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/DerivativeGauge.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/DerivativeGauge.java +@@ -3,22 +3,23 @@ package com.codahale.metrics; + @Deprecated + public abstract class DerivativeGauge implements Gauge { + +- private final io.dropwizard.metrics5.DerivativeGauge delegate; ++ private final io.dropwizard.metrics5.DerivativeGauge delegate; + +- protected DerivativeGauge(Gauge base) { +- DerivativeGauge original = this; +- delegate = new io.dropwizard.metrics5.DerivativeGauge(base.getDelegate()) { +- @Override +- protected T transform(F value) { +- return original.transform(base.getValue()); +- } ++ protected DerivativeGauge(Gauge base) { ++ DerivativeGauge original = this; ++ delegate = ++ new io.dropwizard.metrics5.DerivativeGauge(base.getDelegate()) { ++ @Override ++ protected T transform(F value) { ++ return original.transform(base.getValue()); ++ } + }; +- } ++ } + +- protected abstract T transform(F value); ++ protected abstract T transform(F value); + +- @Override +- public T getValue() { +- return delegate.getValue(); +- } ++ @Override ++ public T getValue() { ++ return delegate.getValue(); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ExponentiallyDecayingReservoir.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ExponentiallyDecayingReservoir.java +@@ -5,41 +5,44 @@ import static java.util.Objects.requireNonNull; + @Deprecated + public class ExponentiallyDecayingReservoir implements Reservoir { + +- private final io.dropwizard.metrics5.ExponentiallyDecayingReservoir delegate; +- +- public ExponentiallyDecayingReservoir() { +- this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir()); +- } +- +- public ExponentiallyDecayingReservoir(int size, double alpha) { +- this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir(size, alpha)); +- } +- +- public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock) { +- this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir(size, alpha, clock.getDelegate())); +- } +- +- public ExponentiallyDecayingReservoir(io.dropwizard.metrics5.ExponentiallyDecayingReservoir delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- @Override +- public io.dropwizard.metrics5.Reservoir getDelegate() { +- return delegate; +- } +- +- @Override +- public int size() { +- return delegate.size(); +- } +- +- @Override +- public void update(long value) { +- delegate.update(value); +- } +- +- @Override +- public Snapshot getSnapshot() { +- return Snapshot.of(delegate.getSnapshot()); +- } ++ private final io.dropwizard.metrics5.ExponentiallyDecayingReservoir delegate; ++ ++ public ExponentiallyDecayingReservoir() { ++ this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir()); ++ } ++ ++ public ExponentiallyDecayingReservoir(int size, double alpha) { ++ this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir(size, alpha)); ++ } ++ ++ public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock) { ++ this( ++ new io.dropwizard.metrics5.ExponentiallyDecayingReservoir( ++ size, alpha, clock.getDelegate())); ++ } ++ ++ public ExponentiallyDecayingReservoir( ++ io.dropwizard.metrics5.ExponentiallyDecayingReservoir delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ @Override ++ public io.dropwizard.metrics5.Reservoir getDelegate() { ++ return delegate; ++ } ++ ++ @Override ++ public int size() { ++ return delegate.size(); ++ } ++ ++ @Override ++ public void update(long value) { ++ delegate.update(value); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ return Snapshot.of(delegate.getSnapshot()); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/FixedNameCsvFileProvider.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/FixedNameCsvFileProvider.java +@@ -5,11 +5,11 @@ import java.io.File; + @Deprecated + public class FixedNameCsvFileProvider implements CsvFileProvider { + +- private final io.dropwizard.metrics5.FixedNameCsvFileProvider delegate = +- new io.dropwizard.metrics5.FixedNameCsvFileProvider(); ++ private final io.dropwizard.metrics5.FixedNameCsvFileProvider delegate = ++ new io.dropwizard.metrics5.FixedNameCsvFileProvider(); + +- @Override +- public File getFile(File directory, String metricName) { +- return delegate.getFile(directory, metricName); +- } ++ @Override ++ public File getFile(File directory, String metricName) { ++ return delegate.getFile(directory, metricName); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Gauge.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Gauge.java +@@ -3,36 +3,36 @@ package com.codahale.metrics; + @Deprecated + public interface Gauge extends Metric { + +- T getValue(); ++ T getValue(); + +- @Override +- default io.dropwizard.metrics5.Gauge getDelegate() { +- return new GaugeAdapter<>(this); +- } ++ @Override ++ default io.dropwizard.metrics5.Gauge getDelegate() { ++ return new GaugeAdapter<>(this); ++ } + +- @SuppressWarnings("unchecked") +- static Gauge of(io.dropwizard.metrics5.Gauge gauge) { +- if (gauge instanceof GaugeAdapter) { +- return ((GaugeAdapter) gauge).delegate; +- } +- return gauge::getValue; ++ @SuppressWarnings("unchecked") ++ static Gauge of(io.dropwizard.metrics5.Gauge gauge) { ++ if (gauge instanceof GaugeAdapter) { ++ return ((GaugeAdapter) gauge).delegate; + } ++ return gauge::getValue; ++ } + +- class GaugeAdapter implements io.dropwizard.metrics5.Gauge { ++ class GaugeAdapter implements io.dropwizard.metrics5.Gauge { + +- private final Gauge delegate; ++ private final Gauge delegate; + +- GaugeAdapter(Gauge gauge) { +- this.delegate = gauge; +- } ++ GaugeAdapter(Gauge gauge) { ++ this.delegate = gauge; ++ } + +- Gauge getGauge() { +- return delegate; +- } ++ Gauge getGauge() { ++ return delegate; ++ } + +- @Override +- public T getValue() { +- return delegate.getValue(); +- } ++ @Override ++ public T getValue() { ++ return delegate.getValue(); + } ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Histogram.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Histogram.java +@@ -5,36 +5,36 @@ import static java.util.Objects.requireNonNull; + @Deprecated + public class Histogram implements Metric, Sampling, Counting { + +- private final io.dropwizard.metrics5.Histogram delegate; +- +- public Histogram(io.dropwizard.metrics5.Histogram delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- public Histogram(Reservoir reservoir) { +- this.delegate = new io.dropwizard.metrics5.Histogram(reservoir.getDelegate()); +- } +- +- public void update(int value) { +- delegate.update(value); +- } +- +- public void update(long value) { +- delegate.update(value); +- } +- +- @Override +- public long getCount() { +- return delegate.getCount(); +- } +- +- @Override +- public Snapshot getSnapshot() { +- return Snapshot.of(delegate.getSnapshot()); +- } +- +- @Override +- public io.dropwizard.metrics5.Histogram getDelegate() { +- return delegate; +- } ++ private final io.dropwizard.metrics5.Histogram delegate; ++ ++ public Histogram(io.dropwizard.metrics5.Histogram delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ public Histogram(Reservoir reservoir) { ++ this.delegate = new io.dropwizard.metrics5.Histogram(reservoir.getDelegate()); ++ } ++ ++ public void update(int value) { ++ delegate.update(value); ++ } ++ ++ public void update(long value) { ++ delegate.update(value); ++ } ++ ++ @Override ++ public long getCount() { ++ return delegate.getCount(); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ return Snapshot.of(delegate.getSnapshot()); ++ } ++ ++ @Override ++ public io.dropwizard.metrics5.Histogram getDelegate() { ++ return delegate; ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java +@@ -1,5 +1,7 @@ + package com.codahale.metrics; + ++import static java.util.Objects.requireNonNull; ++ + import java.util.Collection; + import java.util.List; + import java.util.concurrent.Callable; +@@ -9,87 +11,93 @@ import java.util.concurrent.Future; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.TimeoutException; + +-import static java.util.Objects.requireNonNull; +- + @Deprecated + public class InstrumentedExecutorService implements ExecutorService { + +- private final io.dropwizard.metrics5.InstrumentedExecutorService delegate; +- +- public InstrumentedExecutorService(io.dropwizard.metrics5.InstrumentedExecutorService delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) { +- this(new io.dropwizard.metrics5.InstrumentedExecutorService(delegate, registry.getDelegate())); +- } +- +- public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry, String name) { +- this(new io.dropwizard.metrics5.InstrumentedExecutorService(delegate, registry.getDelegate(), name)); +- } +- +- @Override +- public void shutdown() { +- delegate.shutdown(); +- } +- +- @Override +- public List shutdownNow() { +- return delegate.shutdownNow(); +- } +- +- @Override +- public boolean isShutdown() { +- return delegate.isShutdown(); +- } +- +- @Override +- public boolean isTerminated() { +- return delegate.isTerminated(); +- } +- +- @Override +- public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { +- return delegate.awaitTermination(timeout, unit); +- } +- +- @Override +- public Future submit(Callable task) { +- return delegate.submit(task); +- } +- +- @Override +- public Future submit(Runnable task, T result) { +- return delegate.submit(task, result); +- } +- +- @Override +- public Future submit(Runnable task) { +- return delegate.submit(task); +- } +- +- @Override +- public List> invokeAll(Collection> tasks) throws InterruptedException { +- return delegate.invokeAll(tasks); +- } +- +- @Override +- public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { +- return delegate.invokeAll(tasks, timeout, unit); +- } +- +- @Override +- public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { +- return delegate.invokeAny(tasks); +- } +- +- @Override +- public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { +- return delegate.invokeAny(tasks, timeout, unit); +- } +- +- @Override +- public void execute(Runnable command) { +- delegate.execute(command); +- } ++ private final io.dropwizard.metrics5.InstrumentedExecutorService delegate; ++ ++ public InstrumentedExecutorService(io.dropwizard.metrics5.InstrumentedExecutorService delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) { ++ this(new io.dropwizard.metrics5.InstrumentedExecutorService(delegate, registry.getDelegate())); ++ } ++ ++ public InstrumentedExecutorService( ++ ExecutorService delegate, MetricRegistry registry, String name) { ++ this( ++ new io.dropwizard.metrics5.InstrumentedExecutorService( ++ delegate, registry.getDelegate(), name)); ++ } ++ ++ @Override ++ public void shutdown() { ++ delegate.shutdown(); ++ } ++ ++ @Override ++ public List shutdownNow() { ++ return delegate.shutdownNow(); ++ } ++ ++ @Override ++ public boolean isShutdown() { ++ return delegate.isShutdown(); ++ } ++ ++ @Override ++ public boolean isTerminated() { ++ return delegate.isTerminated(); ++ } ++ ++ @Override ++ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { ++ return delegate.awaitTermination(timeout, unit); ++ } ++ ++ @Override ++ public Future submit(Callable task) { ++ return delegate.submit(task); ++ } ++ ++ @Override ++ public Future submit(Runnable task, T result) { ++ return delegate.submit(task, result); ++ } ++ ++ @Override ++ public Future submit(Runnable task) { ++ return delegate.submit(task); ++ } ++ ++ @Override ++ public List> invokeAll(Collection> tasks) ++ throws InterruptedException { ++ return delegate.invokeAll(tasks); ++ } ++ ++ @Override ++ public List> invokeAll( ++ Collection> tasks, long timeout, TimeUnit unit) ++ throws InterruptedException { ++ return delegate.invokeAll(tasks, timeout, unit); ++ } ++ ++ @Override ++ public T invokeAny(Collection> tasks) ++ throws InterruptedException, ExecutionException { ++ return delegate.invokeAny(tasks); ++ } ++ ++ @Override ++ public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) ++ throws InterruptedException, ExecutionException, TimeoutException { ++ return delegate.invokeAny(tasks, timeout, unit); ++ } ++ ++ @Override ++ public void execute(Runnable command) { ++ delegate.execute(command); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedScheduledExecutorService.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedScheduledExecutorService.java +@@ -1,5 +1,7 @@ + package com.codahale.metrics; + ++import static java.util.Objects.requireNonNull; ++ + import java.util.Collection; + import java.util.List; + import java.util.concurrent.Callable; +@@ -10,107 +12,119 @@ import java.util.concurrent.ScheduledFuture; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.TimeoutException; + +-import static java.util.Objects.requireNonNull; +- + @Deprecated + public class InstrumentedScheduledExecutorService implements ScheduledExecutorService { + +- private final io.dropwizard.metrics5.InstrumentedScheduledExecutorService delegate; +- +- public InstrumentedScheduledExecutorService(io.dropwizard.metrics5.InstrumentedScheduledExecutorService delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- public InstrumentedScheduledExecutorService(ScheduledExecutorService delegate, MetricRegistry registry) { +- this(new io.dropwizard.metrics5.InstrumentedScheduledExecutorService(delegate, registry.getDelegate())); +- } +- +- public InstrumentedScheduledExecutorService(ScheduledExecutorService delegate, MetricRegistry registry, String name) { +- this(new io.dropwizard.metrics5.InstrumentedScheduledExecutorService(delegate, registry.getDelegate(), name)); +- } +- +- @Override +- public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { +- return delegate.schedule(command, delay, unit); +- } +- +- @Override +- public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { +- return delegate.schedule(callable, delay, unit); +- } +- +- @Override +- public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { +- return delegate.scheduleAtFixedRate(command, initialDelay, period, unit); +- } +- +- @Override +- public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { +- return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit); +- } +- +- @Override +- public void shutdown() { +- delegate.shutdown(); +- } +- +- @Override +- public List shutdownNow() { +- return delegate.shutdownNow(); +- } +- +- @Override +- public boolean isShutdown() { +- return delegate.isShutdown(); +- } +- +- @Override +- public boolean isTerminated() { +- return delegate.isTerminated(); +- } +- +- @Override +- public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { +- return delegate.awaitTermination(timeout, unit); +- } +- +- @Override +- public Future submit(Callable task) { +- return delegate.submit(task); +- } +- +- @Override +- public Future submit(Runnable task, T result) { +- return delegate.submit(task, result); +- } +- +- @Override +- public Future submit(Runnable task) { +- return delegate.submit(task); +- } +- +- @Override +- public List> invokeAll(Collection> tasks) throws InterruptedException { +- return delegate.invokeAll(tasks); +- } +- +- @Override +- public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { +- return delegate.invokeAll(tasks, timeout, unit); +- } +- +- @Override +- public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { +- return delegate.invokeAny(tasks); +- } +- +- @Override +- public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { +- return delegate.invokeAny(tasks, timeout, unit); +- } +- +- @Override +- public void execute(Runnable command) { +- delegate.execute(command); +- } ++ private final io.dropwizard.metrics5.InstrumentedScheduledExecutorService delegate; ++ ++ public InstrumentedScheduledExecutorService( ++ io.dropwizard.metrics5.InstrumentedScheduledExecutorService delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ public InstrumentedScheduledExecutorService( ++ ScheduledExecutorService delegate, MetricRegistry registry) { ++ this( ++ new io.dropwizard.metrics5.InstrumentedScheduledExecutorService( ++ delegate, registry.getDelegate())); ++ } ++ ++ public InstrumentedScheduledExecutorService( ++ ScheduledExecutorService delegate, MetricRegistry registry, String name) { ++ this( ++ new io.dropwizard.metrics5.InstrumentedScheduledExecutorService( ++ delegate, registry.getDelegate(), name)); ++ } ++ ++ @Override ++ public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { ++ return delegate.schedule(command, delay, unit); ++ } ++ ++ @Override ++ public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { ++ return delegate.schedule(callable, delay, unit); ++ } ++ ++ @Override ++ public ScheduledFuture scheduleAtFixedRate( ++ Runnable command, long initialDelay, long period, TimeUnit unit) { ++ return delegate.scheduleAtFixedRate(command, initialDelay, period, unit); ++ } ++ ++ @Override ++ public ScheduledFuture scheduleWithFixedDelay( ++ Runnable command, long initialDelay, long delay, TimeUnit unit) { ++ return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit); ++ } ++ ++ @Override ++ public void shutdown() { ++ delegate.shutdown(); ++ } ++ ++ @Override ++ public List shutdownNow() { ++ return delegate.shutdownNow(); ++ } ++ ++ @Override ++ public boolean isShutdown() { ++ return delegate.isShutdown(); ++ } ++ ++ @Override ++ public boolean isTerminated() { ++ return delegate.isTerminated(); ++ } ++ ++ @Override ++ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { ++ return delegate.awaitTermination(timeout, unit); ++ } ++ ++ @Override ++ public Future submit(Callable task) { ++ return delegate.submit(task); ++ } ++ ++ @Override ++ public Future submit(Runnable task, T result) { ++ return delegate.submit(task, result); ++ } ++ ++ @Override ++ public Future submit(Runnable task) { ++ return delegate.submit(task); ++ } ++ ++ @Override ++ public List> invokeAll(Collection> tasks) ++ throws InterruptedException { ++ return delegate.invokeAll(tasks); ++ } ++ ++ @Override ++ public List> invokeAll( ++ Collection> tasks, long timeout, TimeUnit unit) ++ throws InterruptedException { ++ return delegate.invokeAll(tasks, timeout, unit); ++ } ++ ++ @Override ++ public T invokeAny(Collection> tasks) ++ throws InterruptedException, ExecutionException { ++ return delegate.invokeAny(tasks); ++ } ++ ++ @Override ++ public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) ++ throws InterruptedException, ExecutionException, TimeoutException { ++ return delegate.invokeAny(tasks, timeout, unit); ++ } ++ ++ @Override ++ public void execute(Runnable command) { ++ delegate.execute(command); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedThreadFactory.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedThreadFactory.java +@@ -1,28 +1,30 @@ + package com.codahale.metrics; + +-import java.util.concurrent.ThreadFactory; +- + import static java.util.Objects.requireNonNull; + ++import java.util.concurrent.ThreadFactory; ++ + @Deprecated + public class InstrumentedThreadFactory implements ThreadFactory { + +- private final io.dropwizard.metrics5.InstrumentedThreadFactory delegate; ++ private final io.dropwizard.metrics5.InstrumentedThreadFactory delegate; + +- public InstrumentedThreadFactory(io.dropwizard.metrics5.InstrumentedThreadFactory delegate) { +- this.delegate = requireNonNull(delegate); +- } ++ public InstrumentedThreadFactory(io.dropwizard.metrics5.InstrumentedThreadFactory delegate) { ++ this.delegate = requireNonNull(delegate); ++ } + +- public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry) { +- this(new io.dropwizard.metrics5.InstrumentedThreadFactory(delegate, registry.getDelegate())); +- } ++ public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry) { ++ this(new io.dropwizard.metrics5.InstrumentedThreadFactory(delegate, registry.getDelegate())); ++ } + +- public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry, String name) { +- this(new io.dropwizard.metrics5.InstrumentedThreadFactory(delegate, registry.getDelegate(), name)); +- } ++ public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry, String name) { ++ this( ++ new io.dropwizard.metrics5.InstrumentedThreadFactory( ++ delegate, registry.getDelegate(), name)); ++ } + +- @Override +- public Thread newThread(Runnable r) { +- return delegate.newThread(r); +- } ++ @Override ++ public Thread newThread(Runnable r) { ++ return delegate.newThread(r); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Meter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Meter.java +@@ -5,55 +5,55 @@ import static java.util.Objects.requireNonNull; + @Deprecated + public class Meter implements Metered { + +- private final io.dropwizard.metrics5.Meter delegate; +- +- public Meter() { +- this(new io.dropwizard.metrics5.Meter()); +- } +- +- public Meter(Clock clock) { +- this(new io.dropwizard.metrics5.Meter(clock.getDelegate())); +- } +- +- public Meter(io.dropwizard.metrics5.Meter delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- public void mark() { +- delegate.mark(); +- } +- +- public void mark(long n) { +- delegate.mark(n); +- } +- +- @Override +- public long getCount() { +- return delegate.getCount(); +- } +- +- @Override +- public double getFifteenMinuteRate() { +- return delegate.getFifteenMinuteRate(); +- } +- +- @Override +- public double getFiveMinuteRate() { +- return delegate.getFiveMinuteRate(); +- } +- +- @Override +- public double getMeanRate() { +- return delegate.getMeanRate(); +- } +- +- @Override +- public double getOneMinuteRate() { +- return delegate.getOneMinuteRate(); +- } +- +- @Override +- public io.dropwizard.metrics5.Meter getDelegate() { +- return delegate; +- } ++ private final io.dropwizard.metrics5.Meter delegate; ++ ++ public Meter() { ++ this(new io.dropwizard.metrics5.Meter()); ++ } ++ ++ public Meter(Clock clock) { ++ this(new io.dropwizard.metrics5.Meter(clock.getDelegate())); ++ } ++ ++ public Meter(io.dropwizard.metrics5.Meter delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ public void mark() { ++ delegate.mark(); ++ } ++ ++ public void mark(long n) { ++ delegate.mark(n); ++ } ++ ++ @Override ++ public long getCount() { ++ return delegate.getCount(); ++ } ++ ++ @Override ++ public double getFifteenMinuteRate() { ++ return delegate.getFifteenMinuteRate(); ++ } ++ ++ @Override ++ public double getFiveMinuteRate() { ++ return delegate.getFiveMinuteRate(); ++ } ++ ++ @Override ++ public double getMeanRate() { ++ return delegate.getMeanRate(); ++ } ++ ++ @Override ++ public double getOneMinuteRate() { ++ return delegate.getOneMinuteRate(); ++ } ++ ++ @Override ++ public io.dropwizard.metrics5.Meter getDelegate() { ++ return delegate; ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Metered.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Metered.java +@@ -3,14 +3,14 @@ package com.codahale.metrics; + @Deprecated + public interface Metered extends Metric, Counting { + +- @Override +- long getCount(); ++ @Override ++ long getCount(); + +- double getFifteenMinuteRate(); ++ double getFifteenMinuteRate(); + +- double getFiveMinuteRate(); ++ double getFiveMinuteRate(); + +- double getMeanRate(); ++ double getMeanRate(); + +- double getOneMinuteRate(); ++ double getOneMinuteRate(); + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Metric.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Metric.java +@@ -3,24 +3,25 @@ package com.codahale.metrics; + @Deprecated + public interface Metric { + +- io.dropwizard.metrics5.Metric getDelegate(); ++ io.dropwizard.metrics5.Metric getDelegate(); + +- @SuppressWarnings("unchecked") +- static Metric of(io.dropwizard.metrics5.Metric metric) { +- if (metric instanceof io.dropwizard.metrics5.Counter) { +- return new Counter((io.dropwizard.metrics5.Counter) metric); +- } else if (metric instanceof io.dropwizard.metrics5.Histogram) { +- return new Histogram((io.dropwizard.metrics5.Histogram) metric); +- } else if (metric instanceof io.dropwizard.metrics5.Meter) { +- return new Meter((io.dropwizard.metrics5.Meter) metric); +- } else if (metric instanceof io.dropwizard.metrics5.Timer) { +- return new Timer((io.dropwizard.metrics5.Timer) metric); +- } else if (metric instanceof io.dropwizard.metrics5.Gauge) { +- return Gauge.of((io.dropwizard.metrics5.Gauge) metric); +- } else if (metric instanceof io.dropwizard.metrics5.MetricSet) { +- return MetricSet.of((io.dropwizard.metrics5.MetricSet) metric); +- } else { +- throw new IllegalArgumentException("Can't find adaptor class for metric of type: " + metric.getClass().getName()); +- } ++ @SuppressWarnings("unchecked") ++ static Metric of(io.dropwizard.metrics5.Metric metric) { ++ if (metric instanceof io.dropwizard.metrics5.Counter) { ++ return new Counter((io.dropwizard.metrics5.Counter) metric); ++ } else if (metric instanceof io.dropwizard.metrics5.Histogram) { ++ return new Histogram((io.dropwizard.metrics5.Histogram) metric); ++ } else if (metric instanceof io.dropwizard.metrics5.Meter) { ++ return new Meter((io.dropwizard.metrics5.Meter) metric); ++ } else if (metric instanceof io.dropwizard.metrics5.Timer) { ++ return new Timer((io.dropwizard.metrics5.Timer) metric); ++ } else if (metric instanceof io.dropwizard.metrics5.Gauge) { ++ return Gauge.of((io.dropwizard.metrics5.Gauge) metric); ++ } else if (metric instanceof io.dropwizard.metrics5.MetricSet) { ++ return MetricSet.of((io.dropwizard.metrics5.MetricSet) metric); ++ } else { ++ throw new IllegalArgumentException( ++ "Can't find adaptor class for metric of type: " + metric.getClass().getName()); + } ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricAttribute.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricAttribute.java +@@ -5,40 +5,40 @@ import java.util.Set; + + @Deprecated + public enum MetricAttribute { ++ MAX("max"), ++ MEAN("mean"), ++ MIN("min"), ++ STDDEV("stddev"), ++ P50("p50"), ++ P75("p75"), ++ P95("p95"), ++ P98("p98"), ++ P99("p99"), ++ P999("p999"), ++ COUNT("count"), ++ SUM("sum"), ++ M1_RATE("m1_rate"), ++ M5_RATE("m5_rate"), ++ M15_RATE("m15_rate"), ++ MEAN_RATE("mean_rate"); + +- MAX("max"), +- MEAN("mean"), +- MIN("min"), +- STDDEV("stddev"), +- P50("p50"), +- P75("p75"), +- P95("p95"), +- P98("p98"), +- P99("p99"), +- P999("p999"), +- COUNT("count"), +- SUM("sum"), +- M1_RATE("m1_rate"), +- M5_RATE("m5_rate"), +- M15_RATE("m15_rate"), +- MEAN_RATE("mean_rate"); ++ private final String code; + +- private final String code; ++ MetricAttribute(String code) { ++ this.code = code; ++ } + +- MetricAttribute(String code) { +- this.code = code; +- } +- +- public String getCode() { +- return code; +- } ++ public String getCode() { ++ return code; ++ } + +- public static Set transform(Set metricAttributes) { +- EnumSet newAttributes = EnumSet.noneOf( +- io.dropwizard.metrics5.MetricAttribute.class); +- for (MetricAttribute ma : metricAttributes) { +- newAttributes.add(io.dropwizard.metrics5.MetricAttribute.valueOf(ma.name())); +- } +- return newAttributes; ++ public static Set transform( ++ Set metricAttributes) { ++ EnumSet newAttributes = ++ EnumSet.noneOf(io.dropwizard.metrics5.MetricAttribute.class); ++ for (MetricAttribute ma : metricAttributes) { ++ newAttributes.add(io.dropwizard.metrics5.MetricAttribute.valueOf(ma.name())); + } ++ return newAttributes; ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricFilter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricFilter.java +@@ -3,24 +3,24 @@ package com.codahale.metrics; + @Deprecated + public interface MetricFilter { + +- MetricFilter ALL = (name, metric) -> true; ++ MetricFilter ALL = (name, metric) -> true; + +- static MetricFilter startsWith(String prefix) { +- return (name, metric) -> name.startsWith(prefix); +- } ++ static MetricFilter startsWith(String prefix) { ++ return (name, metric) -> name.startsWith(prefix); ++ } + +- static MetricFilter endsWith(String suffix) { +- return (name, metric) -> name.endsWith(suffix); +- } ++ static MetricFilter endsWith(String suffix) { ++ return (name, metric) -> name.endsWith(suffix); ++ } + +- static MetricFilter contains(String substring) { +- return (name, metric) -> name.contains(substring); +- } ++ static MetricFilter contains(String substring) { ++ return (name, metric) -> name.contains(substring); ++ } + +- boolean matches(String name, Metric metric); ++ boolean matches(String name, Metric metric); + +- default io.dropwizard.metrics5.MetricFilter transform() { +- final MetricFilter origin = this; +- return (name, metric) -> origin.matches(name.getKey(), Metric.of(metric)); +- } ++ default io.dropwizard.metrics5.MetricFilter transform() { ++ final MetricFilter origin = this; ++ return (name, metric) -> origin.matches(name.getKey(), Metric.of(metric)); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java +@@ -1,184 +1,181 @@ + package com.codahale.metrics; + +-import io.dropwizard.metrics5.MetricName; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; ++import static java.util.Objects.requireNonNull; ++import static java.util.stream.Collectors.toCollection; + +-import java.util.Collections; ++import io.dropwizard.metrics5.MetricName; + import java.util.Map; +-import java.util.Objects; + import java.util.SortedMap; + import java.util.SortedSet; + import java.util.TreeMap; + import java.util.TreeSet; +-import java.util.stream.Collectors; +- +-import static java.util.Collections.unmodifiableSortedSet; +-import static java.util.Objects.requireNonNull; + + @Deprecated + public class MetricRegistry implements MetricSet { + +- private final io.dropwizard.metrics5.MetricRegistry delegate; ++ private final io.dropwizard.metrics5.MetricRegistry delegate; + +- public static String name(Class klass, String... names) { +- return io.dropwizard.metrics5.MetricRegistry.name(klass, names).getKey(); +- } ++ public static String name(Class klass, String... names) { ++ return io.dropwizard.metrics5.MetricRegistry.name(klass, names).getKey(); ++ } + +- public static String name(String name, String... names) { +- return io.dropwizard.metrics5.MetricRegistry.name(name, names).getKey(); +- } ++ public static String name(String name, String... names) { ++ return io.dropwizard.metrics5.MetricRegistry.name(name, names).getKey(); ++ } + +- public MetricRegistry() { +- this(new io.dropwizard.metrics5.MetricRegistry()); +- } ++ public MetricRegistry() { ++ this(new io.dropwizard.metrics5.MetricRegistry()); ++ } + +- public MetricRegistry(io.dropwizard.metrics5.MetricRegistry delegate) { +- this.delegate = requireNonNull(delegate); +- } ++ public MetricRegistry(io.dropwizard.metrics5.MetricRegistry delegate) { ++ this.delegate = requireNonNull(delegate); ++ } + +- public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { +- delegate.registerGauge(MetricName.build(name), metric.getDelegate()); +- return metric; +- } ++ public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { ++ delegate.registerGauge(MetricName.build(name), metric.getDelegate()); ++ return metric; ++ } + +- public T register(String name, T metric) throws IllegalArgumentException { +- delegate.register(MetricName.build(name), metric.getDelegate()); +- return metric; +- } ++ public T register(String name, T metric) throws IllegalArgumentException { ++ delegate.register(MetricName.build(name), metric.getDelegate()); ++ return metric; ++ } + +- public void registerAll(MetricSet metrics) throws IllegalArgumentException { +- delegate.registerAll(metrics.getDelegate()); +- } ++ public void registerAll(MetricSet metrics) throws IllegalArgumentException { ++ delegate.registerAll(metrics.getDelegate()); ++ } + +- @SuppressWarnings("unchecked") +- public Gauge gauge(String name, MetricSupplier supplier) { +- return Gauge.of(delegate.gauge(MetricName.build(name), supplier.transform())); +- } ++ @SuppressWarnings("unchecked") ++ public Gauge gauge(String name, MetricSupplier supplier) { ++ return Gauge.of(delegate.gauge(MetricName.build(name), supplier.transform())); ++ } + +- public Counter counter(String name) { +- return new Counter(delegate.counter(name)); +- } ++ public Counter counter(String name) { ++ return new Counter(delegate.counter(name)); ++ } ++ ++ public Counter counter(String name, MetricSupplier supplier) { ++ return new Counter(delegate.counter(MetricName.build(name), supplier.transform())); ++ } ++ ++ public Histogram histogram(String name) { ++ return new Histogram(delegate.histogram(MetricName.build(name))); ++ } ++ ++ public Histogram histogram(String name, MetricSupplier supplier) { ++ return new Histogram(delegate.histogram(MetricName.build(name), supplier.transform())); ++ } ++ ++ public Meter meter(String name) { ++ return new Meter(delegate.meter(MetricName.build(name))); ++ } + +- public Counter counter(String name, MetricSupplier supplier) { +- return new Counter(delegate.counter(MetricName.build(name), supplier.transform())); +- } ++ public Meter meter(String name, MetricSupplier supplier) { ++ return new Meter(delegate.meter(MetricName.build(name), supplier.transform())); ++ } + +- public Histogram histogram(String name) { +- return new Histogram(delegate.histogram(MetricName.build(name))); +- } ++ public Timer timer(String name) { ++ return new Timer(delegate.timer(MetricName.build(name))); ++ } + +- public Histogram histogram(String name, MetricSupplier supplier) { +- return new Histogram(delegate.histogram(MetricName.build(name), supplier.transform())); +- } ++ public Timer timer(String name, MetricSupplier supplier) { ++ return new Timer(delegate.timer(MetricName.build(name), supplier.transform())); ++ } + +- public Meter meter(String name) { +- return new Meter(delegate.meter(MetricName.build(name))); +- } ++ public boolean remove(String name) { ++ return delegate.remove(MetricName.build(name)); ++ } + +- public Meter meter(String name, MetricSupplier supplier) { +- return new Meter(delegate.meter(MetricName.build(name), supplier.transform())); +- } ++ public void removeMatching(MetricFilter filter) { ++ delegate.removeMatching(filter.transform()); ++ } + +- public Timer timer(String name) { +- return new Timer(delegate.timer(MetricName.build(name))); +- } ++ public void addListener(MetricRegistryListener listener) { ++ delegate.addListener(new MetricRegistryListener.Adapter(listener)); ++ } + +- public Timer timer(String name, MetricSupplier supplier) { +- return new Timer(delegate.timer(MetricName.build(name), supplier.transform())); +- } ++ public void removeListener(MetricRegistryListener listener) { ++ delegate.removeListener(new MetricRegistryListener.Adapter(listener)); ++ } + +- public boolean remove(String name) { +- return delegate.remove(MetricName.build(name)); +- } ++ public SortedSet getNames() { ++ return unmodifiableSortedSet( ++ delegate.getNames().stream().map(MetricName::getKey).collect(toCollection(TreeSet::new))); ++ } + +- public void removeMatching(MetricFilter filter) { +- delegate.removeMatching(filter.transform()); +- } ++ public SortedMap getGauges() { ++ return adaptMetrics(delegate.getGauges()); ++ } + +- public void addListener(MetricRegistryListener listener) { +- delegate.addListener(new MetricRegistryListener.Adapter(listener)); +- } ++ public SortedMap getGauges(MetricFilter filter) { ++ return adaptMetrics(delegate.getGauges(filter.transform())); ++ } + +- public void removeListener(MetricRegistryListener listener) { +- delegate.removeListener(new MetricRegistryListener.Adapter(listener)); +- } ++ public SortedMap getCounters() { ++ return adaptMetrics(delegate.getCounters()); ++ } + +- public SortedSet getNames() { +- return unmodifiableSortedSet(delegate.getNames() +- .stream() +- .map(MetricName::getKey) +- .collect(Collectors.toCollection(TreeSet::new))); +- } ++ public SortedMap getCounters(MetricFilter filter) { ++ return adaptMetrics(delegate.getCounters(filter.transform())); ++ } + +- public SortedMap getGauges() { +- return adaptMetrics(delegate.getGauges()); +- } ++ public SortedMap getHistograms() { ++ return adaptMetrics(delegate.getHistograms()); ++ } + +- public SortedMap getGauges(MetricFilter filter) { +- return adaptMetrics(delegate.getGauges(filter.transform())); +- } ++ public SortedMap getHistograms(MetricFilter filter) { ++ return adaptMetrics(delegate.getHistograms(filter.transform())); ++ } + +- public SortedMap getCounters() { +- return adaptMetrics(delegate.getCounters()); +- } ++ public SortedMap getMeters() { ++ return adaptMetrics(delegate.getMeters()); ++ } + +- public SortedMap getCounters(MetricFilter filter) { +- return adaptMetrics(delegate.getCounters(filter.transform())); +- } ++ public SortedMap getMeters(MetricFilter filter) { ++ return adaptMetrics(delegate.getMeters(filter.transform())); ++ } + +- public SortedMap getHistograms() { +- return adaptMetrics(delegate.getHistograms()); +- } ++ public SortedMap getTimers() { ++ return adaptMetrics(delegate.getTimers()); ++ } + +- public SortedMap getHistograms(MetricFilter filter) { +- return adaptMetrics(delegate.getHistograms(filter.transform())); +- } ++ public SortedMap getTimers(MetricFilter filter) { ++ return adaptMetrics(delegate.getTimers(filter.transform())); ++ } + +- public SortedMap getMeters() { +- return adaptMetrics(delegate.getMeters()); +- } ++ @Override ++ public Map getMetrics() { ++ return adaptMetrics(delegate.getMetrics()); ++ } + +- public SortedMap getMeters(MetricFilter filter) { +- return adaptMetrics(delegate.getMeters(filter.transform())); ++ @SuppressWarnings("unchecked") ++ static SortedMap adaptMetrics( ++ Map metrics) { ++ final SortedMap items = new TreeMap<>(); ++ for (Map.Entry entry : ++ metrics.entrySet()) { ++ items.put(entry.getKey().getKey(), (T) Metric.of(entry.getValue())); + } ++ return unmodifiableSortedMap(items); ++ } + +- public SortedMap getTimers() { +- return adaptMetrics(delegate.getTimers()); +- } ++ @Override ++ public io.dropwizard.metrics5.MetricRegistry getDelegate() { ++ return delegate; ++ } + +- public SortedMap getTimers(MetricFilter filter) { +- return adaptMetrics(delegate.getTimers(filter.transform())); +- } ++ @FunctionalInterface ++ public interface MetricSupplier { + +- @Override +- public Map getMetrics() { +- return adaptMetrics(delegate.getMetrics()); +- } ++ T newMetric(); + + @SuppressWarnings("unchecked") +- static SortedMap adaptMetrics( +- Map metrics) { +- final SortedMap items = new TreeMap<>(); +- for (Map.Entry entry : metrics.entrySet()) { +- items.put(entry.getKey().getKey(), (T) Metric.of(entry.getValue())); +- } +- return Collections.unmodifiableSortedMap(items); +- } +- +- @Override +- public io.dropwizard.metrics5.MetricRegistry getDelegate() { +- return delegate; +- } +- +- @FunctionalInterface +- public interface MetricSupplier { +- +- T newMetric(); +- +- @SuppressWarnings("unchecked") +- default ++ default + io.dropwizard.metrics5.MetricRegistry.MetricSupplier transform() { +- MetricSupplier original = this; +- return () -> (M) original.newMetric().getDelegate(); +- } ++ MetricSupplier original = this; ++ return () -> (M) original.newMetric().getDelegate(); + } ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistryListener.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistryListener.java +@@ -1,144 +1,133 @@ + package com.codahale.metrics; + + import io.dropwizard.metrics5.MetricName; +- + import java.util.EventListener; + + @Deprecated + public interface MetricRegistryListener extends EventListener { + +- abstract class Base implements MetricRegistryListener { +- @Override +- public void onGaugeAdded(String name, Gauge gauge) { +- } ++ abstract class Base implements MetricRegistryListener { ++ @Override ++ public void onGaugeAdded(String name, Gauge gauge) {} + +- @Override +- public void onGaugeRemoved(String name) { +- } ++ @Override ++ public void onGaugeRemoved(String name) {} + +- @Override +- public void onCounterAdded(String name, Counter counter) { +- } ++ @Override ++ public void onCounterAdded(String name, Counter counter) {} + +- @Override +- public void onCounterRemoved(String name) { +- } ++ @Override ++ public void onCounterRemoved(String name) {} + +- @Override +- public void onHistogramAdded(String name, Histogram histogram) { +- } ++ @Override ++ public void onHistogramAdded(String name, Histogram histogram) {} + +- @Override +- public void onHistogramRemoved(String name) { +- } ++ @Override ++ public void onHistogramRemoved(String name) {} + +- @Override +- public void onMeterAdded(String name, Meter meter) { +- } ++ @Override ++ public void onMeterAdded(String name, Meter meter) {} + +- @Override +- public void onMeterRemoved(String name) { +- } ++ @Override ++ public void onMeterRemoved(String name) {} + +- @Override +- public void onTimerAdded(String name, Timer timer) { +- } ++ @Override ++ public void onTimerAdded(String name, Timer timer) {} + +- @Override +- public void onTimerRemoved(String name) { +- } +- } ++ @Override ++ public void onTimerRemoved(String name) {} ++ } + +- void onGaugeAdded(String name, Gauge gauge); ++ void onGaugeAdded(String name, Gauge gauge); + +- void onGaugeRemoved(String name); ++ void onGaugeRemoved(String name); + +- void onCounterAdded(String name, Counter counter); ++ void onCounterAdded(String name, Counter counter); + +- void onCounterRemoved(String name); ++ void onCounterRemoved(String name); + +- void onHistogramAdded(String name, Histogram histogram); ++ void onHistogramAdded(String name, Histogram histogram); + +- void onHistogramRemoved(String name); ++ void onHistogramRemoved(String name); + +- void onMeterAdded(String name, Meter meter); ++ void onMeterAdded(String name, Meter meter); + +- void onMeterRemoved(String name); ++ void onMeterRemoved(String name); + +- void onTimerAdded(String name, Timer timer); ++ void onTimerAdded(String name, Timer timer); + +- void onTimerRemoved(String name); ++ void onTimerRemoved(String name); + +- class Adapter implements io.dropwizard.metrics5.MetricRegistryListener { ++ class Adapter implements io.dropwizard.metrics5.MetricRegistryListener { + +- private MetricRegistryListener delegate; ++ private MetricRegistryListener delegate; + +- public Adapter(MetricRegistryListener delegate) { +- this.delegate = delegate; +- } ++ public Adapter(MetricRegistryListener delegate) { ++ this.delegate = delegate; ++ } + +- @Override +- public void onGaugeAdded(MetricName name, io.dropwizard.metrics5.Gauge gauge) { +- delegate.onGaugeAdded(name.getKey(), Gauge.of(gauge)); +- } ++ @Override ++ public void onGaugeAdded(MetricName name, io.dropwizard.metrics5.Gauge gauge) { ++ delegate.onGaugeAdded(name.getKey(), Gauge.of(gauge)); ++ } + +- @Override +- public void onGaugeRemoved(MetricName name) { +- delegate.onGaugeRemoved(name.getKey()); +- } ++ @Override ++ public void onGaugeRemoved(MetricName name) { ++ delegate.onGaugeRemoved(name.getKey()); ++ } + +- @Override +- public void onCounterAdded(MetricName name, io.dropwizard.metrics5.Counter counter) { +- delegate.onCounterAdded(name.getKey(), new Counter(counter)); +- } ++ @Override ++ public void onCounterAdded(MetricName name, io.dropwizard.metrics5.Counter counter) { ++ delegate.onCounterAdded(name.getKey(), new Counter(counter)); ++ } + +- @Override +- public void onCounterRemoved(MetricName name) { +- delegate.onCounterRemoved(name.getKey()); +- } ++ @Override ++ public void onCounterRemoved(MetricName name) { ++ delegate.onCounterRemoved(name.getKey()); ++ } + +- @Override +- public void onHistogramAdded(MetricName name, io.dropwizard.metrics5.Histogram histogram) { +- delegate.onHistogramAdded(name.getKey(), new Histogram(histogram)); +- } ++ @Override ++ public void onHistogramAdded(MetricName name, io.dropwizard.metrics5.Histogram histogram) { ++ delegate.onHistogramAdded(name.getKey(), new Histogram(histogram)); ++ } + +- @Override +- public void onHistogramRemoved(MetricName name) { +- delegate.onHistogramRemoved(name.getKey()); +- } ++ @Override ++ public void onHistogramRemoved(MetricName name) { ++ delegate.onHistogramRemoved(name.getKey()); ++ } + +- @Override +- public void onMeterAdded(MetricName name, io.dropwizard.metrics5.Meter meter) { +- delegate.onMeterAdded(name.getKey(), new Meter(meter)); +- } ++ @Override ++ public void onMeterAdded(MetricName name, io.dropwizard.metrics5.Meter meter) { ++ delegate.onMeterAdded(name.getKey(), new Meter(meter)); ++ } + +- @Override +- public void onMeterRemoved(MetricName name) { +- delegate.onMeterRemoved(name.getKey()); +- } ++ @Override ++ public void onMeterRemoved(MetricName name) { ++ delegate.onMeterRemoved(name.getKey()); ++ } + +- @Override +- public void onTimerAdded(MetricName name, io.dropwizard.metrics5.Timer timer) { +- delegate.onTimerAdded(name.getKey(), new Timer(timer)); +- } ++ @Override ++ public void onTimerAdded(MetricName name, io.dropwizard.metrics5.Timer timer) { ++ delegate.onTimerAdded(name.getKey(), new Timer(timer)); ++ } + +- @Override +- public void onTimerRemoved(MetricName name) { +- delegate.onTimerRemoved(name.getKey()); +- } ++ @Override ++ public void onTimerRemoved(MetricName name) { ++ delegate.onTimerRemoved(name.getKey()); ++ } + +- @Override +- public boolean equals(Object o) { +- if (o instanceof Adapter) { +- Adapter adapter = (Adapter) o; +- return delegate.equals(adapter.delegate); +- } +- return false; +- } ++ @Override ++ public boolean equals(Object o) { ++ if (o instanceof Adapter) { ++ Adapter adapter = (Adapter) o; ++ return delegate.equals(adapter.delegate); ++ } ++ return false; ++ } + +- @Override +- public int hashCode() { +- return delegate.hashCode(); +- } ++ @Override ++ public int hashCode() { ++ return delegate.hashCode(); + } +-} +\ No newline at end of file ++ } ++} +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java +@@ -1,55 +1,55 @@ + package com.codahale.metrics; + +-import io.dropwizard.metrics5.MetricName; ++import static java.util.Collections.unmodifiableMap; + +-import java.util.Collections; ++import io.dropwizard.metrics5.MetricName; + import java.util.HashMap; + import java.util.Map; + + @Deprecated + public interface MetricSet extends Metric { + +- Map getMetrics(); +- +- @Override +- default io.dropwizard.metrics5.MetricSet getDelegate() { +- return new Adapter(this); +- } +- +- static MetricSet of(io.dropwizard.metrics5.MetricSet original) { +- return new MetricSet() { +- @Override +- public Map getMetrics() { +- final Map items = new HashMap<>(); +- for (Map.Entry entry : original.getMetrics().entrySet()) { +- items.put(entry.getKey().getKey(), Metric.of(entry.getValue())); +- } +- return Collections.unmodifiableMap(items); +- } +- +- @Override +- public io.dropwizard.metrics5.MetricSet getDelegate() { +- return original; +- } +- }; +- } ++ Map getMetrics(); ++ ++ @Override ++ default io.dropwizard.metrics5.MetricSet getDelegate() { ++ return new Adapter(this); ++ } ++ ++ static MetricSet of(io.dropwizard.metrics5.MetricSet original) { ++ return new MetricSet() { ++ @Override ++ public Map getMetrics() { ++ final Map items = new HashMap<>(); ++ for (Map.Entry entry : ++ original.getMetrics().entrySet()) { ++ items.put(entry.getKey().getKey(), Metric.of(entry.getValue())); ++ } ++ return unmodifiableMap(items); ++ } + +- class Adapter implements io.dropwizard.metrics5.MetricSet { ++ @Override ++ public io.dropwizard.metrics5.MetricSet getDelegate() { ++ return original; ++ } ++ }; ++ } + +- private final MetricSet delegate; ++ class Adapter implements io.dropwizard.metrics5.MetricSet { + +- Adapter(MetricSet delegate) { +- this.delegate = delegate; +- } ++ private final MetricSet delegate; + +- @Override +- public Map getMetrics() { +- final Map items = new HashMap<>(); +- for (Map.Entry entry : delegate.getMetrics().entrySet()) { +- items.put(MetricName.build(entry.getKey()), entry.getValue().getDelegate()); +- } +- return Collections.unmodifiableMap(items); +- } ++ Adapter(MetricSet delegate) { ++ this.delegate = delegate; + } + ++ @Override ++ public Map getMetrics() { ++ final Map items = new HashMap<>(); ++ for (Map.Entry entry : delegate.getMetrics().entrySet()) { ++ items.put(MetricName.build(entry.getKey()), entry.getValue().getDelegate()); ++ } ++ return unmodifiableMap(items); ++ } ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/RatioGauge.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/RatioGauge.java +@@ -5,32 +5,32 @@ import static java.util.Objects.requireNonNull; + @Deprecated + public abstract class RatioGauge implements Gauge { + +- public static class Ratio { ++ public static class Ratio { + +- private io.dropwizard.metrics5.RatioGauge.Ratio delegate; ++ private io.dropwizard.metrics5.RatioGauge.Ratio delegate; + +- public static Ratio of(double numerator, double denominator) { +- return new Ratio(io.dropwizard.metrics5.RatioGauge.Ratio.of(numerator, denominator)); +- } +- +- public Ratio(io.dropwizard.metrics5.RatioGauge.Ratio delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- public double getValue() { +- return delegate.getValue(); +- } ++ public static Ratio of(double numerator, double denominator) { ++ return new Ratio(io.dropwizard.metrics5.RatioGauge.Ratio.of(numerator, denominator)); ++ } + +- @Override +- public String toString() { +- return delegate.toString(); +- } ++ public Ratio(io.dropwizard.metrics5.RatioGauge.Ratio delegate) { ++ this.delegate = requireNonNull(delegate); + } + +- protected abstract Ratio getRatio(); ++ public double getValue() { ++ return delegate.getValue(); ++ } + + @Override +- public Double getValue() { +- return getRatio().getValue(); ++ public String toString() { ++ return delegate.toString(); + } ++ } ++ ++ protected abstract Ratio getRatio(); ++ ++ @Override ++ public Double getValue() { ++ return getRatio().getValue(); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Reporter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Reporter.java +@@ -1,6 +1,4 @@ + package com.codahale.metrics; + + @Deprecated +-public interface Reporter { +- +-} ++public interface Reporter {} +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Reservoir.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Reservoir.java +@@ -3,11 +3,11 @@ package com.codahale.metrics; + @Deprecated + public interface Reservoir { + +- int size(); ++ int size(); + +- void update(long value); ++ void update(long value); + +- Snapshot getSnapshot(); ++ Snapshot getSnapshot(); + +- io.dropwizard.metrics5.Reservoir getDelegate(); ++ io.dropwizard.metrics5.Reservoir getDelegate(); + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Sampling.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Sampling.java +@@ -3,5 +3,5 @@ package com.codahale.metrics; + @Deprecated + public interface Sampling { + +- Snapshot getSnapshot(); ++ Snapshot getSnapshot(); + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java +@@ -1,9 +1,10 @@ + package com.codahale.metrics; + +-import io.dropwizard.metrics5.MetricName; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Objects.requireNonNull; + ++import io.dropwizard.metrics5.MetricName; + import java.io.Closeable; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -11,142 +12,218 @@ import java.util.TreeMap; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; + +-import static java.util.Objects.requireNonNull; +- + @Deprecated + public abstract class ScheduledReporter implements Closeable, Reporter { + +- private io.dropwizard.metrics5.ScheduledReporter delegate; +- +- protected ScheduledReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, +- TimeUnit durationUnit) { +- delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, this); +- } +- +- protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, +- TimeUnit durationUnit, ScheduledExecutorService executor) { +- delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, executor, this); +- } +- +- protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, +- TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop) { +- delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, this); +- } +- +- protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, +- TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop, +- Set disabledMetricAttributes) { +- delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, +- disabledMetricAttributes, this); +- } +- +- public void start(long period, TimeUnit unit) { +- delegate.start(period, unit); +- } +- +- synchronized public void start(long initialDelay, long period, TimeUnit unit) { +- delegate.start(initialDelay, period, unit); +- } +- +- public void stop() { +- delegate.stop(); ++ private io.dropwizard.metrics5.ScheduledReporter delegate; ++ ++ protected ScheduledReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ protected ScheduledReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit) { ++ delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, this); ++ } ++ ++ protected ScheduledReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor) { ++ delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, executor, this); ++ } ++ ++ protected ScheduledReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop) { ++ delegate = ++ new Adapter( ++ registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, this); ++ } ++ ++ protected ScheduledReporter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes) { ++ delegate = ++ new Adapter( ++ registry, ++ name, ++ filter, ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop, ++ disabledMetricAttributes, ++ this); ++ } ++ ++ public void start(long period, TimeUnit unit) { ++ delegate.start(period, unit); ++ } ++ ++ public synchronized void start(long initialDelay, long period, TimeUnit unit) { ++ delegate.start(initialDelay, period, unit); ++ } ++ ++ public void stop() { ++ delegate.stop(); ++ } ++ ++ @Override ++ public void close() { ++ delegate.close(); ++ } ++ ++ public void report() { ++ delegate.report(); ++ } ++ ++ public io.dropwizard.metrics5.ScheduledReporter getDelegate() { ++ return delegate; ++ } ++ ++ @SuppressWarnings("rawtypes") ++ public abstract void report( ++ SortedMap gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers); ++ ++ @SuppressWarnings("unchecked") ++ protected SortedMap transform( ++ SortedMap metrics) { ++ final SortedMap items = new TreeMap<>(); ++ for (Map.Entry entry : metrics.entrySet()) { ++ items.put(MetricName.build(entry.getKey()), (T) entry.getValue().getDelegate()); ++ } ++ return unmodifiableSortedMap(items); ++ } ++ ++ protected String getRateUnit() { ++ return delegate.getRateUnit(); ++ } ++ ++ protected String getDurationUnit() { ++ return delegate.getDurationUnit(); ++ } ++ ++ protected double convertDuration(double duration) { ++ return delegate.convertDuration(duration); ++ } ++ ++ protected double convertRate(double rate) { ++ return delegate.convertRate(rate); ++ } ++ ++ protected boolean isShutdownExecutorOnStop() { ++ return delegate.isShutdownExecutorOnStop(); ++ } ++ ++ protected Set getDisabledMetricAttributes() { ++ return delegate.getDisabledMetricAttributes(); ++ } ++ ++ public static class Adapter extends io.dropwizard.metrics5.ScheduledReporter { ++ ++ private final ScheduledReporter delegate; ++ ++ public Adapter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledReporter delegate) { ++ super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit); ++ this.delegate = delegate; ++ } ++ ++ public Adapter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor, ++ ScheduledReporter delegate) { ++ super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit, executor); ++ this.delegate = delegate; ++ } ++ ++ public Adapter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ ScheduledReporter delegate) { ++ super( ++ registry.getDelegate(), ++ name, ++ filter.transform(), ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop); ++ this.delegate = delegate; ++ } ++ ++ public Adapter( ++ MetricRegistry registry, ++ String name, ++ MetricFilter filter, ++ TimeUnit rateUnit, ++ TimeUnit durationUnit, ++ ScheduledExecutorService executor, ++ boolean shutdownExecutorOnStop, ++ Set disabledMetricAttributes, ++ ScheduledReporter delegate) { ++ super( ++ registry.getDelegate(), ++ name, ++ filter.transform(), ++ rateUnit, ++ durationUnit, ++ executor, ++ shutdownExecutorOnStop, ++ MetricAttribute.transform(disabledMetricAttributes)); ++ this.delegate = delegate; + } + + @Override +- public void close() { +- delegate.close(); +- } +- +- public void report() { +- delegate.report(); +- } +- +- public io.dropwizard.metrics5.ScheduledReporter getDelegate() { +- return delegate; +- } +- +- @SuppressWarnings("rawtypes") +- public abstract void report(SortedMap gauges, +- SortedMap counters, +- SortedMap histograms, +- SortedMap meters, +- SortedMap timers); +- +- @SuppressWarnings("unchecked") +- protected SortedMap transform( +- SortedMap metrics) { +- final SortedMap items = new TreeMap<>(); +- for (Map.Entry entry : metrics.entrySet()) { +- items.put(MetricName.build(entry.getKey()), (T) entry.getValue().getDelegate()); +- } +- return Collections.unmodifiableSortedMap(items); +- } +- +- protected String getRateUnit() { +- return delegate.getRateUnit(); +- } +- +- protected String getDurationUnit() { +- return delegate.getDurationUnit(); +- } +- +- protected double convertDuration(double duration) { +- return delegate.convertDuration(duration); +- } +- +- protected double convertRate(double rate) { +- return delegate.convertRate(rate); +- } +- +- protected boolean isShutdownExecutorOnStop() { +- return delegate.isShutdownExecutorOnStop(); +- } +- +- protected Set getDisabledMetricAttributes() { +- return delegate.getDisabledMetricAttributes(); +- } +- +- public static class Adapter extends io.dropwizard.metrics5.ScheduledReporter { +- +- private final ScheduledReporter delegate; +- +- public Adapter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, +- ScheduledReporter delegate) { +- super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit); +- this.delegate = delegate; +- } +- +- public Adapter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, +- ScheduledExecutorService executor, ScheduledReporter delegate) { +- super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit, executor); +- this.delegate = delegate; +- } +- +- public Adapter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, +- ScheduledExecutorService executor, boolean shutdownExecutorOnStop, ScheduledReporter delegate) { +- super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit, executor, shutdownExecutorOnStop); +- this.delegate = delegate; +- } +- +- public Adapter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, +- ScheduledExecutorService executor, boolean shutdownExecutorOnStop, Set disabledMetricAttributes, +- ScheduledReporter delegate) { +- super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit, executor, shutdownExecutorOnStop, +- MetricAttribute.transform(disabledMetricAttributes)); +- this.delegate = delegate; +- } +- +- @Override +- public void report(SortedMap> gauges, SortedMap counters, +- SortedMap histograms, SortedMap meters, +- SortedMap timers) { +- delegate.report(MetricRegistry.adaptMetrics(gauges), MetricRegistry.adaptMetrics(counters), +- MetricRegistry.adaptMetrics(histograms), MetricRegistry.adaptMetrics(meters), +- MetricRegistry.adaptMetrics(timers)); +- } +- } ++ public void report( ++ SortedMap> gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ delegate.report( ++ MetricRegistry.adaptMetrics(gauges), ++ MetricRegistry.adaptMetrics(counters), ++ MetricRegistry.adaptMetrics(histograms), ++ MetricRegistry.adaptMetrics(meters), ++ MetricRegistry.adaptMetrics(timers)); ++ } ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SharedMetricRegistries.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SharedMetricRegistries.java +@@ -2,48 +2,47 @@ package com.codahale.metrics; + + import java.util.Optional; + import java.util.Set; +-import java.util.concurrent.atomic.AtomicReference; + + @Deprecated + public class SharedMetricRegistries { + +- public static void clear() { +- io.dropwizard.metrics5.SharedMetricRegistries.clear(); +- } +- +- public static Set names() { +- return io.dropwizard.metrics5.SharedMetricRegistries.names(); +- } +- +- public static void remove(String key) { +- io.dropwizard.metrics5.SharedMetricRegistries.remove(key); +- } +- +- public static MetricRegistry add(String name, MetricRegistry registry) { +- io.dropwizard.metrics5.SharedMetricRegistries.add(name, registry.getDelegate()); +- return registry; +- } +- +- public static MetricRegistry getOrCreate(String name) { +- return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.getOrCreate(name)); +- } +- +- public synchronized static MetricRegistry setDefault(String name) { +- return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.setDefault(name)); +- } +- +- public static MetricRegistry setDefault(String name, MetricRegistry metricRegistry) { +- io.dropwizard.metrics5.SharedMetricRegistries.setDefault(name, metricRegistry.getDelegate()); +- return metricRegistry; +- } +- +- public static MetricRegistry getDefault() { +- return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.getDefault()); +- } +- +- public static MetricRegistry tryGetDefault() { +- return Optional.ofNullable(io.dropwizard.metrics5.SharedMetricRegistries.tryGetDefault()) +- .map(MetricRegistry::new) +- .orElse(null); +- } ++ public static void clear() { ++ io.dropwizard.metrics5.SharedMetricRegistries.clear(); ++ } ++ ++ public static Set names() { ++ return io.dropwizard.metrics5.SharedMetricRegistries.names(); ++ } ++ ++ public static void remove(String key) { ++ io.dropwizard.metrics5.SharedMetricRegistries.remove(key); ++ } ++ ++ public static MetricRegistry add(String name, MetricRegistry registry) { ++ io.dropwizard.metrics5.SharedMetricRegistries.add(name, registry.getDelegate()); ++ return registry; ++ } ++ ++ public static MetricRegistry getOrCreate(String name) { ++ return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.getOrCreate(name)); ++ } ++ ++ public static synchronized MetricRegistry setDefault(String name) { ++ return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.setDefault(name)); ++ } ++ ++ public static MetricRegistry setDefault(String name, MetricRegistry metricRegistry) { ++ io.dropwizard.metrics5.SharedMetricRegistries.setDefault(name, metricRegistry.getDelegate()); ++ return metricRegistry; ++ } ++ ++ public static MetricRegistry getDefault() { ++ return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.getDefault()); ++ } ++ ++ public static MetricRegistry tryGetDefault() { ++ return Optional.ofNullable(io.dropwizard.metrics5.SharedMetricRegistries.tryGetDefault()) ++ .map(MetricRegistry::new) ++ .orElse(null); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Slf4jReporter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Slf4jReporter.java +@@ -1,91 +1,106 @@ + package com.codahale.metrics; + +-import org.slf4j.Logger; +-import org.slf4j.Marker; ++import static java.util.Objects.requireNonNull; + + import java.util.SortedMap; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; +- +-import static java.util.Objects.requireNonNull; ++import org.slf4j.Logger; ++import org.slf4j.Marker; + + @Deprecated + public class Slf4jReporter extends ScheduledReporter { + +- public static Slf4jReporter.Builder forRegistry(MetricRegistry registry) { +- return new Slf4jReporter.Builder(io.dropwizard.metrics5.Slf4jReporter.forRegistry(registry.getDelegate())); +- } +- +- public enum LoggingLevel {TRACE, DEBUG, INFO, WARN, ERROR} ++ public static Slf4jReporter.Builder forRegistry(MetricRegistry registry) { ++ return new Slf4jReporter.Builder( ++ io.dropwizard.metrics5.Slf4jReporter.forRegistry(registry.getDelegate())); ++ } + +- public static class Builder { ++ public enum LoggingLevel { ++ TRACE, ++ DEBUG, ++ INFO, ++ WARN, ++ ERROR ++ } + +- private io.dropwizard.metrics5.Slf4jReporter.Builder delegate; ++ public static class Builder { + +- private Builder(io.dropwizard.metrics5.Slf4jReporter.Builder delegate) { +- this.delegate = requireNonNull(delegate); +- } ++ private io.dropwizard.metrics5.Slf4jReporter.Builder delegate; + +- public Slf4jReporter.Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { +- delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); +- return this; +- } +- +- public Slf4jReporter.Builder scheduleOn(ScheduledExecutorService executor) { +- delegate.scheduleOn(executor); +- return this; +- } ++ private Builder(io.dropwizard.metrics5.Slf4jReporter.Builder delegate) { ++ this.delegate = requireNonNull(delegate); ++ } + +- public Slf4jReporter.Builder outputTo(Logger logger) { +- delegate.outputTo(logger); +- return this; +- } ++ public Slf4jReporter.Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { ++ delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); ++ return this; ++ } + +- public Slf4jReporter.Builder markWith(Marker marker) { +- delegate.markWith(marker); +- return this; +- } ++ public Slf4jReporter.Builder scheduleOn(ScheduledExecutorService executor) { ++ delegate.scheduleOn(executor); ++ return this; ++ } + +- public Slf4jReporter.Builder prefixedWith(String prefix) { +- delegate.prefixedWith(prefix); +- return this; +- } ++ public Slf4jReporter.Builder outputTo(Logger logger) { ++ delegate.outputTo(logger); ++ return this; ++ } + +- public Slf4jReporter.Builder convertRatesTo(TimeUnit rateUnit) { +- delegate.convertRatesTo(rateUnit); +- return this; +- } ++ public Slf4jReporter.Builder markWith(Marker marker) { ++ delegate.markWith(marker); ++ return this; ++ } + +- public Slf4jReporter.Builder convertDurationsTo(TimeUnit durationUnit) { +- delegate.convertDurationsTo(durationUnit); +- return this; +- } ++ public Slf4jReporter.Builder prefixedWith(String prefix) { ++ delegate.prefixedWith(prefix); ++ return this; ++ } + +- public Slf4jReporter.Builder filter(MetricFilter filter) { +- delegate.filter(filter.transform()); +- return this; +- } ++ public Slf4jReporter.Builder convertRatesTo(TimeUnit rateUnit) { ++ delegate.convertRatesTo(rateUnit); ++ return this; ++ } + +- public Slf4jReporter.Builder withLoggingLevel(LoggingLevel loggingLevel) { +- delegate.withLoggingLevel(io.dropwizard.metrics5.Slf4jReporter.LoggingLevel.valueOf(loggingLevel.name())); +- return this; +- } ++ public Slf4jReporter.Builder convertDurationsTo(TimeUnit durationUnit) { ++ delegate.convertDurationsTo(durationUnit); ++ return this; ++ } + +- public Slf4jReporter build() { +- return new Slf4jReporter(delegate.build()); +- } ++ public Slf4jReporter.Builder filter(MetricFilter filter) { ++ delegate.filter(filter.transform()); ++ return this; + } + +- private Slf4jReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { +- super(delegate); ++ public Slf4jReporter.Builder withLoggingLevel(LoggingLevel loggingLevel) { ++ delegate.withLoggingLevel( ++ io.dropwizard.metrics5.Slf4jReporter.LoggingLevel.valueOf(loggingLevel.name())); ++ return this; + } + +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap gauges, SortedMap counters, +- SortedMap histograms, SortedMap meters, +- SortedMap timers) { +- getDelegate().report(transform(gauges), transform(counters), transform(histograms), transform(meters), +- transform(timers)); ++ public Slf4jReporter build() { ++ return new Slf4jReporter(delegate.build()); + } ++ } ++ ++ private Slf4jReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { ++ super(delegate); ++ } ++ ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ getDelegate() ++ .report( ++ transform(gauges), ++ transform(counters), ++ transform(histograms), ++ transform(meters), ++ transform(timers)); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingTimeWindowArrayReservoir.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingTimeWindowArrayReservoir.java +@@ -1,43 +1,46 @@ + package com.codahale.metrics; + +-import java.util.concurrent.TimeUnit; +- + import static java.util.Objects.requireNonNull; + ++import java.util.concurrent.TimeUnit; ++ + @Deprecated + public class SlidingTimeWindowArrayReservoir implements Reservoir { + +- private io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir delegate; +- +- public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit) { +- this(new io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir(window, windowUnit)); +- } +- +- public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit, Clock clock) { +- this(new io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir(window, windowUnit, clock.getDelegate())); +- } +- +- public SlidingTimeWindowArrayReservoir(io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- @Override +- public io.dropwizard.metrics5.Reservoir getDelegate() { +- return delegate; +- } +- +- @Override +- public int size() { +- return delegate.size(); +- } +- +- @Override +- public void update(long value) { +- delegate.update(value); +- } +- +- @Override +- public Snapshot getSnapshot() { +- return Snapshot.of(delegate.getSnapshot()); +- } ++ private io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir delegate; ++ ++ public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit) { ++ this(new io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir(window, windowUnit)); ++ } ++ ++ public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit, Clock clock) { ++ this( ++ new io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir( ++ window, windowUnit, clock.getDelegate())); ++ } ++ ++ public SlidingTimeWindowArrayReservoir( ++ io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ @Override ++ public io.dropwizard.metrics5.Reservoir getDelegate() { ++ return delegate; ++ } ++ ++ @Override ++ public int size() { ++ return delegate.size(); ++ } ++ ++ @Override ++ public void update(long value) { ++ delegate.update(value); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ return Snapshot.of(delegate.getSnapshot()); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingTimeWindowReservoir.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingTimeWindowReservoir.java +@@ -1,43 +1,45 @@ + package com.codahale.metrics; + +-import java.util.concurrent.TimeUnit; +- + import static java.util.Objects.requireNonNull; + ++import java.util.concurrent.TimeUnit; ++ + @Deprecated + public class SlidingTimeWindowReservoir implements Reservoir { + +- private io.dropwizard.metrics5.SlidingTimeWindowReservoir delegate; +- +- public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit) { +- this(new io.dropwizard.metrics5.SlidingTimeWindowReservoir(window, windowUnit)); +- } +- +- public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) { +- this(new io.dropwizard.metrics5.SlidingTimeWindowReservoir(window, windowUnit, clock.getDelegate())); +- } +- +- public SlidingTimeWindowReservoir(io.dropwizard.metrics5.SlidingTimeWindowReservoir delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- @Override +- public io.dropwizard.metrics5.Reservoir getDelegate() { +- return delegate; +- } +- +- @Override +- public int size() { +- return delegate.size(); +- } +- +- @Override +- public void update(long value) { +- delegate.update(value); +- } +- +- @Override +- public Snapshot getSnapshot() { +- return Snapshot.of(delegate.getSnapshot()); +- } ++ private io.dropwizard.metrics5.SlidingTimeWindowReservoir delegate; ++ ++ public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit) { ++ this(new io.dropwizard.metrics5.SlidingTimeWindowReservoir(window, windowUnit)); ++ } ++ ++ public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) { ++ this( ++ new io.dropwizard.metrics5.SlidingTimeWindowReservoir( ++ window, windowUnit, clock.getDelegate())); ++ } ++ ++ public SlidingTimeWindowReservoir(io.dropwizard.metrics5.SlidingTimeWindowReservoir delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ @Override ++ public io.dropwizard.metrics5.Reservoir getDelegate() { ++ return delegate; ++ } ++ ++ @Override ++ public int size() { ++ return delegate.size(); ++ } ++ ++ @Override ++ public void update(long value) { ++ delegate.update(value); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ return Snapshot.of(delegate.getSnapshot()); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingWindowReservoir.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingWindowReservoir.java +@@ -5,33 +5,33 @@ import static java.util.Objects.requireNonNull; + @Deprecated + public class SlidingWindowReservoir implements Reservoir { + +- private io.dropwizard.metrics5.SlidingWindowReservoir delegate; +- +- public SlidingWindowReservoir(int size) { +- this(new io.dropwizard.metrics5.SlidingWindowReservoir(size)); +- } +- +- public SlidingWindowReservoir(io.dropwizard.metrics5.SlidingWindowReservoir delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- @Override +- public io.dropwizard.metrics5.Reservoir getDelegate() { +- return delegate; +- } +- +- @Override +- public int size() { +- return delegate.size(); +- } +- +- @Override +- public void update(long value) { +- delegate.update(value); +- } +- +- @Override +- public Snapshot getSnapshot() { +- return Snapshot.of(delegate.getSnapshot()); +- } ++ private io.dropwizard.metrics5.SlidingWindowReservoir delegate; ++ ++ public SlidingWindowReservoir(int size) { ++ this(new io.dropwizard.metrics5.SlidingWindowReservoir(size)); ++ } ++ ++ public SlidingWindowReservoir(io.dropwizard.metrics5.SlidingWindowReservoir delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ @Override ++ public io.dropwizard.metrics5.Reservoir getDelegate() { ++ return delegate; ++ } ++ ++ @Override ++ public int size() { ++ return delegate.size(); ++ } ++ ++ @Override ++ public void update(long value) { ++ delegate.update(value); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ return Snapshot.of(delegate.getSnapshot()); ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Snapshot.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Snapshot.java +@@ -5,88 +5,88 @@ import java.io.OutputStream; + @Deprecated + public abstract class Snapshot { + +- public abstract double getValue(double quantile); ++ public abstract double getValue(double quantile); + +- public abstract long[] getValues(); ++ public abstract long[] getValues(); + +- public abstract int size(); ++ public abstract int size(); + +- public double getMedian() { +- return getValue(0.5); +- } ++ public double getMedian() { ++ return getValue(0.5); ++ } + +- public double get75thPercentile() { +- return getValue(0.75); +- } ++ public double get75thPercentile() { ++ return getValue(0.75); ++ } + +- public double get95thPercentile() { +- return getValue(0.95); +- } ++ public double get95thPercentile() { ++ return getValue(0.95); ++ } + +- public double get98thPercentile() { +- return getValue(0.98); +- } ++ public double get98thPercentile() { ++ return getValue(0.98); ++ } + +- public double get99thPercentile() { +- return getValue(0.99); +- } ++ public double get99thPercentile() { ++ return getValue(0.99); ++ } + +- public double get999thPercentile() { +- return getValue(0.999); +- } ++ public double get999thPercentile() { ++ return getValue(0.999); ++ } + +- public abstract long getMax(); ++ public abstract long getMax(); + +- public abstract double getMean(); ++ public abstract double getMean(); + +- public abstract long getMin(); ++ public abstract long getMin(); + +- public abstract double getStdDev(); ++ public abstract double getStdDev(); + +- public abstract void dump(OutputStream output); ++ public abstract void dump(OutputStream output); + +- public static Snapshot of(io.dropwizard.metrics5.Snapshot delegate) { +- return new Snapshot() { ++ public static Snapshot of(io.dropwizard.metrics5.Snapshot delegate) { ++ return new Snapshot() { + +- @Override +- public double getValue(double quantile) { +- return delegate.getValue(quantile); +- } ++ @Override ++ public double getValue(double quantile) { ++ return delegate.getValue(quantile); ++ } + +- @Override +- public long[] getValues() { +- return delegate.getValues(); +- } ++ @Override ++ public long[] getValues() { ++ return delegate.getValues(); ++ } + +- @Override +- public int size() { +- return delegate.size(); +- } ++ @Override ++ public int size() { ++ return delegate.size(); ++ } + +- @Override +- public long getMax() { +- return delegate.getMax(); +- } ++ @Override ++ public long getMax() { ++ return delegate.getMax(); ++ } + +- @Override +- public double getMean() { +- return delegate.getMean(); +- } ++ @Override ++ public double getMean() { ++ return delegate.getMean(); ++ } + +- @Override +- public long getMin() { +- return delegate.getMin(); +- } ++ @Override ++ public long getMin() { ++ return delegate.getMin(); ++ } + +- @Override +- public double getStdDev() { +- return delegate.getStdDev(); +- } ++ @Override ++ public double getStdDev() { ++ return delegate.getStdDev(); ++ } + +- @Override +- public void dump(OutputStream output) { +- delegate.dump(output); +- } +- }; +- } ++ @Override ++ public void dump(OutputStream output) { ++ delegate.dump(output); ++ } ++ }; ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Timer.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Timer.java +@@ -1,109 +1,107 @@ + package com.codahale.metrics; + ++import static java.util.Objects.requireNonNull; ++ + import java.io.Closeable; + import java.time.Duration; + import java.util.concurrent.Callable; + import java.util.concurrent.TimeUnit; + import java.util.function.Supplier; + +-import static java.util.Objects.requireNonNull; +- + @Deprecated + public class Timer implements Metered, Sampling { + +- private final io.dropwizard.metrics5.Timer delegate; +- +- public static class Context implements Closeable { +- +- private final io.dropwizard.metrics5.Timer.Context context; +- +- private Context(io.dropwizard.metrics5.Timer.Context context) { +- this.context = context; +- } +- +- public long stop() { +- return context.stop(); +- } +- +- @Override +- public void close() { +- context.close(); +- } +- } +- +- public Timer() { +- this(new io.dropwizard.metrics5.Timer()); +- } +- +- public Timer(Reservoir reservoir) { +- this(reservoir, Clock.defaultClock()); +- } ++ private final io.dropwizard.metrics5.Timer delegate; + +- public Timer(Reservoir reservoir, Clock clock) { +- this(new io.dropwizard.metrics5.Timer(reservoir.getDelegate(), clock.getDelegate())); +- } +- +- public Timer(io.dropwizard.metrics5.Timer delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- @Override +- public Snapshot getSnapshot() { +- return Snapshot.of(delegate.getSnapshot()); +- } +- +- @Override +- public long getCount() { +- return delegate.getCount(); +- } ++ public static class Context implements Closeable { + +- @Override +- public double getFifteenMinuteRate() { +- return delegate.getFifteenMinuteRate(); +- } ++ private final io.dropwizard.metrics5.Timer.Context context; + +- @Override +- public double getFiveMinuteRate() { +- return delegate.getFiveMinuteRate(); ++ private Context(io.dropwizard.metrics5.Timer.Context context) { ++ this.context = context; + } + +- @Override +- public double getMeanRate() { +- return delegate.getMeanRate(); ++ public long stop() { ++ return context.stop(); + } + + @Override +- public double getOneMinuteRate() { +- return delegate.getOneMinuteRate(); +- } +- +- public void update(long duration, TimeUnit unit) { +- delegate.update(duration, unit); +- } +- +- public void update(Duration duration) { +- delegate.update(duration); +- } +- +- public T time(Callable event) throws Exception { +- return delegate.time(event); +- } +- +- public void time(Runnable event) { +- delegate.time(event); +- } +- +- public T timeSupplier(Supplier event) { +- return delegate.timeSupplier(event); +- } +- +- public Context time() { +- return new Context(delegate.time()); +- } +- +- public io.dropwizard.metrics5.Timer getDelegate() { +- return delegate; +- } +- +- ++ public void close() { ++ context.close(); ++ } ++ } ++ ++ public Timer() { ++ this(new io.dropwizard.metrics5.Timer()); ++ } ++ ++ public Timer(Reservoir reservoir) { ++ this(reservoir, Clock.defaultClock()); ++ } ++ ++ public Timer(Reservoir reservoir, Clock clock) { ++ this(new io.dropwizard.metrics5.Timer(reservoir.getDelegate(), clock.getDelegate())); ++ } ++ ++ public Timer(io.dropwizard.metrics5.Timer delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ return Snapshot.of(delegate.getSnapshot()); ++ } ++ ++ @Override ++ public long getCount() { ++ return delegate.getCount(); ++ } ++ ++ @Override ++ public double getFifteenMinuteRate() { ++ return delegate.getFifteenMinuteRate(); ++ } ++ ++ @Override ++ public double getFiveMinuteRate() { ++ return delegate.getFiveMinuteRate(); ++ } ++ ++ @Override ++ public double getMeanRate() { ++ return delegate.getMeanRate(); ++ } ++ ++ @Override ++ public double getOneMinuteRate() { ++ return delegate.getOneMinuteRate(); ++ } ++ ++ public void update(long duration, TimeUnit unit) { ++ delegate.update(duration, unit); ++ } ++ ++ public void update(Duration duration) { ++ delegate.update(duration); ++ } ++ ++ public T time(Callable event) throws Exception { ++ return delegate.time(event); ++ } ++ ++ public void time(Runnable event) { ++ delegate.time(event); ++ } ++ ++ public T timeSupplier(Supplier event) { ++ return delegate.timeSupplier(event); ++ } ++ ++ public Context time() { ++ return new Context(delegate.time()); ++ } ++ ++ public io.dropwizard.metrics5.Timer getDelegate() { ++ return delegate; ++ } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/UniformReservoir.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/UniformReservoir.java +@@ -5,37 +5,37 @@ import static java.util.Objects.requireNonNull; + @Deprecated + public class UniformReservoir implements Reservoir { + +- private io.dropwizard.metrics5.UniformReservoir delegate; +- +- public UniformReservoir() { +- this(new io.dropwizard.metrics5.UniformReservoir()); +- } +- +- public UniformReservoir(int size) { +- this(new io.dropwizard.metrics5.UniformReservoir(size)); +- } +- +- public UniformReservoir(io.dropwizard.metrics5.UniformReservoir delegate) { +- this.delegate = requireNonNull(delegate); +- } +- +- @Override +- public io.dropwizard.metrics5.Reservoir getDelegate() { +- return delegate; +- } +- +- @Override +- public int size() { +- return delegate.size(); +- } +- +- @Override +- public void update(long value) { +- delegate.update(value); +- } +- +- @Override +- public Snapshot getSnapshot() { +- return Snapshot.of(delegate.getSnapshot()); +- } ++ private io.dropwizard.metrics5.UniformReservoir delegate; ++ ++ public UniformReservoir() { ++ this(new io.dropwizard.metrics5.UniformReservoir()); ++ } ++ ++ public UniformReservoir(int size) { ++ this(new io.dropwizard.metrics5.UniformReservoir(size)); ++ } ++ ++ public UniformReservoir(io.dropwizard.metrics5.UniformReservoir delegate) { ++ this.delegate = requireNonNull(delegate); ++ } ++ ++ @Override ++ public io.dropwizard.metrics5.Reservoir getDelegate() { ++ return delegate; ++ } ++ ++ @Override ++ public int size() { ++ return delegate.size(); ++ } ++ ++ @Override ++ public void update(long value) { ++ delegate.update(value); ++ } ++ ++ @Override ++ public Snapshot getSnapshot() { ++ return Snapshot.of(delegate.getSnapshot()); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java +@@ -1,34 +1,34 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class CachedGaugeTest { ++final class CachedGaugeTest { + +- @Test +- void testCreate() { +- CachedGauge cachedGauge = new CachedGauge(100, TimeUnit.MILLISECONDS) { +- @Override +- protected String loadValue() { +- return "heavyValue"; +- } ++ @Test ++ void create() { ++ CachedGauge cachedGauge = ++ new CachedGauge(100, TimeUnit.MILLISECONDS) { ++ @Override ++ protected String loadValue() { ++ return "heavyValue"; ++ } + }; +- assertThat(cachedGauge.getValue()).isEqualTo("heavyValue"); +- } ++ assertThat(cachedGauge.getValue()).isEqualTo("heavyValue"); ++ } + +- @Test +- void testCreateWothClock() { +- CachedGauge cachedGauge = new CachedGauge(new Clock.UserTimeClock(), 100, +- TimeUnit.MILLISECONDS) { +- @Override +- protected String loadValue() { +- return "heavyValue"; +- } ++ @Test ++ void createWothClock() { ++ CachedGauge cachedGauge = ++ new CachedGauge(new Clock.UserTimeClock(), 100, TimeUnit.MILLISECONDS) { ++ @Override ++ protected String loadValue() { ++ return "heavyValue"; ++ } + }; +- assertThat(cachedGauge.getValue()).isEqualTo("heavyValue"); +- } ++ assertThat(cachedGauge.getValue()).isEqualTo("heavyValue"); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java +@@ -1,32 +1,33 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + ++import org.junit.jupiter.api.Test; ++ + @SuppressWarnings("deprecation") +-class ClockTest { ++final class ClockTest { + +- @Test +- void testDefaultClockCanBeUsed() { +- Clock clock = Clock.defaultClock(); +- assertThat(clock.getTick()).isGreaterThan(0); +- } ++ @Test ++ void defaultClockCanBeUsed() { ++ Clock clock = Clock.defaultClock(); ++ assertThat(clock.getTick()).isPositive(); ++ } + +- @Test +- void testUserTimeClockCanBeUsed() { +- Clock clock = new Clock.UserTimeClock(); +- assertThat(clock.getTick()).isGreaterThan(0); +- } ++ @Test ++ void userTimeClockCanBeUsed() { ++ Clock clock = new Clock.UserTimeClock(); ++ assertThat(clock.getTick()).isPositive(); ++ } + +- @Test +- void testCustomTimeClockCanBeUsed() { +- Clock clock = new Clock() { +- @Override +- public long getTick() { +- return 24; +- } ++ @Test ++ void customTimeClockCanBeUsed() { ++ Clock clock = ++ new Clock() { ++ @Override ++ public long getTick() { ++ return 24; ++ } + }; +- assertThat(clock.getTick()).isEqualTo(24); +- } ++ assertThat(clock.getTick()).isEqualTo(24); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java +@@ -1,124 +1,129 @@ + package com.codahale.metrics; + ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import java.io.ByteArrayOutputStream; + import java.io.PrintStream; +-import java.nio.charset.StandardCharsets; + import java.util.EnumSet; + import java.util.Locale; + import java.util.TimeZone; + import java.util.concurrent.Executors; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; +- + import org.apache.commons.lang3.JavaVersion; + import org.apache.commons.lang3.SystemUtils; + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class ConsoleReporterTest { ++final class ConsoleReporterTest { + +- private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); +- private final String dateHeader = SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8) ? +- "3/17/13 6:04:36 PM =============================================================" : +- // https://bugs.openjdk.org/browse/JDK-8304925 +- SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_20) ? +- "3/17/13, 6:04:36\u202FPM ============================================================" : +- "3/17/13, 6:04:36 PM ============================================================"; ++ private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); ++ private final String dateHeader = ++ SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8) ++ ? "3/17/13 6:04:36 PM =============================================================" ++ : ++ // https://bugs.openjdk.org/browse/JDK-8304925 ++ SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_20) ++ ? "3/17/13, 6:04:36\u202FPM ============================================================" ++ : "3/17/13, 6:04:36 PM ============================================================"; + +- @AfterEach +- void tearDown() throws Exception { +- executor.shutdownNow(); +- } ++ @AfterEach ++ void tearDown() throws Exception { ++ executor.shutdownNow(); ++ } + +- @Test +- void testCreateConsoleReporter() throws Exception { +- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ++ @Test ++ void createConsoleReporter() throws Exception { ++ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + +- MetricRegistry metricRegistry = new MetricRegistry(); +- metricRegistry.timer("test-timer"); +- metricRegistry.meter("test-meter"); +- metricRegistry.histogram("test-histogram"); +- metricRegistry.counter("test-counter"); +- metricRegistry.register("test-gauge", (Gauge) () -> 20); ++ MetricRegistry metricRegistry = new MetricRegistry(); ++ metricRegistry.timer("test-timer"); ++ metricRegistry.meter("test-meter"); ++ metricRegistry.histogram("test-histogram"); ++ metricRegistry.counter("test-counter"); ++ metricRegistry.register("test-gauge", (Gauge) () -> 20); + +- ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(metricRegistry) +- .shutdownExecutorOnStop(false) +- .scheduleOn(executor) +- .outputTo(new PrintStream(byteArrayOutputStream)) +- .formattedFor(Locale.ENGLISH) +- .withClock(new Clock() { ++ ConsoleReporter consoleReporter = ++ ConsoleReporter.forRegistry(metricRegistry) ++ .shutdownExecutorOnStop(false) ++ .scheduleOn(executor) ++ .outputTo(new PrintStream(byteArrayOutputStream)) ++ .formattedFor(Locale.ENGLISH) ++ .withClock( ++ new Clock() { + +- @Override +- public long getTime() { +- return 1363568676000L; +- } ++ @Override ++ public long getTime() { ++ return 1363568676000L; ++ } + +- @Override +- public long getTick() { +- return 0; +- } +- }).formattedFor(TimeZone.getTimeZone("America/Los_Angeles")) +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .disabledMetricAttributes(EnumSet.of(MetricAttribute.P98, MetricAttribute.P99)) +- .build(); +- consoleReporter.report(); ++ @Override ++ public long getTick() { ++ return 0; ++ } ++ }) ++ .formattedFor(TimeZone.getTimeZone("America/Los_Angeles")) ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .disabledMetricAttributes(EnumSet.of(MetricAttribute.P98, MetricAttribute.P99)) ++ .build(); ++ consoleReporter.report(); + +- assertThat(new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8)) +- .isEqualToNormalizingNewlines(dateHeader + "\n" + +- "\n" + +- "-- Gauges ----------------------------------------------------------------------\n" + +- "test-gauge\n" + +- " value = 20\n" + +- "\n" + +- "-- Counters --------------------------------------------------------------------\n" + +- "test-counter\n" + +- " count = 0\n" + +- "\n" + +- "-- Histograms ------------------------------------------------------------------\n" + +- "test-histogram\n" + +- " count = 0\n" + +- " sum = 0\n" + +- " min = 0\n" + +- " max = 0\n" + +- " mean = 0.00\n" + +- " stddev = 0.00\n" + +- " median = 0.00\n" + +- " 75% <= 0.00\n" + +- " 95% <= 0.00\n" + +- " 99.9% <= 0.00\n" + +- "\n" + +- "-- Meters ----------------------------------------------------------------------\n" + +- "test-meter\n" + +- " count = 0\n" + +- " sum = 0\n" + +- " mean rate = 0.00 events/second\n" + +- " 1-minute rate = 0.00 events/second\n" + +- " 5-minute rate = 0.00 events/second\n" + +- " 15-minute rate = 0.00 events/second\n" + +- "\n" + +- "-- Timers ----------------------------------------------------------------------\n" + +- "test-timer\n" + +- " count = 0\n" + +- " sum = 0.00\n" + +- " mean rate = 0.00 calls/second\n" + +- " 1-minute rate = 0.00 calls/second\n" + +- " 5-minute rate = 0.00 calls/second\n" + +- " 15-minute rate = 0.00 calls/second\n" + +- " min = 0.00 milliseconds\n" + +- " max = 0.00 milliseconds\n" + +- " mean = 0.00 milliseconds\n" + +- " stddev = 0.00 milliseconds\n" + +- " median = 0.00 milliseconds\n" + +- " 75% <= 0.00 milliseconds\n" + +- " 95% <= 0.00 milliseconds\n" + +- " 99.9% <= 0.00 milliseconds\n" + +- "\n" + +- "\n" +- ); +- } ++ assertThat(new String(byteArrayOutputStream.toByteArray(), UTF_8)) ++ .isEqualToNormalizingNewlines( ++ dateHeader ++ + "\n" ++ + "\n" ++ + "-- Gauges ----------------------------------------------------------------------\n" ++ + "test-gauge\n" ++ + " value = 20\n" ++ + "\n" ++ + "-- Counters --------------------------------------------------------------------\n" ++ + "test-counter\n" ++ + " count = 0\n" ++ + "\n" ++ + "-- Histograms ------------------------------------------------------------------\n" ++ + "test-histogram\n" ++ + " count = 0\n" ++ + " sum = 0\n" ++ + " min = 0\n" ++ + " max = 0\n" ++ + " mean = 0.00\n" ++ + " stddev = 0.00\n" ++ + " median = 0.00\n" ++ + " 75% <= 0.00\n" ++ + " 95% <= 0.00\n" ++ + " 99.9% <= 0.00\n" ++ + "\n" ++ + "-- Meters ----------------------------------------------------------------------\n" ++ + "test-meter\n" ++ + " count = 0\n" ++ + " sum = 0\n" ++ + " mean rate = 0.00 events/second\n" ++ + " 1-minute rate = 0.00 events/second\n" ++ + " 5-minute rate = 0.00 events/second\n" ++ + " 15-minute rate = 0.00 events/second\n" ++ + "\n" ++ + "-- Timers ----------------------------------------------------------------------\n" ++ + "test-timer\n" ++ + " count = 0\n" ++ + " sum = 0.00\n" ++ + " mean rate = 0.00 calls/second\n" ++ + " 1-minute rate = 0.00 calls/second\n" ++ + " 5-minute rate = 0.00 calls/second\n" ++ + " 15-minute rate = 0.00 calls/second\n" ++ + " min = 0.00 milliseconds\n" ++ + " max = 0.00 milliseconds\n" ++ + " mean = 0.00 milliseconds\n" ++ + " stddev = 0.00 milliseconds\n" ++ + " median = 0.00 milliseconds\n" ++ + " 75% <= 0.00 milliseconds\n" ++ + " 95% <= 0.00 milliseconds\n" ++ + " 99.9% <= 0.00 milliseconds\n" ++ + "\n" ++ + "\n"); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java +@@ -1,40 +1,40 @@ + package com.codahale.metrics; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.Counter; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- + @SuppressWarnings("deprecation") +-class CounterTest { ++final class CounterTest { + +- private Counter counter = new Counter(); ++ private Counter counter = new Counter(); + +- @Test +- void testIncrementCounter() { +- counter.inc(); ++ @Test ++ void incrementCounter() { ++ counter.inc(); + +- assertThat(counter.getCount()).isEqualTo(1); +- } ++ assertThat(counter.getCount()).isEqualTo(1); ++ } + +- @Test +- void testIncrementCounterOnManyPoints() { +- counter.inc(5); ++ @Test ++ void incrementCounterOnManyPoints() { ++ counter.inc(5); + +- assertThat(counter.getCount()).isEqualTo(5); +- } ++ assertThat(counter.getCount()).isEqualTo(5); ++ } + +- @Test +- void testDecrementCounter() { +- counter.dec(); ++ @Test ++ void decrementCounter() { ++ counter.dec(); + +- assertThat(counter.getCount()).isEqualTo(-1); +- } ++ assertThat(counter.getCount()).isEqualTo(-1); ++ } + +- @Test +- void testDecrementCounterOnManyPoints() { +- counter.dec(5); ++ @Test ++ void decrementCounterOnManyPoints() { ++ counter.dec(5); + +- assertThat(counter.getCount()).isEqualTo(-5); +- } ++ assertThat(counter.getCount()).isEqualTo(-5); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java +@@ -1,20 +1,21 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + ++import org.junit.jupiter.api.Test; ++ + @SuppressWarnings("deprecation") +-class DerivativeGaugeTest { ++final class DerivativeGaugeTest { + +- @Test +- void testCalculate() { +- DerivativeGauge derivativeGauge = new DerivativeGauge(() -> "23") { +- @Override +- protected Integer transform(String value) { +- return Integer.parseInt(value); +- } ++ @Test ++ void calculate() { ++ DerivativeGauge derivativeGauge = ++ new DerivativeGauge(() -> "23") { ++ @Override ++ protected Integer transform(String value) { ++ return Integer.parseInt(value); ++ } + }; +- assertThat(derivativeGauge.getValue()).isEqualTo(23); +- } ++ assertThat(derivativeGauge.getValue()).isEqualTo(23); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java +@@ -1,53 +1,55 @@ + package com.codahale.metrics; + +-import org.assertj.core.data.Offset; +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + +-@SuppressWarnings("deprecation") +-class ExponentiallyDecayingReservoirTest { +- +- @Test +- void testCreateReservoir() { +- ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(); +- reservoir.update(120); +- reservoir.update(190); +- reservoir.update(200); +- reservoir.update(130); +- reservoir.update(140); +- +- Snapshot snapshot = reservoir.getSnapshot(); +- assertThat(snapshot.size()).isEqualTo(5); +- assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); +- assertThat(snapshot.getMin()).isEqualTo(120); +- assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); +- assertThat(snapshot.get75thPercentile()).isEqualTo(190); +- assertThat(snapshot.get95thPercentile()).isEqualTo(200); +- assertThat(snapshot.get98thPercentile()).isEqualTo(200); +- assertThat(snapshot.get99thPercentile()).isEqualTo(200); +- assertThat(snapshot.get999thPercentile()).isEqualTo(200); +- } +- +- @Test +- void testCreateReservoirWithCustomSizeAndAlpha() { +- ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01); +- reservoir.update(100); +- assertThat(reservoir.size()).isEqualTo(1); +- } +- ++import org.junit.jupiter.api.Test; + +- @Test +- void testCreateReservoirWithCustomSizeAlphaAndClock() { +- ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01, +- new Clock() { +- @Override +- public long getTick() { +- return 24; +- } +- }); +- reservoir.update(100); +- assertThat(reservoir.size()).isEqualTo(1); +- } ++@SuppressWarnings("deprecation") ++final class ExponentiallyDecayingReservoirTest { ++ ++ @Test ++ void createReservoir() { ++ ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(); ++ reservoir.update(120); ++ reservoir.update(190); ++ reservoir.update(200); ++ reservoir.update(130); ++ reservoir.update(140); ++ ++ Snapshot snapshot = reservoir.getSnapshot(); ++ assertThat(snapshot.size()).isEqualTo(5); ++ assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); ++ assertThat(snapshot.getMin()).isEqualTo(120); ++ assertThat(snapshot.getMax()).isEqualTo(200); ++ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isEqualTo(190); ++ assertThat(snapshot.get95thPercentile()).isEqualTo(200); ++ assertThat(snapshot.get98thPercentile()).isEqualTo(200); ++ assertThat(snapshot.get99thPercentile()).isEqualTo(200); ++ assertThat(snapshot.get999thPercentile()).isEqualTo(200); ++ } ++ ++ @Test ++ void createReservoirWithCustomSizeAndAlpha() { ++ ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01); ++ reservoir.update(100); ++ assertThat(reservoir.size()).isEqualTo(1); ++ } ++ ++ @Test ++ void createReservoirWithCustomSizeAlphaAndClock() { ++ ExponentiallyDecayingReservoir reservoir = ++ new ExponentiallyDecayingReservoir( ++ 512, ++ 0.01, ++ new Clock() { ++ @Override ++ public long getTick() { ++ return 24; ++ } ++ }); ++ reservoir.update(100); ++ assertThat(reservoir.size()).isEqualTo(1); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java +@@ -1,35 +1,34 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.io.File; + import java.nio.file.Files; + import java.nio.file.Path; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class FixedNameCsvFileProviderTest { +- +- private Path tempDirectory; +- private FixedNameCsvFileProvider fixedNameCsvFileProvider = new FixedNameCsvFileProvider(); +- +- @BeforeEach +- void setUp() throws Exception { +- tempDirectory = Files.createTempDirectory("csv-test"); +- } +- +- @AfterEach +- void tearDown() throws Exception { +- Files.delete(tempDirectory); +- } +- +- @Test +- void getFile() throws Exception { +- File file = fixedNameCsvFileProvider.getFile(tempDirectory.toFile(), "timer-test"); +- assertThat(file.toString()).startsWith(tempDirectory.toString()); +- assertThat(file.toString()).endsWith("timer-test.csv"); +- } ++final class FixedNameCsvFileProviderTest { ++ ++ private Path tempDirectory; ++ private FixedNameCsvFileProvider fixedNameCsvFileProvider = new FixedNameCsvFileProvider(); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ tempDirectory = Files.createTempDirectory("csv-test"); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ Files.delete(tempDirectory); ++ } ++ ++ @Test ++ void getFile() throws Exception { ++ File file = fixedNameCsvFileProvider.getFile(tempDirectory.toFile(), "timer-test"); ++ assertThat(file.toString()).startsWith(tempDirectory.toString()); ++ assertThat(file.toString()).endsWith("timer-test.csv"); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java +@@ -1,16 +1,16 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; + ++import org.junit.jupiter.api.Test; ++ + @SuppressWarnings("deprecation") +-class GaugeTest { ++final class GaugeTest { + +- private Gauge gauge = () -> 83; ++ private Gauge gauge = () -> 83; + +- @Test +- void testGetValue() { +- assertThat(gauge.getValue()).isEqualTo(83); +- } ++ @Test ++ void getValue() { ++ assertThat(gauge.getValue()).isEqualTo(83); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java +@@ -1,33 +1,33 @@ + package com.codahale.metrics; + +-import org.assertj.core.data.Offset; +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; ++ ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class HistogramTest { ++final class HistogramTest { + +- @Test +- void testCreate() { +- Histogram histogram = new Histogram(new ExponentiallyDecayingReservoir()); +- histogram.update(120); +- histogram.update(190); +- histogram.update(200L); +- histogram.update(130); +- histogram.update(140); ++ @Test ++ void create() { ++ Histogram histogram = new Histogram(new ExponentiallyDecayingReservoir()); ++ histogram.update(120); ++ histogram.update(190); ++ histogram.update(200L); ++ histogram.update(130); ++ histogram.update(140); + +- assertThat(histogram.getCount()).isEqualTo(5); +- Snapshot snapshot = histogram.getSnapshot(); +- assertThat(snapshot.size()).isEqualTo(5); +- assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); +- assertThat(snapshot.getMin()).isEqualTo(120); +- assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); +- assertThat(snapshot.get75thPercentile()).isEqualTo(190); +- assertThat(snapshot.get95thPercentile()).isEqualTo(200); +- assertThat(snapshot.get98thPercentile()).isEqualTo(200); +- assertThat(snapshot.get99thPercentile()).isEqualTo(200); +- assertThat(snapshot.get999thPercentile()).isEqualTo(200); +- } ++ assertThat(histogram.getCount()).isEqualTo(5); ++ Snapshot snapshot = histogram.getSnapshot(); ++ assertThat(snapshot.size()).isEqualTo(5); ++ assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); ++ assertThat(snapshot.getMin()).isEqualTo(120); ++ assertThat(snapshot.getMax()).isEqualTo(200); ++ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isEqualTo(190); ++ assertThat(snapshot.get95thPercentile()).isEqualTo(200); ++ assertThat(snapshot.get98thPercentile()).isEqualTo(200); ++ assertThat(snapshot.get99thPercentile()).isEqualTo(200); ++ assertThat(snapshot.get999thPercentile()).isEqualTo(200); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java +@@ -1,34 +1,37 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.ExecutorService; + import java.util.concurrent.Executors; + import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class InstrumentedExecutorServiceTest { +- ++final class InstrumentedExecutorServiceTest { + +- @Test +- void testCreate() throws Exception { +- ExecutorService executorService = Executors.newSingleThreadExecutor(); +- MetricRegistry registry = new MetricRegistry(); +- InstrumentedExecutorService instrumentedExecutorService = new InstrumentedExecutorService(executorService, +- registry, "test-instrumented"); +- CountDownLatch countDownLatch = new CountDownLatch(10); +- for (int i = 0; i < 10; i++) { +- instrumentedExecutorService.submit(countDownLatch::countDown); +- } +- countDownLatch.await(5, TimeUnit.SECONDS); +- executorService.shutdown(); +- executorService.awaitTermination(5, TimeUnit.SECONDS); +- +- assertThat(registry.getMetrics()).containsOnlyKeys("test-instrumented.completed", +- "test-instrumented.submitted", "test-instrumented.duration", "test-instrumented.idle", +- "test-instrumented.running", "test-instrumented.rejected"); ++ @Test ++ void create() throws Exception { ++ ExecutorService executorService = Executors.newSingleThreadExecutor(); ++ MetricRegistry registry = new MetricRegistry(); ++ InstrumentedExecutorService instrumentedExecutorService = ++ new InstrumentedExecutorService(executorService, registry, "test-instrumented"); ++ CountDownLatch countDownLatch = new CountDownLatch(10); ++ for (int i = 0; i < 10; i++) { ++ instrumentedExecutorService.submit(countDownLatch::countDown); + } ++ countDownLatch.await(5, TimeUnit.SECONDS); ++ executorService.shutdown(); ++ executorService.awaitTermination(5, TimeUnit.SECONDS); ++ ++ assertThat(registry.getMetrics()) ++ .containsOnlyKeys( ++ "test-instrumented.completed", ++ "test-instrumented.submitted", ++ "test-instrumented.duration", ++ "test-instrumented.idle", ++ "test-instrumented.running", ++ "test-instrumented.rejected"); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java +@@ -1,37 +1,44 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.Executors; + import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class InstrumentedScheduledExecutorServiceTest { +- private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); ++final class InstrumentedScheduledExecutorServiceTest { ++ private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + +- @AfterEach +- void tearDown() { +- executorService.shutdown(); +- } ++ @AfterEach ++ void tearDown() { ++ executorService.shutdown(); ++ } + +- @Test +- void testCreate() throws Exception { +- MetricRegistry registry = new MetricRegistry(); +- InstrumentedScheduledExecutorService instrumentedExecutorService = new InstrumentedScheduledExecutorService( +- executorService, registry, "test-scheduled-instrumented"); +- CountDownLatch countDownLatch = new CountDownLatch(10); +- instrumentedExecutorService.scheduleAtFixedRate(countDownLatch::countDown, 0, 10, TimeUnit.MILLISECONDS); +- countDownLatch.await(5, TimeUnit.SECONDS); +- instrumentedExecutorService.shutdown(); ++ @Test ++ void create() throws Exception { ++ MetricRegistry registry = new MetricRegistry(); ++ InstrumentedScheduledExecutorService instrumentedExecutorService = ++ new InstrumentedScheduledExecutorService( ++ executorService, registry, "test-scheduled-instrumented"); ++ CountDownLatch countDownLatch = new CountDownLatch(10); ++ instrumentedExecutorService.scheduleAtFixedRate( ++ countDownLatch::countDown, 0, 10, TimeUnit.MILLISECONDS); ++ countDownLatch.await(5, TimeUnit.SECONDS); ++ instrumentedExecutorService.shutdown(); + +- assertThat(registry.getMetrics()).containsOnlyKeys("test-scheduled-instrumented.completed", +- "test-scheduled-instrumented.submitted", "test-scheduled-instrumented.duration", "test-scheduled-instrumented.running", +- "test-scheduled-instrumented.scheduled.once", "test-scheduled-instrumented.scheduled.overrun", +- "test-scheduled-instrumented.scheduled.percent-of-period", "test-scheduled-instrumented.scheduled.repetitively"); +- } ++ assertThat(registry.getMetrics()) ++ .containsOnlyKeys( ++ "test-scheduled-instrumented.completed", ++ "test-scheduled-instrumented.submitted", ++ "test-scheduled-instrumented.duration", ++ "test-scheduled-instrumented.running", ++ "test-scheduled-instrumented.scheduled.once", ++ "test-scheduled-instrumented.scheduled.overrun", ++ "test-scheduled-instrumented.scheduled.percent-of-period", ++ "test-scheduled-instrumented.scheduled.repetitively"); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java +@@ -1,28 +1,29 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class InstrumentedThreadFactoryTest { ++final class InstrumentedThreadFactoryTest { + +- @Test +- @SuppressWarnings("DoNotCall") +- void testFactory() throws Exception { +- MetricRegistry registry = new MetricRegistry(); +- InstrumentedThreadFactory threadFactory = new InstrumentedThreadFactory(Thread::new, registry, +- "test-instrumented-thread-factory"); +- CountDownLatch latch = new CountDownLatch(4); +- for (int i = 0; i < 4; i++) { +- threadFactory.newThread(latch::countDown).run(); +- } +- latch.await(5, TimeUnit.SECONDS); +- assertThat(registry.meter("test-instrumented-thread-factory.created").getCount()).isEqualTo(4); +- assertThat(registry.counter("test-instrumented-thread-factory.running").getCount()).isEqualTo(0); +- assertThat(registry.meter("test-instrumented-thread-factory.terminated").getCount()).isEqualTo(4); ++ @SuppressWarnings("DoNotCall") ++ @Test ++ void factory() throws Exception { ++ MetricRegistry registry = new MetricRegistry(); ++ InstrumentedThreadFactory threadFactory = ++ new InstrumentedThreadFactory(Thread::new, registry, "test-instrumented-thread-factory"); ++ CountDownLatch latch = new CountDownLatch(4); ++ for (int i = 0; i < 4; i++) { ++ threadFactory.newThread(latch::countDown).run(); + } ++ latch.await(5, TimeUnit.SECONDS); ++ assertThat(registry.meter("test-instrumented-thread-factory.created").getCount()).isEqualTo(4); ++ assertThat(registry.counter("test-instrumented-thread-factory.running").getCount()) ++ .isEqualTo(0); ++ assertThat(registry.meter("test-instrumented-thread-factory.terminated").getCount()) ++ .isEqualTo(4); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java +@@ -1,50 +1,53 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class MeterTest { +- +- @Test +- void testCreateMeteer() { +- Meter meter = new Meter(); +- assertThat(meter.getCount()).isEqualTo(0); +- } +- +- @Test +- void testCreateMeterWithCustomClock() { +- Meter meter = new Meter(new Clock() { +- @Override +- public long getTick() { ++final class MeterTest { ++ ++ @Test ++ void createMeteer() { ++ Meter meter = new Meter(); ++ assertThat(meter.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void createMeterWithCustomClock() { ++ Meter meter = ++ new Meter( ++ new Clock() { ++ @Override ++ public long getTick() { + return 0; +- } +- }); +- assertThat(meter.getCount()).isEqualTo(0); +- } ++ } ++ }); ++ assertThat(meter.getCount()).isEqualTo(0); ++ } + +- @Test +- void testMark() { +- Meter meter = new Meter(new Clock() { ++ @Test ++ void mark() { ++ Meter meter = ++ new Meter( ++ new Clock() { + +- private long start = System.nanoTime(); ++ private long start = System.nanoTime(); + +- @Override +- public long getTick() { ++ @Override ++ public long getTick() { + return start += TimeUnit.SECONDS.toNanos(1); +- } +- }); +- for (int i = 0; i < 60; i++) { +- meter.mark(); +- } +- for (int i = 0; i < 60; i++) { +- meter.mark(2); +- } +- +- assertThat(meter.getCount()).isEqualTo(180); +- assertThat(meter.getMeanRate()).isBetween(1.0, 2.0); ++ } ++ }); ++ for (int i = 0; i < 60; i++) { ++ meter.mark(); + } ++ for (int i = 0; i < 60; i++) { ++ meter.mark(2); ++ } ++ ++ assertThat(meter.getCount()).isEqualTo(180); ++ assertThat(meter.getMeanRate()).isBetween(1.0, 2.0); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java +@@ -1,509 +1,554 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + + import java.util.HashMap; + import java.util.Map; + import java.util.SortedMap; + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.data.Offset.offset; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class MetricRegistryTest { +- +- private MetricRegistry metricRegistry = new MetricRegistry(); +- +- @Test +- void testRegisterMetric() { +- Counter counter = metricRegistry.register("test-counter", new Counter()); +- counter.inc(42); +- assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); +- } +- +- @Test +- void testRegisterAll() { +- metricRegistry.registerAll(() -> { +- Map map = new HashMap<>(); +- map.put("test-counter", new Counter()); +- map.put("test-gauge", (Gauge) () -> 28); +- map.put("test-histogram", new Histogram(new ExponentiallyDecayingReservoir())); +- return map; +- }); +- Map metrics = metricRegistry.getMetrics(); +- assertThat(metrics).containsOnlyKeys("test-counter", "test-histogram", "test-gauge"); +- assertThat(metrics.get("test-counter")).isInstanceOf(Counter.class); +- assertThat(metrics.get("test-histogram")).isInstanceOf(Histogram.class); +- assertThat(metrics.get("test-gauge")).isInstanceOf(Gauge.class); +- } +- +- @Test +- void testRegisterGauge() { +- metricRegistry.registerGauge("test-gauge", () -> 42); +- assertThat(metricRegistry.getGauges().get("test-gauge").getValue()).isEqualTo(42); +- } +- +- @Test +- void testCreateCustomGauge() { +- Gauge gauge = metricRegistry.gauge("test-gauge-supplier", () -> () -> 42); +- assertThat(gauge.getValue()).isEqualTo(42); +- } +- +- @Test +- void testCreateCounter() { +- Counter counter = metricRegistry.counter("test-counter"); +- counter.inc(42); +- assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); +- } +- +- @Test +- void testCreateCustomCounter() { +- Counter counter = metricRegistry.counter("test-custom-counter", () -> { +- Counter c = new Counter(); +- c.inc(8); +- return c; +- }); +- counter.inc(16); +- assertThat(metricRegistry.counter("test-custom-counter").getCount()).isEqualTo(24); +- } +- +- @Test +- void testCreateHistogram() { +- Histogram histogram = metricRegistry.histogram("test-histogram"); +- histogram.update(100); +- histogram.update(200); +- histogram.update(180); +- assertThat(metricRegistry.histogram("test-histogram").getSnapshot().getMean()) +- .isCloseTo(160.0, offset(0.1)); +- } +- +- @Test +- void testCreateCustomHistogram() { +- Histogram histogram = metricRegistry.histogram("test-custom-histogram", +- () -> new Histogram(new SlidingWindowReservoir(2))); +- histogram.update(100); +- histogram.update(200); +- histogram.update(180); +- assertThat(metricRegistry.histogram("test-custom-histogram").getSnapshot().getMean()) +- .isCloseTo(190.0, offset(0.1)); +- } +- +- @Test +- void testCreateMeter() { +- Meter meter = metricRegistry.meter("test-meter"); +- meter.mark(); +- meter.mark(2); +- +- assertThat(metricRegistry.meter("test-meter").getCount()).isEqualTo(3); +- } +- +- @Test +- void testCreateCustomMeter() { +- Meter meter = metricRegistry.meter("test-custom-meter", () -> { +- Meter m = new Meter(); +- m.mark(16); +- return m; +- }); +- meter.mark(); +- +- assertThat(metricRegistry.meter("test-custom-meter").getCount()).isEqualTo(17); +- } +- +- @Test +- void testCreateTimer() { +- Timer timer = metricRegistry.timer("test-timer"); +- timer.update(100, TimeUnit.MILLISECONDS); +- timer.update(200, TimeUnit.MILLISECONDS); +- timer.update(180, TimeUnit.MILLISECONDS); +- +- assertThat(metricRegistry.timer("test-timer").getCount()).isEqualTo(3); +- } +- +- @Test +- void testCreateCustomTimer() { +- Timer timer = metricRegistry.timer("custom-test-timer", () -> { +- Timer t = new Timer(new UniformReservoir()); +- t.update(300, TimeUnit.MILLISECONDS); +- t.update(200, TimeUnit.MILLISECONDS); +- return t; ++final class MetricRegistryTest { ++ ++ private MetricRegistry metricRegistry = new MetricRegistry(); ++ ++ @Test ++ void registerMetric() { ++ Counter counter = metricRegistry.register("test-counter", new Counter()); ++ counter.inc(42); ++ assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); ++ } ++ ++ @Test ++ void registerAll() { ++ metricRegistry.registerAll( ++ () -> { ++ Map map = new HashMap<>(); ++ map.put("test-counter", new Counter()); ++ map.put("test-gauge", (Gauge) () -> 28); ++ map.put("test-histogram", new Histogram(new ExponentiallyDecayingReservoir())); ++ return map; + }); +- timer.update(180, TimeUnit.MILLISECONDS); +- +- assertThat(metricRegistry.timer("custom-test-timer").getCount()).isEqualTo(3); +- } +- +- @Test +- void testRemoveMetric() { +- metricRegistry.timer("test-timer"); +- metricRegistry.counter("test-counter"); +- metricRegistry.meter("test-meter"); +- +- assertThat(metricRegistry.remove("test-counter")).isTrue(); +- +- assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-timer", "test-meter"); +- } +- +- @Test +- void testRemoveMatching() { +- metricRegistry.counter("test-counter"); +- metricRegistry.timer("test-timer"); +- metricRegistry.timer("test-custom-timer"); +- metricRegistry.meter("test-meter"); +- +- metricRegistry.removeMatching((name, metric) -> metric instanceof Timer && name.startsWith("test")); +- assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-counter", "test-meter"); +- } +- +- @Test +- void testAddListenerForGauge() throws Exception { +- CountDownLatch gaugeAddedLatch = new CountDownLatch(1); +- CountDownLatch gaugeRemovedLatch = new CountDownLatch(1); +- metricRegistry.addListener(new MetricRegistryListener.Base() { +- @Override +- public void onGaugeAdded(String name, Gauge gauge) { +- assertThat(name).isEqualTo("test-gauge"); +- assertThat(gauge.getValue()).isEqualTo(42); +- gaugeAddedLatch.countDown(); +- } +- +- @Override +- public void onGaugeRemoved(String name) { +- assertThat(name).isEqualTo("test-gauge"); +- gaugeRemovedLatch.countDown(); +- } ++ Map metrics = metricRegistry.getMetrics(); ++ assertThat(metrics).containsOnlyKeys("test-counter", "test-histogram", "test-gauge"); ++ assertThat(metrics.get("test-counter")).isInstanceOf(Counter.class); ++ assertThat(metrics.get("test-histogram")).isInstanceOf(Histogram.class); ++ assertThat(metrics.get("test-gauge")).isInstanceOf(Gauge.class); ++ } ++ ++ @Test ++ void registerGauge() { ++ metricRegistry.registerGauge("test-gauge", () -> 42); ++ assertThat(metricRegistry.getGauges().get("test-gauge").getValue()).isEqualTo(42); ++ } ++ ++ @Test ++ void createCustomGauge() { ++ Gauge gauge = metricRegistry.gauge("test-gauge-supplier", () -> () -> 42); ++ assertThat(gauge.getValue()).isEqualTo(42); ++ } ++ ++ @Test ++ void createCounter() { ++ Counter counter = metricRegistry.counter("test-counter"); ++ counter.inc(42); ++ assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); ++ } ++ ++ @Test ++ void createCustomCounter() { ++ Counter counter = ++ metricRegistry.counter( ++ "test-custom-counter", ++ () -> { ++ Counter c = new Counter(); ++ c.inc(8); ++ return c; ++ }); ++ counter.inc(16); ++ assertThat(metricRegistry.counter("test-custom-counter").getCount()).isEqualTo(24); ++ } ++ ++ @Test ++ void createHistogram() { ++ Histogram histogram = metricRegistry.histogram("test-histogram"); ++ histogram.update(100); ++ histogram.update(200); ++ histogram.update(180); ++ assertThat(metricRegistry.histogram("test-histogram").getSnapshot().getMean()) ++ .isCloseTo(160.0, offset(0.1)); ++ } ++ ++ @Test ++ void createCustomHistogram() { ++ Histogram histogram = ++ metricRegistry.histogram( ++ "test-custom-histogram", () -> new Histogram(new SlidingWindowReservoir(2))); ++ histogram.update(100); ++ histogram.update(200); ++ histogram.update(180); ++ assertThat(metricRegistry.histogram("test-custom-histogram").getSnapshot().getMean()) ++ .isCloseTo(190.0, offset(0.1)); ++ } ++ ++ @Test ++ void createMeter() { ++ Meter meter = metricRegistry.meter("test-meter"); ++ meter.mark(); ++ meter.mark(2); ++ ++ assertThat(metricRegistry.meter("test-meter").getCount()).isEqualTo(3); ++ } ++ ++ @Test ++ void createCustomMeter() { ++ Meter meter = ++ metricRegistry.meter( ++ "test-custom-meter", ++ () -> { ++ Meter m = new Meter(); ++ m.mark(16); ++ return m; ++ }); ++ meter.mark(); ++ ++ assertThat(metricRegistry.meter("test-custom-meter").getCount()).isEqualTo(17); ++ } ++ ++ @Test ++ void createTimer() { ++ Timer timer = metricRegistry.timer("test-timer"); ++ timer.update(100, TimeUnit.MILLISECONDS); ++ timer.update(200, TimeUnit.MILLISECONDS); ++ timer.update(180, TimeUnit.MILLISECONDS); ++ ++ assertThat(metricRegistry.timer("test-timer").getCount()).isEqualTo(3); ++ } ++ ++ @Test ++ void createCustomTimer() { ++ Timer timer = ++ metricRegistry.timer( ++ "custom-test-timer", ++ () -> { ++ Timer t = new Timer(new UniformReservoir()); ++ t.update(300, TimeUnit.MILLISECONDS); ++ t.update(200, TimeUnit.MILLISECONDS); ++ return t; ++ }); ++ timer.update(180, TimeUnit.MILLISECONDS); ++ ++ assertThat(metricRegistry.timer("custom-test-timer").getCount()).isEqualTo(3); ++ } ++ ++ @Test ++ void removeMetric() { ++ metricRegistry.timer("test-timer"); ++ metricRegistry.counter("test-counter"); ++ metricRegistry.meter("test-meter"); ++ ++ assertThat(metricRegistry.remove("test-counter")).isTrue(); ++ ++ assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-timer", "test-meter"); ++ } ++ ++ @Test ++ void removeMatching() { ++ metricRegistry.counter("test-counter"); ++ metricRegistry.timer("test-timer"); ++ metricRegistry.timer("test-custom-timer"); ++ metricRegistry.meter("test-meter"); ++ ++ metricRegistry.removeMatching( ++ (name, metric) -> metric instanceof Timer && name.startsWith("test")); ++ assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-counter", "test-meter"); ++ } ++ ++ @Test ++ void addListenerForGauge() throws Exception { ++ CountDownLatch gaugeAddedLatch = new CountDownLatch(1); ++ CountDownLatch gaugeRemovedLatch = new CountDownLatch(1); ++ metricRegistry.addListener( ++ new MetricRegistryListener.Base() { ++ @Override ++ public void onGaugeAdded(String name, Gauge gauge) { ++ assertThat(name).isEqualTo("test-gauge"); ++ assertThat(gauge.getValue()).isEqualTo(42); ++ gaugeAddedLatch.countDown(); ++ } ++ ++ @Override ++ public void onGaugeRemoved(String name) { ++ assertThat(name).isEqualTo("test-gauge"); ++ gaugeRemovedLatch.countDown(); ++ } + }); + +- metricRegistry.register("test-gauge", (Gauge) () -> 42); +- gaugeAddedLatch.await(5, TimeUnit.SECONDS); +- assertThat(gaugeAddedLatch.getCount()).isEqualTo(0); +- +- metricRegistry.remove("test-gauge"); +- gaugeRemovedLatch.await(5, TimeUnit.SECONDS); +- assertThat(gaugeRemovedLatch.getCount()).isEqualTo(0); +- } +- +- @Test +- void testAddListenerForCounter() throws Exception { +- CountDownLatch counterAddedLatch = new CountDownLatch(1); +- CountDownLatch counterRemovedLatch = new CountDownLatch(1); +- metricRegistry.addListener(new MetricRegistryListener.Base() { +- @Override +- public void onCounterAdded(String name, Counter counter) { +- assertThat(name).isEqualTo("test-counter"); +- counterAddedLatch.countDown(); +- } +- +- @Override +- public void onCounterRemoved(String name) { +- assertThat(name).isEqualTo("test-counter"); +- counterRemovedLatch.countDown(); +- } ++ metricRegistry.register("test-gauge", (Gauge) () -> 42); ++ gaugeAddedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(gaugeAddedLatch.getCount()).isEqualTo(0); ++ ++ metricRegistry.remove("test-gauge"); ++ gaugeRemovedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(gaugeRemovedLatch.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void addListenerForCounter() throws Exception { ++ CountDownLatch counterAddedLatch = new CountDownLatch(1); ++ CountDownLatch counterRemovedLatch = new CountDownLatch(1); ++ metricRegistry.addListener( ++ new MetricRegistryListener.Base() { ++ @Override ++ public void onCounterAdded(String name, Counter counter) { ++ assertThat(name).isEqualTo("test-counter"); ++ counterAddedLatch.countDown(); ++ } ++ ++ @Override ++ public void onCounterRemoved(String name) { ++ assertThat(name).isEqualTo("test-counter"); ++ counterRemovedLatch.countDown(); ++ } + }); + +- metricRegistry.counter("test-counter"); +- counterAddedLatch.await(5, TimeUnit.SECONDS); +- assertThat(counterAddedLatch.getCount()).isEqualTo(0); +- +- metricRegistry.remove("test-counter"); +- counterRemovedLatch.await(5, TimeUnit.SECONDS); +- assertThat(counterRemovedLatch.getCount()).isEqualTo(0); +- } +- +- @Test +- void testAddListenerForHistogram() throws Exception { +- CountDownLatch histogramAddedLatch = new CountDownLatch(1); +- CountDownLatch histogramRemovedLatch = new CountDownLatch(1); +- metricRegistry.addListener(new MetricRegistryListener.Base() { +- +- +- @Override +- public void onHistogramAdded(String name, Histogram histogram) { +- assertThat(name).isEqualTo("test-histogram"); +- histogramAddedLatch.countDown(); +- } +- +- @Override +- public void onHistogramRemoved(String name) { +- assertThat(name).isEqualTo("test-histogram"); +- histogramRemovedLatch.countDown(); +- } ++ metricRegistry.counter("test-counter"); ++ counterAddedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(counterAddedLatch.getCount()).isEqualTo(0); ++ ++ metricRegistry.remove("test-counter"); ++ counterRemovedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(counterRemovedLatch.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void addListenerForHistogram() throws Exception { ++ CountDownLatch histogramAddedLatch = new CountDownLatch(1); ++ CountDownLatch histogramRemovedLatch = new CountDownLatch(1); ++ metricRegistry.addListener( ++ new MetricRegistryListener.Base() { ++ ++ @Override ++ public void onHistogramAdded(String name, Histogram histogram) { ++ assertThat(name).isEqualTo("test-histogram"); ++ histogramAddedLatch.countDown(); ++ } ++ ++ @Override ++ public void onHistogramRemoved(String name) { ++ assertThat(name).isEqualTo("test-histogram"); ++ histogramRemovedLatch.countDown(); ++ } + }); + +- metricRegistry.histogram("test-histogram"); +- histogramAddedLatch.await(5, TimeUnit.SECONDS); +- assertThat(histogramAddedLatch.getCount()).isEqualTo(0); +- +- metricRegistry.remove("test-histogram"); +- histogramRemovedLatch.await(5, TimeUnit.SECONDS); +- assertThat(histogramRemovedLatch.getCount()).isEqualTo(0); +- } +- +- @Test +- void testAddListenerForMeter() throws Exception { +- CountDownLatch meterAddedLatch = new CountDownLatch(1); +- CountDownLatch meterRemovedLatch = new CountDownLatch(1); +- metricRegistry.addListener(new MetricRegistryListener.Base() { +- +- @Override +- public void onMeterAdded(String name, Meter meter) { +- assertThat(name).isEqualTo("test-meter"); +- meterAddedLatch.countDown(); +- } +- +- @Override +- public void onMeterRemoved(String name) { +- assertThat(name).isEqualTo("test-meter"); +- meterRemovedLatch.countDown(); +- } ++ metricRegistry.histogram("test-histogram"); ++ histogramAddedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(histogramAddedLatch.getCount()).isEqualTo(0); ++ ++ metricRegistry.remove("test-histogram"); ++ histogramRemovedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(histogramRemovedLatch.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void addListenerForMeter() throws Exception { ++ CountDownLatch meterAddedLatch = new CountDownLatch(1); ++ CountDownLatch meterRemovedLatch = new CountDownLatch(1); ++ metricRegistry.addListener( ++ new MetricRegistryListener.Base() { ++ ++ @Override ++ public void onMeterAdded(String name, Meter meter) { ++ assertThat(name).isEqualTo("test-meter"); ++ meterAddedLatch.countDown(); ++ } ++ ++ @Override ++ public void onMeterRemoved(String name) { ++ assertThat(name).isEqualTo("test-meter"); ++ meterRemovedLatch.countDown(); ++ } + }); + +- metricRegistry.meter("test-meter"); +- meterAddedLatch.await(5, TimeUnit.SECONDS); +- assertThat(meterAddedLatch.getCount()).isEqualTo(0); +- +- metricRegistry.remove("test-meter"); +- meterRemovedLatch.await(5, TimeUnit.SECONDS); +- assertThat(meterRemovedLatch.getCount()).isEqualTo(0); +- } +- +- @Test +- void testAddListenerForTimer() throws Exception { +- CountDownLatch timerAddedLatch = new CountDownLatch(1); +- CountDownLatch timerRemovedLatch = new CountDownLatch(1); +- metricRegistry.addListener(new MetricRegistryListener.Base() { +- +- @Override +- public void onTimerAdded(String name, Timer timer) { +- assertThat(name).isEqualTo("test-timer"); +- timerAddedLatch.countDown(); +- } +- +- @Override +- public void onTimerRemoved(String name) { +- assertThat(name).isEqualTo("test-timer"); +- timerRemovedLatch.countDown(); +- } ++ metricRegistry.meter("test-meter"); ++ meterAddedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(meterAddedLatch.getCount()).isEqualTo(0); ++ ++ metricRegistry.remove("test-meter"); ++ meterRemovedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(meterRemovedLatch.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void addListenerForTimer() throws Exception { ++ CountDownLatch timerAddedLatch = new CountDownLatch(1); ++ CountDownLatch timerRemovedLatch = new CountDownLatch(1); ++ metricRegistry.addListener( ++ new MetricRegistryListener.Base() { ++ ++ @Override ++ public void onTimerAdded(String name, Timer timer) { ++ assertThat(name).isEqualTo("test-timer"); ++ timerAddedLatch.countDown(); ++ } ++ ++ @Override ++ public void onTimerRemoved(String name) { ++ assertThat(name).isEqualTo("test-timer"); ++ timerRemovedLatch.countDown(); ++ } + }); + +- metricRegistry.timer("test-timer"); +- timerAddedLatch.await(5, TimeUnit.SECONDS); +- assertThat(timerAddedLatch.getCount()).isEqualTo(0); +- +- metricRegistry.remove("test-timer"); +- timerRemovedLatch.await(5, TimeUnit.SECONDS); +- assertThat(timerRemovedLatch.getCount()).isEqualTo(0); +- } +- +- @Test +- void testRemoveListener() throws Exception { +- CountDownLatch gaugeAddedLatch = new CountDownLatch(1); +- MetricRegistryListener listener = new MetricRegistryListener.Base() { +- @Override +- public void onGaugeAdded(String name, Gauge gauge) { +- gaugeAddedLatch.countDown(); +- } ++ metricRegistry.timer("test-timer"); ++ timerAddedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(timerAddedLatch.getCount()).isEqualTo(0); ++ ++ metricRegistry.remove("test-timer"); ++ timerRemovedLatch.await(5, TimeUnit.SECONDS); ++ assertThat(timerRemovedLatch.getCount()).isEqualTo(0); ++ } ++ ++ @Test ++ void removeListener() throws Exception { ++ CountDownLatch gaugeAddedLatch = new CountDownLatch(1); ++ MetricRegistryListener listener = ++ new MetricRegistryListener.Base() { ++ @Override ++ public void onGaugeAdded(String name, Gauge gauge) { ++ gaugeAddedLatch.countDown(); ++ } + }; +- metricRegistry.addListener(listener); +- metricRegistry.removeListener(listener); +- +- metricRegistry.register("test-gauge", (Gauge) () -> 39); +- +- gaugeAddedLatch.await(100, TimeUnit.MILLISECONDS); +- assertThat(gaugeAddedLatch.getCount()).isEqualTo(1); +- } +- +- @Test +- void testGetNames() { +- metricRegistry.counter("test-counter"); +- metricRegistry.timer("test-timer"); +- metricRegistry.timer("test-custom-timer"); +- metricRegistry.meter("test-meter"); +- +- assertThat(metricRegistry.getNames()).containsExactly("test-counter", "test-custom-timer", +- "test-meter", "test-timer"); +- } +- +- @Test +- void testGetGauges() { +- metricRegistry.counter("test-counter"); +- metricRegistry.timer("test-timer"); +- metricRegistry.meter("test-meter"); +- metricRegistry.register("test-text-gauge-2", new CachedGauge(1, TimeUnit.MINUTES) { +- @Override +- protected String loadValue() { +- return "eu2"; +- } ++ metricRegistry.addListener(listener); ++ metricRegistry.removeListener(listener); ++ ++ metricRegistry.register("test-gauge", (Gauge) () -> 39); ++ ++ gaugeAddedLatch.await(100, TimeUnit.MILLISECONDS); ++ assertThat(gaugeAddedLatch.getCount()).isEqualTo(1); ++ } ++ ++ @Test ++ void getNames() { ++ metricRegistry.counter("test-counter"); ++ metricRegistry.timer("test-timer"); ++ metricRegistry.timer("test-custom-timer"); ++ metricRegistry.meter("test-meter"); ++ ++ assertThat(metricRegistry.getNames()) ++ .containsExactly("test-counter", "test-custom-timer", "test-meter", "test-timer"); ++ } ++ ++ @Test ++ void getGauges() { ++ metricRegistry.counter("test-counter"); ++ metricRegistry.timer("test-timer"); ++ metricRegistry.meter("test-meter"); ++ metricRegistry.register( ++ "test-text-gauge-2", ++ new CachedGauge(1, TimeUnit.MINUTES) { ++ @Override ++ protected String loadValue() { ++ return "eu2"; ++ } + }); +- metricRegistry.register("test-gauge", (Gauge) () -> 42); +- metricRegistry.register("test-text-gauge-1", new DerivativeGauge(() -> 1) { +- @Override +- protected String transform(Integer value) { +- return "eu" + value; +- } ++ metricRegistry.register("test-gauge", (Gauge) () -> 42); ++ metricRegistry.register( ++ "test-text-gauge-1", ++ new DerivativeGauge(() -> 1) { ++ @Override ++ protected String transform(Integer value) { ++ return "eu" + value; ++ } + }); + +- SortedMap gauges = metricRegistry.getGauges(); +- assertThat(gauges).containsOnlyKeys("test-gauge", "test-text-gauge-1", "test-text-gauge-2"); +- } +- +- @Test +- void testGetGaugesWithFilter() { +- metricRegistry.counter("test-counter"); +- metricRegistry.timer("test-timer"); +- metricRegistry.meter("test-meter"); +- metricRegistry.register("test-text-gauge-2", new CachedGauge(1, TimeUnit.MINUTES) { +- @Override +- protected String loadValue() { +- return "eu2"; +- } ++ SortedMap gauges = metricRegistry.getGauges(); ++ assertThat(gauges).containsOnlyKeys("test-gauge", "test-text-gauge-1", "test-text-gauge-2"); ++ } ++ ++ @Test ++ void getGaugesWithFilter() { ++ metricRegistry.counter("test-counter"); ++ metricRegistry.timer("test-timer"); ++ metricRegistry.meter("test-meter"); ++ metricRegistry.register( ++ "test-text-gauge-2", ++ new CachedGauge(1, TimeUnit.MINUTES) { ++ @Override ++ protected String loadValue() { ++ return "eu2"; ++ } + }); +- metricRegistry.register("test-gauge", (Gauge) () -> 42); +- metricRegistry.register("test-text-gauge-1", new DerivativeGauge(() -> 1) { +- @Override +- protected String transform(Integer value) { +- return "eu" + value; +- } ++ metricRegistry.register("test-gauge", (Gauge) () -> 42); ++ metricRegistry.register( ++ "test-text-gauge-1", ++ new DerivativeGauge(() -> 1) { ++ @Override ++ protected String transform(Integer value) { ++ return "eu" + value; ++ } + }); + +- assertThat(metricRegistry.getGauges((name, metric) -> name.contains("gauge") && metric instanceof CachedGauge)) +- .containsOnlyKeys("test-text-gauge-2"); +- } +- +- @Test +- void testGetHistograms() { +- metricRegistry.counter("test-counter"); +- metricRegistry.timer("test-timer"); +- metricRegistry.meter("test-meter"); +- metricRegistry.histogram("test-histogram-1"); +- metricRegistry.histogram("test-histogram-3"); +- metricRegistry.histogram("test-histogram-2"); +- +- assertThat(metricRegistry.getHistograms()) +- .containsOnlyKeys("test-histogram-1", "test-histogram-2", "test-histogram-3"); +- } +- +- @Test +- void testGetHistogramsWithFilter() { +- metricRegistry.counter("sw-counter"); +- metricRegistry.timer("sw-timer"); +- metricRegistry.meter("sw-meter"); +- metricRegistry.histogram("sw-histogram-1"); +- metricRegistry.histogram("se-histogram-3"); +- metricRegistry.histogram("sw-histogram-2"); +- +- assertThat(metricRegistry.getHistograms(MetricFilter.startsWith("sw"))) +- .containsOnlyKeys("sw-histogram-1", "sw-histogram-2"); +- } +- +- @Test +- void testGetCounters() { +- metricRegistry.histogram("test-histogram"); +- metricRegistry.timer("test-timer"); +- metricRegistry.meter("test-meter"); +- metricRegistry.counter("test-counter-1"); +- metricRegistry.counter("test-counter-3"); +- metricRegistry.counter("test-counter-2"); +- +- assertThat(metricRegistry.getCounters()) +- .containsOnlyKeys("test-counter-1", "test-counter-2", "test-counter-3"); +- } +- +- @Test +- void testGetCountersWithFilter() { +- metricRegistry.histogram("test-histogram"); +- metricRegistry.timer("test-timer"); +- metricRegistry.meter("test-meter"); +- metricRegistry.counter("test-counter-1"); +- metricRegistry.counter("test-counter-3"); +- metricRegistry.counter("test-cnt-2"); +- +- assertThat(metricRegistry.getCounters(MetricFilter.contains("counter"))) +- .containsOnlyKeys("test-counter-1", "test-counter-3"); +- } +- +- @Test +- void testGetMeters() { +- metricRegistry.register("test-gauge", (Gauge) () -> 42); +- metricRegistry.histogram("test-histogram"); +- metricRegistry.timer("test-timer"); +- metricRegistry.counter("test-counter"); +- metricRegistry.meter("test-meter-1"); +- metricRegistry.meter("test-meter-3"); +- metricRegistry.meter("test-meter-2"); +- +- assertThat(metricRegistry.getMeters()).containsOnlyKeys("test-meter-1", "test-meter-2", "test-meter-3"); +- } +- +- @Test +- void testGetMetersWithFilter() { +- metricRegistry.register("sw-gauge", (Gauge) () -> 42); +- metricRegistry.histogram("sw-histogram"); +- metricRegistry.timer("sw-timer"); +- metricRegistry.counter("sw-counter"); +- metricRegistry.meter("nw-meter-1"); +- metricRegistry.meter("sw-meter-3"); +- metricRegistry.meter("nw-meter-2"); +- +- assertThat(metricRegistry.getMeters(MetricFilter.startsWith("sw"))).containsOnlyKeys("sw-meter-3"); +- } +- +- @Test +- void testGetTimers() { +- metricRegistry.histogram("test-histogram"); +- metricRegistry.meter("test-meter"); +- metricRegistry.counter("test-counter"); +- metricRegistry.timer("test-timer-1"); +- metricRegistry.timer("test-timer-3"); +- metricRegistry.timer("test-timer-2"); +- +- assertThat(metricRegistry.getTimers()).containsOnlyKeys("test-timer-1", "test-timer-2", "test-timer-3"); +- } +- +- @Test +- void testGetTimersWithFilter() { +- metricRegistry.histogram("test-histogram-2"); +- metricRegistry.meter("test-meter-2"); +- metricRegistry.counter("test-counter-2"); +- metricRegistry.timer("test-timer-1"); +- metricRegistry.timer("test-timer-3"); +- metricRegistry.timer("test-timer-2"); +- +- assertThat(metricRegistry.getTimers(MetricFilter.endsWith("2"))).containsOnlyKeys("test-timer-2"); +- } +- +- @Test +- void testGetMetrics() { +- metricRegistry.register("test-text-gauge-2", new CachedGauge(1, TimeUnit.MINUTES) { +- @Override +- protected String loadValue() { +- return "eu2"; +- } ++ assertThat( ++ metricRegistry.getGauges( ++ (name, metric) -> name.contains("gauge") && metric instanceof CachedGauge)) ++ .containsOnlyKeys("test-text-gauge-2"); ++ } ++ ++ @Test ++ void getHistograms() { ++ metricRegistry.counter("test-counter"); ++ metricRegistry.timer("test-timer"); ++ metricRegistry.meter("test-meter"); ++ metricRegistry.histogram("test-histogram-1"); ++ metricRegistry.histogram("test-histogram-3"); ++ metricRegistry.histogram("test-histogram-2"); ++ ++ assertThat(metricRegistry.getHistograms()) ++ .containsOnlyKeys("test-histogram-1", "test-histogram-2", "test-histogram-3"); ++ } ++ ++ @Test ++ void getHistogramsWithFilter() { ++ metricRegistry.counter("sw-counter"); ++ metricRegistry.timer("sw-timer"); ++ metricRegistry.meter("sw-meter"); ++ metricRegistry.histogram("sw-histogram-1"); ++ metricRegistry.histogram("se-histogram-3"); ++ metricRegistry.histogram("sw-histogram-2"); ++ ++ assertThat(metricRegistry.getHistograms(MetricFilter.startsWith("sw"))) ++ .containsOnlyKeys("sw-histogram-1", "sw-histogram-2"); ++ } ++ ++ @Test ++ void getCounters() { ++ metricRegistry.histogram("test-histogram"); ++ metricRegistry.timer("test-timer"); ++ metricRegistry.meter("test-meter"); ++ metricRegistry.counter("test-counter-1"); ++ metricRegistry.counter("test-counter-3"); ++ metricRegistry.counter("test-counter-2"); ++ ++ assertThat(metricRegistry.getCounters()) ++ .containsOnlyKeys("test-counter-1", "test-counter-2", "test-counter-3"); ++ } ++ ++ @Test ++ void getCountersWithFilter() { ++ metricRegistry.histogram("test-histogram"); ++ metricRegistry.timer("test-timer"); ++ metricRegistry.meter("test-meter"); ++ metricRegistry.counter("test-counter-1"); ++ metricRegistry.counter("test-counter-3"); ++ metricRegistry.counter("test-cnt-2"); ++ ++ assertThat(metricRegistry.getCounters(MetricFilter.contains("counter"))) ++ .containsOnlyKeys("test-counter-1", "test-counter-3"); ++ } ++ ++ @Test ++ void getMeters() { ++ metricRegistry.register("test-gauge", (Gauge) () -> 42); ++ metricRegistry.histogram("test-histogram"); ++ metricRegistry.timer("test-timer"); ++ metricRegistry.counter("test-counter"); ++ metricRegistry.meter("test-meter-1"); ++ metricRegistry.meter("test-meter-3"); ++ metricRegistry.meter("test-meter-2"); ++ ++ assertThat(metricRegistry.getMeters()) ++ .containsOnlyKeys("test-meter-1", "test-meter-2", "test-meter-3"); ++ } ++ ++ @Test ++ void getMetersWithFilter() { ++ metricRegistry.register("sw-gauge", (Gauge) () -> 42); ++ metricRegistry.histogram("sw-histogram"); ++ metricRegistry.timer("sw-timer"); ++ metricRegistry.counter("sw-counter"); ++ metricRegistry.meter("nw-meter-1"); ++ metricRegistry.meter("sw-meter-3"); ++ metricRegistry.meter("nw-meter-2"); ++ ++ assertThat(metricRegistry.getMeters(MetricFilter.startsWith("sw"))) ++ .containsOnlyKeys("sw-meter-3"); ++ } ++ ++ @Test ++ void getTimers() { ++ metricRegistry.histogram("test-histogram"); ++ metricRegistry.meter("test-meter"); ++ metricRegistry.counter("test-counter"); ++ metricRegistry.timer("test-timer-1"); ++ metricRegistry.timer("test-timer-3"); ++ metricRegistry.timer("test-timer-2"); ++ ++ assertThat(metricRegistry.getTimers()) ++ .containsOnlyKeys("test-timer-1", "test-timer-2", "test-timer-3"); ++ } ++ ++ @Test ++ void getTimersWithFilter() { ++ metricRegistry.histogram("test-histogram-2"); ++ metricRegistry.meter("test-meter-2"); ++ metricRegistry.counter("test-counter-2"); ++ metricRegistry.timer("test-timer-1"); ++ metricRegistry.timer("test-timer-3"); ++ metricRegistry.timer("test-timer-2"); ++ ++ assertThat(metricRegistry.getTimers(MetricFilter.endsWith("2"))) ++ .containsOnlyKeys("test-timer-2"); ++ } ++ ++ @Test ++ void getMetrics() { ++ metricRegistry.register( ++ "test-text-gauge-2", ++ new CachedGauge(1, TimeUnit.MINUTES) { ++ @Override ++ protected String loadValue() { ++ return "eu2"; ++ } + }); +- metricRegistry.register("test-gauge", (Gauge) () -> 42); +- metricRegistry.register("test-text-gauge-1", new RatioGauge() { +- @Override +- protected Ratio getRatio() { +- return Ratio.of(1, 2); +- } ++ metricRegistry.register("test-gauge", (Gauge) () -> 42); ++ metricRegistry.register( ++ "test-text-gauge-1", ++ new RatioGauge() { ++ @Override ++ protected Ratio getRatio() { ++ return Ratio.of(1, 2); ++ } + }); +- metricRegistry.histogram("test-histogram-1"); +- metricRegistry.histogram("test-histogram-2"); +- metricRegistry.meter("test-meter-1"); +- metricRegistry.meter("test-meter-2"); +- metricRegistry.counter("test-counter"); +- metricRegistry.timer("test-timer-1"); +- metricRegistry.timer("test-timer-2"); +- MetricRegistry subMetrics = new MetricRegistry(); +- subMetrics.counter("sb-counter-1"); +- subMetrics.counter("sb-counter-2"); +- subMetrics.histogram("sb-histogram-1"); +- metricRegistry.register("test-ms", subMetrics); +- +- assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-text-gauge-2", "test-gauge", "test-text-gauge-1", +- "test-histogram-1", "test-histogram-2", "test-meter-1", "test-meter-2", "test-counter", +- "test-timer-1", "test-timer-2", +- "test-ms.sb-counter-1", "test-ms.sb-counter-2", "test-ms.sb-histogram-1"); +- } ++ metricRegistry.histogram("test-histogram-1"); ++ metricRegistry.histogram("test-histogram-2"); ++ metricRegistry.meter("test-meter-1"); ++ metricRegistry.meter("test-meter-2"); ++ metricRegistry.counter("test-counter"); ++ metricRegistry.timer("test-timer-1"); ++ metricRegistry.timer("test-timer-2"); ++ MetricRegistry subMetrics = new MetricRegistry(); ++ subMetrics.counter("sb-counter-1"); ++ subMetrics.counter("sb-counter-2"); ++ subMetrics.histogram("sb-histogram-1"); ++ metricRegistry.register("test-ms", subMetrics); ++ ++ assertThat(metricRegistry.getMetrics()) ++ .containsOnlyKeys( ++ "test-text-gauge-2", ++ "test-gauge", ++ "test-text-gauge-1", ++ "test-histogram-1", ++ "test-histogram-2", ++ "test-meter-1", ++ "test-meter-2", ++ "test-counter", ++ "test-timer-1", ++ "test-timer-2", ++ "test-ms.sb-counter-1", ++ "test-ms.sb-counter-2", ++ "test-ms.sb-histogram-1"); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java +@@ -1,28 +1,28 @@ + package com.codahale.metrics; + +-import org.assertj.core.data.Offset; +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; ++ ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class RatioGaugeTest { ++final class RatioGaugeTest { + +- private RatioGauge ratioGauge = new RatioGauge() { ++ private RatioGauge ratioGauge = ++ new RatioGauge() { + @Override + protected Ratio getRatio() { +- return Ratio.of(1, 3); ++ return Ratio.of(1, 3); + } +- }; +- +- @Test +- void testViewRatin() { +- assertThat(ratioGauge.getRatio().toString()).isEqualTo("1.0:3.0"); +- } ++ }; + ++ @Test ++ void viewRatin() { ++ assertThat(ratioGauge.getRatio()).hasToString("1.0:3.0"); ++ } + +- @Test +- void testCalculateRatio() { +- assertThat(ratioGauge.getValue()).isCloseTo(0.33, Offset.offset(0.01)); +- } ++ @Test ++ void calculateRatio() { ++ assertThat(ratioGauge.getValue()).isCloseTo(0.33, offset(0.01)); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java +@@ -1,80 +1,82 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.util.SortedMap; + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class ScheduledReporterTest { ++final class ScheduledReporterTest { + +- private MetricRegistry metricRegistry = new MetricRegistry(); +- private ScheduledReporter scheduledReporter; ++ private MetricRegistry metricRegistry = new MetricRegistry(); ++ private ScheduledReporter scheduledReporter; + +- @BeforeEach +- void setUp() throws Exception { +- metricRegistry.register("sw-gauge", (Gauge) () -> 28); +- metricRegistry.counter("sw-counter"); +- metricRegistry.timer("sw-timer"); +- metricRegistry.meter("sw-meter"); +- metricRegistry.histogram("sw-histogram"); +- } ++ @BeforeEach ++ void setUp() throws Exception { ++ metricRegistry.register("sw-gauge", (Gauge) () -> 28); ++ metricRegistry.counter("sw-counter"); ++ metricRegistry.timer("sw-timer"); ++ metricRegistry.meter("sw-meter"); ++ metricRegistry.histogram("sw-histogram"); ++ } + +- @AfterEach +- void tearDown() throws Exception { +- scheduledReporter.stop(); +- } ++ @AfterEach ++ void tearDown() throws Exception { ++ scheduledReporter.stop(); ++ } + +- private ScheduledReporter createScheduledReporter(CountDownLatch latch) { +- return new ScheduledReporter(metricRegistry, "test", MetricFilter.ALL, TimeUnit.MILLISECONDS, +- TimeUnit.MINUTES) { +- @Override +- @SuppressWarnings("rawtypes") +- public void report(SortedMap gauges, SortedMap counters, +- SortedMap histograms, SortedMap meters, +- SortedMap timers) { +- assertThat(gauges).containsOnlyKeys("sw-gauge"); +- assertThat(counters).containsOnlyKeys("sw-counter"); +- assertThat(histograms).containsOnlyKeys("sw-histogram"); +- assertThat(meters).containsOnlyKeys("sw-meter"); +- assertThat(timers).containsOnlyKeys("sw-timer"); +- latch.countDown(); +- } +- }; +- } ++ private ScheduledReporter createScheduledReporter(CountDownLatch latch) { ++ return new ScheduledReporter( ++ metricRegistry, "test", MetricFilter.ALL, TimeUnit.MILLISECONDS, TimeUnit.MINUTES) { ++ @Override ++ @SuppressWarnings("rawtypes") ++ public void report( ++ SortedMap gauges, ++ SortedMap counters, ++ SortedMap histograms, ++ SortedMap meters, ++ SortedMap timers) { ++ assertThat(gauges).containsOnlyKeys("sw-gauge"); ++ assertThat(counters).containsOnlyKeys("sw-counter"); ++ assertThat(histograms).containsOnlyKeys("sw-histogram"); ++ assertThat(meters).containsOnlyKeys("sw-meter"); ++ assertThat(timers).containsOnlyKeys("sw-timer"); ++ latch.countDown(); ++ } ++ }; ++ } + +- @Test +- void testReport() throws Exception { +- CountDownLatch latch = new CountDownLatch(1); +- scheduledReporter = createScheduledReporter(latch); +- scheduledReporter.report(); ++ @Test ++ void report() throws Exception { ++ CountDownLatch latch = new CountDownLatch(1); ++ scheduledReporter = createScheduledReporter(latch); ++ scheduledReporter.report(); + +- latch.await(5, TimeUnit.SECONDS); +- assertThat(latch.getCount()).isEqualTo(0); +- } ++ latch.await(5, TimeUnit.SECONDS); ++ assertThat(latch.getCount()).isEqualTo(0); ++ } + +- @Test +- void testStart() throws Exception { +- CountDownLatch latch = new CountDownLatch(2); +- scheduledReporter = createScheduledReporter(latch); +- scheduledReporter.start(10, TimeUnit.MILLISECONDS); ++ @Test ++ void start() throws Exception { ++ CountDownLatch latch = new CountDownLatch(2); ++ scheduledReporter = createScheduledReporter(latch); ++ scheduledReporter.start(10, TimeUnit.MILLISECONDS); + +- latch.await(5, TimeUnit.SECONDS); +- assertThat(latch.getCount()).isEqualTo(0); +- } ++ latch.await(5, TimeUnit.SECONDS); ++ assertThat(latch.getCount()).isEqualTo(0); ++ } + +- @Test +- void testStartWithoutDelay() throws Exception { +- CountDownLatch latch = new CountDownLatch(2); +- scheduledReporter = createScheduledReporter(latch); +- scheduledReporter.start(0, 10, TimeUnit.MILLISECONDS); ++ @Test ++ void startWithoutDelay() throws Exception { ++ CountDownLatch latch = new CountDownLatch(2); ++ scheduledReporter = createScheduledReporter(latch); ++ scheduledReporter.start(0, 10, TimeUnit.MILLISECONDS); + +- latch.await(5, TimeUnit.SECONDS); +- assertThat(latch.getCount()).isEqualTo(0); +- } ++ latch.await(5, TimeUnit.SECONDS); ++ assertThat(latch.getCount()).isEqualTo(0); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java +@@ -1,53 +1,55 @@ + package com.codahale.metrics; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++ + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +- + @SuppressWarnings("deprecation") +-class SharedMetricRegistriesTest { +- +- @AfterEach +- void tearDown() throws Exception { +- SharedMetricRegistries.clear(); +- } +- +- @Test +- void testGetOrCreateMetricRegistry() { +- SharedMetricRegistries.getOrCreate("get-or-create").counter("test-counter"); +- +- assertThat(SharedMetricRegistries.getOrCreate("get-or-create").getCounters()) +- .containsOnlyKeys("test-counter"); +- } +- +- @Test +- void testAddMetricRegistry() { +- MetricRegistry metricRegistry = new MetricRegistry(); +- metricRegistry.histogram("test-histogram"); +- SharedMetricRegistries.add("add", metricRegistry); +- +- assertThat(SharedMetricRegistries.getOrCreate("add").getHistograms()) +- .containsOnlyKeys("test-histogram"); +- } +- +- @Test +- void testNames() { +- SharedMetricRegistries.add("registry-1", new MetricRegistry()); +- SharedMetricRegistries.add("registry-2", new MetricRegistry()); +- SharedMetricRegistries.add("registry-3", new MetricRegistry()); +- +- assertThat(SharedMetricRegistries.names()).containsOnly("registry-1", "registry-2", "registry-3"); +- } +- +- @Test +- void testTryGetDefaultRegistry() { +- assertThat(SharedMetricRegistries.tryGetDefault()).isNull(); +- } +- +- @Test +- void testGetDefaultRegistry() { +- assertThatIllegalStateException().isThrownBy(SharedMetricRegistries::getDefault); +- } ++final class SharedMetricRegistriesTest { ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ SharedMetricRegistries.clear(); ++ } ++ ++ @Test ++ void getOrCreateMetricRegistry() { ++ SharedMetricRegistries.getOrCreate("get-or-create").counter("test-counter"); ++ ++ assertThat(SharedMetricRegistries.getOrCreate("get-or-create").getCounters()) ++ .containsOnlyKeys("test-counter"); ++ } ++ ++ @Test ++ void addMetricRegistry() { ++ MetricRegistry metricRegistry = new MetricRegistry(); ++ metricRegistry.histogram("test-histogram"); ++ SharedMetricRegistries.add("add", metricRegistry); ++ ++ assertThat(SharedMetricRegistries.getOrCreate("add").getHistograms()) ++ .containsOnlyKeys("test-histogram"); ++ } ++ ++ @Test ++ void names() { ++ SharedMetricRegistries.add("registry-1", new MetricRegistry()); ++ SharedMetricRegistries.add("registry-2", new MetricRegistry()); ++ SharedMetricRegistries.add("registry-3", new MetricRegistry()); ++ ++ assertThat(SharedMetricRegistries.names()) ++ .containsOnly("registry-1", "registry-2", "registry-3"); ++ } ++ ++ @Test ++ void tryGetDefaultRegistry() { ++ assertThat(SharedMetricRegistries.tryGetDefault()).isNull(); ++ } ++ ++ @Test ++ void getDefaultRegistry() { ++ assertThatThrownBy(SharedMetricRegistries::getDefault) ++ .isInstanceOf(IllegalStateException.class); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java +@@ -1,55 +1,55 @@ + package com.codahale.metrics; + ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ ++import java.util.concurrent.Executors; ++import java.util.concurrent.ScheduledExecutorService; ++import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.slf4j.Logger; + import org.slf4j.Marker; + +-import java.util.concurrent.Executors; +-import java.util.concurrent.ScheduledExecutorService; +-import java.util.concurrent.TimeUnit; +- +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- + @SuppressWarnings("deprecation") +-class Slf4jReporterTest { +- +- private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); +- private Logger logger = mock(Logger.class); +- private Marker marker = mock(Marker.class); +- +- @BeforeEach +- void setUp() throws Exception { +- when(logger.isInfoEnabled(marker)).thenReturn(true); +- } +- +- @AfterEach +- void tearDown() throws Exception { +- executor.shutdownNow(); +- } +- +- @Test +- void testReport() throws Exception { +- MetricRegistry metricRegistry = new MetricRegistry(); +- metricRegistry.counter("test-counter").inc(100); +- +- Slf4jReporter slf4jReporter = Slf4jReporter.forRegistry(metricRegistry) +- .shutdownExecutorOnStop(false) +- .scheduleOn(executor) +- .outputTo(logger) +- .markWith(marker) +- .prefixedWith("us-nw") +- .convertRatesTo(TimeUnit.SECONDS) +- .convertDurationsTo(TimeUnit.MILLISECONDS) +- .filter(MetricFilter.ALL) +- .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) +- .build(); +- +- slf4jReporter.report(); +- +- verify(logger).info(marker, "type=COUNTER, name=us-nw.test-counter, count=100"); +- } ++final class Slf4jReporterTest { ++ ++ private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); ++ private Logger logger = mock(); ++ private Marker marker = mock(); ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ when(logger.isInfoEnabled(marker)).thenReturn(true); ++ } ++ ++ @AfterEach ++ void tearDown() throws Exception { ++ executor.shutdownNow(); ++ } ++ ++ @Test ++ void report() throws Exception { ++ MetricRegistry metricRegistry = new MetricRegistry(); ++ metricRegistry.counter("test-counter").inc(100); ++ ++ Slf4jReporter slf4jReporter = ++ Slf4jReporter.forRegistry(metricRegistry) ++ .shutdownExecutorOnStop(false) ++ .scheduleOn(executor) ++ .outputTo(logger) ++ .markWith(marker) ++ .prefixedWith("us-nw") ++ .convertRatesTo(TimeUnit.SECONDS) ++ .convertDurationsTo(TimeUnit.MILLISECONDS) ++ .filter(MetricFilter.ALL) ++ .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) ++ .build(); ++ ++ slf4jReporter.report(); ++ ++ verify(logger).info(marker, "type=COUNTER, name=us-nw.test-counter, count=100"); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java +@@ -1,34 +1,34 @@ + package com.codahale.metrics; + +-import org.assertj.core.data.Offset; +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + + import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class SlidingTimeWindowArrayReservoirTest { +- +- @Test +- void testCreateWithWindow() { +- SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS); +- reservoir.update(100); +- reservoir.update(200); +- reservoir.update(30); +- +- assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); +- } +- +- @Test +- void testCreateWithWindowAndClock() { +- SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS, +- new Clock.UserTimeClock()); +- reservoir.update(400); +- reservoir.update(300); +- +- assertThat(reservoir.size()).isEqualTo(2); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); +- } ++final class SlidingTimeWindowArrayReservoirTest { ++ ++ @Test ++ void createWithWindow() { ++ SlidingTimeWindowArrayReservoir reservoir = ++ new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS); ++ reservoir.update(100); ++ reservoir.update(200); ++ reservoir.update(30); ++ ++ assertThat(reservoir.size()).isEqualTo(3); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); ++ } ++ ++ @Test ++ void createWithWindowAndClock() { ++ SlidingTimeWindowArrayReservoir reservoir = ++ new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); ++ reservoir.update(400); ++ reservoir.update(300); ++ ++ assertThat(reservoir.size()).isEqualTo(2); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java +@@ -1,34 +1,33 @@ + package com.codahale.metrics; + +-import org.assertj.core.data.Offset; +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + + import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class SlidingTimeWindowReservoirTest { +- +- @Test +- void testCreateWithWindow() { +- SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS); +- reservoir.update(100); +- reservoir.update(200); +- reservoir.update(30); +- +- assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); +- } +- +- @Test +- void testCreateWithWindowAndClock() { +- SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS, +- new Clock.UserTimeClock()); +- reservoir.update(400); +- reservoir.update(300); +- +- assertThat(reservoir.size()).isEqualTo(2); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); +- } ++final class SlidingTimeWindowReservoirTest { ++ ++ @Test ++ void createWithWindow() { ++ SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS); ++ reservoir.update(100); ++ reservoir.update(200); ++ reservoir.update(30); ++ ++ assertThat(reservoir.size()).isEqualTo(3); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); ++ } ++ ++ @Test ++ void createWithWindowAndClock() { ++ SlidingTimeWindowReservoir reservoir = ++ new SlidingTimeWindowReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); ++ reservoir.update(400); ++ reservoir.update(300); ++ ++ assertThat(reservoir.size()).isEqualTo(2); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java +@@ -1,33 +1,33 @@ + package com.codahale.metrics; + +-import org.assertj.core.data.Offset; +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; ++ ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class SlidingWindowReservoirTest { ++final class SlidingWindowReservoirTest { + +- @Test +- void testCreateWithBigWindow() { +- SlidingWindowReservoir reservoir = new SlidingWindowReservoir(100); +- reservoir.update(100); +- reservoir.update(220); +- reservoir.update(130); ++ @Test ++ void createWithBigWindow() { ++ SlidingWindowReservoir reservoir = new SlidingWindowReservoir(100); ++ reservoir.update(100); ++ reservoir.update(220); ++ reservoir.update(130); + +- assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, Offset.offset(0.1)); +- } ++ assertThat(reservoir.size()).isEqualTo(3); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, offset(0.1)); ++ } + +- @Test +- void testCreateWithLowWindow() { +- SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); +- reservoir.update(500); +- reservoir.update(220); +- reservoir.update(100); +- reservoir.update(40); ++ @Test ++ void createWithLowWindow() { ++ SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); ++ reservoir.update(500); ++ reservoir.update(220); ++ reservoir.update(100); ++ reservoir.update(40); + +- assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, Offset.offset(0.1)); +- } ++ assertThat(reservoir.size()).isEqualTo(3); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, offset(0.1)); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java +@@ -1,38 +1,34 @@ + package com.codahale.metrics; + +-import io.dropwizard.metrics5.UniformSnapshot; +-import org.assertj.core.data.Offset; +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + ++import io.dropwizard.metrics5.UniformSnapshot; + import java.io.ByteArrayOutputStream; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class SnapshotTest { ++final class SnapshotTest { + +- @Test +- void testCreateSnapshot() throws Exception { +- Snapshot snapshot = Snapshot.of(new UniformSnapshot(new long[]{5, 1, 2, 3, 4})); ++ @Test ++ void createSnapshot() throws Exception { ++ Snapshot snapshot = Snapshot.of(new UniformSnapshot(new long[] {5, 1, 2, 3, 4})); + +- assertThat(snapshot.getValues()).isEqualTo(new long[]{1, 2, 3, 4, 5}); +- assertThat(snapshot.size()).isEqualTo(5); +- assertThat(snapshot.getMin()).isEqualTo(1); +- assertThat(snapshot.getMax()).isEqualTo(5); +- assertThat(snapshot.getStdDev()).isEqualTo(1.58, Offset.offset(0.01)); +- assertThat(snapshot.getMedian()).isEqualTo(3, Offset.offset(0.01)); +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, Offset.offset(0.01)); +- assertThat(snapshot.get95thPercentile()).isEqualTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get98thPercentile()).isEqualTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get99thPercentile()).isEqualTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get999thPercentile()).isEqualTo(5, Offset.offset(0.01)); ++ assertThat(snapshot.getValues()).isEqualTo(new long[] {1, 2, 3, 4, 5}); ++ assertThat(snapshot.size()).isEqualTo(5); ++ assertThat(snapshot.getMin()).isEqualTo(1); ++ assertThat(snapshot.getMax()).isEqualTo(5); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.58, offset(0.01)); ++ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.01)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.01)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5, offset(0.01)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5, offset(0.01)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5, offset(0.01)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5, offset(0.01)); + +- ByteArrayOutputStream baos = new ByteArrayOutputStream(); +- snapshot.dump(baos); +- assertThat(baos.toString("UTF-8")).isEqualToNormalizingNewlines("1\n" + +- "2\n" + +- "3\n" + +- "4\n" + +- "5\n"); +- } ++ ByteArrayOutputStream baos = new ByteArrayOutputStream(); ++ snapshot.dump(baos); ++ assertThat(baos.toString("UTF-8")) ++ .isEqualToNormalizingNewlines("1\n" + "2\n" + "3\n" + "4\n" + "5\n"); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java +@@ -1,103 +1,102 @@ + package com.codahale.metrics; + +-import org.junit.jupiter.api.Test; ++import static org.assertj.core.api.Assertions.assertThat; + + import java.time.Duration; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicInteger; +- +-import static org.assertj.core.api.Assertions.assertThat; ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class TimerTest { ++final class TimerTest { + +- private static class ManualClock extends Clock { ++ private static class ManualClock extends Clock { + +- long startTime = System.nanoTime(); ++ long startTime = System.nanoTime(); + +- @Override +- public long getTick() { +- return startTime += 100_000_000; +- } ++ @Override ++ public long getTick() { ++ return startTime += 100_000_000; + } ++ } + +- private static void verifyOneEvent(Timer timer) { +- assertThat(timer.getCount()).isEqualTo(1); +- assertThat(timer.getSnapshot().getValues()).containsExactly(100_000_000L); +- } ++ private static void verifyOneEvent(Timer timer) { ++ assertThat(timer.getCount()).isEqualTo(1); ++ assertThat(timer.getSnapshot().getValues()).containsExactly(100_000_000L); ++ } + +- @Test +- void testCreate() { +- Timer timer = new Timer(); +- timer.update(100, TimeUnit.MILLISECONDS); +- timer.update(200, TimeUnit.MILLISECONDS); ++ @Test ++ void create() { ++ Timer timer = new Timer(); ++ timer.update(100, TimeUnit.MILLISECONDS); ++ timer.update(200, TimeUnit.MILLISECONDS); + +- assertThat(timer.getCount()).isEqualTo(2); +- } ++ assertThat(timer.getCount()).isEqualTo(2); ++ } + +- @Test +- void testCreateWithCustomReservoir() { +- Timer timer = new Timer(new SlidingWindowReservoir(100)); +- timer.update(100, TimeUnit.MILLISECONDS); +- timer.update(200, TimeUnit.MILLISECONDS); ++ @Test ++ void createWithCustomReservoir() { ++ Timer timer = new Timer(new SlidingWindowReservoir(100)); ++ timer.update(100, TimeUnit.MILLISECONDS); ++ timer.update(200, TimeUnit.MILLISECONDS); + +- assertThat(timer.getCount()).isEqualTo(2); +- } ++ assertThat(timer.getCount()).isEqualTo(2); ++ } + +- @Test +- void testCreateWithCustomReservoirAndClock() { +- Timer timer = new Timer(new SlidingWindowReservoir(100), new Clock.UserTimeClock()); +- timer.update(100, TimeUnit.MILLISECONDS); +- timer.update(200, TimeUnit.MILLISECONDS); ++ @Test ++ void createWithCustomReservoirAndClock() { ++ Timer timer = new Timer(new SlidingWindowReservoir(100), new Clock.UserTimeClock()); ++ timer.update(100, TimeUnit.MILLISECONDS); ++ timer.update(200, TimeUnit.MILLISECONDS); + +- assertThat(timer.getCount()).isEqualTo(2); +- } ++ assertThat(timer.getCount()).isEqualTo(2); ++ } + +- @Test +- void testTimerContext() { +- Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); +- timer.time().stop(); ++ @Test ++ void timerContext() { ++ Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); ++ timer.time().stop(); + +- verifyOneEvent(timer); +- } ++ verifyOneEvent(timer); ++ } + +- @Test +- void testTimerRunnable() { +- Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); ++ @Test ++ void timerRunnable() { ++ Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + +- AtomicInteger counter = new AtomicInteger(); +- timer.time((Runnable) counter::incrementAndGet); ++ AtomicInteger counter = new AtomicInteger(); ++ timer.time((Runnable) counter::incrementAndGet); + +- assertThat(counter.get()).isEqualTo(1); +- verifyOneEvent(timer); +- } ++ assertThat(counter.get()).isEqualTo(1); ++ verifyOneEvent(timer); ++ } + +- @Test +- void testTimerCallable() throws Exception { +- Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); ++ @Test ++ void timerCallable() throws Exception { ++ Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + +- String message = timer.time(() -> "SUCCESS"); ++ String message = timer.time(() -> "SUCCESS"); + +- assertThat(message).isEqualTo("SUCCESS"); +- verifyOneEvent(timer); +- } ++ assertThat(message).isEqualTo("SUCCESS"); ++ verifyOneEvent(timer); ++ } + +- @Test +- void testTimerSupplier() throws Exception { +- Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); ++ @Test ++ void timerSupplier() throws Exception { ++ Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + +- Integer result = timer.timeSupplier(() -> 42); ++ Integer result = timer.timeSupplier(() -> 42); + +- assertThat(result).isEqualTo(42); +- verifyOneEvent(timer); +- } ++ assertThat(result).isEqualTo(42); ++ verifyOneEvent(timer); ++ } + +- @Test +- void testUpdateDuration() { +- Timer timer = new Timer(); +- timer.update(Duration.ofMillis(100)); +- timer.update(Duration.ofMillis(200)); ++ @Test ++ void updateDuration() { ++ Timer timer = new Timer(); ++ timer.update(Duration.ofMillis(100)); ++ timer.update(Duration.ofMillis(200)); + +- assertThat(timer.getCount()).isEqualTo(2); +- } ++ assertThat(timer.getCount()).isEqualTo(2); ++ } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java +@@ -1,42 +1,42 @@ + package com.codahale.metrics; + +-import org.assertj.core.data.Offset; +-import org.junit.jupiter.api.Test; +- + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; ++ ++import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class UniformReservoirTest { ++final class UniformReservoirTest { + +- @Test +- void testCreateReservoir() { +- UniformReservoir reservoir = new UniformReservoir(); +- reservoir.update(120); +- reservoir.update(190); +- reservoir.update(200); +- reservoir.update(130); +- reservoir.update(140); ++ @Test ++ void createReservoir() { ++ UniformReservoir reservoir = new UniformReservoir(); ++ reservoir.update(120); ++ reservoir.update(190); ++ reservoir.update(200); ++ reservoir.update(130); ++ reservoir.update(140); + +- Snapshot snapshot = reservoir.getSnapshot(); +- assertThat(snapshot.size()).isEqualTo(5); +- assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); +- assertThat(snapshot.getMin()).isEqualTo(120); +- assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isEqualTo(36.47, Offset.offset(0.1)); +- assertThat(snapshot.get75thPercentile()).isEqualTo(195); +- assertThat(snapshot.get95thPercentile()).isEqualTo(200); +- assertThat(snapshot.get98thPercentile()).isEqualTo(200); +- assertThat(snapshot.get99thPercentile()).isEqualTo(200); +- assertThat(snapshot.get999thPercentile()).isEqualTo(200); +- } ++ Snapshot snapshot = reservoir.getSnapshot(); ++ assertThat(snapshot.size()).isEqualTo(5); ++ assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); ++ assertThat(snapshot.getMin()).isEqualTo(120); ++ assertThat(snapshot.getMax()).isEqualTo(200); ++ assertThat(snapshot.getStdDev()).isCloseTo(36.47, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isEqualTo(195); ++ assertThat(snapshot.get95thPercentile()).isEqualTo(200); ++ assertThat(snapshot.get98thPercentile()).isEqualTo(200); ++ assertThat(snapshot.get99thPercentile()).isEqualTo(200); ++ assertThat(snapshot.get999thPercentile()).isEqualTo(200); ++ } + +- @Test +- void testCreateReservoirWithCustomSize() { +- UniformReservoir reservoir = new UniformReservoir(128); +- reservoir.update(440); +- reservoir.update(250); +- reservoir.update(380); ++ @Test ++ void createReservoirWithCustomSize() { ++ UniformReservoir reservoir = new UniformReservoir(128); ++ reservoir.update(440); ++ reservoir.update(250); ++ reservoir.update(380); + +- assertThat(reservoir.size()).isEqualTo(3); +- } ++ assertThat(reservoir.size()).isEqualTo(3); ++ } + } +--- a/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java ++++ b/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java +@@ -1,8 +1,11 @@ + package io.dropwizard.metrics5.log4j2; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.SharedMetricRegistries; ++import java.io.Serializable; + import org.apache.logging.log4j.core.Appender; + import org.apache.logging.log4j.core.Filter; + import org.apache.logging.log4j.core.Layout; +@@ -12,127 +15,131 @@ import org.apache.logging.log4j.core.config.plugins.Plugin; + import org.apache.logging.log4j.core.config.plugins.PluginAttribute; + import org.apache.logging.log4j.core.config.plugins.PluginFactory; + +-import java.io.Serializable; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + /** +- * A Log4J 2.x {@link Appender} which has seven meters, one for each logging level and one for the total +- * number of statements being logged. The meter names are the logging level names appended to the +- * name of the appender. ++ * A Log4J 2.x {@link Appender} which has seven meters, one for each logging level and one for the ++ * total number of statements being logged. The meter names are the logging level names appended to ++ * the name of the appender. + */ + @Plugin(name = "MetricsAppender", category = "Core", elementType = "appender") + public class InstrumentedAppender extends AbstractAppender { + +- private transient final MetricRegistry registry; ++ private final transient MetricRegistry registry; + +- private transient Meter all; +- private transient Meter trace; +- private transient Meter debug; +- private transient Meter info; +- private transient Meter warn; +- private transient Meter error; +- private transient Meter fatal; ++ private transient Meter all; ++ private transient Meter trace; ++ private transient Meter debug; ++ private transient Meter info; ++ private transient Meter warn; ++ private transient Meter error; ++ private transient Meter fatal; + +- /** +- * Create a new instrumented appender using the given registry name. +- * +- * @param registryName the name of the registry in {@link SharedMetricRegistries} +- * @param filter The Filter to associate with the Appender. +- * @param layout The layout to use to format the event. +- * @param ignoreExceptions If true, exceptions will be logged and suppressed. If false errors will be +- * logged and then passed to the application. +- */ +- public InstrumentedAppender(String registryName, Filter filter, Layout layout, boolean ignoreExceptions) { +- this(SharedMetricRegistries.getOrCreate(registryName), filter, layout, ignoreExceptions); +- } ++ /** ++ * Create a new instrumented appender using the given registry name. ++ * ++ * @param registryName the name of the registry in {@link SharedMetricRegistries} ++ * @param filter The Filter to associate with the Appender. ++ * @param layout The layout to use to format the event. ++ * @param ignoreExceptions If true, exceptions will be logged and suppressed. If false errors will ++ * be logged and then passed to the application. ++ */ ++ public InstrumentedAppender( ++ String registryName, ++ Filter filter, ++ Layout layout, ++ boolean ignoreExceptions) { ++ this(SharedMetricRegistries.getOrCreate(registryName), filter, layout, ignoreExceptions); ++ } + +- /** +- * Create a new instrumented appender using the given registry name. +- * +- * @param registryName the name of the registry in {@link SharedMetricRegistries} +- */ +- public InstrumentedAppender(String registryName) { +- this(SharedMetricRegistries.getOrCreate(registryName)); +- } ++ /** ++ * Create a new instrumented appender using the given registry name. ++ * ++ * @param registryName the name of the registry in {@link SharedMetricRegistries} ++ */ ++ public InstrumentedAppender(String registryName) { ++ this(SharedMetricRegistries.getOrCreate(registryName)); ++ } + +- /** +- * Create a new instrumented appender using the given registry. +- * +- * @param registry the metric registry +- */ +- public InstrumentedAppender(MetricRegistry registry) { +- this(registry, null, null, true); +- } ++ /** ++ * Create a new instrumented appender using the given registry. ++ * ++ * @param registry the metric registry ++ */ ++ public InstrumentedAppender(MetricRegistry registry) { ++ this(registry, null, null, true); ++ } + +- /** +- * Create a new instrumented appender using the given registry. +- * +- * @param registry the metric registry +- * @param filter The Filter to associate with the Appender. +- * @param layout The layout to use to format the event. +- * @param ignoreExceptions If true, exceptions will be logged and suppressed. If false errors will be +- * logged and then passed to the application. +- */ +- public InstrumentedAppender(MetricRegistry registry, Filter filter, Layout layout, boolean ignoreExceptions) { +- super(name(Appender.class).getKey(), filter, layout, ignoreExceptions); +- this.registry = registry; +- } ++ /** ++ * Create a new instrumented appender using the given registry. ++ * ++ * @param registry the metric registry ++ * @param filter The Filter to associate with the Appender. ++ * @param layout The layout to use to format the event. ++ * @param ignoreExceptions If true, exceptions will be logged and suppressed. If false errors will ++ * be logged and then passed to the application. ++ */ ++ public InstrumentedAppender( ++ MetricRegistry registry, ++ Filter filter, ++ Layout layout, ++ boolean ignoreExceptions) { ++ super(name(Appender.class).getKey(), filter, layout, ignoreExceptions); ++ this.registry = registry; ++ } + +- /** +- * Create a new instrumented appender using the given appender name and registry. +- * +- * @param appenderName The name of the appender. +- * @param registry the metric registry +- */ +- public InstrumentedAppender(String appenderName, MetricRegistry registry) { +- super(appenderName, null, null, true); +- this.registry = registry; +- } ++ /** ++ * Create a new instrumented appender using the given appender name and registry. ++ * ++ * @param appenderName The name of the appender. ++ * @param registry the metric registry ++ */ ++ public InstrumentedAppender(String appenderName, MetricRegistry registry) { ++ super(appenderName, null, null, true); ++ this.registry = registry; ++ } + +- @PluginFactory +- public static InstrumentedAppender createAppender( +- @PluginAttribute("name") String name, +- @PluginAttribute(value = "registryName", defaultString = "log4j2Metrics") String registry) { +- return new InstrumentedAppender(name, SharedMetricRegistries.getOrCreate(registry)); +- } ++ @PluginFactory ++ public static InstrumentedAppender createAppender( ++ @PluginAttribute("name") String name, ++ @PluginAttribute(value = "registryName", defaultString = "log4j2Metrics") String registry) { ++ return new InstrumentedAppender(name, SharedMetricRegistries.getOrCreate(registry)); ++ } + +- @Override +- public void start() { +- this.all = registry.meter(name(getName(), "all")); +- this.trace = registry.meter(name(getName(), "trace")); +- this.debug = registry.meter(name(getName(), "debug")); +- this.info = registry.meter(name(getName(), "info")); +- this.warn = registry.meter(name(getName(), "warn")); +- this.error = registry.meter(name(getName(), "error")); +- this.fatal = registry.meter(name(getName(), "fatal")); +- super.start(); +- } ++ @Override ++ public void start() { ++ this.all = registry.meter(name(getName(), "all")); ++ this.trace = registry.meter(name(getName(), "trace")); ++ this.debug = registry.meter(name(getName(), "debug")); ++ this.info = registry.meter(name(getName(), "info")); ++ this.warn = registry.meter(name(getName(), "warn")); ++ this.error = registry.meter(name(getName(), "error")); ++ this.fatal = registry.meter(name(getName(), "fatal")); ++ super.start(); ++ } + +- @Override +- public void append(LogEvent event) { +- all.mark(); +- switch (event.getLevel().getStandardLevel()) { +- case TRACE: +- trace.mark(); +- break; +- case DEBUG: +- debug.mark(); +- break; +- case INFO: +- info.mark(); +- break; +- case WARN: +- warn.mark(); +- break; +- case ERROR: +- error.mark(); +- break; +- case FATAL: +- fatal.mark(); +- break; +- default: +- break; +- } ++ @Override ++ public void append(LogEvent event) { ++ all.mark(); ++ switch (event.getLevel().getStandardLevel()) { ++ case TRACE: ++ trace.mark(); ++ break; ++ case DEBUG: ++ debug.mark(); ++ break; ++ case INFO: ++ info.mark(); ++ break; ++ case WARN: ++ warn.mark(); ++ break; ++ case ERROR: ++ error.mark(); ++ break; ++ case FATAL: ++ fatal.mark(); ++ break; ++ default: ++ break; + } ++ } + } +--- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java ++++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.log4j2; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.SharedMetricRegistries; + import org.apache.logging.log4j.core.Logger; +@@ -10,57 +12,55 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-public class InstrumentedAppenderConfigTest { +- public static final String METRIC_NAME_PREFIX = "metrics"; +- public static final String REGISTRY_NAME = "shared-metrics-registry"; +- +- private final MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME); +- private ConfigurationSource source; +- private LoggerContext context; ++final class InstrumentedAppenderConfigTest { ++ public static final String METRIC_NAME_PREFIX = "metrics"; ++ public static final String REGISTRY_NAME = "shared-metrics-registry"; + +- @BeforeEach +- void setUp() throws Exception { +- source = new ConfigurationSource(this.getClass().getClassLoader().getResourceAsStream("log4j2-testconfig.xml")); +- context = Configurator.initialize(null, source); +- } ++ private final MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME); ++ private ConfigurationSource source; ++ private LoggerContext context; + +- @AfterEach +- void tearDown() { +- context.stop(); +- } ++ @BeforeEach ++ void setUp() throws Exception { ++ source = ++ new ConfigurationSource( ++ this.getClass().getClassLoader().getResourceAsStream("log4j2-testconfig.xml")); ++ context = Configurator.initialize(null, source); ++ } + +- // The biggest test is that we can initialize the log4j2 config at all. ++ @AfterEach ++ void tearDown() { ++ context.stop(); ++ } + +- @Test +- void canRecordAll() { +- Logger logger = context.getLogger(this.getClass().getName()); ++ // The biggest test is that we can initialize the log4j2 config at all. + +- long initialAllCount = registry.meter(METRIC_NAME_PREFIX + ".all").getCount(); +- logger.error("an error message"); +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(initialAllCount + 1); +- } ++ @Test ++ void canRecordAll() { ++ Logger logger = context.getLogger(this.getClass().getName()); + +- @Test +- void canRecordError() { +- Logger logger = context.getLogger(this.getClass().getName()); ++ long initialAllCount = registry.meter(METRIC_NAME_PREFIX + ".all").getCount(); ++ logger.error("an error message"); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) ++ .isEqualTo(initialAllCount + 1); ++ } + +- long initialErrorCount = registry.meter(METRIC_NAME_PREFIX + ".error").getCount(); +- logger.error("an error message"); +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(initialErrorCount + 1); +- } ++ @Test ++ void canRecordError() { ++ Logger logger = context.getLogger(this.getClass().getName()); + +- @Test +- void noInvalidRecording() { +- Logger logger = context.getLogger(this.getClass().getName()); ++ long initialErrorCount = registry.meter(METRIC_NAME_PREFIX + ".error").getCount(); ++ logger.error("an error message"); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) ++ .isEqualTo(initialErrorCount + 1); ++ } + +- long initialInfoCount = registry.meter(METRIC_NAME_PREFIX + ".info").getCount(); +- logger.error("an error message"); +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(initialInfoCount); +- } ++ @Test ++ void noInvalidRecording() { ++ Logger logger = context.getLogger(this.getClass().getName()); + ++ long initialInfoCount = registry.meter(METRIC_NAME_PREFIX + ".info").getCount(); ++ logger.error("an error message"); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(initialInfoCount); ++ } + } +--- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java ++++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.log4j2; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.SharedMetricRegistries; + import org.apache.logging.log4j.Level; +@@ -8,121 +12,104 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-public class InstrumentedAppenderTest { ++final class InstrumentedAppenderTest { + +- public static final String METRIC_NAME_PREFIX = "org.apache.logging.log4j.core.Appender"; ++ public static final String METRIC_NAME_PREFIX = "org.apache.logging.log4j.core.Appender"; + +- private final MetricRegistry registry = new MetricRegistry(); +- private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final LogEvent event = mock(LogEvent.class); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final InstrumentedAppender appender = new InstrumentedAppender(registry); ++ private final LogEvent event = mock(); + +- @BeforeEach +- void setUp() { +- appender.start(); +- } ++ @BeforeEach ++ void setUp() { ++ appender.start(); ++ } + +- @AfterEach +- void tearDown() { +- SharedMetricRegistries.clear(); +- } ++ @AfterEach ++ void tearDown() { ++ SharedMetricRegistries.clear(); ++ } + +- @Test +- void metersTraceEvents() { +- when(event.getLevel()).thenReturn(Level.TRACE); ++ @Test ++ void metersTraceEvents() { ++ when(event.getLevel()).thenReturn(Level.TRACE); + +- appender.append(event); ++ appender.append(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()).isEqualTo(1); ++ } + +- @Test +- void metersDebugEvents() { +- when(event.getLevel()).thenReturn(Level.DEBUG); ++ @Test ++ void metersDebugEvents() { ++ when(event.getLevel()).thenReturn(Level.DEBUG); + +- appender.append(event); ++ appender.append(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()).isEqualTo(1); ++ } + +- @Test +- void metersInfoEvents() { +- when(event.getLevel()).thenReturn(Level.INFO); ++ @Test ++ void metersInfoEvents() { ++ when(event.getLevel()).thenReturn(Level.INFO); + +- appender.append(event); ++ appender.append(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- @Test +- void metersWarnEvents() { +- when(event.getLevel()).thenReturn(Level.WARN); ++ @Test ++ void metersWarnEvents() { ++ when(event.getLevel()).thenReturn(Level.WARN); + +- appender.append(event); ++ appender.append(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()).isEqualTo(1); ++ } + +- @Test +- void metersErrorEvents() { +- when(event.getLevel()).thenReturn(Level.ERROR); ++ @Test ++ void metersErrorEvents() { ++ when(event.getLevel()).thenReturn(Level.ERROR); + +- appender.append(event); ++ appender.append(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()).isEqualTo(1); ++ } + +- @Test +- void metersFatalEvents() { +- when(event.getLevel()).thenReturn(Level.FATAL); ++ @Test ++ void metersFatalEvents() { ++ when(event.getLevel()).thenReturn(Level.FATAL); + +- appender.append(event); ++ appender.append(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".fatal").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".fatal").getCount()).isEqualTo(1); ++ } + +- @Test +- void usesSharedRegistries() { ++ @Test ++ void usesSharedRegistries() { + +- String registryName = "registry"; ++ String registryName = "registry"; + +- SharedMetricRegistries.add(registryName, registry); ++ SharedMetricRegistries.add(registryName, registry); + +- final InstrumentedAppender shared = new InstrumentedAppender(registryName); +- shared.start(); ++ final InstrumentedAppender shared = new InstrumentedAppender(registryName); ++ shared.start(); + +- when(event.getLevel()).thenReturn(Level.INFO); ++ when(event.getLevel()).thenReturn(Level.INFO); + +- shared.append(event); ++ shared.append(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + } +--- a/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java ++++ b/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics.logback13; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import ch.qos.logback.classic.Level; + import ch.qos.logback.classic.spi.ILoggingEvent; + import ch.qos.logback.core.Appender; +@@ -8,84 +10,79 @@ import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.SharedMetricRegistries; + +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + /** + * A Logback {@link Appender} which has six meters, one for each logging level and one for the total + * number of statements being logged. The meter names are the logging level names appended to the + * name of the appender. + */ + public class InstrumentedAppender extends UnsynchronizedAppenderBase { +- private final MetricRegistry registry; +- public static final String DEFAULT_REGISTRY = "logback-metrics"; +- public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; ++ private final MetricRegistry registry; ++ public static final String DEFAULT_REGISTRY = "logback-metrics"; ++ public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; + +- private Meter all; +- private Meter trace; +- private Meter debug; +- private Meter info; +- private Meter warn; +- private Meter error; ++ private Meter all; ++ private Meter trace; ++ private Meter debug; ++ private Meter info; ++ private Meter warn; ++ private Meter error; + ++ /** Create a new instrumented appender using the given registry name. */ ++ public InstrumentedAppender() { ++ this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); ++ } + +- /** +- * Create a new instrumented appender using the given registry name. +- */ +- public InstrumentedAppender() { +- this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); +- } ++ /** ++ * Create a new instrumented appender using the given registry name. ++ * ++ * @param registryName the name of the registry in {@link SharedMetricRegistries} ++ */ ++ public InstrumentedAppender(String registryName) { ++ this(SharedMetricRegistries.getOrCreate(registryName)); ++ } + +- /** +- * Create a new instrumented appender using the given registry name. +- * +- * @param registryName the name of the registry in {@link SharedMetricRegistries} +- */ +- public InstrumentedAppender(String registryName) { +- this(SharedMetricRegistries.getOrCreate(registryName)); +- } +- +- /** +- * Create a new instrumented appender using the given registry. +- * +- * @param registry the metric registry +- */ +- public InstrumentedAppender(MetricRegistry registry) { +- this.registry = registry; +- setName(Appender.class.getName()); +- } ++ /** ++ * Create a new instrumented appender using the given registry. ++ * ++ * @param registry the metric registry ++ */ ++ public InstrumentedAppender(MetricRegistry registry) { ++ this.registry = registry; ++ setName(Appender.class.getName()); ++ } + +- @Override +- public void start() { +- this.all = registry.meter(name(getName(), "all")); +- this.trace = registry.meter(name(getName(), "trace")); +- this.debug = registry.meter(name(getName(), "debug")); +- this.info = registry.meter(name(getName(), "info")); +- this.warn = registry.meter(name(getName(), "warn")); +- this.error = registry.meter(name(getName(), "error")); +- super.start(); +- } ++ @Override ++ public void start() { ++ this.all = registry.meter(name(getName(), "all")); ++ this.trace = registry.meter(name(getName(), "trace")); ++ this.debug = registry.meter(name(getName(), "debug")); ++ this.info = registry.meter(name(getName(), "info")); ++ this.warn = registry.meter(name(getName(), "warn")); ++ this.error = registry.meter(name(getName(), "error")); ++ super.start(); ++ } + +- @Override +- protected void append(ILoggingEvent event) { +- all.mark(); +- switch (event.getLevel().toInt()) { +- case Level.TRACE_INT: +- trace.mark(); +- break; +- case Level.DEBUG_INT: +- debug.mark(); +- break; +- case Level.INFO_INT: +- info.mark(); +- break; +- case Level.WARN_INT: +- warn.mark(); +- break; +- case Level.ERROR_INT: +- error.mark(); +- break; +- default: +- break; +- } ++ @Override ++ protected void append(ILoggingEvent event) { ++ all.mark(); ++ switch (event.getLevel().toInt()) { ++ case Level.TRACE_INT: ++ trace.mark(); ++ break; ++ case Level.DEBUG_INT: ++ debug.mark(); ++ break; ++ case Level.INFO_INT: ++ info.mark(); ++ break; ++ case Level.WARN_INT: ++ warn.mark(); ++ break; ++ case Level.ERROR_INT: ++ error.mark(); ++ break; ++ default: ++ break; + } ++ } + } +--- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java ++++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics.logback13; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import ch.qos.logback.classic.Level; + import ch.qos.logback.classic.spi.ILoggingEvent; + import io.dropwizard.metrics5.MetricRegistry; +@@ -8,135 +12,117 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-public class InstrumentedAppenderTest { +- +- public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; ++final class InstrumentedAppenderTest { + +- private final MetricRegistry registry = new MetricRegistry(); +- private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; + +- @BeforeEach +- void setUp() { +- appender.start(); +- } ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final InstrumentedAppender appender = new InstrumentedAppender(registry); ++ private final ILoggingEvent event = mock(); + +- @AfterEach +- void tearDown() { +- SharedMetricRegistries.clear(); +- } ++ @BeforeEach ++ void setUp() { ++ appender.start(); ++ } + +- @Test +- void metersTraceEvents() { +- when(event.getLevel()).thenReturn(Level.TRACE); ++ @AfterEach ++ void tearDown() { ++ SharedMetricRegistries.clear(); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersTraceEvents() { ++ when(event.getLevel()).thenReturn(Level.TRACE); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersDebugEvents() { +- when(event.getLevel()).thenReturn(Level.DEBUG); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersDebugEvents() { ++ when(event.getLevel()).thenReturn(Level.DEBUG); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersInfoEvents() { +- when(event.getLevel()).thenReturn(Level.INFO); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersInfoEvents() { ++ when(event.getLevel()).thenReturn(Level.INFO); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersWarnEvents() { +- when(event.getLevel()).thenReturn(Level.WARN); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersWarnEvents() { ++ when(event.getLevel()).thenReturn(Level.WARN); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersErrorEvents() { +- when(event.getLevel()).thenReturn(Level.ERROR); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersErrorEvents() { ++ when(event.getLevel()).thenReturn(Level.ERROR); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void usesSharedRegistries() { ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()).isEqualTo(1); ++ } + +- String registryName = "registry"; ++ @Test ++ void usesSharedRegistries() { + +- SharedMetricRegistries.add(registryName, registry); +- final InstrumentedAppender shared = new InstrumentedAppender(registryName); +- shared.start(); ++ String registryName = "registry"; + +- when(event.getLevel()).thenReturn(Level.INFO); ++ SharedMetricRegistries.add(registryName, registry); ++ final InstrumentedAppender shared = new InstrumentedAppender(registryName); ++ shared.start(); + +- shared.doAppend(event); ++ when(event.getLevel()).thenReturn(Level.INFO); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ shared.doAppend(event); + +- @Test +- void usesDefaultRegistry() { +- SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); +- final InstrumentedAppender shared = new InstrumentedAppender(); +- shared.start(); +- when(event.getLevel()).thenReturn(Level.INFO); +- shared.doAppend(event); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ @Test ++ void usesDefaultRegistry() { ++ SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); ++ final InstrumentedAppender shared = new InstrumentedAppender(); ++ shared.start(); ++ when(event.getLevel()).thenReturn(Level.INFO); ++ shared.doAppend(event); + +- @Test +- void usesRegistryFromProperty() { +- SharedMetricRegistries.add("something_else", registry); +- System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); +- final InstrumentedAppender shared = new InstrumentedAppender(); +- shared.start(); +- when(event.getLevel()).thenReturn(Level.INFO); +- shared.doAppend(event); ++ assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- assertThat(SharedMetricRegistries.names()).contains("something_else"); +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ @Test ++ void usesRegistryFromProperty() { ++ SharedMetricRegistries.add("something_else", registry); ++ System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); ++ final InstrumentedAppender shared = new InstrumentedAppender(); ++ shared.start(); ++ when(event.getLevel()).thenReturn(Level.INFO); ++ shared.doAppend(event); + ++ assertThat(SharedMetricRegistries.names()).contains("something_else"); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + } +--- a/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java ++++ b/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics.logback14; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import ch.qos.logback.classic.Level; + import ch.qos.logback.classic.spi.ILoggingEvent; + import ch.qos.logback.core.Appender; +@@ -8,84 +10,79 @@ import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.SharedMetricRegistries; + +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + /** + * A Logback {@link Appender} which has six meters, one for each logging level and one for the total + * number of statements being logged. The meter names are the logging level names appended to the + * name of the appender. + */ + public class InstrumentedAppender extends UnsynchronizedAppenderBase { +- private final MetricRegistry registry; +- public static final String DEFAULT_REGISTRY = "logback-metrics"; +- public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; ++ private final MetricRegistry registry; ++ public static final String DEFAULT_REGISTRY = "logback-metrics"; ++ public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; + +- private Meter all; +- private Meter trace; +- private Meter debug; +- private Meter info; +- private Meter warn; +- private Meter error; ++ private Meter all; ++ private Meter trace; ++ private Meter debug; ++ private Meter info; ++ private Meter warn; ++ private Meter error; + ++ /** Create a new instrumented appender using the given registry name. */ ++ public InstrumentedAppender() { ++ this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); ++ } + +- /** +- * Create a new instrumented appender using the given registry name. +- */ +- public InstrumentedAppender() { +- this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); +- } ++ /** ++ * Create a new instrumented appender using the given registry name. ++ * ++ * @param registryName the name of the registry in {@link SharedMetricRegistries} ++ */ ++ public InstrumentedAppender(String registryName) { ++ this(SharedMetricRegistries.getOrCreate(registryName)); ++ } + +- /** +- * Create a new instrumented appender using the given registry name. +- * +- * @param registryName the name of the registry in {@link SharedMetricRegistries} +- */ +- public InstrumentedAppender(String registryName) { +- this(SharedMetricRegistries.getOrCreate(registryName)); +- } +- +- /** +- * Create a new instrumented appender using the given registry. +- * +- * @param registry the metric registry +- */ +- public InstrumentedAppender(MetricRegistry registry) { +- this.registry = registry; +- setName(Appender.class.getName()); +- } ++ /** ++ * Create a new instrumented appender using the given registry. ++ * ++ * @param registry the metric registry ++ */ ++ public InstrumentedAppender(MetricRegistry registry) { ++ this.registry = registry; ++ setName(Appender.class.getName()); ++ } + +- @Override +- public void start() { +- this.all = registry.meter(name(getName(), "all")); +- this.trace = registry.meter(name(getName(), "trace")); +- this.debug = registry.meter(name(getName(), "debug")); +- this.info = registry.meter(name(getName(), "info")); +- this.warn = registry.meter(name(getName(), "warn")); +- this.error = registry.meter(name(getName(), "error")); +- super.start(); +- } ++ @Override ++ public void start() { ++ this.all = registry.meter(name(getName(), "all")); ++ this.trace = registry.meter(name(getName(), "trace")); ++ this.debug = registry.meter(name(getName(), "debug")); ++ this.info = registry.meter(name(getName(), "info")); ++ this.warn = registry.meter(name(getName(), "warn")); ++ this.error = registry.meter(name(getName(), "error")); ++ super.start(); ++ } + +- @Override +- protected void append(ILoggingEvent event) { +- all.mark(); +- switch (event.getLevel().toInt()) { +- case Level.TRACE_INT: +- trace.mark(); +- break; +- case Level.DEBUG_INT: +- debug.mark(); +- break; +- case Level.INFO_INT: +- info.mark(); +- break; +- case Level.WARN_INT: +- warn.mark(); +- break; +- case Level.ERROR_INT: +- error.mark(); +- break; +- default: +- break; +- } ++ @Override ++ protected void append(ILoggingEvent event) { ++ all.mark(); ++ switch (event.getLevel().toInt()) { ++ case Level.TRACE_INT: ++ trace.mark(); ++ break; ++ case Level.DEBUG_INT: ++ debug.mark(); ++ break; ++ case Level.INFO_INT: ++ info.mark(); ++ break; ++ case Level.WARN_INT: ++ warn.mark(); ++ break; ++ case Level.ERROR_INT: ++ error.mark(); ++ break; ++ default: ++ break; + } ++ } + } +--- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java ++++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics.logback14; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import ch.qos.logback.classic.Level; + import ch.qos.logback.classic.spi.ILoggingEvent; + import io.dropwizard.metrics5.MetricRegistry; +@@ -8,135 +12,117 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-public class InstrumentedAppenderTest { +- +- public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; ++final class InstrumentedAppenderTest { + +- private final MetricRegistry registry = new MetricRegistry(); +- private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; + +- @BeforeEach +- void setUp() { +- appender.start(); +- } ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final InstrumentedAppender appender = new InstrumentedAppender(registry); ++ private final ILoggingEvent event = mock(); + +- @AfterEach +- void tearDown() { +- SharedMetricRegistries.clear(); +- } ++ @BeforeEach ++ void setUp() { ++ appender.start(); ++ } + +- @Test +- void metersTraceEvents() { +- when(event.getLevel()).thenReturn(Level.TRACE); ++ @AfterEach ++ void tearDown() { ++ SharedMetricRegistries.clear(); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersTraceEvents() { ++ when(event.getLevel()).thenReturn(Level.TRACE); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersDebugEvents() { +- when(event.getLevel()).thenReturn(Level.DEBUG); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersDebugEvents() { ++ when(event.getLevel()).thenReturn(Level.DEBUG); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersInfoEvents() { +- when(event.getLevel()).thenReturn(Level.INFO); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersInfoEvents() { ++ when(event.getLevel()).thenReturn(Level.INFO); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersWarnEvents() { +- when(event.getLevel()).thenReturn(Level.WARN); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersWarnEvents() { ++ when(event.getLevel()).thenReturn(Level.WARN); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersErrorEvents() { +- when(event.getLevel()).thenReturn(Level.ERROR); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersErrorEvents() { ++ when(event.getLevel()).thenReturn(Level.ERROR); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void usesSharedRegistries() { ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()).isEqualTo(1); ++ } + +- String registryName = "registry"; ++ @Test ++ void usesSharedRegistries() { + +- SharedMetricRegistries.add(registryName, registry); +- final InstrumentedAppender shared = new InstrumentedAppender(registryName); +- shared.start(); ++ String registryName = "registry"; + +- when(event.getLevel()).thenReturn(Level.INFO); ++ SharedMetricRegistries.add(registryName, registry); ++ final InstrumentedAppender shared = new InstrumentedAppender(registryName); ++ shared.start(); + +- shared.doAppend(event); ++ when(event.getLevel()).thenReturn(Level.INFO); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ shared.doAppend(event); + +- @Test +- void usesDefaultRegistry() { +- SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); +- final InstrumentedAppender shared = new InstrumentedAppender(); +- shared.start(); +- when(event.getLevel()).thenReturn(Level.INFO); +- shared.doAppend(event); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ @Test ++ void usesDefaultRegistry() { ++ SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); ++ final InstrumentedAppender shared = new InstrumentedAppender(); ++ shared.start(); ++ when(event.getLevel()).thenReturn(Level.INFO); ++ shared.doAppend(event); + +- @Test +- void usesRegistryFromProperty() { +- SharedMetricRegistries.add("something_else", registry); +- System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); +- final InstrumentedAppender shared = new InstrumentedAppender(); +- shared.start(); +- when(event.getLevel()).thenReturn(Level.INFO); +- shared.doAppend(event); ++ assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- assertThat(SharedMetricRegistries.names()).contains("something_else"); +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ @Test ++ void usesRegistryFromProperty() { ++ SharedMetricRegistries.add("something_else", registry); ++ System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); ++ final InstrumentedAppender shared = new InstrumentedAppender(); ++ shared.start(); ++ when(event.getLevel()).thenReturn(Level.INFO); ++ shared.doAppend(event); + ++ assertThat(SharedMetricRegistries.names()).contains("something_else"); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + } +--- a/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java ++++ b/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.logback15; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import ch.qos.logback.classic.Level; + import ch.qos.logback.classic.spi.ILoggingEvent; + import ch.qos.logback.core.Appender; +@@ -8,84 +10,79 @@ import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.SharedMetricRegistries; + +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + /** + * A Logback {@link Appender} which has six meters, one for each logging level and one for the total + * number of statements being logged. The meter names are the logging level names appended to the + * name of the appender. + */ + public class InstrumentedAppender extends UnsynchronizedAppenderBase { +- private final MetricRegistry registry; +- public static final String DEFAULT_REGISTRY = "logback-metrics"; +- public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; ++ private final MetricRegistry registry; ++ public static final String DEFAULT_REGISTRY = "logback-metrics"; ++ public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; + +- private Meter all; +- private Meter trace; +- private Meter debug; +- private Meter info; +- private Meter warn; +- private Meter error; ++ private Meter all; ++ private Meter trace; ++ private Meter debug; ++ private Meter info; ++ private Meter warn; ++ private Meter error; + ++ /** Create a new instrumented appender using the given registry name. */ ++ public InstrumentedAppender() { ++ this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); ++ } + +- /** +- * Create a new instrumented appender using the given registry name. +- */ +- public InstrumentedAppender() { +- this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); +- } ++ /** ++ * Create a new instrumented appender using the given registry name. ++ * ++ * @param registryName the name of the registry in {@link SharedMetricRegistries} ++ */ ++ public InstrumentedAppender(String registryName) { ++ this(SharedMetricRegistries.getOrCreate(registryName)); ++ } + +- /** +- * Create a new instrumented appender using the given registry name. +- * +- * @param registryName the name of the registry in {@link SharedMetricRegistries} +- */ +- public InstrumentedAppender(String registryName) { +- this(SharedMetricRegistries.getOrCreate(registryName)); +- } +- +- /** +- * Create a new instrumented appender using the given registry. +- * +- * @param registry the metric registry +- */ +- public InstrumentedAppender(MetricRegistry registry) { +- this.registry = registry; +- setName(Appender.class.getName()); +- } ++ /** ++ * Create a new instrumented appender using the given registry. ++ * ++ * @param registry the metric registry ++ */ ++ public InstrumentedAppender(MetricRegistry registry) { ++ this.registry = registry; ++ setName(Appender.class.getName()); ++ } + +- @Override +- public void start() { +- this.all = registry.meter(name(getName(), "all")); +- this.trace = registry.meter(name(getName(), "trace")); +- this.debug = registry.meter(name(getName(), "debug")); +- this.info = registry.meter(name(getName(), "info")); +- this.warn = registry.meter(name(getName(), "warn")); +- this.error = registry.meter(name(getName(), "error")); +- super.start(); +- } ++ @Override ++ public void start() { ++ this.all = registry.meter(name(getName(), "all")); ++ this.trace = registry.meter(name(getName(), "trace")); ++ this.debug = registry.meter(name(getName(), "debug")); ++ this.info = registry.meter(name(getName(), "info")); ++ this.warn = registry.meter(name(getName(), "warn")); ++ this.error = registry.meter(name(getName(), "error")); ++ super.start(); ++ } + +- @Override +- protected void append(ILoggingEvent event) { +- all.mark(); +- switch (event.getLevel().toInt()) { +- case Level.TRACE_INT: +- trace.mark(); +- break; +- case Level.DEBUG_INT: +- debug.mark(); +- break; +- case Level.INFO_INT: +- info.mark(); +- break; +- case Level.WARN_INT: +- warn.mark(); +- break; +- case Level.ERROR_INT: +- error.mark(); +- break; +- default: +- break; +- } ++ @Override ++ protected void append(ILoggingEvent event) { ++ all.mark(); ++ switch (event.getLevel().toInt()) { ++ case Level.TRACE_INT: ++ trace.mark(); ++ break; ++ case Level.DEBUG_INT: ++ debug.mark(); ++ break; ++ case Level.INFO_INT: ++ info.mark(); ++ break; ++ case Level.WARN_INT: ++ warn.mark(); ++ break; ++ case Level.ERROR_INT: ++ error.mark(); ++ break; ++ default: ++ break; + } ++ } + } +--- a/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java ++++ b/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.logback15; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import ch.qos.logback.classic.Level; + import ch.qos.logback.classic.spi.ILoggingEvent; + import io.dropwizard.metrics5.MetricRegistry; +@@ -8,135 +12,117 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-public class InstrumentedAppenderTest { +- +- public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; ++final class InstrumentedAppenderTest { + +- private final MetricRegistry registry = new MetricRegistry(); +- private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; + +- @BeforeEach +- void setUp() { +- appender.start(); +- } ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final InstrumentedAppender appender = new InstrumentedAppender(registry); ++ private final ILoggingEvent event = mock(); + +- @AfterEach +- void tearDown() { +- SharedMetricRegistries.clear(); +- } ++ @BeforeEach ++ void setUp() { ++ appender.start(); ++ } + +- @Test +- void metersTraceEvents() { +- when(event.getLevel()).thenReturn(Level.TRACE); ++ @AfterEach ++ void tearDown() { ++ SharedMetricRegistries.clear(); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersTraceEvents() { ++ when(event.getLevel()).thenReturn(Level.TRACE); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersDebugEvents() { +- when(event.getLevel()).thenReturn(Level.DEBUG); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersDebugEvents() { ++ when(event.getLevel()).thenReturn(Level.DEBUG); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersInfoEvents() { +- when(event.getLevel()).thenReturn(Level.INFO); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersInfoEvents() { ++ when(event.getLevel()).thenReturn(Level.INFO); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersWarnEvents() { +- when(event.getLevel()).thenReturn(Level.WARN); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersWarnEvents() { ++ when(event.getLevel()).thenReturn(Level.WARN); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void metersErrorEvents() { +- when(event.getLevel()).thenReturn(Level.ERROR); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()).isEqualTo(1); ++ } + +- appender.doAppend(event); ++ @Test ++ void metersErrorEvents() { ++ when(event.getLevel()).thenReturn(Level.ERROR); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) +- .isEqualTo(1); ++ appender.doAppend(event); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()) +- .isEqualTo(1); +- } ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + +- @Test +- void usesSharedRegistries() { ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()).isEqualTo(1); ++ } + +- String registryName = "registry"; ++ @Test ++ void usesSharedRegistries() { + +- SharedMetricRegistries.add(registryName, registry); +- final InstrumentedAppender shared = new InstrumentedAppender(registryName); +- shared.start(); ++ String registryName = "registry"; + +- when(event.getLevel()).thenReturn(Level.INFO); ++ SharedMetricRegistries.add(registryName, registry); ++ final InstrumentedAppender shared = new InstrumentedAppender(registryName); ++ shared.start(); + +- shared.doAppend(event); ++ when(event.getLevel()).thenReturn(Level.INFO); + +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ shared.doAppend(event); + +- @Test +- void usesDefaultRegistry() { +- SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); +- final InstrumentedAppender shared = new InstrumentedAppender(); +- shared.start(); +- when(event.getLevel()).thenReturn(Level.INFO); +- shared.doAppend(event); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ @Test ++ void usesDefaultRegistry() { ++ SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); ++ final InstrumentedAppender shared = new InstrumentedAppender(); ++ shared.start(); ++ when(event.getLevel()).thenReturn(Level.INFO); ++ shared.doAppend(event); + +- @Test +- void usesRegistryFromProperty() { +- SharedMetricRegistries.add("something_else", registry); +- System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); +- final InstrumentedAppender shared = new InstrumentedAppender(); +- shared.start(); +- when(event.getLevel()).thenReturn(Level.INFO); +- shared.doAppend(event); ++ assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + +- assertThat(SharedMetricRegistries.names()).contains("something_else"); +- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) +- .isEqualTo(1); +- } ++ @Test ++ void usesRegistryFromProperty() { ++ SharedMetricRegistries.add("something_else", registry); ++ System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); ++ final InstrumentedAppender shared = new InstrumentedAppender(); ++ shared.start(); ++ when(event.getLevel()).thenReturn(Level.INFO); ++ shared.doAppend(event); + ++ assertThat(SharedMetricRegistries.names()).contains("something_else"); ++ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); ++ } + } +--- a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java ++++ b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java +@@ -1,10 +1,17 @@ + package io.dropwizard.metrics5.servlet; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; +- ++import java.io.IOException; ++import java.util.Map; ++import java.util.Map.Entry; ++import java.util.concurrent.ConcurrentHashMap; ++import java.util.concurrent.ConcurrentMap; + import javax.servlet.AsyncEvent; + import javax.servlet.AsyncListener; + import javax.servlet.Filter; +@@ -15,204 +22,192 @@ import javax.servlet.ServletRequest; + import javax.servlet.ServletResponse; + import javax.servlet.http.HttpServletResponse; + import javax.servlet.http.HttpServletResponseWrapper; +-import java.io.IOException; +-import java.util.Map; +-import java.util.Map.Entry; +-import java.util.concurrent.ConcurrentHashMap; +-import java.util.concurrent.ConcurrentMap; +- +-import static io.dropwizard.metrics5.MetricRegistry.name; + + /** + * {@link Filter} implementation which captures request information and a breakdown of the response + * codes being returned. + */ + public abstract class AbstractInstrumentedFilter implements Filter { +- static final String METRIC_PREFIX = "name-prefix"; +- +- private final String otherMetricName; +- private final Map meterNamesByStatusCode; +- private final String registryAttribute; +- +- // initialized after call of init method +- private ConcurrentMap metersByStatusCode; +- private Meter otherMeter; +- private Meter timeoutsMeter; +- private Meter errorsMeter; +- private Counter activeRequests; +- private Timer requestTimer; +- +- +- /** +- * Creates a new instance of the filter. +- * +- * @param registryAttribute the attribute used to look up the metrics registry in the +- * servlet context +- * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are +- * interested in. +- * @param otherMetricName The name used for the catch-all meter. +- */ +- protected AbstractInstrumentedFilter(String registryAttribute, +- Map meterNamesByStatusCode, +- String otherMetricName) { +- this.registryAttribute = registryAttribute; +- this.otherMetricName = otherMetricName; +- this.meterNamesByStatusCode = meterNamesByStatusCode; ++ static final String METRIC_PREFIX = "name-prefix"; ++ ++ private final String otherMetricName; ++ private final Map meterNamesByStatusCode; ++ private final String registryAttribute; ++ ++ // initialized after call of init method ++ private ConcurrentMap metersByStatusCode; ++ private Meter otherMeter; ++ private Meter timeoutsMeter; ++ private Meter errorsMeter; ++ private Counter activeRequests; ++ private Timer requestTimer; ++ ++ /** ++ * Creates a new instance of the filter. ++ * ++ * @param registryAttribute the attribute used to look up the metrics registry in the servlet ++ * context ++ * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are ++ * interested in. ++ * @param otherMetricName The name used for the catch-all meter. ++ */ ++ protected AbstractInstrumentedFilter( ++ String registryAttribute, ++ Map meterNamesByStatusCode, ++ String otherMetricName) { ++ this.registryAttribute = registryAttribute; ++ this.otherMetricName = otherMetricName; ++ this.meterNamesByStatusCode = meterNamesByStatusCode; ++ } ++ ++ @Override ++ public void init(FilterConfig filterConfig) throws ServletException { ++ final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); ++ ++ String metricName = filterConfig.getInitParameter(METRIC_PREFIX); ++ if (Strings.isNullOrEmpty(metricName)) { ++ metricName = getClass().getName(); + } + +- @Override +- public void init(FilterConfig filterConfig) throws ServletException { +- final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); +- +- String metricName = filterConfig.getInitParameter(METRIC_PREFIX); +- if (metricName == null || metricName.isEmpty()) { +- metricName = getClass().getName(); +- } +- +- this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); +- for (Entry entry : meterNamesByStatusCode.entrySet()) { +- metersByStatusCode.put(entry.getKey(), +- metricsRegistry.meter(name(metricName, entry.getValue()))); +- } +- this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); +- this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); +- this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); +- this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); +- this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); +- ++ this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); ++ for (Entry entry : meterNamesByStatusCode.entrySet()) { ++ metersByStatusCode.put( ++ entry.getKey(), metricsRegistry.meter(name(metricName, entry.getValue()))); + } +- +- private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { +- final MetricRegistry metricsRegistry; +- +- final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); +- if (o instanceof MetricRegistry) { +- metricsRegistry = (MetricRegistry) o; ++ this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); ++ this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); ++ this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); ++ this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); ++ this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); ++ } ++ ++ private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { ++ final MetricRegistry metricsRegistry; ++ ++ final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); ++ if (o instanceof MetricRegistry) { ++ metricsRegistry = (MetricRegistry) o; ++ } else { ++ metricsRegistry = new MetricRegistry(); ++ } ++ return metricsRegistry; ++ } ++ ++ @Override ++ public void destroy() {} ++ ++ @Override ++ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) ++ throws IOException, ServletException { ++ final StatusExposingServletResponse wrappedResponse = ++ new StatusExposingServletResponse((HttpServletResponse) response); ++ activeRequests.inc(); ++ final Timer.Context context = requestTimer.time(); ++ boolean error = false; ++ try { ++ chain.doFilter(request, wrappedResponse); ++ } catch (IOException | RuntimeException | ServletException e) { ++ error = true; ++ throw e; ++ } finally { ++ if (!error && request.isAsyncStarted()) { ++ request.getAsyncContext().addListener(new AsyncResultListener(context)); ++ } else { ++ context.stop(); ++ activeRequests.dec(); ++ if (error) { ++ errorsMeter.mark(); + } else { +- metricsRegistry = new MetricRegistry(); ++ markMeterForStatusCode(wrappedResponse.getStatus()); + } +- return metricsRegistry; ++ } ++ } ++ } ++ ++ private void markMeterForStatusCode(int status) { ++ final Meter metric = metersByStatusCode.get(status); ++ if (metric != null) { ++ metric.mark(); ++ } else { ++ otherMeter.mark(); + } ++ } + +- @Override +- public void destroy() { ++ private static class StatusExposingServletResponse extends HttpServletResponseWrapper { ++ // The Servlet spec says: calling setStatus is optional, if no status is set, the default is ++ // 200. ++ private int httpStatus = 200; + ++ public StatusExposingServletResponse(HttpServletResponse response) { ++ super(response); + } + + @Override +- public void doFilter(ServletRequest request, +- ServletResponse response, +- FilterChain chain) throws IOException, ServletException { +- final StatusExposingServletResponse wrappedResponse = +- new StatusExposingServletResponse((HttpServletResponse) response); +- activeRequests.inc(); +- final Timer.Context context = requestTimer.time(); +- boolean error = false; +- try { +- chain.doFilter(request, wrappedResponse); +- } catch (IOException | RuntimeException | ServletException e) { +- error = true; +- throw e; +- } finally { +- if (!error && request.isAsyncStarted()) { +- request.getAsyncContext().addListener(new AsyncResultListener(context)); +- } else { +- context.stop(); +- activeRequests.dec(); +- if (error) { +- errorsMeter.mark(); +- } else { +- markMeterForStatusCode(wrappedResponse.getStatus()); +- } +- } +- } ++ public void sendError(int sc) throws IOException { ++ httpStatus = sc; ++ super.sendError(sc); + } + +- private void markMeterForStatusCode(int status) { +- final Meter metric = metersByStatusCode.get(status); +- if (metric != null) { +- metric.mark(); +- } else { +- otherMeter.mark(); +- } ++ @Override ++ public void sendError(int sc, String msg) throws IOException { ++ httpStatus = sc; ++ super.sendError(sc, msg); + } + +- private static class StatusExposingServletResponse extends HttpServletResponseWrapper { +- // The Servlet spec says: calling setStatus is optional, if no status is set, the default is 200. +- private int httpStatus = 200; +- +- public StatusExposingServletResponse(HttpServletResponse response) { +- super(response); +- } +- +- @Override +- public void sendError(int sc) throws IOException { +- httpStatus = sc; +- super.sendError(sc); +- } +- +- @Override +- public void sendError(int sc, String msg) throws IOException { +- httpStatus = sc; +- super.sendError(sc, msg); +- } +- +- @Override +- public void setStatus(int sc) { +- httpStatus = sc; +- super.setStatus(sc); +- } +- +- @Override +- @SuppressWarnings("deprecation") +- public void setStatus(int sc, String sm) { +- httpStatus = sc; +- super.setStatus(sc, sm); +- } +- +- @Override +- public int getStatus() { +- return httpStatus; +- } ++ @Override ++ public void setStatus(int sc) { ++ httpStatus = sc; ++ super.setStatus(sc); + } + +- private class AsyncResultListener implements AsyncListener { +- private Timer.Context context; +- private boolean done = false; ++ @Override ++ @SuppressWarnings("deprecation") ++ public void setStatus(int sc, String sm) { ++ httpStatus = sc; ++ super.setStatus(sc, sm); ++ } + +- public AsyncResultListener(Timer.Context context) { +- this.context = context; +- } ++ @Override ++ public int getStatus() { ++ return httpStatus; ++ } ++ } + +- @Override +- public void onComplete(AsyncEvent event) throws IOException { +- if (!done) { +- HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); +- context.stop(); +- activeRequests.dec(); +- markMeterForStatusCode(suppliedResponse.getStatus()); +- } +- } ++ private class AsyncResultListener implements AsyncListener { ++ private Timer.Context context; ++ private boolean done = false; + +- @Override +- public void onTimeout(AsyncEvent event) throws IOException { +- context.stop(); +- activeRequests.dec(); +- timeoutsMeter.mark(); +- done = true; +- } ++ public AsyncResultListener(Timer.Context context) { ++ this.context = context; ++ } + +- @Override +- public void onError(AsyncEvent event) throws IOException { +- context.stop(); +- activeRequests.dec(); +- errorsMeter.mark(); +- done = true; +- } ++ @Override ++ public void onComplete(AsyncEvent event) throws IOException { ++ if (!done) { ++ HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); ++ context.stop(); ++ activeRequests.dec(); ++ markMeterForStatusCode(suppliedResponse.getStatus()); ++ } ++ } + +- @Override +- public void onStartAsync(AsyncEvent event) throws IOException { ++ @Override ++ public void onTimeout(AsyncEvent event) throws IOException { ++ context.stop(); ++ activeRequests.dec(); ++ timeoutsMeter.mark(); ++ done = true; ++ } + +- } ++ @Override ++ public void onError(AsyncEvent event) throws IOException { ++ context.stop(); ++ activeRequests.dec(); ++ errorsMeter.mark(); ++ done = true; + } ++ ++ @Override ++ public void onStartAsync(AsyncEvent event) throws IOException {} ++ } + } +--- a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilter.java ++++ b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilter.java +@@ -4,8 +4,13 @@ import java.util.HashMap; + import java.util.Map; + + /** +- * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response codes +- * to capture information about.

    Use it in your servlet.xml like this:

    ++ * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response ++ * codes to capture information about. ++ * ++ *

    Use it in your servlet.xml like this: ++ * ++ *

    ++ * + *

    {@code
    +  * 
    +  *     instrumentedFilter
    +@@ -18,31 +23,29 @@ import java.util.Map;
    +  * }
    + */ + public class InstrumentedFilter extends AbstractInstrumentedFilter { +- public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; ++ public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; + +- private static final String NAME_PREFIX = "responseCodes."; +- private static final int OK = 200; +- private static final int CREATED = 201; +- private static final int NO_CONTENT = 204; +- private static final int BAD_REQUEST = 400; +- private static final int NOT_FOUND = 404; +- private static final int SERVER_ERROR = 500; ++ private static final String NAME_PREFIX = "responseCodes."; ++ private static final int OK = 200; ++ private static final int CREATED = 201; ++ private static final int NO_CONTENT = 204; ++ private static final int BAD_REQUEST = 400; ++ private static final int NOT_FOUND = 404; ++ private static final int SERVER_ERROR = 500; + +- /** +- * Creates a new instance of the filter. +- */ +- public InstrumentedFilter() { +- super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); +- } ++ /** Creates a new instance of the filter. */ ++ public InstrumentedFilter() { ++ super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); ++ } + +- private static Map createMeterNamesByStatusCode() { +- final Map meterNamesByStatusCode = new HashMap<>(6); +- meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); +- meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); +- meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); +- meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); +- meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); +- meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); +- return meterNamesByStatusCode; +- } ++ private static Map createMeterNamesByStatusCode() { ++ final Map meterNamesByStatusCode = new HashMap<>(6); ++ meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); ++ meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); ++ meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); ++ meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); ++ meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); ++ meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); ++ return meterNamesByStatusCode; ++ } + } +--- a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListener.java ++++ b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListener.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.servlet; + + import io.dropwizard.metrics5.MetricRegistry; +- + import javax.servlet.ServletContextEvent; + import javax.servlet.ServletContextListener; + +@@ -11,17 +10,17 @@ import javax.servlet.ServletContextListener; + * application. + */ + public abstract class InstrumentedFilterContextListener implements ServletContextListener { +- /** +- * @return the {@link MetricRegistry} to inject into the servlet context. +- */ +- protected abstract MetricRegistry getMetricRegistry(); ++ /** ++ * @return the {@link MetricRegistry} to inject into the servlet context. ++ */ ++ protected abstract MetricRegistry getMetricRegistry(); + +- @Override +- public void contextInitialized(ServletContextEvent sce) { +- sce.getServletContext().setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); +- } ++ @Override ++ public void contextInitialized(ServletContextEvent sce) { ++ sce.getServletContext() ++ .setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); ++ } + +- @Override +- public void contextDestroyed(ServletContextEvent sce) { +- } ++ @Override ++ public void contextDestroyed(ServletContextEvent sce) {} + } +--- a/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +@@ -1,33 +1,34 @@ + package io.dropwizard.metrics5.servlet; + +-import io.dropwizard.metrics5.MetricRegistry; +-import org.junit.jupiter.api.Test; +- +-import javax.servlet.ServletContext; +-import javax.servlet.ServletContextEvent; +- + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +-class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final InstrumentedFilterContextListener listener = new InstrumentedFilterContextListener() { ++import io.dropwizard.metrics5.MetricRegistry; ++import javax.servlet.ServletContext; ++import javax.servlet.ServletContextEvent; ++import org.junit.jupiter.api.Test; ++ ++final class InstrumentedFilterContextListenerTest { ++ private final MetricRegistry registry = mock(); ++ private final InstrumentedFilterContextListener listener = ++ new InstrumentedFilterContextListener() { + @Override + protected MetricRegistry getMetricRegistry() { +- return registry; ++ return registry; + } +- }; ++ }; + +- @Test +- void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ @Test ++ void injectsTheMetricRegistryIntoTheServletContext() { ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); +- when(event.getServletContext()).thenReturn(context); ++ final ServletContextEvent event = mock(); ++ when(event.getServletContext()).thenReturn(context); + +- listener.contextInitialized(event); ++ listener.contextInitialized(event); + +- verify(context).setAttribute("io.dropwizard.metrics5.servlet.InstrumentedFilter.registry", registry); +- } ++ verify(context) ++ .setAttribute("io.dropwizard.metrics5.servlet.InstrumentedFilter.registry", registry); ++ } + } +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/AdminServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/AdminServlet.java +@@ -1,189 +1,210 @@ + package io.dropwizard.metrics5.servlets; + ++import java.io.IOException; ++import java.io.PrintWriter; ++import java.text.MessageFormat; + import javax.servlet.ServletConfig; + import javax.servlet.ServletContext; + import javax.servlet.ServletException; + import javax.servlet.http.HttpServlet; + import javax.servlet.http.HttpServletRequest; + import javax.servlet.http.HttpServletResponse; +-import java.io.IOException; +-import java.io.PrintWriter; +-import java.text.MessageFormat; + + public class AdminServlet extends HttpServlet { +- public static final String DEFAULT_HEALTHCHECK_URI = "/healthcheck"; +- public static final String DEFAULT_METRICS_URI = "/metrics"; +- public static final String DEFAULT_PING_URI = "/ping"; +- public static final String DEFAULT_THREADS_URI = "/threads"; +- public static final String DEFAULT_CPU_PROFILE_URI = "/pprof"; +- +- public static final String METRICS_ENABLED_PARAM_KEY = "metrics-enabled"; +- public static final String METRICS_URI_PARAM_KEY = "metrics-uri"; +- public static final String PING_ENABLED_PARAM_KEY = "ping-enabled"; +- public static final String PING_URI_PARAM_KEY = "ping-uri"; +- public static final String THREADS_ENABLED_PARAM_KEY = "threads-enabled"; +- public static final String THREADS_URI_PARAM_KEY = "threads-uri"; +- public static final String HEALTHCHECK_ENABLED_PARAM_KEY = "healthcheck-enabled"; +- public static final String HEALTHCHECK_URI_PARAM_KEY = "healthcheck-uri"; +- public static final String SERVICE_NAME_PARAM_KEY = "service-name"; +- public static final String CPU_PROFILE_ENABLED_PARAM_KEY = "cpu-profile-enabled"; +- public static final String CPU_PROFILE_URI_PARAM_KEY = "cpu-profile-uri"; +- +- private static final String BASE_TEMPLATE = +- "%n" + +- "%n" + +- "%n" + +- " Metrics{10}%n" + +- "%n" + +- "%n" + +- "

    Operational Menu{10}

    %n" + +- "
      %n" + +- "%s" + +- "
    %n" + +- "%n" + +- ""; +- private static final String METRICS_LINK = "
  • Metrics
  • %n"; +- private static final String PING_LINK = "
  • Ping
  • %n" ; +- private static final String THREADS_LINK = "
  • Threads
  • %n" ; +- private static final String HEALTHCHECK_LINK = "
  • Healthcheck
  • %n" ; +- private static final String CPU_PROFILE_LINK = "
  • CPU Profile
  • %n" + +- "
  • CPU Contention
  • %n"; +- +- +- private static final String CONTENT_TYPE = "text/html"; +- private static final long serialVersionUID = -2850794040708785318L; +- +- private transient HealthCheckServlet healthCheckServlet; +- private transient MetricsServlet metricsServlet; +- private transient PingServlet pingServlet; +- private transient ThreadDumpServlet threadDumpServlet; +- private transient CpuProfileServlet cpuProfileServlet; +- private transient boolean metricsEnabled; +- private transient String metricsUri; +- private transient boolean pingEnabled; +- private transient String pingUri; +- private transient boolean threadsEnabled; +- private transient String threadsUri; +- private transient boolean healthcheckEnabled; +- private transient String healthcheckUri; +- private transient boolean cpuProfileEnabled; +- private transient String cpuProfileUri; +- private transient String serviceName; +- private transient String pageContentTemplate; +- +- @Override +- public void init(ServletConfig config) throws ServletException { +- super.init(config); +- +- final ServletContext context = config.getServletContext(); +- final StringBuilder servletLinks = new StringBuilder(); +- +- this.metricsEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(METRICS_ENABLED_PARAM_KEY), "true")); +- if (this.metricsEnabled) { +- servletLinks.append(METRICS_LINK); +- } +- this.metricsServlet = new MetricsServlet(); +- metricsServlet.init(config); +- +- this.pingEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(PING_ENABLED_PARAM_KEY), "true")); +- if (this.pingEnabled) { +- servletLinks.append(PING_LINK); +- } +- this.pingServlet = new PingServlet(); +- pingServlet.init(config); +- +- this.threadsEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(THREADS_ENABLED_PARAM_KEY), "true")); +- if (this.threadsEnabled) { +- servletLinks.append(THREADS_LINK); +- } +- this.threadDumpServlet = new ThreadDumpServlet(); +- threadDumpServlet.init(config); +- +- this.healthcheckEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(HEALTHCHECK_ENABLED_PARAM_KEY), "true")); +- if (this.healthcheckEnabled) { +- servletLinks.append(HEALTHCHECK_LINK); +- } +- this.healthCheckServlet = new HealthCheckServlet(); +- healthCheckServlet.init(config); +- +- this.cpuProfileEnabled = +- Boolean.parseBoolean(getParam(context.getInitParameter(CPU_PROFILE_ENABLED_PARAM_KEY), "true")); +- if (this.cpuProfileEnabled) { +- servletLinks.append(CPU_PROFILE_LINK); +- } +- this.cpuProfileServlet = new CpuProfileServlet(); +- cpuProfileServlet.init(config); +- +- pageContentTemplate = String.format(BASE_TEMPLATE, String.format(servletLinks.toString())); +- +- this.metricsUri = getParam(context.getInitParameter(METRICS_URI_PARAM_KEY), DEFAULT_METRICS_URI); +- this.pingUri = getParam(context.getInitParameter(PING_URI_PARAM_KEY), DEFAULT_PING_URI); +- this.threadsUri = getParam(context.getInitParameter(THREADS_URI_PARAM_KEY), DEFAULT_THREADS_URI); +- this.healthcheckUri = getParam(context.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI); +- this.cpuProfileUri = getParam(context.getInitParameter(CPU_PROFILE_URI_PARAM_KEY), DEFAULT_CPU_PROFILE_URI); +- this.serviceName = getParam(context.getInitParameter(SERVICE_NAME_PARAM_KEY), null); ++ public static final String DEFAULT_HEALTHCHECK_URI = "/healthcheck"; ++ public static final String DEFAULT_METRICS_URI = "/metrics"; ++ public static final String DEFAULT_PING_URI = "/ping"; ++ public static final String DEFAULT_THREADS_URI = "/threads"; ++ public static final String DEFAULT_CPU_PROFILE_URI = "/pprof"; ++ ++ public static final String METRICS_ENABLED_PARAM_KEY = "metrics-enabled"; ++ public static final String METRICS_URI_PARAM_KEY = "metrics-uri"; ++ public static final String PING_ENABLED_PARAM_KEY = "ping-enabled"; ++ public static final String PING_URI_PARAM_KEY = "ping-uri"; ++ public static final String THREADS_ENABLED_PARAM_KEY = "threads-enabled"; ++ public static final String THREADS_URI_PARAM_KEY = "threads-uri"; ++ public static final String HEALTHCHECK_ENABLED_PARAM_KEY = "healthcheck-enabled"; ++ public static final String HEALTHCHECK_URI_PARAM_KEY = "healthcheck-uri"; ++ public static final String SERVICE_NAME_PARAM_KEY = "service-name"; ++ public static final String CPU_PROFILE_ENABLED_PARAM_KEY = "cpu-profile-enabled"; ++ public static final String CPU_PROFILE_URI_PARAM_KEY = "cpu-profile-uri"; ++ ++ private static final String BASE_TEMPLATE = ++ "%n" ++ + "%n" ++ + "%n" ++ + " Metrics{10}%n" ++ + "%n" ++ + "%n" ++ + "

    Operational Menu{10}

    %n" ++ + "
      %n" ++ + "%s" ++ + "
    %n" ++ + "%n" ++ + ""; ++ private static final String METRICS_LINK = ++ "
  • Metrics
  • %n"; ++ private static final String PING_LINK = "
  • Ping
  • %n"; ++ private static final String THREADS_LINK = "
  • Threads
  • %n"; ++ private static final String HEALTHCHECK_LINK = ++ "
  • Healthcheck
  • %n"; ++ private static final String CPU_PROFILE_LINK = ++ "
  • CPU Profile
  • %n" ++ + "
  • CPU Contention
  • %n"; ++ ++ private static final String CONTENT_TYPE = "text/html"; ++ private static final long serialVersionUID = -2850794040708785318L; ++ ++ private transient HealthCheckServlet healthCheckServlet; ++ private transient MetricsServlet metricsServlet; ++ private transient PingServlet pingServlet; ++ private transient ThreadDumpServlet threadDumpServlet; ++ private transient CpuProfileServlet cpuProfileServlet; ++ private transient boolean metricsEnabled; ++ private transient String metricsUri; ++ private transient boolean pingEnabled; ++ private transient String pingUri; ++ private transient boolean threadsEnabled; ++ private transient String threadsUri; ++ private transient boolean healthcheckEnabled; ++ private transient String healthcheckUri; ++ private transient boolean cpuProfileEnabled; ++ private transient String cpuProfileUri; ++ private transient String serviceName; ++ private transient String pageContentTemplate; ++ ++ @Override ++ public void init(ServletConfig config) throws ServletException { ++ super.init(config); ++ ++ final ServletContext context = config.getServletContext(); ++ final StringBuilder servletLinks = new StringBuilder(); ++ ++ this.metricsEnabled = ++ Boolean.parseBoolean(getParam(context.getInitParameter(METRICS_ENABLED_PARAM_KEY), "true")); ++ if (this.metricsEnabled) { ++ servletLinks.append(METRICS_LINK); + } ++ this.metricsServlet = new MetricsServlet(); ++ metricsServlet.init(config); + +- @Override +- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { +- final String path = req.getContextPath() + req.getServletPath(); +- +- resp.setStatus(HttpServletResponse.SC_OK); +- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); +- resp.setContentType(CONTENT_TYPE); +- try (PrintWriter writer = resp.getWriter()) { +- writer.println(MessageFormat.format(pageContentTemplate, path, metricsUri, path, pingUri, path, +- threadsUri, path, healthcheckUri, path, cpuProfileUri, +- serviceName == null ? "" : " (" + serviceName + ")")); +- } ++ this.pingEnabled = ++ Boolean.parseBoolean(getParam(context.getInitParameter(PING_ENABLED_PARAM_KEY), "true")); ++ if (this.pingEnabled) { ++ servletLinks.append(PING_LINK); + } ++ this.pingServlet = new PingServlet(); ++ pingServlet.init(config); + +- @Override +- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { +- final String uri = req.getPathInfo(); +- if (uri == null || uri.equals("/")) { +- super.service(req, resp); +- } else if (uri.equals(healthcheckUri)) { +- if (healthcheckEnabled) { +- healthCheckServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else if (uri.startsWith(metricsUri)) { +- if (metricsEnabled) { +- metricsServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else if (uri.equals(pingUri)) { +- if (pingEnabled) { +- pingServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else if (uri.equals(threadsUri)) { +- if (threadsEnabled) { +- threadDumpServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else if (uri.equals(cpuProfileUri)) { +- if (cpuProfileEnabled) { +- cpuProfileServlet.service(req, resp); +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } +- } else { +- resp.sendError(HttpServletResponse.SC_NOT_FOUND); +- } ++ this.threadsEnabled = ++ Boolean.parseBoolean(getParam(context.getInitParameter(THREADS_ENABLED_PARAM_KEY), "true")); ++ if (this.threadsEnabled) { ++ servletLinks.append(THREADS_LINK); + } +- +- private static String getParam(String initParam, String defaultValue) { +- return initParam == null ? defaultValue : initParam; ++ this.threadDumpServlet = new ThreadDumpServlet(); ++ threadDumpServlet.init(config); ++ ++ this.healthcheckEnabled = ++ Boolean.parseBoolean( ++ getParam(context.getInitParameter(HEALTHCHECK_ENABLED_PARAM_KEY), "true")); ++ if (this.healthcheckEnabled) { ++ servletLinks.append(HEALTHCHECK_LINK); ++ } ++ this.healthCheckServlet = new HealthCheckServlet(); ++ healthCheckServlet.init(config); ++ ++ this.cpuProfileEnabled = ++ Boolean.parseBoolean( ++ getParam(context.getInitParameter(CPU_PROFILE_ENABLED_PARAM_KEY), "true")); ++ if (this.cpuProfileEnabled) { ++ servletLinks.append(CPU_PROFILE_LINK); ++ } ++ this.cpuProfileServlet = new CpuProfileServlet(); ++ cpuProfileServlet.init(config); ++ ++ pageContentTemplate = String.format(BASE_TEMPLATE, String.format(servletLinks.toString())); ++ ++ this.metricsUri = ++ getParam(context.getInitParameter(METRICS_URI_PARAM_KEY), DEFAULT_METRICS_URI); ++ this.pingUri = getParam(context.getInitParameter(PING_URI_PARAM_KEY), DEFAULT_PING_URI); ++ this.threadsUri = ++ getParam(context.getInitParameter(THREADS_URI_PARAM_KEY), DEFAULT_THREADS_URI); ++ this.healthcheckUri = ++ getParam(context.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI); ++ this.cpuProfileUri = ++ getParam(context.getInitParameter(CPU_PROFILE_URI_PARAM_KEY), DEFAULT_CPU_PROFILE_URI); ++ this.serviceName = getParam(context.getInitParameter(SERVICE_NAME_PARAM_KEY), null); ++ } ++ ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ final String path = req.getContextPath() + req.getServletPath(); ++ ++ resp.setStatus(HttpServletResponse.SC_OK); ++ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); ++ resp.setContentType(CONTENT_TYPE); ++ try (PrintWriter writer = resp.getWriter()) { ++ writer.println( ++ MessageFormat.format( ++ pageContentTemplate, ++ path, ++ metricsUri, ++ path, ++ pingUri, ++ path, ++ threadsUri, ++ path, ++ healthcheckUri, ++ path, ++ cpuProfileUri, ++ serviceName == null ? "" : " (" + serviceName + ")")); + } ++ } ++ ++ @Override ++ protected void service(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ final String uri = req.getPathInfo(); ++ if (uri == null || uri.equals("/")) { ++ super.service(req, resp); ++ } else if (uri.equals(healthcheckUri)) { ++ if (healthcheckEnabled) { ++ healthCheckServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else if (uri.startsWith(metricsUri)) { ++ if (metricsEnabled) { ++ metricsServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else if (uri.equals(pingUri)) { ++ if (pingEnabled) { ++ pingServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else if (uri.equals(threadsUri)) { ++ if (threadsEnabled) { ++ threadDumpServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else if (uri.equals(cpuProfileUri)) { ++ if (cpuProfileEnabled) { ++ cpuProfileServlet.service(req, resp); ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } else { ++ resp.sendError(HttpServletResponse.SC_NOT_FOUND); ++ } ++ } ++ ++ private static String getParam(String initParam, String defaultValue) { ++ return initParam == null ? defaultValue : initParam; ++ } + } +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.servlets; + ++import com.papertrail.profiler.CpuProfile; + import java.io.IOException; + import java.io.OutputStream; + import java.time.Duration; +@@ -10,70 +11,69 @@ import javax.servlet.http.HttpServlet; + import javax.servlet.http.HttpServletRequest; + import javax.servlet.http.HttpServletResponse; + +-import com.papertrail.profiler.CpuProfile; +- + /** +- * An HTTP servlets which outputs a pprof parseable response. ++ * An HTTP servlets which outputs a pprof ++ * parseable response. + */ + public class CpuProfileServlet extends HttpServlet { +- private static final long serialVersionUID = -668666696530287501L; +- private static final String CONTENT_TYPE = "pprof/raw"; +- private static final String CACHE_CONTROL = "Cache-Control"; +- private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; +- private final Lock lock = new ReentrantLock(); ++ private static final long serialVersionUID = -668666696530287501L; ++ private static final String CONTENT_TYPE = "pprof/raw"; ++ private static final String CACHE_CONTROL = "Cache-Control"; ++ private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; ++ private final Lock lock = new ReentrantLock(); + +- @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { + +- int duration = 10; +- if (req.getParameter("duration") != null) { +- try { +- duration = Integer.parseInt(req.getParameter("duration")); +- } catch (NumberFormatException e) { +- duration = 10; +- } +- } ++ int duration = 10; ++ if (req.getParameter("duration") != null) { ++ try { ++ duration = Integer.parseInt(req.getParameter("duration")); ++ } catch (NumberFormatException e) { ++ duration = 10; ++ } ++ } + +- int frequency = 100; +- if (req.getParameter("frequency") != null) { +- try { +- frequency = Integer.parseInt(req.getParameter("frequency")); +- frequency = Math.min(Math.max(frequency, 1), 1000); +- } catch (NumberFormatException e) { +- frequency = 100; +- } +- } ++ int frequency = 100; ++ if (req.getParameter("frequency") != null) { ++ try { ++ frequency = Integer.parseInt(req.getParameter("frequency")); ++ frequency = Math.min(Math.max(frequency, 1), 1000); ++ } catch (NumberFormatException e) { ++ frequency = 100; ++ } ++ } + +- final Thread.State state; +- if ("blocked".equalsIgnoreCase(req.getParameter("state"))) { +- state = Thread.State.BLOCKED; +- } else { +- state = Thread.State.RUNNABLE; +- } ++ final Thread.State state; ++ if ("blocked".equalsIgnoreCase(req.getParameter("state"))) { ++ state = Thread.State.BLOCKED; ++ } else { ++ state = Thread.State.RUNNABLE; ++ } + +- resp.setStatus(HttpServletResponse.SC_OK); +- resp.setHeader(CACHE_CONTROL, NO_CACHE); +- resp.setContentType(CONTENT_TYPE); +- try (OutputStream output = resp.getOutputStream()) { +- doProfile(output, duration, frequency, state); +- } ++ resp.setStatus(HttpServletResponse.SC_OK); ++ resp.setHeader(CACHE_CONTROL, NO_CACHE); ++ resp.setContentType(CONTENT_TYPE); ++ try (OutputStream output = resp.getOutputStream()) { ++ doProfile(output, duration, frequency, state); + } ++ } + +- protected void doProfile(OutputStream out, int duration, int frequency, Thread.State state) throws IOException { +- if (lock.tryLock()) { +- try { +- CpuProfile profile = CpuProfile.record(Duration.ofSeconds(duration), +- frequency, state); +- if (profile == null) { +- throw new RuntimeException("could not create CpuProfile"); +- } +- profile.writeGoogleProfile(out); +- return; +- } finally { +- lock.unlock(); +- } ++ protected void doProfile(OutputStream out, int duration, int frequency, Thread.State state) ++ throws IOException { ++ if (lock.tryLock()) { ++ try { ++ CpuProfile profile = CpuProfile.record(Duration.ofSeconds(duration), frequency, state); ++ if (profile == null) { ++ throw new RuntimeException("could not create CpuProfile"); + } +- throw new RuntimeException("Only one profile request may be active at a time"); ++ profile.writeGoogleProfile(out); ++ return; ++ } finally { ++ lock.unlock(); ++ } + } ++ throw new RuntimeException("Only one profile request may be active at a time"); ++ } + } +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java +@@ -6,7 +6,11 @@ import io.dropwizard.metrics5.health.HealthCheck; + import io.dropwizard.metrics5.health.HealthCheckFilter; + import io.dropwizard.metrics5.health.HealthCheckRegistry; + import io.dropwizard.metrics5.json.HealthCheckModule; +- ++import java.io.IOException; ++import java.io.OutputStream; ++import java.util.Map; ++import java.util.SortedMap; ++import java.util.concurrent.ExecutorService; + import javax.servlet.ServletConfig; + import javax.servlet.ServletContext; + import javax.servlet.ServletContextEvent; +@@ -15,181 +19,181 @@ import javax.servlet.ServletException; + import javax.servlet.http.HttpServlet; + import javax.servlet.http.HttpServletRequest; + import javax.servlet.http.HttpServletResponse; +-import java.io.IOException; +-import java.io.OutputStream; +-import java.util.Map; +-import java.util.SortedMap; +-import java.util.concurrent.ExecutorService; + + public class HealthCheckServlet extends HttpServlet { +- public static abstract class ContextListener implements ServletContextListener { +- /** +- * @return the {@link HealthCheckRegistry} to inject into the servlet context. +- */ +- protected abstract HealthCheckRegistry getHealthCheckRegistry(); +- +- /** +- * @return the {@link ExecutorService} to inject into the servlet context, or {@code null} +- * if the health checks should be run in the servlet worker thread. +- */ +- protected ExecutorService getExecutorService() { +- // don't use a thread pool by default +- return null; +- } +- +- /** +- * @return the {@link HealthCheckFilter} that shall be used to filter health checks, +- * or {@link HealthCheckFilter#ALL} if the default should be used. +- */ +- protected HealthCheckFilter getHealthCheckFilter() { +- return HealthCheckFilter.ALL; +- } +- +- /** +- * @return the {@link ObjectMapper} that shall be used to render health checks, +- * or {@code null} if the default object mapper should be used. +- */ +- protected ObjectMapper getObjectMapper() { +- // don't use an object mapper by default +- return null; +- } +- +- @Override +- public void contextInitialized(ServletContextEvent event) { +- final ServletContext context = event.getServletContext(); +- context.setAttribute(HEALTH_CHECK_REGISTRY, getHealthCheckRegistry()); +- context.setAttribute(HEALTH_CHECK_EXECUTOR, getExecutorService()); +- context.setAttribute(HEALTH_CHECK_MAPPER, getObjectMapper()); +- } +- +- @Override +- public void contextDestroyed(ServletContextEvent event) { +- // no-op +- } +- } +- +- public static final String HEALTH_CHECK_REGISTRY = HealthCheckServlet.class.getCanonicalName() + ".registry"; +- public static final String HEALTH_CHECK_EXECUTOR = HealthCheckServlet.class.getCanonicalName() + ".executor"; +- public static final String HEALTH_CHECK_FILTER = HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter"; +- public static final String HEALTH_CHECK_MAPPER = HealthCheckServlet.class.getCanonicalName() + ".mapper"; +- public static final String HEALTH_CHECK_HTTP_STATUS_INDICATOR = HealthCheckServlet.class.getCanonicalName() + ".httpStatusIndicator"; +- +- private static final long serialVersionUID = -8432996484889177321L; +- private static final String CONTENT_TYPE = "application/json"; +- private static final String HTTP_STATUS_INDICATOR_PARAM = "httpStatusIndicator"; +- +- private transient HealthCheckRegistry registry; +- private transient ExecutorService executorService; +- private transient HealthCheckFilter filter; +- private transient ObjectMapper mapper; +- private transient boolean httpStatusIndicator; +- +- public HealthCheckServlet() { +- } +- +- public HealthCheckServlet(HealthCheckRegistry registry) { +- this.registry = registry; ++ public abstract static class ContextListener implements ServletContextListener { ++ /** ++ * @return the {@link HealthCheckRegistry} to inject into the servlet context. ++ */ ++ protected abstract HealthCheckRegistry getHealthCheckRegistry(); ++ ++ /** ++ * @return the {@link ExecutorService} to inject into the servlet context, or {@code null} if ++ * the health checks should be run in the servlet worker thread. ++ */ ++ protected ExecutorService getExecutorService() { ++ // don't use a thread pool by default ++ return null; + } + +- @Override +- public void init(ServletConfig config) throws ServletException { +- super.init(config); +- +- final ServletContext context = config.getServletContext(); +- if (null == registry) { +- final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); +- if (registryAttr instanceof HealthCheckRegistry) { +- this.registry = (HealthCheckRegistry) registryAttr; +- } else { +- throw new ServletException("Couldn't find a HealthCheckRegistry instance."); +- } +- } +- +- final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR); +- if (executorAttr instanceof ExecutorService) { +- this.executorService = (ExecutorService) executorAttr; +- } +- +- final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER); +- if (filterAttr instanceof HealthCheckFilter) { +- filter = (HealthCheckFilter) filterAttr; +- } +- if (filter == null) { +- filter = HealthCheckFilter.ALL; +- } +- +- final Object mapperAttr = context.getAttribute(HEALTH_CHECK_MAPPER); +- if (mapperAttr instanceof ObjectMapper) { +- this.mapper = (ObjectMapper) mapperAttr; +- } else { +- this.mapper = new ObjectMapper(); +- } +- this.mapper.registerModule(new HealthCheckModule()); +- +- final Object httpStatusIndicatorAttr = context.getAttribute(HEALTH_CHECK_HTTP_STATUS_INDICATOR); +- if (httpStatusIndicatorAttr instanceof Boolean) { +- this.httpStatusIndicator = (Boolean) httpStatusIndicatorAttr; +- } else { +- this.httpStatusIndicator = true; +- } ++ /** ++ * @return the {@link HealthCheckFilter} that shall be used to filter health checks, or {@link ++ * HealthCheckFilter#ALL} if the default should be used. ++ */ ++ protected HealthCheckFilter getHealthCheckFilter() { ++ return HealthCheckFilter.ALL; ++ } ++ ++ /** ++ * @return the {@link ObjectMapper} that shall be used to render health checks, or {@code null} ++ * if the default object mapper should be used. ++ */ ++ protected ObjectMapper getObjectMapper() { ++ // don't use an object mapper by default ++ return null; + } + + @Override +- public void destroy() { +- super.destroy(); +- registry.shutdown(); ++ public void contextInitialized(ServletContextEvent event) { ++ final ServletContext context = event.getServletContext(); ++ context.setAttribute(HEALTH_CHECK_REGISTRY, getHealthCheckRegistry()); ++ context.setAttribute(HEALTH_CHECK_EXECUTOR, getExecutorService()); ++ context.setAttribute(HEALTH_CHECK_MAPPER, getObjectMapper()); + } + + @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { +- final SortedMap results = runHealthChecks(); +- resp.setContentType(CONTENT_TYPE); +- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); +- if (results.isEmpty()) { +- resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); +- } else { +- final String reqParameter = req.getParameter(HTTP_STATUS_INDICATOR_PARAM); +- final boolean httpStatusIndicatorParam = Boolean.parseBoolean(reqParameter); +- final boolean useHttpStatusForHealthCheck = reqParameter == null ? httpStatusIndicator : httpStatusIndicatorParam; +- if (!useHttpStatusForHealthCheck || isAllHealthy(results)) { +- resp.setStatus(HttpServletResponse.SC_OK); +- } else { +- resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); +- } +- } +- +- try (OutputStream output = resp.getOutputStream()) { +- getWriter(req).writeValue(output, results); +- } +- } +- +- private ObjectWriter getWriter(HttpServletRequest request) { +- final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); +- if (prettyPrint) { +- return mapper.writerWithDefaultPrettyPrinter(); +- } +- return mapper.writer(); +- } +- +- private SortedMap runHealthChecks() { +- if (executorService == null) { +- return registry.runHealthChecks(filter); +- } +- return registry.runHealthChecks(executorService, filter); +- } +- +- private static boolean isAllHealthy(Map results) { +- for (HealthCheck.Result result : results.values()) { +- if (!result.isHealthy()) { +- return false; +- } +- } +- return true; +- } +- +- // visible for testing +- ObjectMapper getMapper() { +- return mapper; ++ public void contextDestroyed(ServletContextEvent event) { ++ // no-op ++ } ++ } ++ ++ public static final String HEALTH_CHECK_REGISTRY = ++ HealthCheckServlet.class.getCanonicalName() + ".registry"; ++ public static final String HEALTH_CHECK_EXECUTOR = ++ HealthCheckServlet.class.getCanonicalName() + ".executor"; ++ public static final String HEALTH_CHECK_FILTER = ++ HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter"; ++ public static final String HEALTH_CHECK_MAPPER = ++ HealthCheckServlet.class.getCanonicalName() + ".mapper"; ++ public static final String HEALTH_CHECK_HTTP_STATUS_INDICATOR = ++ HealthCheckServlet.class.getCanonicalName() + ".httpStatusIndicator"; ++ ++ private static final long serialVersionUID = -8432996484889177321L; ++ private static final String CONTENT_TYPE = "application/json"; ++ private static final String HTTP_STATUS_INDICATOR_PARAM = "httpStatusIndicator"; ++ ++ private transient HealthCheckRegistry registry; ++ private transient ExecutorService executorService; ++ private transient HealthCheckFilter filter; ++ private transient ObjectMapper mapper; ++ private transient boolean httpStatusIndicator; ++ ++ public HealthCheckServlet() {} ++ ++ public HealthCheckServlet(HealthCheckRegistry registry) { ++ this.registry = registry; ++ } ++ ++ @Override ++ public void init(ServletConfig config) throws ServletException { ++ super.init(config); ++ ++ final ServletContext context = config.getServletContext(); ++ if (registry == null) { ++ final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); ++ if (registryAttr instanceof HealthCheckRegistry) { ++ this.registry = (HealthCheckRegistry) registryAttr; ++ } else { ++ throw new ServletException("Couldn't find a HealthCheckRegistry instance."); ++ } ++ } ++ ++ final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR); ++ if (executorAttr instanceof ExecutorService) { ++ this.executorService = (ExecutorService) executorAttr; + } ++ ++ final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER); ++ if (filterAttr instanceof HealthCheckFilter) { ++ filter = (HealthCheckFilter) filterAttr; ++ } ++ if (filter == null) { ++ filter = HealthCheckFilter.ALL; ++ } ++ ++ final Object mapperAttr = context.getAttribute(HEALTH_CHECK_MAPPER); ++ if (mapperAttr instanceof ObjectMapper) { ++ this.mapper = (ObjectMapper) mapperAttr; ++ } else { ++ this.mapper = new ObjectMapper(); ++ } ++ this.mapper.registerModule(new HealthCheckModule()); ++ ++ final Object httpStatusIndicatorAttr = context.getAttribute(HEALTH_CHECK_HTTP_STATUS_INDICATOR); ++ if (httpStatusIndicatorAttr instanceof Boolean) { ++ this.httpStatusIndicator = (Boolean) httpStatusIndicatorAttr; ++ } else { ++ this.httpStatusIndicator = true; ++ } ++ } ++ ++ @Override ++ public void destroy() { ++ super.destroy(); ++ registry.shutdown(); ++ } ++ ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ final SortedMap results = runHealthChecks(); ++ resp.setContentType(CONTENT_TYPE); ++ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); ++ if (results.isEmpty()) { ++ resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); ++ } else { ++ final String reqParameter = req.getParameter(HTTP_STATUS_INDICATOR_PARAM); ++ final boolean httpStatusIndicatorParam = Boolean.parseBoolean(reqParameter); ++ final boolean useHttpStatusForHealthCheck = ++ reqParameter == null ? httpStatusIndicator : httpStatusIndicatorParam; ++ if (!useHttpStatusForHealthCheck || isAllHealthy(results)) { ++ resp.setStatus(HttpServletResponse.SC_OK); ++ } else { ++ resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ++ } ++ } ++ ++ try (OutputStream output = resp.getOutputStream()) { ++ getWriter(req).writeValue(output, results); ++ } ++ } ++ ++ private ObjectWriter getWriter(HttpServletRequest request) { ++ final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); ++ if (prettyPrint) { ++ return mapper.writerWithDefaultPrettyPrinter(); ++ } ++ return mapper.writer(); ++ } ++ ++ private SortedMap runHealthChecks() { ++ if (executorService == null) { ++ return registry.runHealthChecks(filter); ++ } ++ return registry.runHealthChecks(executorService, filter); ++ } ++ ++ private static boolean isAllHealthy(Map results) { ++ for (HealthCheck.Result result : results.values()) { ++ if (!result.isHealthy()) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ // visible for testing ++ ObjectMapper getMapper() { ++ return mapper; ++ } + } +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +@@ -6,7 +6,10 @@ import com.fasterxml.jackson.databind.util.JSONPObject; + import io.dropwizard.metrics5.MetricFilter; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.json.MetricsModule; +- ++import java.io.IOException; ++import java.io.OutputStream; ++import java.util.Locale; ++import java.util.concurrent.TimeUnit; + import javax.servlet.ServletConfig; + import javax.servlet.ServletContext; + import javax.servlet.ServletContextEvent; +@@ -15,185 +18,182 @@ import javax.servlet.ServletException; + import javax.servlet.http.HttpServlet; + import javax.servlet.http.HttpServletRequest; + import javax.servlet.http.HttpServletResponse; +-import java.io.IOException; +-import java.io.OutputStream; +-import java.util.Locale; +-import java.util.concurrent.TimeUnit; + + /** + * A servlet which returns the metrics in a given registry as an {@code application/json} response. + */ + public class MetricsServlet extends HttpServlet { ++ /** ++ * An abstract {@link ServletContextListener} which allows you to programmatically inject the ++ * {@link MetricRegistry}, rate and duration units, and allowed origin for {@link MetricsServlet}. ++ */ ++ public abstract static class ContextListener implements ServletContextListener { + /** +- * An abstract {@link ServletContextListener} which allows you to programmatically inject the +- * {@link MetricRegistry}, rate and duration units, and allowed origin for +- * {@link MetricsServlet}. ++ * @return the {@link MetricRegistry} to inject into the servlet context. + */ +- public static abstract class ContextListener implements ServletContextListener { +- /** +- * @return the {@link MetricRegistry} to inject into the servlet context. +- */ +- protected abstract MetricRegistry getMetricRegistry(); +- +- /** +- * @return the {@link TimeUnit} to which rates should be converted, or {@code null} if the +- * default should be used. +- */ +- protected TimeUnit getRateUnit() { +- // use the default +- return null; +- } +- +- /** +- * @return the {@link TimeUnit} to which durations should be converted, or {@code null} if +- * the default should be used. +- */ +- protected TimeUnit getDurationUnit() { +- // use the default +- return null; +- } +- +- /** +- * @return the {@code Access-Control-Allow-Origin} header value, if any. +- */ +- protected String getAllowedOrigin() { +- // use the default +- return null; +- } +- +- /** +- * Returns the name of the parameter used to specify the jsonp callback, if any. +- */ +- protected String getJsonpCallbackParameter() { +- return null; +- } +- +- /** +- * Returns the {@link MetricFilter} that shall be used to filter metrics, or {@link MetricFilter#ALL} if +- * the default should be used. +- */ +- protected MetricFilter getMetricFilter() { +- // use the default +- return MetricFilter.ALL; +- } +- +- @Override +- public void contextInitialized(ServletContextEvent event) { +- final ServletContext context = event.getServletContext(); +- context.setAttribute(METRICS_REGISTRY, getMetricRegistry()); +- context.setAttribute(METRIC_FILTER, getMetricFilter()); +- if (getDurationUnit() != null) { +- context.setInitParameter(MetricsServlet.DURATION_UNIT, getDurationUnit().toString()); +- } +- if (getRateUnit() != null) { +- context.setInitParameter(MetricsServlet.RATE_UNIT, getRateUnit().toString()); +- } +- if (getAllowedOrigin() != null) { +- context.setInitParameter(MetricsServlet.ALLOWED_ORIGIN, getAllowedOrigin()); +- } +- if (getJsonpCallbackParameter() != null) { +- context.setAttribute(CALLBACK_PARAM, getJsonpCallbackParameter()); +- } +- } +- +- @Override +- public void contextDestroyed(ServletContextEvent event) { +- // no-op +- } +- } +- +- public static final String RATE_UNIT = MetricsServlet.class.getCanonicalName() + ".rateUnit"; +- public static final String DURATION_UNIT = MetricsServlet.class.getCanonicalName() + ".durationUnit"; +- public static final String SHOW_SAMPLES = MetricsServlet.class.getCanonicalName() + ".showSamples"; +- public static final String METRICS_REGISTRY = MetricsServlet.class.getCanonicalName() + ".registry"; +- public static final String ALLOWED_ORIGIN = MetricsServlet.class.getCanonicalName() + ".allowedOrigin"; +- public static final String METRIC_FILTER = MetricsServlet.class.getCanonicalName() + ".metricFilter"; +- public static final String CALLBACK_PARAM = MetricsServlet.class.getCanonicalName() + ".jsonpCallback"; ++ protected abstract MetricRegistry getMetricRegistry(); + +- private static final long serialVersionUID = 1049773947734939602L; +- private static final String CONTENT_TYPE = "application/json"; ++ /** ++ * @return the {@link TimeUnit} to which rates should be converted, or {@code null} if the ++ * default should be used. ++ */ ++ protected TimeUnit getRateUnit() { ++ // use the default ++ return null; ++ } + +- protected String allowedOrigin; +- protected String jsonpParamName; +- protected transient MetricRegistry registry; +- protected transient ObjectMapper mapper; ++ /** ++ * @return the {@link TimeUnit} to which durations should be converted, or {@code null} if the ++ * default should be used. ++ */ ++ protected TimeUnit getDurationUnit() { ++ // use the default ++ return null; ++ } + +- public MetricsServlet() { ++ /** ++ * @return the {@code Access-Control-Allow-Origin} header value, if any. ++ */ ++ protected String getAllowedOrigin() { ++ // use the default ++ return null; + } + +- public MetricsServlet(MetricRegistry registry) { +- this.registry = registry; ++ /** Returns the name of the parameter used to specify the jsonp callback, if any. */ ++ protected String getJsonpCallbackParameter() { ++ return null; + } + +- @Override +- public void init(ServletConfig config) throws ServletException { +- super.init(config); +- +- final ServletContext context = config.getServletContext(); +- if (null == registry) { +- final Object registryAttr = context.getAttribute(METRICS_REGISTRY); +- if (registryAttr instanceof MetricRegistry) { +- this.registry = (MetricRegistry) registryAttr; +- } else { +- throw new ServletException("Couldn't find a MetricRegistry instance."); +- } +- } +- this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); +- this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); +- +- setupMetricsModule(context); ++ /** ++ * Returns the {@link MetricFilter} that shall be used to filter metrics, or {@link ++ * MetricFilter#ALL} if the default should be used. ++ */ ++ protected MetricFilter getMetricFilter() { ++ // use the default ++ return MetricFilter.ALL; + } + +- protected void setupMetricsModule(ServletContext context) { +- final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), +- TimeUnit.SECONDS); +- final TimeUnit durationUnit = parseTimeUnit(context.getInitParameter(DURATION_UNIT), +- TimeUnit.SECONDS); +- final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES)); +- MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER); +- if (filter == null) { +- filter = MetricFilter.ALL; +- } +- +- this.mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit, +- durationUnit, +- showSamples, +- filter)); ++ @Override ++ public void contextInitialized(ServletContextEvent event) { ++ final ServletContext context = event.getServletContext(); ++ context.setAttribute(METRICS_REGISTRY, getMetricRegistry()); ++ context.setAttribute(METRIC_FILTER, getMetricFilter()); ++ if (getDurationUnit() != null) { ++ context.setInitParameter(MetricsServlet.DURATION_UNIT, getDurationUnit().toString()); ++ } ++ if (getRateUnit() != null) { ++ context.setInitParameter(MetricsServlet.RATE_UNIT, getRateUnit().toString()); ++ } ++ if (getAllowedOrigin() != null) { ++ context.setInitParameter(MetricsServlet.ALLOWED_ORIGIN, getAllowedOrigin()); ++ } ++ if (getJsonpCallbackParameter() != null) { ++ context.setAttribute(CALLBACK_PARAM, getJsonpCallbackParameter()); ++ } + } + + @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { +- resp.setContentType(CONTENT_TYPE); +- if (allowedOrigin != null) { +- resp.setHeader("Access-Control-Allow-Origin", allowedOrigin); +- } +- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); +- resp.setStatus(HttpServletResponse.SC_OK); +- +- try (OutputStream output = resp.getOutputStream()) { +- if (jsonpParamName != null && req.getParameter(jsonpParamName) != null) { +- getWriter(req).writeValue(output, new JSONPObject(req.getParameter(jsonpParamName), registry)); +- } else { +- getWriter(req).writeValue(output, registry); +- } +- } ++ public void contextDestroyed(ServletContextEvent event) { ++ // no-op ++ } ++ } ++ ++ public static final String RATE_UNIT = MetricsServlet.class.getCanonicalName() + ".rateUnit"; ++ public static final String DURATION_UNIT = ++ MetricsServlet.class.getCanonicalName() + ".durationUnit"; ++ public static final String SHOW_SAMPLES = ++ MetricsServlet.class.getCanonicalName() + ".showSamples"; ++ public static final String METRICS_REGISTRY = ++ MetricsServlet.class.getCanonicalName() + ".registry"; ++ public static final String ALLOWED_ORIGIN = ++ MetricsServlet.class.getCanonicalName() + ".allowedOrigin"; ++ public static final String METRIC_FILTER = ++ MetricsServlet.class.getCanonicalName() + ".metricFilter"; ++ public static final String CALLBACK_PARAM = ++ MetricsServlet.class.getCanonicalName() + ".jsonpCallback"; ++ ++ private static final long serialVersionUID = 1049773947734939602L; ++ private static final String CONTENT_TYPE = "application/json"; ++ ++ protected String allowedOrigin; ++ protected String jsonpParamName; ++ protected transient MetricRegistry registry; ++ protected transient ObjectMapper mapper; ++ ++ public MetricsServlet() {} ++ ++ public MetricsServlet(MetricRegistry registry) { ++ this.registry = registry; ++ } ++ ++ @Override ++ public void init(ServletConfig config) throws ServletException { ++ super.init(config); ++ ++ final ServletContext context = config.getServletContext(); ++ if (registry == null) { ++ final Object registryAttr = context.getAttribute(METRICS_REGISTRY); ++ if (registryAttr instanceof MetricRegistry) { ++ this.registry = (MetricRegistry) registryAttr; ++ } else { ++ throw new ServletException("Couldn't find a MetricRegistry instance."); ++ } ++ } ++ this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); ++ this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); ++ ++ setupMetricsModule(context); ++ } ++ ++ protected void setupMetricsModule(ServletContext context) { ++ final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), TimeUnit.SECONDS); ++ final TimeUnit durationUnit = ++ parseTimeUnit(context.getInitParameter(DURATION_UNIT), TimeUnit.SECONDS); ++ final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES)); ++ MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER); ++ if (filter == null) { ++ filter = MetricFilter.ALL; + } + +- protected ObjectWriter getWriter(HttpServletRequest request) { +- final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); +- if (prettyPrint) { +- return mapper.writerWithDefaultPrettyPrinter(); +- } +- return mapper.writer(); ++ this.mapper = ++ new ObjectMapper() ++ .registerModule(new MetricsModule(rateUnit, durationUnit, showSamples, filter)); ++ } ++ ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ resp.setContentType(CONTENT_TYPE); ++ if (allowedOrigin != null) { ++ resp.setHeader("Access-Control-Allow-Origin", allowedOrigin); ++ } ++ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); ++ resp.setStatus(HttpServletResponse.SC_OK); ++ ++ try (OutputStream output = resp.getOutputStream()) { ++ if (jsonpParamName != null && req.getParameter(jsonpParamName) != null) { ++ getWriter(req) ++ .writeValue(output, new JSONPObject(req.getParameter(jsonpParamName), registry)); ++ } else { ++ getWriter(req).writeValue(output, registry); ++ } + } ++ } + +- @SuppressWarnings("IdentityConversion") +- protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { +- try { +- return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); +- } catch (IllegalArgumentException e) { +- return defaultValue; +- } ++ protected ObjectWriter getWriter(HttpServletRequest request) { ++ final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); ++ if (prettyPrint) { ++ return mapper.writerWithDefaultPrettyPrinter(); ++ } ++ return mapper.writer(); ++ } ++ ++ @SuppressWarnings("IdentityConversion") ++ protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { ++ try { ++ return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); ++ } catch (IllegalArgumentException e) { ++ return defaultValue; + } ++ } + } +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/PingServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/PingServlet.java +@@ -1,30 +1,28 @@ + package io.dropwizard.metrics5.servlets; + ++import java.io.IOException; ++import java.io.PrintWriter; + import javax.servlet.ServletException; + import javax.servlet.http.HttpServlet; + import javax.servlet.http.HttpServletRequest; + import javax.servlet.http.HttpServletResponse; +-import java.io.IOException; +-import java.io.PrintWriter; + +-/** +- * An HTTP servlets which outputs a {@code text/plain} {@code "pong"} response. +- */ ++/** An HTTP servlets which outputs a {@code text/plain} {@code "pong"} response. */ + public class PingServlet extends HttpServlet { +- private static final long serialVersionUID = 3772654177231086757L; +- private static final String CONTENT_TYPE = "text/plain"; +- private static final String CONTENT = "pong"; +- private static final String CACHE_CONTROL = "Cache-Control"; +- private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; ++ private static final long serialVersionUID = 3772654177231086757L; ++ private static final String CONTENT_TYPE = "text/plain"; ++ private static final String CONTENT = "pong"; ++ private static final String CACHE_CONTROL = "Cache-Control"; ++ private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; + +- @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { +- resp.setStatus(HttpServletResponse.SC_OK); +- resp.setHeader(CACHE_CONTROL, NO_CACHE); +- resp.setContentType(CONTENT_TYPE); +- try (PrintWriter writer = resp.getWriter()) { +- writer.println(CONTENT); +- } ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ resp.setStatus(HttpServletResponse.SC_OK); ++ resp.setHeader(CACHE_CONTROL, NO_CACHE); ++ resp.setContentType(CONTENT_TYPE); ++ try (PrintWriter writer = resp.getWriter()) { ++ writer.println(CONTENT); + } ++ } + } +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/ThreadDumpServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/ThreadDumpServlet.java +@@ -1,55 +1,54 @@ + package io.dropwizard.metrics5.servlets; + + import io.dropwizard.metrics5.jvm.ThreadDump; +- ++import java.io.IOException; ++import java.io.OutputStream; ++import java.lang.management.ManagementFactory; + import javax.servlet.ServletException; + import javax.servlet.http.HttpServlet; + import javax.servlet.http.HttpServletRequest; + import javax.servlet.http.HttpServletResponse; +-import java.io.IOException; +-import java.io.OutputStream; +-import java.lang.management.ManagementFactory; + + /** +- * An HTTP servlets which outputs a {@code text/plain} dump of all threads in +- * the VM. Only responds to {@code GET} requests. ++ * An HTTP servlets which outputs a {@code text/plain} dump of all threads in the VM. Only responds ++ * to {@code GET} requests. + */ + public class ThreadDumpServlet extends HttpServlet { + +- private static final long serialVersionUID = -2690343532336103046L; +- private static final String CONTENT_TYPE = "text/plain"; ++ private static final long serialVersionUID = -2690343532336103046L; ++ private static final String CONTENT_TYPE = "text/plain"; + +- private transient ThreadDump threadDump; ++ private transient ThreadDump threadDump; + +- @Override +- public void init() throws ServletException { +- try { +- // Some PaaS like Google App Engine blacklist java.lang.managament +- this.threadDump = new ThreadDump(ManagementFactory.getThreadMXBean()); +- } catch (NoClassDefFoundError ncdfe) { +- this.threadDump = null; // we won't be able to provide thread dump +- } ++ @Override ++ public void init() throws ServletException { ++ try { ++ // Some PaaS like Google App Engine blacklist java.lang.managament ++ this.threadDump = new ThreadDump(ManagementFactory.getThreadMXBean()); ++ } catch (NoClassDefFoundError ncdfe) { ++ this.threadDump = null; // we won't be able to provide thread dump + } +- +- @Override +- protected void doGet(HttpServletRequest req, +- HttpServletResponse resp) throws ServletException, IOException { +- final boolean includeMonitors = getParam(req.getParameter("monitors"), true); +- final boolean includeSynchronizers = getParam(req.getParameter("synchronizers"), true); +- +- resp.setStatus(HttpServletResponse.SC_OK); +- resp.setContentType(CONTENT_TYPE); +- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); +- if (threadDump == null) { +- resp.getWriter().println("Sorry your runtime environment does not allow to dump threads."); +- return; +- } +- try (OutputStream output = resp.getOutputStream()) { +- threadDump.dump(includeMonitors, includeSynchronizers, output); +- } ++ } ++ ++ @Override ++ protected void doGet(HttpServletRequest req, HttpServletResponse resp) ++ throws ServletException, IOException { ++ final boolean includeMonitors = getParam(req.getParameter("monitors"), true); ++ final boolean includeSynchronizers = getParam(req.getParameter("synchronizers"), true); ++ ++ resp.setStatus(HttpServletResponse.SC_OK); ++ resp.setContentType(CONTENT_TYPE); ++ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); ++ if (threadDump == null) { ++ resp.getWriter().println("Sorry your runtime environment does not allow to dump threads."); ++ return; + } +- +- private static Boolean getParam(String initParam, boolean defaultValue) { +- return initParam == null ? defaultValue : Boolean.parseBoolean(initParam); ++ try (OutputStream output = resp.getOutputStream()) { ++ threadDump.dump(includeMonitors, includeSynchronizers, output); + } ++ } ++ ++ private static Boolean getParam(String initParam, boolean defaultValue) { ++ return initParam == null ? defaultValue : Boolean.parseBoolean(initParam); ++ } + } +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java +@@ -6,24 +6,24 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + + public abstract class AbstractServletTest { +- private final ServletTester tester = new ServletTester(); +- protected final HttpTester.Request request = HttpTester.newRequest(); +- protected HttpTester.Response response; ++ private final ServletTester tester = new ServletTester(); ++ protected final HttpTester.Request request = HttpTester.newRequest(); ++ protected HttpTester.Response response; + +- @BeforeEach +- public void setUpTester() throws Exception { +- setUp(tester); +- tester.start(); +- } ++ @BeforeEach ++ public void setUpTester() throws Exception { ++ setUp(tester); ++ tester.start(); ++ } + +- protected abstract void setUp(ServletTester tester); ++ protected abstract void setUp(ServletTester tester); + +- @AfterEach +- public void tearDownTester() throws Exception { +- tester.stop(); +- } ++ @AfterEach ++ public void tearDownTester() throws Exception { ++ tester.stop(); ++ } + +- protected void processRequest() throws Exception { +- this.response = HttpTester.parseResponse(tester.getResponses(request.generate())); +- } ++ protected void processRequest() throws Exception { ++ this.response = HttpTester.parseResponse(tester.getResponses(request.generate())); ++ } + } +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.health.HealthCheckRegistry; + import org.eclipse.jetty.http.HttpHeader; +@@ -7,56 +9,53 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class AdminServletTest extends AbstractServletTest { +- private final MetricRegistry registry = new MetricRegistry(); +- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); +- +- @Override +- protected void setUp(ServletTester tester) { +- tester.setContextPath("/context"); +- +- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); +- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); +- tester.addServlet(AdminServlet.class, "/admin"); +- } +- +- @BeforeEach +- void setUp() { +- request.setMethod("GET"); +- request.setURI("/context/admin"); +- request.setVersion("HTTP/1.0"); +- } +- +- @Test +- void returnsA200() throws Exception { +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.getContent()) +- .isEqualTo(String.format( +- "%n" + +- "%n" + +- "%n" + +- " Metrics%n" + +- "%n" + +- "%n" + +- "

    Operational Menu

    %n" + +- " %n" + +- "%n" + +- "%n" +- )); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("text/html;charset=UTF-8"); +- } ++final class AdminServletTest extends AbstractServletTest { ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.setContextPath("/context"); ++ ++ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); ++ tester.setAttribute( ++ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); ++ tester.addServlet(AdminServlet.class, "/admin"); ++ } ++ ++ @BeforeEach ++ void setUp() { ++ request.setMethod("GET"); ++ request.setURI("/context/admin"); ++ request.setVersion("HTTP/1.0"); ++ } ++ ++ @Test ++ void returnsA200() throws Exception { ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "%n" ++ + "%n" ++ + "%n" ++ + " Metrics%n" ++ + "%n" ++ + "%n" ++ + "

    Operational Menu

    %n" ++ + " %n" ++ + "%n" ++ + "%n")); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); ++ } + } +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.health.HealthCheckRegistry; + import org.eclipse.jetty.http.HttpHeader; +@@ -7,61 +9,58 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class AdminServletUriTest extends AbstractServletTest { +- private final MetricRegistry registry = new MetricRegistry(); +- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); ++final class AdminServletUriTest extends AbstractServletTest { ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + +- @Override +- protected void setUp(ServletTester tester) { +- tester.setContextPath("/context"); ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.setContextPath("/context"); + +- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); +- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); +- tester.setInitParameter("metrics-uri", "/metrics-test"); +- tester.setInitParameter("ping-uri", "/ping-test"); +- tester.setInitParameter("threads-uri", "/threads-test"); +- tester.setInitParameter("healthcheck-uri", "/healthcheck-test"); +- tester.setInitParameter("cpu-profile-uri", "/pprof-test"); +- tester.addServlet(AdminServlet.class, "/admin"); +- } ++ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); ++ tester.setAttribute( ++ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); ++ tester.setInitParameter("metrics-uri", "/metrics-test"); ++ tester.setInitParameter("ping-uri", "/ping-test"); ++ tester.setInitParameter("threads-uri", "/threads-test"); ++ tester.setInitParameter("healthcheck-uri", "/healthcheck-test"); ++ tester.setInitParameter("cpu-profile-uri", "/pprof-test"); ++ tester.addServlet(AdminServlet.class, "/admin"); ++ } + +- @BeforeEach +- void setUp() { +- request.setMethod("GET"); +- request.setURI("/context/admin"); +- request.setVersion("HTTP/1.0"); +- } ++ @BeforeEach ++ void setUp() { ++ request.setMethod("GET"); ++ request.setURI("/context/admin"); ++ request.setVersion("HTTP/1.0"); ++ } + +- @Test +- void returnsA200() throws Exception { +- processRequest(); ++ @Test ++ void returnsA200() throws Exception { ++ processRequest(); + +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.getContent()) +- .isEqualTo(String.format( +- "%n" + +- "%n" + +- "%n" + +- " Metrics%n" + +- "%n" + +- "%n" + +- "

    Operational Menu

    %n" + +- " %n" + +- "%n" + +- "%n" +- )); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("text/html;charset=UTF-8"); +- } ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "%n" ++ + "%n" ++ + "%n" ++ + " Metrics%n" ++ + "%n" ++ + "%n" ++ + "

    Operational Menu

    %n" ++ + " %n" ++ + "%n" ++ + "%n")); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); ++ } + } +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +@@ -7,38 +7,35 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class CpuProfileServletTest extends AbstractServletTest { +- +- @Override +- protected void setUp(ServletTester tester) { +- tester.addServlet(CpuProfileServlet.class, "/pprof"); +- } +- +- @BeforeEach +- void setUp() throws Exception { +- request.setMethod("GET"); +- request.setURI("/pprof?duration=1"); +- request.setVersion("HTTP/1.0"); +- +- processRequest(); +- } +- +- @Test +- void returns200OK() { +- assertThat(response.getStatus()) +- .isEqualTo(200); +- } +- +- @Test +- void returnsPprofRaw() { +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("pprof/raw"); +- } +- +- @Test +- void returnsUncacheable() { +- assertThat(response.get(HttpHeader.CACHE_CONTROL)) +- .isEqualTo("must-revalidate,no-cache,no-store"); +- +- } ++final class CpuProfileServletTest extends AbstractServletTest { ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.addServlet(CpuProfileServlet.class, "/pprof"); ++ } ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ request.setMethod("GET"); ++ request.setURI("/pprof?duration=1"); ++ request.setVersion("HTTP/1.0"); ++ ++ processRequest(); ++ } ++ ++ @Test ++ void returns200OK() { ++ assertThat(response.getStatus()).isEqualTo(200); ++ } ++ ++ @Test ++ void returnsPprofRaw() { ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("pprof/raw"); ++ } ++ ++ @Test ++ void returnsUncacheable() { ++ assertThat(response.get(HttpHeader.CACHE_CONTROL)) ++ .isEqualTo("must-revalidate,no-cache,no-store"); ++ } + } +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +@@ -1,258 +1,269 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.never; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import com.fasterxml.jackson.databind.ObjectMapper; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.health.HealthCheck; + import io.dropwizard.metrics5.health.HealthCheckFilter; + import io.dropwizard.metrics5.health.HealthCheckRegistry; +-import org.eclipse.jetty.http.HttpHeader; +-import org.eclipse.jetty.servlet.ServletTester; +-import org.junit.jupiter.api.AfterEach; +-import org.junit.jupiter.api.BeforeEach; +-import org.junit.jupiter.api.Test; +- +-import javax.servlet.ServletConfig; +-import javax.servlet.ServletContext; +-import javax.servlet.ServletException; + import java.time.ZonedDateTime; + import java.time.format.DateTimeFormatter; + import java.util.concurrent.Callable; + import java.util.concurrent.ExecutorService; + import java.util.concurrent.Executors; ++import javax.servlet.ServletConfig; ++import javax.servlet.ServletContext; ++import javax.servlet.ServletException; ++import org.eclipse.jetty.http.HttpHeader; ++import org.eclipse.jetty.servlet.ServletTester; ++import org.junit.jupiter.api.AfterEach; ++import org.junit.jupiter.api.BeforeEach; ++import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- +-class HealthCheckServletTest extends AbstractServletTest { ++final class HealthCheckServletTest extends AbstractServletTest { + +- private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); ++ private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); + +- private static final DateTimeFormatter DATE_TIME_FORMATTER = +- DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); ++ private static final DateTimeFormatter DATE_TIME_FORMATTER = ++ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + +- private static final String EXPECTED_TIMESTAMP = DATE_TIME_FORMATTER.format(FIXED_TIME); ++ private static final String EXPECTED_TIMESTAMP = DATE_TIME_FORMATTER.format(FIXED_TIME); + +- private static final Clock FIXED_CLOCK = new Clock() { ++ private static final Clock FIXED_CLOCK = ++ new Clock() { + @Override + public long getTick() { +- return 0L; ++ return 0L; + } + + @Override + public long getTime() { +- return FIXED_TIME.toInstant().toEpochMilli(); ++ return FIXED_TIME.toInstant().toEpochMilli(); + } +- }; +- +- private final HealthCheckRegistry registry = new HealthCheckRegistry(); +- private final ExecutorService threadPool = Executors.newCachedThreadPool(); +- private final ObjectMapper mapper = new ObjectMapper(); +- +- @Override +- protected void setUp(ServletTester tester) { +- tester.addServlet(HealthCheckServlet.class, "/healthchecks"); +- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", registry); +- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".executor", threadPool); +- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".mapper", mapper); +- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter", +- (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); +- } +- +- @BeforeEach +- void setUp() { +- request.setMethod("GET"); +- request.setURI("/healthchecks"); +- request.setVersion("HTTP/1.0"); +- } +- +- @AfterEach +- void tearDown() { +- threadPool.shutdown(); +- } +- +- @Test +- void returns501IfNoHealthChecksAreRegistered() throws Exception { +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(501); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()).isEqualTo("{}"); +- } +- +- @Test +- void returnsA200IfAllHealthChecksAreHealthy() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()) +- .isEqualTo("{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + +- EXPECTED_TIMESTAMP + +- "\"}}"); ++ }; ++ ++ private final HealthCheckRegistry registry = new HealthCheckRegistry(); ++ private final ExecutorService threadPool = Executors.newCachedThreadPool(); ++ private final ObjectMapper mapper = new ObjectMapper(); ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.addServlet(HealthCheckServlet.class, "/healthchecks"); ++ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", registry); ++ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".executor", threadPool); ++ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".mapper", mapper); ++ tester.setAttribute( ++ HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter", ++ (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); ++ } ++ ++ @BeforeEach ++ void setUp() { ++ request.setMethod("GET"); ++ request.setURI("/healthchecks"); ++ request.setVersion("HTTP/1.0"); ++ } ++ ++ @AfterEach ++ void tearDown() { ++ threadPool.shutdown(); ++ } ++ ++ @Test ++ void returns501IfNoHealthChecksAreRegistered() throws Exception { ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(501); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()).isEqualTo("{}"); ++ } ++ ++ @Test ++ void returnsA200IfAllHealthChecksAreHealthy() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); ++ } ++ ++ @Test ++ void returnsASubsetOfHealthChecksIfFiltered() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); ++ registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); ++ } ++ ++ @Test ++ void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); ++ registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(500); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .contains( ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" ++ + EXPECTED_TIMESTAMP ++ + "\"}", ++ ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" ++ + EXPECTED_TIMESTAMP ++ + "\"}}"); ++ } ++ ++ @Test ++ void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); ++ registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); ++ request.setURI("/healthchecks?httpStatusIndicator=false"); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .contains( ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" ++ + EXPECTED_TIMESTAMP ++ + "\"}", ++ ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" ++ + EXPECTED_TIMESTAMP ++ + "\"}}"); ++ } ++ ++ @Test ++ void optionallyPrettyPrintsTheJson() throws Exception { ++ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); ++ ++ request.setURI("/healthchecks?pretty=true"); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", ++ EXPECTED_TIMESTAMP)); ++ } ++ ++ private static HealthCheck.Result healthyResultWithMessage(String message) { ++ return HealthCheck.Result.builder() ++ .healthy() ++ .withMessage(message) ++ .usingClock(FIXED_CLOCK) ++ .build(); ++ } ++ ++ private static HealthCheck.Result unhealthyResultWithMessage(String message) { ++ return HealthCheck.Result.builder() ++ .unhealthy() ++ .withMessage(message) ++ .usingClock(FIXED_CLOCK) ++ .build(); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); ++ healthCheckServlet.init(servletConfig); ++ ++ verify(servletConfig).getServletContext(); ++ verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn(healthCheckRegistry); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() ++ throws Exception { ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); ++ } ++ ++ @Test ++ void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() ++ throws Exception { ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn(registry); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_MAPPER)) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ ++ assertThat(healthCheckServlet.getMapper()).isNotNull().isInstanceOf(ObjectMapper.class); ++ } ++ ++ static class TestHealthCheck implements HealthCheck { ++ private final Callable check; ++ ++ public TestHealthCheck(Callable check) { ++ this.check = check; + } + +- @Test +- void returnsASubsetOfHealthChecksIfFiltered() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); +- registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()) +- .isEqualTo("{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + +- EXPECTED_TIMESTAMP + +- "\"}}"); +- } +- +- @Test +- void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); +- registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(500); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()).contains( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", +- ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); +- } +- +- @Test +- void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); +- registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); +- request.setURI("/healthchecks?httpStatusIndicator=false"); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()).contains( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", +- ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); +- } +- +- @Test +- void optionallyPrettyPrintsTheJson() throws Exception { +- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); +- +- request.setURI("/healthchecks?pretty=true"); +- +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); +- assertThat(response.getContent()) +- .isEqualTo(String.format("{%n" + +- " \"fun\" : {%n" + +- " \"healthy\" : true,%n" + +- " \"message\" : \"foo bar 123\",%n" + +- " \"duration\" : 0,%n" + +- " \"timestamp\" : \"" + EXPECTED_TIMESTAMP + "\"" + +- "%n }%n}")); +- } +- +- private static HealthCheck.Result healthyResultWithMessage(String message) { +- return HealthCheck.Result.builder() +- .healthy() +- .withMessage(message) +- .usingClock(FIXED_CLOCK) +- .build(); +- } +- +- private static HealthCheck.Result unhealthyResultWithMessage(String message) { +- return HealthCheck.Result.builder() +- .unhealthy() +- .withMessage(message) +- .usingClock(FIXED_CLOCK) +- .build(); +- } +- +- @Test +- void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); +- healthCheckServlet.init(servletConfig); +- +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); +- } +- +- @Test +- void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) +- .thenReturn(healthCheckRegistry); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); +- +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); +- } +- +- @Test +- void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { +- assertThrows(ServletException.class, () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) +- .thenReturn("IRELLEVANT_STRING"); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); +- }); +- } +- +- @Test +- void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)).thenReturn(registry); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_MAPPER)).thenReturn("IRELLEVANT_STRING"); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); +- +- assertThat(healthCheckServlet.getMapper()) +- .isNotNull() +- .isInstanceOf(ObjectMapper.class); ++ @Override ++ public Result check() throws Exception { ++ return check.call(); + } + +- static class TestHealthCheck implements HealthCheck { +- private final Callable check; +- +- public TestHealthCheck(Callable check) { +- this.check = check; +- } +- +- @Override +- public Result check() throws Exception { +- return check.call(); +- } +- +- @Override +- public Clock clock() { +- return FIXED_CLOCK; +- } ++ @Override ++ public Clock clock() { ++ return FIXED_CLOCK; + } +-} +\ No newline at end of file ++ } ++} +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Gauge; +@@ -7,166 +11,163 @@ import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; ++import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.when; +- +-class MetricsServletContextListenerTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); +- private final MetricRegistry registry = new MetricRegistry(); +- private final String allowedOrigin = "some.other.origin"; +- +- @Override +- protected void setUp(ServletTester tester) { +- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); +- tester.addServlet(MetricsServlet.class, "/metrics"); +- tester.getContext().addEventListener(new MetricsServlet.ContextListener() { +- @Override +- protected MetricRegistry getMetricRegistry() { ++final class MetricsServletContextListenerTest extends AbstractServletTest { ++ private final Clock clock = mock(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private final String allowedOrigin = "some.other.origin"; ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); ++ tester.addServlet(MetricsServlet.class, "/metrics"); ++ tester ++ .getContext() ++ .addEventListener( ++ new MetricsServlet.ContextListener() { ++ @Override ++ protected MetricRegistry getMetricRegistry() { + return registry; +- } ++ } + +- @Override +- protected TimeUnit getDurationUnit() { ++ @Override ++ protected TimeUnit getDurationUnit() { + return TimeUnit.MILLISECONDS; +- } ++ } + +- @Override +- protected TimeUnit getRateUnit() { ++ @Override ++ protected TimeUnit getRateUnit() { + return TimeUnit.MINUTES; +- } ++ } + +- @Override +- protected String getAllowedOrigin() { ++ @Override ++ protected String getAllowedOrigin() { + return allowedOrigin; +- } +- }); +- } +- +- @BeforeEach +- void setUp() { +- // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves +- // will call getTick again several times and always get the same value (the last specified here) +- when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); +- +- registry.register(MetricName.build("g1"), (Gauge) () -> 100L); +- registry.counter("c").inc(); +- registry.histogram("h").update(1); +- registry.register(MetricName.build("m"), new Meter(clock)).mark(); +- registry.register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) +- .update(1, TimeUnit.SECONDS); +- +- request.setMethod("GET"); +- request.setURI("/metrics"); +- request.setVersion("HTTP/1.0"); +- } +- +- @Test +- void returnsA200() throws Exception { +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo(allowedOrigin); +- assertThat(response.getContent()) +- .isEqualTo("{" + +- "\"version\":\"5.0.0\"," + +- "\"gauges\":{" + +- "\"g1\":{\"value\":100}" + +- "}," + +- "\"counters\":{" + +- "\"c\":{\"count\":1}" + +- "}," + +- "\"histograms\":{" + +- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + +- "}," + +- "\"meters\":{" + +- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":2.0E8,\"units\":\"events/minute\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1000.0,\"mean\":1000.0,\"min\":1000.0,\"p50\":1000.0,\"p75\":1000.0,\"p95\":1000.0,\"p98\":1000.0,\"p99\":1000.0,\"p999\":1000.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":6.0E8,\"duration_units\":\"milliseconds\",\"rate_units\":\"calls/minute\"}" + +- "}" + +- "}"); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void optionallyPrettyPrintsTheJson() throws Exception { +- request.setURI("/metrics?pretty=true"); +- +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo(allowedOrigin); +- assertThat(response.getContent()) +- .isEqualTo(String.format("{%n" + +- " \"version\" : \"5.0.0\",%n" + +- " \"gauges\" : {%n" + +- " \"g1\" : {%n" + +- " \"value\" : 100%n" + +- " }%n" + +- " },%n" + +- " \"counters\" : {%n" + +- " \"c\" : {%n" + +- " \"count\" : 1%n" + +- " }%n" + +- " },%n" + +- " \"histograms\" : {%n" + +- " \"h\" : {%n" + +- " \"count\" : 1,%n" + +- " \"max\" : 1,%n" + +- " \"mean\" : 1.0,%n" + +- " \"min\" : 1,%n" + +- " \"p50\" : 1.0,%n" + +- " \"p75\" : 1.0,%n" + +- " \"p95\" : 1.0,%n" + +- " \"p98\" : 1.0,%n" + +- " \"p99\" : 1.0,%n" + +- " \"p999\" : 1.0,%n" + +- " \"stddev\" : 0.0%n" + +- " }%n" + +- " },%n" + +- " \"meters\" : {%n" + +- " \"m\" : {%n" + +- " \"count\" : 1,%n" + +- " \"m15_rate\" : 0.0,%n" + +- " \"m1_rate\" : 0.0,%n" + +- " \"m5_rate\" : 0.0,%n" + +- " \"mean_rate\" : 2.0E8,%n" + +- " \"units\" : \"events/minute\"%n" + +- " }%n" + +- " },%n" + +- " \"timers\" : {%n" + +- " \"t\" : {%n" + +- " \"count\" : 1,%n" + +- " \"max\" : 1000.0,%n" + +- " \"mean\" : 1000.0,%n" + +- " \"min\" : 1000.0,%n" + +- " \"p50\" : 1000.0,%n" + +- " \"p75\" : 1000.0,%n" + +- " \"p95\" : 1000.0,%n" + +- " \"p98\" : 1000.0,%n" + +- " \"p99\" : 1000.0,%n" + +- " \"p999\" : 1000.0,%n" + +- " \"stddev\" : 0.0,%n" + +- " \"m15_rate\" : 0.0,%n" + +- " \"m1_rate\" : 0.0,%n" + +- " \"m5_rate\" : 0.0,%n" + +- " \"mean_rate\" : 6.0E8,%n" + +- " \"duration_units\" : \"milliseconds\",%n" + +- " \"rate_units\" : \"calls/minute\"%n" + +- " }%n" + +- " }%n" + +- "}")); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } ++ } ++ }); ++ } ++ ++ @BeforeEach ++ void setUp() { ++ // provide ticks for the setup (calls getTick 6 times). The serialization in the tests ++ // themselves ++ // will call getTick again several times and always get the same value (the last specified here) ++ when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); ++ ++ registry.register(MetricName.build("g1"), (Gauge) () -> 100L); ++ registry.counter("c").inc(); ++ registry.histogram("h").update(1); ++ registry.register(MetricName.build("m"), new Meter(clock)).mark(); ++ registry ++ .register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) ++ .update(1, TimeUnit.SECONDS); ++ ++ request.setMethod("GET"); ++ request.setURI("/metrics"); ++ request.setVersion("HTTP/1.0"); ++ } ++ ++ @Test ++ void returnsA200() throws Exception { ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo(allowedOrigin); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{" ++ + "\"version\":\"5.0.0\"," ++ + "\"gauges\":{" ++ + "\"g1\":{\"value\":100}" ++ + "}," ++ + "\"counters\":{" ++ + "\"c\":{\"count\":1}" ++ + "}," ++ + "\"histograms\":{" ++ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" ++ + "}," ++ + "\"meters\":{" ++ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":2.0E8,\"units\":\"events/minute\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1000.0,\"mean\":1000.0,\"min\":1000.0,\"p50\":1000.0,\"p75\":1000.0,\"p95\":1000.0,\"p98\":1000.0,\"p99\":1000.0,\"p999\":1000.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":6.0E8,\"duration_units\":\"milliseconds\",\"rate_units\":\"calls/minute\"}" ++ + "}" ++ + "}"); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void optionallyPrettyPrintsTheJson() throws Exception { ++ request.setURI("/metrics?pretty=true"); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo(allowedOrigin); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "{%n" ++ + " \"version\" : \"5.0.0\",%n" ++ + " \"gauges\" : {%n" ++ + " \"g1\" : {%n" ++ + " \"value\" : 100%n" ++ + " }%n" ++ + " },%n" ++ + " \"counters\" : {%n" ++ + " \"c\" : {%n" ++ + " \"count\" : 1%n" ++ + " }%n" ++ + " },%n" ++ + " \"histograms\" : {%n" ++ + " \"h\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"max\" : 1,%n" ++ + " \"mean\" : 1.0,%n" ++ + " \"min\" : 1,%n" ++ + " \"p50\" : 1.0,%n" ++ + " \"p75\" : 1.0,%n" ++ + " \"p95\" : 1.0,%n" ++ + " \"p98\" : 1.0,%n" ++ + " \"p99\" : 1.0,%n" ++ + " \"p999\" : 1.0,%n" ++ + " \"stddev\" : 0.0%n" ++ + " }%n" ++ + " },%n" ++ + " \"meters\" : {%n" ++ + " \"m\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"m15_rate\" : 0.0,%n" ++ + " \"m1_rate\" : 0.0,%n" ++ + " \"m5_rate\" : 0.0,%n" ++ + " \"mean_rate\" : 2.0E8,%n" ++ + " \"units\" : \"events/minute\"%n" ++ + " }%n" ++ + " },%n" ++ + " \"timers\" : {%n" ++ + " \"t\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"max\" : 1000.0,%n" ++ + " \"mean\" : 1000.0,%n" ++ + " \"min\" : 1000.0,%n" ++ + " \"p50\" : 1000.0,%n" ++ + " \"p75\" : 1000.0,%n" ++ + " \"p95\" : 1000.0,%n" ++ + " \"p98\" : 1000.0,%n" ++ + " \"p99\" : 1000.0,%n" ++ + " \"p999\" : 1000.0,%n" ++ + " \"stddev\" : 0.0,%n" ++ + " \"m15_rate\" : 0.0,%n" ++ + " \"m1_rate\" : 0.0,%n" ++ + " \"m5_rate\" : 0.0,%n" ++ + " \"mean_rate\" : 6.0E8,%n" ++ + " \"duration_units\" : \"milliseconds\",%n" ++ + " \"rate_units\" : \"calls/minute\"%n" ++ + " }%n" ++ + " }%n" ++ + "}")); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } + } +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +@@ -1,5 +1,12 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.never; ++import static org.mockito.Mockito.verify; ++import static org.mockito.Mockito.when; ++ + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Gauge; +@@ -7,261 +14,241 @@ import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Timer; ++import java.util.concurrent.TimeUnit; ++import javax.servlet.ServletConfig; ++import javax.servlet.ServletContext; ++import javax.servlet.ServletException; + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import javax.servlet.ServletConfig; +-import javax.servlet.ServletContext; +-import javax.servlet.ServletException; +-import java.util.concurrent.TimeUnit; +- +-import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.mockito.ArgumentMatchers.eq; +-import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; +-import static org.mockito.Mockito.verify; +-import static org.mockito.Mockito.when; +- +-class MetricsServletTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); +- private final MetricRegistry registry = new MetricRegistry(); +- private ServletTester tester; +- +- @Override +- protected void setUp(ServletTester tester) { +- this.tester = tester; +- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); +- tester.addServlet(MetricsServlet.class, "/metrics"); +- tester.getContext().setInitParameter("io.dropwizard.metrics5.servlets.MetricsServlet.allowedOrigin", "*"); +- } +- +- @BeforeEach +- void setUp() { +- // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves +- // will call getTick again several times and always get the same value (the last specified here) +- when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); +- +- registry.register(MetricName.build("g1"), (Gauge) () -> 100L); +- registry.counter("c").inc(); +- registry.histogram("h").update(1); +- registry.register(MetricName.build("m"), new Meter(clock)).mark(); +- registry.register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) +- .update(1, TimeUnit.SECONDS); +- +- request.setMethod("GET"); +- request.setURI("/metrics"); +- request.setVersion("HTTP/1.0"); +- } +- +- @Test +- void returnsA200() throws Exception { +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo("*"); +- assertThat(response.getContent()) +- .isEqualTo("{" + +- "\"version\":\"5.0.0\"," + +- "\"gauges\":{" + +- "\"g1\":{\"value\":100}" + +- "}," + +- "\"counters\":{" + +- "\"c\":{\"count\":1}" + +- "}," + +- "\"histograms\":{" + +- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + +- "}," + +- "\"meters\":{" + +- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + +- "}" + +- "}"); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void returnsJsonWhenJsonpInitParamNotSet() throws Exception { +- String callbackParamName = "callbackParam"; +- String callbackParamVal = "callbackParamVal"; +- request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo("*"); +- assertThat(response.getContent()) +- .isEqualTo("{" + +- "\"version\":\"5.0.0\"," + +- "\"gauges\":{" + +- "\"g1\":{\"value\":100}" + +- "}," + +- "\"counters\":{" + +- "\"c\":{\"count\":1}" + +- "}," + +- "\"histograms\":{" + +- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + +- "}," + +- "\"meters\":{" + +- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + +- "}" + +- "}"); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void returnsJsonpWhenInitParamSet() throws Exception { +- String callbackParamName = "callbackParam"; +- String callbackParamVal = "callbackParamVal"; +- request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); +- tester.getContext().setInitParameter("io.dropwizard.metrics5.servlets.MetricsServlet.jsonpCallback", callbackParamName); +- processRequest(); +- +- assertThat(response.getStatus()).isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo("*"); +- assertThat(response.getContent()) +- .isEqualTo(callbackParamVal + "({" + +- "\"version\":\"5.0.0\"," + +- "\"gauges\":{" + +- "\"g1\":{\"value\":100}" + +- "}," + +- "\"counters\":{" + +- "\"c\":{\"count\":1}" + +- "}," + +- "\"histograms\":{" + +- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + +- "}," + +- "\"meters\":{" + +- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + +- "}" + +- "})"); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void optionallyPrettyPrintsTheJson() throws Exception { +- request.setURI("/metrics?pretty=true"); +- +- processRequest(); +- +- assertThat(response.getStatus()) +- .isEqualTo(200); +- assertThat(response.get("Access-Control-Allow-Origin")) +- .isEqualTo("*"); +- assertThat(response.getContent()) +- .isEqualTo(String.format("{%n" + +- " \"version\" : \"5.0.0\",%n" + +- " \"gauges\" : {%n" + +- " \"g1\" : {%n" + +- " \"value\" : 100%n" + +- " }%n" + +- " },%n" + +- " \"counters\" : {%n" + +- " \"c\" : {%n" + +- " \"count\" : 1%n" + +- " }%n" + +- " },%n" + +- " \"histograms\" : {%n" + +- " \"h\" : {%n" + +- " \"count\" : 1,%n" + +- " \"max\" : 1,%n" + +- " \"mean\" : 1.0,%n" + +- " \"min\" : 1,%n" + +- " \"p50\" : 1.0,%n" + +- " \"p75\" : 1.0,%n" + +- " \"p95\" : 1.0,%n" + +- " \"p98\" : 1.0,%n" + +- " \"p99\" : 1.0,%n" + +- " \"p999\" : 1.0,%n" + +- " \"stddev\" : 0.0%n" + +- " }%n" + +- " },%n" + +- " \"meters\" : {%n" + +- " \"m\" : {%n" + +- " \"count\" : 1,%n" + +- " \"m15_rate\" : 0.0,%n" + +- " \"m1_rate\" : 0.0,%n" + +- " \"m5_rate\" : 0.0,%n" + +- " \"mean_rate\" : 3333333.3333333335,%n" + +- " \"units\" : \"events/second\"%n" + +- " }%n" + +- " },%n" + +- " \"timers\" : {%n" + +- " \"t\" : {%n" + +- " \"count\" : 1,%n" + +- " \"max\" : 1.0,%n" + +- " \"mean\" : 1.0,%n" + +- " \"min\" : 1.0,%n" + +- " \"p50\" : 1.0,%n" + +- " \"p75\" : 1.0,%n" + +- " \"p95\" : 1.0,%n" + +- " \"p98\" : 1.0,%n" + +- " \"p99\" : 1.0,%n" + +- " \"p999\" : 1.0,%n" + +- " \"stddev\" : 0.0,%n" + +- " \"m15_rate\" : 0.0,%n" + +- " \"m1_rate\" : 0.0,%n" + +- " \"m5_rate\" : 0.0,%n" + +- " \"mean_rate\" : 1.0E7,%n" + +- " \"duration_units\" : \"seconds\",%n" + +- " \"rate_units\" : \"calls/second\"%n" + +- " }%n" + +- " }%n" + +- "}")); +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("application/json"); +- } +- +- @Test +- void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- +- final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); +- metricsServlet.init(servletConfig); +- +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); +- } +- +- @Test +- void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn(metricRegistry); +- +- final MetricsServlet metricsServlet = new MetricsServlet(null); +- metricsServlet.init(servletConfig); +- +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); +- } +- +- @Test +- void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { +- assertThrows(ServletException.class, () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn("IRELLEVANT_STRING"); +- +- final MetricsServlet metricsServlet = new MetricsServlet(null); +- metricsServlet.init(servletConfig); +- }); +- } ++final class MetricsServletTest extends AbstractServletTest { ++ private final Clock clock = mock(); ++ private final MetricRegistry registry = new MetricRegistry(); ++ private ServletTester tester; ++ ++ @Override ++ protected void setUp(ServletTester tester) { ++ this.tester = tester; ++ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); ++ tester.addServlet(MetricsServlet.class, "/metrics"); ++ tester ++ .getContext() ++ .setInitParameter("io.dropwizard.metrics5.servlets.MetricsServlet.allowedOrigin", "*"); ++ } ++ ++ @BeforeEach ++ void setUp() { ++ // provide ticks for the setup (calls getTick 6 times). The serialization in the tests ++ // themselves ++ // will call getTick again several times and always get the same value (the last specified here) ++ when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); ++ ++ registry.register(MetricName.build("g1"), (Gauge) () -> 100L); ++ registry.counter("c").inc(); ++ registry.histogram("h").update(1); ++ registry.register(MetricName.build("m"), new Meter(clock)).mark(); ++ registry ++ .register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) ++ .update(1, TimeUnit.SECONDS); ++ ++ request.setMethod("GET"); ++ request.setURI("/metrics"); ++ request.setVersion("HTTP/1.0"); ++ } ++ ++ @Test ++ void returnsA200() throws Exception { ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{" ++ + "\"version\":\"5.0.0\"," ++ + "\"gauges\":{" ++ + "\"g1\":{\"value\":100}" ++ + "}," ++ + "\"counters\":{" ++ + "\"c\":{\"count\":1}" ++ + "}," ++ + "\"histograms\":{" ++ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" ++ + "}," ++ + "\"meters\":{" ++ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" ++ + "}" ++ + "}"); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void returnsJsonWhenJsonpInitParamNotSet() throws Exception { ++ String callbackParamName = "callbackParam"; ++ String callbackParamVal = "callbackParamVal"; ++ request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "{" ++ + "\"version\":\"5.0.0\"," ++ + "\"gauges\":{" ++ + "\"g1\":{\"value\":100}" ++ + "}," ++ + "\"counters\":{" ++ + "\"c\":{\"count\":1}" ++ + "}," ++ + "\"histograms\":{" ++ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" ++ + "}," ++ + "\"meters\":{" ++ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" ++ + "}" ++ + "}"); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void returnsJsonpWhenInitParamSet() throws Exception { ++ String callbackParamName = "callbackParam"; ++ String callbackParamVal = "callbackParamVal"; ++ request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); ++ tester ++ .getContext() ++ .setInitParameter( ++ "io.dropwizard.metrics5.servlets.MetricsServlet.jsonpCallback", callbackParamName); ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ "%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", ++ callbackParamVal); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void optionallyPrettyPrintsTheJson() throws Exception { ++ request.setURI("/metrics?pretty=true"); ++ ++ processRequest(); ++ ++ assertThat(response.getStatus()).isEqualTo(200); ++ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); ++ assertThat(response.getContent()) ++ .isEqualTo( ++ String.format( ++ "{%n" ++ + " \"version\" : \"5.0.0\",%n" ++ + " \"gauges\" : {%n" ++ + " \"g1\" : {%n" ++ + " \"value\" : 100%n" ++ + " }%n" ++ + " },%n" ++ + " \"counters\" : {%n" ++ + " \"c\" : {%n" ++ + " \"count\" : 1%n" ++ + " }%n" ++ + " },%n" ++ + " \"histograms\" : {%n" ++ + " \"h\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"max\" : 1,%n" ++ + " \"mean\" : 1.0,%n" ++ + " \"min\" : 1,%n" ++ + " \"p50\" : 1.0,%n" ++ + " \"p75\" : 1.0,%n" ++ + " \"p95\" : 1.0,%n" ++ + " \"p98\" : 1.0,%n" ++ + " \"p99\" : 1.0,%n" ++ + " \"p999\" : 1.0,%n" ++ + " \"stddev\" : 0.0%n" ++ + " }%n" ++ + " },%n" ++ + " \"meters\" : {%n" ++ + " \"m\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"m15_rate\" : 0.0,%n" ++ + " \"m1_rate\" : 0.0,%n" ++ + " \"m5_rate\" : 0.0,%n" ++ + " \"mean_rate\" : 3333333.3333333335,%n" ++ + " \"units\" : \"events/second\"%n" ++ + " }%n" ++ + " },%n" ++ + " \"timers\" : {%n" ++ + " \"t\" : {%n" ++ + " \"count\" : 1,%n" ++ + " \"max\" : 1.0,%n" ++ + " \"mean\" : 1.0,%n" ++ + " \"min\" : 1.0,%n" ++ + " \"p50\" : 1.0,%n" ++ + " \"p75\" : 1.0,%n" ++ + " \"p95\" : 1.0,%n" ++ + " \"p98\" : 1.0,%n" ++ + " \"p99\" : 1.0,%n" ++ + " \"p999\" : 1.0,%n" ++ + " \"stddev\" : 0.0,%n" ++ + " \"m15_rate\" : 0.0,%n" ++ + " \"m1_rate\" : 0.0,%n" ++ + " \"m5_rate\" : 0.0,%n" ++ + " \"mean_rate\" : 1.0E7,%n" ++ + " \"duration_units\" : \"seconds\",%n" ++ + " \"rate_units\" : \"calls/second\"%n" ++ + " }%n" ++ + " }%n" ++ + "}")); ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ ++ final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); ++ metricsServlet.init(servletConfig); ++ ++ verify(servletConfig).getServletContext(); ++ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); ++ ++ final MetricsServlet metricsServlet = new MetricsServlet(null); ++ metricsServlet.init(servletConfig); ++ ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); ++ } ++ ++ @Test ++ void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() ++ throws Exception { ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final MetricsServlet metricsServlet = new MetricsServlet(null); ++ metricsServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); ++ } + } +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +@@ -1,49 +1,45 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class PingServletTest extends AbstractServletTest { +- @Override +- protected void setUp(ServletTester tester) { +- tester.addServlet(PingServlet.class, "/ping"); +- } +- +- @BeforeEach +- void setUp() throws Exception { +- request.setMethod("GET"); +- request.setURI("/ping"); +- request.setVersion("HTTP/1.0"); +- +- processRequest(); +- } +- +- @Test +- void returns200OK() { +- assertThat(response.getStatus()) +- .isEqualTo(200); +- } +- +- @Test +- void returnsPong() { +- assertThat(response.getContent()) +- .isEqualTo(String.format("pong%n")); +- } +- +- @Test +- void returnsTextPlain() { +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("text/plain;charset=ISO-8859-1"); +- } +- +- @Test +- void returnsUncacheable() { +- assertThat(response.get(HttpHeader.CACHE_CONTROL)) +- .isEqualTo("must-revalidate,no-cache,no-store"); +- +- } ++final class PingServletTest extends AbstractServletTest { ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.addServlet(PingServlet.class, "/ping"); ++ } ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ request.setMethod("GET"); ++ request.setURI("/ping"); ++ request.setVersion("HTTP/1.0"); ++ ++ processRequest(); ++ } ++ ++ @Test ++ void returns200OK() { ++ assertThat(response.getStatus()).isEqualTo(200); ++ } ++ ++ @Test ++ void returnsPong() { ++ assertThat(response.getContent()).isEqualTo(String.format("pong%n")); ++ } ++ ++ @Test ++ void returnsTextPlain() { ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/plain;charset=ISO-8859-1"); ++ } ++ ++ @Test ++ void returnsUncacheable() { ++ assertThat(response.get(HttpHeader.CACHE_CONTROL)) ++ .isEqualTo("must-revalidate,no-cache,no-store"); ++ } + } +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +@@ -1,49 +1,45 @@ + package io.dropwizard.metrics5.servlets; + ++import static org.assertj.core.api.Assertions.assertThat; ++ + import org.eclipse.jetty.http.HttpHeader; + import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-import static org.assertj.core.api.Assertions.assertThat; +- +-class ThreadDumpServletTest extends AbstractServletTest { +- @Override +- protected void setUp(ServletTester tester) { +- tester.addServlet(ThreadDumpServlet.class, "/threads"); +- } +- +- @BeforeEach +- void setUp() throws Exception { +- request.setMethod("GET"); +- request.setURI("/threads"); +- request.setVersion("HTTP/1.0"); +- +- processRequest(); +- } +- +- @Test +- void returns200OK() { +- assertThat(response.getStatus()) +- .isEqualTo(200); +- } +- +- @Test +- void returnsAThreadDump() { +- assertThat(response.getContent()) +- .contains("Finalizer"); +- } +- +- @Test +- void returnsTextPlain() { +- assertThat(response.get(HttpHeader.CONTENT_TYPE)) +- .isEqualTo("text/plain"); +- } +- +- @Test +- void returnsUncacheable() { +- assertThat(response.get(HttpHeader.CACHE_CONTROL)) +- .isEqualTo("must-revalidate,no-cache,no-store"); +- +- } ++final class ThreadDumpServletTest extends AbstractServletTest { ++ @Override ++ protected void setUp(ServletTester tester) { ++ tester.addServlet(ThreadDumpServlet.class, "/threads"); ++ } ++ ++ @BeforeEach ++ void setUp() throws Exception { ++ request.setMethod("GET"); ++ request.setURI("/threads"); ++ request.setVersion("HTTP/1.0"); ++ ++ processRequest(); ++ } ++ ++ @Test ++ void returns200OK() { ++ assertThat(response.getStatus()).isEqualTo(200); ++ } ++ ++ @Test ++ void returnsAThreadDump() { ++ assertThat(response.getContent()).contains("Finalizer"); ++ } ++ ++ @Test ++ void returnsTextPlain() { ++ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/plain"); ++ } ++ ++ @Test ++ void returnsUncacheable() { ++ assertThat(response.get(HttpHeader.CACHE_CONTROL)) ++ .isEqualTo("must-revalidate,no-cache,no-store"); ++ } + } +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/experiments/ExampleServer.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/experiments/ExampleServer.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.servlets.experiments; + ++import static io.dropwizard.metrics5.MetricRegistry.name; ++ + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricRegistry; +@@ -18,43 +20,48 @@ import org.eclipse.jetty.servlet.ServletContextHandler; + import org.eclipse.jetty.servlet.ServletHolder; + import org.eclipse.jetty.util.thread.ThreadPool; + +-import static io.dropwizard.metrics5.MetricRegistry.name; +- + public class ExampleServer { +- private static final MetricRegistry REGISTRY = new MetricRegistry(); +- private static final Counter COUNTER_1 = REGISTRY.counter(name(ExampleServer.class, "wah", "doody")); +- private static final Counter COUNTER_2 = REGISTRY.counter(name(ExampleServer.class, "woo")); ++ private static final MetricRegistry REGISTRY = new MetricRegistry(); ++ private static final Counter COUNTER_1 = ++ REGISTRY.counter(name(ExampleServer.class, "wah", "doody")); ++ private static final Counter COUNTER_2 = REGISTRY.counter(name(ExampleServer.class, "woo")); + +- static { +- REGISTRY.register(name(ExampleServer.class, "boo"), (Gauge) () -> { +- throw new RuntimeException("asplode!"); +- }); +- } ++ static { ++ REGISTRY.register( ++ name(ExampleServer.class, "boo"), ++ (Gauge) ++ () -> { ++ throw new RuntimeException("asplode!"); ++ }); ++ } + +- public static void main(String[] args) throws Exception { +- COUNTER_1.inc(); +- COUNTER_2.inc(); ++ public static void main(String[] args) throws Exception { ++ COUNTER_1.inc(); ++ COUNTER_2.inc(); + +- final ThreadPool threadPool = new InstrumentedQueuedThreadPool(REGISTRY); +- final Server server = new Server(threadPool); ++ final ThreadPool threadPool = new InstrumentedQueuedThreadPool(REGISTRY); ++ final Server server = new Server(threadPool); + +- final Connector connector = new ServerConnector(server, new InstrumentedConnectionFactory( ++ final Connector connector = ++ new ServerConnector( ++ server, ++ new InstrumentedConnectionFactory( + new HttpConnectionFactory(), REGISTRY.timer("http.connection"))); +- server.addConnector(connector); ++ server.addConnector(connector); + +- final ServletContextHandler context = new ServletContextHandler(); +- context.setContextPath("/initial"); +- context.setAttribute(MetricsServlet.METRICS_REGISTRY, REGISTRY); +- context.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, new HealthCheckRegistry()); ++ final ServletContextHandler context = new ServletContextHandler(); ++ context.setContextPath("/initial"); ++ context.setAttribute(MetricsServlet.METRICS_REGISTRY, REGISTRY); ++ context.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, new HealthCheckRegistry()); + +- final ServletHolder holder = new ServletHolder(new AdminServlet()); +- context.addServlet(holder, "/dingo/*"); ++ final ServletHolder holder = new ServletHolder(new AdminServlet()); ++ context.addServlet(holder, "/dingo/*"); + +- final InstrumentedHandler handler = new InstrumentedHandler(REGISTRY); +- handler.setHandler(context); +- server.setHandler(handler); ++ final InstrumentedHandler handler = new InstrumentedHandler(REGISTRY); ++ handler.setHandler(context); ++ server.setHandler(handler); + +- server.start(); +- server.join(); +- } ++ server.start(); ++ server.join(); ++ } + } diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index 93deb90769..e69de29bb2 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -1,287 +0,0 @@ -metrics-annotation/src/main/java/com/codahale/metrics/annotation/CachedGauge.java:[32,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/CachedGauge.java:[37,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/CachedGauge.java:[43,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/CachedGauge.java:[48,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Counted.java:[39,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Counted.java:[44,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Counted.java:[51,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/ExceptionMetered.java:[55,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/ExceptionMetered.java:[61,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/ExceptionMetered.java:[68,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Gauge.java:[27,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Gauge.java:[32,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Metered.java:[36,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Metered.java:[41,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Metric.java:[39,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Metric.java:[44,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/ResponseMetered.java:[37,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/ResponseMetered.java:[42,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/ResponseMetered.java:[49,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Timed.java:[36,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-annotation/src/main/java/com/codahale/metrics/annotation/Timed.java:[41,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-benchmarks/src/main/java/com/codahale/metrics/benchmarks/SlidingTimeWindowReservoirsBenchmark.java:[21,3] [MissingSummary] A summary line is required on public/protected Javadocs. -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[3,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[4,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[5,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[6,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[7,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,21] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,27] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,33] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,39] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,45] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,51] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,57] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,63] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,69] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,75] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,81] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,87] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,93] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,99] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[8,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[9,15] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-benchmarks/target/generated-sources/annotations/com/codahale/metrics/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B3.java:[9,9] [HidingField] Hiding fields of superclasses may cause confusion and errors. This field is hiding a field of the same name in superclass: ReservoirBenchmark_jmhType_B1 -metrics-caffeine/src/test/java/com/codahale/metrics/caffeine/MetricsStatsCounterTest.java:[89,9] [deprecation] recordEviction() in MetricsStatsCounter has been deprecated -metrics-caffeine/src/test/java/com/codahale/metrics/caffeine/MetricsStatsCounterTest.java:[96,9] [deprecation] recordEviction(int) in MetricsStatsCounter has been deprecated -metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[193,13] [InconsistentCapitalization] Found the field 'hostName' with the same name as the parameter 'hostname' but with different capitalization. -metrics-collectd/src/main/java/com/codahale/metrics/collectd/CollectdReporter.java:[305,14] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[160,12] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[165,11] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[171,17] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[196,8] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[199,21] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[202,11] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/PacketWriter.java:[248,36] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/com/codahale/metrics/collectd/Sanitize.java:[7,3] [MissingSummary] A summary fragment is required; consider using the value of the @see block as a summary fragment instead. -metrics-collectd/src/test/java/com/codahale/metrics/collectd/Receiver.java:[51,16] [CatchAndPrintStackTrace] Logging or rethrowing exceptions should usually be preferred to catching and calling printStackTrace -metrics-collectd/src/test/java/com/codahale/metrics/collectd/SanitizeTest.java:[26,41] [UnnecessaryParentheses] These grouping parentheses are unnecessary; it is unlikely the code will be misinterpreted without them -metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java:[239,46] [JavaUtilDate] Date has a bad API that leads to bugs; prefer java.time.Instant or LocalDate. -metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java:[406,43] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-core/src/main/java/com/codahale/metrics/ConsoleReporter.java:[413,43] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-core/src/main/java/com/codahale/metrics/CsvReporter.java:[310,39] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-core/src/main/java/com/codahale/metrics/CsvReporter.java:[312,39] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-core/src/main/java/com/codahale/metrics/CsvReporter.java:[382,35] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-core/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java:[196,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement -metrics-core/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java:[218,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement -metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java:[329,29] [TypeParameterUnusedInFormals] Declaring a type parameter that is only used in the return type is a misuse of generics: operations on the type parameter are unchecked, it hides unsafe casts at invocations of the method, and it interacts badly with method overload resolution. -metrics-core/src/main/java/com/codahale/metrics/MovingAverages.java:[26,5] [EmptyBlockTag] A block tag (@param, @return, @throws, @deprecated) has an empty description. Block tags without descriptions don't add much value for future readers of the code; consider removing the tag entirely or adding a description. -metrics-core/src/main/java/com/codahale/metrics/NoopMetricRegistry.java:[102,29] [TypeParameterUnusedInFormals] Declaring a type parameter that is only used in the return type is a misuse of generics: operations on the type parameter are unchecked, it hides unsafe casts at invocations of the method, and it interacts badly with method overload resolution. -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[37,12] [removal] SecurityManager in java.lang has been deprecated and marked for removal -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[37,38] [removal] getSecurityManager() in System has been deprecated and marked for removal -metrics-core/src/main/java/com/codahale/metrics/ScheduledReporter.java:[47,21] [ThreadPriorityCheck] Relying on the thread scheduler is discouraged. -metrics-core/src/main/java/com/codahale/metrics/Slf4jReporter.java:[183,29] [InvalidInlineTag] Curly braces should be used for inline Javadoc tags: {@link ...} -metrics-core/src/main/java/com/codahale/metrics/WeightedSnapshot.java:[76,26] [UnnecessaryParentheses] These grouping parentheses are unnecessary; it is unlikely the code will be misinterpreted without them -metrics-core/src/test/java/com/codahale/metrics/ClockTest.java:[14,75] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-core/src/test/java/com/codahale/metrics/ClockTest.java:[16,66] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java:[37,19] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java:[48,19] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-core/src/test/java/com/codahale/metrics/MeterApproximationTest.java:[59,19] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[230,41] [DirectInvocationOnMock] Methods should not be directly invoked on the mock `mockExecutor`. Should this be part of a verify(..) call? -metrics-core/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[231,39] [DirectInvocationOnMock] Methods should not be directly invoked on the mock `mockExecutor`. Should this be part of a verify(..) call? -metrics-core/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[12,62] [deprecation] none() in ExpectedException has been deprecated -metrics-core/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[88,15] [UnnecessaryAsync] Variables which are initialized and do not escape the current scope do not need to worry about concurrency. Using the non-concurrent type will reduce overhead and verbosity. -metrics-core/src/test/java/com/codahale/metrics/UniformSnapshotTest.java:[128,30] [DefaultCharset] Implicit use of the platform default charset, which can result in differing behaviour between JVM executions or incorrect behavior if the encoding of the data source doesn't match expectations. -metrics-core/src/test/java/com/codahale/metrics/WeightedSnapshotTest.java:[136,30] [DefaultCharset] Implicit use of the platform default charset, which can result in differing behaviour between JVM executions or incorrect behavior if the encoding of the data source doesn't match expectations. -metrics-graphite/src/main/java/com/codahale/metrics/graphite/Graphite.java:[129,57] [OperatorPrecedence] Use grouping parenthesis to make the operator precedence explicit -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[253,46] [UnnecessaryLambda] Returning a lambda from a helper method or saving it in a constant is unnecessary; prefer to implement the functional interface method directly and use a method reference instead. -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[431,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[436,19] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[449,20] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[456,60] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-graphite/src/main/java/com/codahale/metrics/graphite/GraphiteReporter.java:[458,60] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java:[140,65] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java:[30,66] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteTest.java:[59,26] [DirectInvocationOnMock] Methods should not be directly invoked on the mock `socket`. Should this be part of a verify(..) call? -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java:[25,73] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java:[35,49] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java:[40,60] [StringCharset] StringCharset -metrics-graphite/src/test/java/com/codahale/metrics/graphite/GraphiteUDPTest.java:[41,34] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address -metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java:[36,66] [AddressSelection] Prefer InetAddress.getAllByName to APIs that convert a hostname to a single IP address -metrics-graphite/src/test/java/com/codahale/metrics/graphite/PickledGraphiteTest.java:[68,26] [DirectInvocationOnMock] Methods should not be directly invoked on the mock `socket`. Should this be part of a verify(..) call? -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[203,19] [EqualsGetClass] Prefer instanceof to getClass when implementing Object#equals. -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[222,32] [UnnecessaryParentheses] These grouping parentheses are unnecessary; it is unlikely the code will be misinterpreted without them -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[318,25] [AnnotateFormatMethod] This method uses a pair of parameters as a format string and its arguments, but the enclosing method wasn't annotated @FormatMethod. Doing so gives compile-time rather than run-time protection against malformed format strings. -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[55,25] [AnnotateFormatMethod] This method uses a pair of parameters as a format string and its arguments, but the enclosing method wasn't annotated @FormatMethod. Doing so gives compile-time rather than run-time protection against malformed format strings. -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java:[79,25] [AnnotateFormatMethod] This method uses a pair of parameters as a format string and its arguments, but the enclosing method wasn't annotated @FormatMethod. Doing so gives compile-time rather than run-time protection against malformed format strings. -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[269,32] [removal] getSecurityManager() in System has been deprecated and marked for removal -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[269,6] [removal] SecurityManager in java.lang has been deprecated and marked for removal -metrics-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java:[278,64] [ThreadPriorityCheck] Relying on the thread scheduler is discouraged. -metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[189,46] [JavaTimeDefaultTimeZone] ZonedDateTime.now() is not allowed because it silently uses the system default time-zone. You must pass an explicit time-zone (e.g., ZoneId.of("America/Los_Angeles")) to this method. -metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone -metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[203,46] [JavaTimeDefaultTimeZone] ZonedDateTime.now() is not allowed because it silently uses the system default time-zone. You must pass an explicit time-zone (e.g., ZoneId.of("America/Los_Angeles")) to this method. -metrics-healthchecks/src/test/java/com/codahale/metrics/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone -metrics-healthchecks/src/test/java/com/codahale/metrics/health/SharedHealthCheckRegistriesTest.java:[13,70] [deprecation] none() in ExpectedException has been deprecated -metrics-httpasyncclient/src/test/java/com/codahale/metrics/httpasyncclient/HttpClientTestBase.java:[24,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-httpclient/src/main/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategies.java:[43,59] [StringCaseLocaleUsage] Specify a `Locale` when calling `String#to{Lower,Upper}Case`. (Note: there are multiple suggested fixes; the third may be most appropriate if you're dealing with ASCII Strings.) -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[101,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[112,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[120,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[31,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[38,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[45,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[54,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[63,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[70,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[78,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[86,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient/src/test/java/com/codahale/metrics/httpclient/HttpClientMetricNameStrategiesTest.java:[94,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[23,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[30,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[37,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[44,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[53,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[62,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[69,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[80,4] [deprecation] assertThat(T,Matcher) in Assert has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/HttpClientMetricNameStrategiesTest.java:[88,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[126,8] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[182,10] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[26,47] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpAsyncClientsTest.java:[77,8] [deprecation] SimpleHttpRequests in org.apache.hc.client5.http.async.methods has been deprecated -metrics-httpclient5/src/test/java/com/codahale/metrics/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics/servlet/InstrumentedFilterContextListener.java:[14,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/AdminServlet.java:[32,30] [InlineFormatString] Prefer to create format strings inline, instead of extracting them to a single-use constant -metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java:[26,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java:[31,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/HealthCheckServlet.java:[40,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java:[32,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java:[37,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java:[46,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java:[55,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[104,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[145,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[219,25] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[30,67] [JavaTimeDefaultTimeZone] ZonedDateTime.now() is not allowed because it silently uses the system default time-zone. You must pass an explicit time-zone (e.g., ZoneId.of("America/Los_Angeles")) to this method. -metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/HealthCheckServletTest.java:[30,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone -metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics/servlets/MetricsServletTest.java:[130,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[1] [DefaultPackage] Java classes shouldn't use default package -metrics-jdbi3/src/main/java/com/codahale/metrics/jdbi3/InstrumentedTimingCollector.java:[9,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated -metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/SmartNameStrategyTest.java:[17,10] [deprecation] InstrumentedTimingCollector in com.codahale.metrics.jdbi3 has been deprecated -metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/SmartNameStrategyTest.java:[23,20] [deprecation] InstrumentedTimingCollector in com.codahale.metrics.jdbi3 has been deprecated -metrics-jdbi3/src/test/java/com/codahale/metrics/jdbi3/strategies/SmartNameStrategyTest.java:[8,33] [deprecation] InstrumentedTimingCollector in com.codahale.metrics.jdbi3 has been deprecated -metrics-jersey2/src/main/java/com/codahale/metrics/jersey2/InstrumentedResourceMethodApplicationListener.java:[582,19] [EqualsGetClass] Prefer instanceof to getClass when implementing Object#equals. -metrics-jersey3/src/main/java/com/codahale/metrics/jersey3/InstrumentedResourceMethodApplicationListener.java:[582,19] [EqualsGetClass] Prefer instanceof to getClass when implementing Object#equals. -metrics-jersey31/src/main/java/io/dropwizard/metrics/jersey31/InstrumentedResourceMethodApplicationListener.java:[582,19] [EqualsGetClass] Prefer instanceof to getClass when implementing Object#equals. -metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java:[134,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jetty10/src/test/java/io/dropwizard/metrics/jetty10/InstrumentedHandlerTest.java:[138,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java:[136,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java:[140,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java:[136,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jetty9/src/test/java/com/codahale/metrics/jetty9/InstrumentedHandlerTest.java:[140,44] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jmx/src/main/java/com/codahale/metrics/jmx/DefaultObjectNameFactory.java:[18,45] [JdkObsolete] Hashtable performs synchronization this is usually unnecessary; prefer LinkedHashMap. -metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[131,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[20,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[28,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[43,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[62,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-json/src/test/java/com/codahale/metrics/json/HealthCheckModuleTest.java:[90,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-jvm/src/main/java/com/codahale/metrics/jvm/FileDescriptorRatioGauge.java:[42,55] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/main/java/com/codahale/metrics/jvm/FileDescriptorRatioGauge.java:[42,91] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[107,31] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[107,56] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[77,41] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[77,57] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[93,29] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/main/java/com/codahale/metrics/jvm/MemoryUsageGaugeSet.java:[93,54] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/main/java/com/codahale/metrics/jvm/ThreadStatesGaugeSet.java:[47,43] [StringCaseLocaleUsage] Specify a `Locale` when calling `String#to{Lower,Upper}Case`. (Note: there are multiple suggested fixes; the third may be most appropriate if you're dealing with ASCII Strings.) -metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java:[15,75] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/test/java/com/codahale/metrics/jvm/CpuTimeClockTest.java:[19,71] [LongDoubleConversion] Conversion from long to double may lose precision; use an explicit cast to double if this was intentional -metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[55,10] [removal] AccessController in java.security has been deprecated and marked for removal -metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[67,36] [URLEqualsHashCode] Avoid hash-based containers of java.net.URL--the containers rely on equals() and hashCode(), which cause java.net.URL to make blocking internet connections. -metrics-jvm/src/test/java/com/codahale/metrics/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java:[9,20] [removal] AccessController in java.security has been deprecated and marked for removal -metrics-jvm/src/test/java/com/codahale/metrics/jvm/ThreadDumpTest.java:[42,30] [DefaultCharset] Implicit use of the platform default charset, which can result in differing behaviour between JVM executions or incorrect behavior if the encoding of the data source doesn't match expectations. -metrics-log4j2/src/main/java/com/codahale/metrics/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -metrics-log4j2/src/main/java/com/codahale/metrics/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -metrics-servlet/src/main/java/com/codahale/metrics/servlet/InstrumentedFilterContextListener.java:[14,5] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-servlets/src/main/java/com/codahale/metrics/servlets/AdminServlet.java:[32,30] [InlineFormatString] Prefer to create format strings inline, instead of extracting them to a single-use constant -metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java:[26,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java:[31,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java:[40,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-servlets/src/main/java/com/codahale/metrics/servlets/HealthCheckServlet.java:[48,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java:[32,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java:[37,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java:[46,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java:[55,7] [MissingSummary] A summary fragment is required; consider using the value of the @return block as a summary fragment instead. -metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[112,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[170,25] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[31,67] [JavaTimeDefaultTimeZone] ZonedDateTime.now() is not allowed because it silently uses the system default time-zone. You must pass an explicit time-zone (e.g., ZoneId.of("America/Los_Angeles")) to this method. -metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone -metrics-servlets/src/test/java/com/codahale/metrics/servlets/HealthCheckServletTest.java:[96,18] [FormatStringConcatenation] Defer string concatenation to the invoked method -metrics-servlets/src/test/java/com/codahale/metrics/servlets/MetricsServletTest.java:[130,18] [FormatStringConcatenation] Defer string concatenation to the invoked method diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index 9a00955441..b4401ee861 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -1,7 +1,36 @@ -diff --git a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java -index a248dd8..4e7f053 100644 ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics/servlets/MetricsServlet.java +diff --git a/metrics-caffeine3/pom.xml b/metrics-caffeine3/pom.xml +index 1e7c155..fd441a4 100644 +--- a/metrics-caffeine3/pom.xml ++++ b/metrics-caffeine3/pom.xml +@@ -35,6 +35,12 @@ + com.github.ben-manes.caffeine + caffeine + 3.1.8 ++ ++ ++ com.google.errorprone ++ error_prone_annotations ++ ++ + + + org.checkerframework +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +index a9d5984..dd9ecd5 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +@@ -231,6 +231,7 @@ public class CsvReporterTest { + return builder.toString(); + } + ++ @SuppressWarnings("FilesReadStringWithCharset") + private String fileContents(String filename) throws IOException { + return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); + } +diff --git a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +index 195619b..5584f91 100644 +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java @@ -188,6 +188,7 @@ public class MetricsServlet extends HttpServlet { return mapper.writer(); } @@ -10,11 +39,24 @@ index a248dd8..4e7f053 100644 protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { try { return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); -diff --git a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java -index 0bd1297..7c69a08 100644 ---- a/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java -+++ b/metrics-servlets/src/main/java/com/codahale/metrics/servlets/MetricsServlet.java -@@ -189,6 +189,7 @@ public class MetricsServlet extends HttpServlet { +diff --git a/metrics-jcstress/pom.xml b/metrics-jcstress/pom.xml +index b02832d..d9be879 100644 +--- a/metrics-jcstress/pom.xml ++++ b/metrics-jcstress/pom.xml +@@ -41,7 +41,7 @@ + +- 1.8 ++ 17 + + ++ ++ ++ com.google.guava ++ guava ++ 33.3.1-jre ++ ++ ++ com.google.errorprone ++ error_prone_annotations ++ ++ ++ ++ ++ ++ com.google.errorprone ++ error_prone_annotations ++ ${errorprone.version} ++ ++ ++ + +- +- jdk8 +- +- 1.8 +- +- +- +- +- org.apache.maven.plugins +- maven-compiler-plugin +- +- javac-with-errorprone +- true +- true +- -Xlint:all +- 1.8 +- 1.8 +- true +- +- -XepExcludedPaths:.*/target/generated-sources/.* +- -J-Xbootclasspath/p:${settings.localRepository}/com/google/errorprone/javac/${errorprone.javac.version}/javac-${errorprone.javac.version}.jar +- +- +- +- +- org.codehaus.plexus +- plexus-compiler-javac-errorprone +- 2.15.0 +- +- +- +- com.google.errorprone +- error_prone_core +- ${errorprone.version} +- +- +- +- +- +- +- +- jdk11 +- +- 11 +- +- +- +- +- org.apache.maven.plugins +- maven-compiler-plugin +- ${maven-compiler-plugin.version} +- +- 1.8 +- 1.8 +- true +- true +- +- +- +- +- + + jdk17 + +@@ -218,7 +182,7 @@ + -Xlint:all -XDcompilePolicy=simple - -Xplugin:ErrorProne -XepExcludedPaths:.*/target/generated-sources/.* ++ ${error-prone-support.flags} -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED -@@ -181,18 +181,129 @@ +@@ -230,12 +194,22 @@ -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED - -- -- com.google.errorprone -- error_prone_core -- ${errorprone.version} -- -- ++ + + com.google.errorprone + error_prone_core + ${errorprone.version} + ++ ++ tech.picnic.error-prone-support ++ error-prone-contrib ++ ${error-prone-support.version} ++ ++ ++ tech.picnic.error-prone-support ++ refaster-runner ++ ${error-prone-support.version} ++ + - - - -+ -+ error-prone-compile -+ -+ -+ -+ org.apache.maven.plugins -+ maven-compiler-plugin -+ ${maven-compiler-plugin.version} -+ -+ -+ -+ default-compile -+ compile -+ -+ compile -+ -+ -+ true -+ -+ -+ -+ error-prone-compile -+ compile -+ -+ compile -+ -+ -+ true -+ ${java.version} -+ ${java.version} -+ -+ -Xpkginfo:always -+ -XDcompilePolicy=simple -+ ${error-prone-support.flags} -+ -+ -+ -+ com.google.errorprone -+ error_prone_core -+ ${error-prone.version} -+ -+ -+ tech.picnic.error-prone-support -+ error-prone-contrib -+ ${error-prone-support.version} -+ -+ -+ tech.picnic.error-prone-support -+ refaster-runner -+ ${error-prone-support.version} -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ -+ error-prone-test-compile -+ -+ -+ -+ org.apache.maven.plugins -+ maven-compiler-plugin -+ ${maven-compiler-plugin.version} -+ -+ -+ -+ default-testCompile -+ test-compile -+ -+ testCompile -+ -+ -+ true -+ -+ -+ -+ error-prone-test-compile -+ test-compile -+ -+ testCompile -+ -+ -+ true -+ ${java.version} -+ ${java.version} -+ -+ -Xpkginfo:always -+ -XDcompilePolicy=simple -+ ${error-prone-support.flags} -+ -+ -+ -+ com.google.errorprone -+ error_prone_core -+ ${error-prone.version} -+ -+ -+ tech.picnic.error-prone-support -+ error-prone-contrib -+ ${error-prone-support.version} -+ -+ -+ tech.picnic.error-prone-support -+ refaster-runner -+ ${error-prone-support.version} -+ -+ -+ -+ -+ -+ -+ -+ -+ - - release-sign-artifacts - -@@ -323,15 +434,7 @@ - - -Xlint:all - -XDcompilePolicy=simple -- -Xplugin:ErrorProne -XepExcludedPaths:.*/target/generated-sources/.* - -- -- -- com.google.errorprone -- error_prone_core -- ${errorprone.version} -- -- - - - +@@ -364,7 +338,7 @@ + org.apache.maven.plugins + maven-compiler-plugin + +- 8 ++ 17 + true + true + true +@@ -418,7 +392,7 @@ + enforce + + +- ++ + + + diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 38e14fb07c..ae6ee84a8f 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -3,30 +3,32 @@ set -e -u -o pipefail test_name="$(basename "${0}" .sh)" -project=metrics -repository=https://github.com/dropwizard/metrics.git -revision=v4.2.19 +project='metrics' +repository='https://github.com/dropwizard/metrics.git' +#revision='v4.2.28' +revision='v5.0.0-rc22' +additional_build_flags='' +additional_source_directories='${project.basedir}${file.separator}src${file.separator}it${file.separator}java,${project.basedir}${file.separator}src${file.separator}xdocs-examples${file.separator}java' +# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Refaster rules +# as they introduce changes that expect Guava to be on the classpath. +#patch_error_prone_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!.*File).*" +patch_error_prone_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*" +validation_error_prone_flags='' +validation_build_flags='' if [ "${#}" -gt 2 ] || ([ "${#}" = 2 ] && [ "${1:---sync}" != '--sync' ]); then echo "Usage: ${0} [--sync] []" exit 1 fi -do_sync="$([ "${#}" = 0 ] || [ "${1:-}" != '--sync' ] || echo 1)" -report_directory="$([ "${#}" = 0 ] || ([ -z "${do_sync}" ] && echo "${1}") || ([ "${#}" = 1 ] || echo "${2}"))" - -# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Refaster rules -# as they introduce changes that expect Guava to be on the classpath. -patch_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!ImmutableSetRules\$ImmutableSetOf).*" "$(dirname "${0}")"/run-integration-test.sh \ "${test_name}" \ "${project}" \ "${repository}" \ "${revision}" \ - "" \ - "" \ - "${patch_flags}" \ - "" \ - "" \ - "${do_sync}" \ - "${report_directory}" + "${additional_build_flags}" \ + "${additional_source_directories}" \ + "${patch_error_prone_flags}" \ + "${validation_error_prone_flags}" \ + "${validation_build_flags}" \ + $@ diff --git a/integration-tests/run-integration-test.sh b/integration-tests/run-integration-test.sh index 9944a7b133..5a20345046 100755 --- a/integration-tests/run-integration-test.sh +++ b/integration-tests/run-integration-test.sh @@ -51,8 +51,8 @@ case "$(uname -s)" in ;; esac +# -Perror-prone-compile,error-prone-test-compile shared_build_flags=" - -Perror-prone-compile,error-prone-test-compile -Derror-prone.version=$( mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=version.error-prone -q -DforceStdout ) @@ -69,7 +69,10 @@ shared_build_flags=" # `shared_build_flags`. format_goal='com.spotify.fmt:fmt-maven-plugin:2.21.1:format' -error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' +#error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' +#error_prone_shared_flags="-XepExcludedPaths:.*[\\/]resources[\\/].*" +error_prone_shared_flags="" + error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( find "${error_prone_support_root}" \ @@ -133,14 +136,19 @@ git config user.name || git config user.name 'Integration Test' git clean -fdx git apply < "${integration_test_root}/${test_name}-init.patch" git commit -m 'dependency: Introduce Error Prone Support' . -mvn ${shared_build_flags} "${format_goal}" -git commit -m 'minor: Reformat using Google Java Format' . +#mvn ${shared_build_flags} "${format_goal}" +#git commit -m 'minor: Reformat using Google Java Format' . diff_base="$(git rev-parse HEAD)" # Apply Error Prone Support-suggested changes until a fixed point is reached. function apply_patch() { local extra_build_args="${1}" + echo "hier ${shared_build_flags} ${extra_build_args} \ + package "${format_goal}" \ + -Derror-prone.configuration-args="${error_prone_patch_flags}" \ + -DskipTests" + mvn ${shared_build_flags} ${extra_build_args} \ package "${format_goal}" \ -Derror-prone.configuration-args="${error_prone_patch_flags}" \ @@ -163,6 +171,8 @@ function apply_patch() { } apply_patch '' + +echo "RUN ONE MORE FULL --------" # Run one more full build and log the output. # # By also running the tests, we validate that the (majority of) applied changes From 01a97f056126b7a5ece8048d37046eec1c7935e2 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Fri, 15 Nov 2024 08:25:51 +0100 Subject: [PATCH 29/59] First full version! --- .../metrics-expected-changes.patch | 95033 ++-------------- .../metrics-expected-warnings.txt | 94 + integration-tests/metrics.sh | 1 + integration-tests/run-integration-test.sh | 6 +- 4 files changed, 9785 insertions(+), 85349 deletions(-) diff --git a/integration-tests/metrics-expected-changes.patch b/integration-tests/metrics-expected-changes.patch index c4961042fa..f2c74a2d04 100644 --- a/integration-tests/metrics-expected-changes.patch +++ b/integration-tests/metrics-expected-changes.patch @@ -1,4423 +1,460 @@ ---- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/CachedGauge.java -+++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/CachedGauge.java -@@ -9,8 +9,8 @@ import java.util.concurrent.TimeUnit; - /** - * An annotation for marking a method as a gauge, which caches the result for a specified time. - * -- *

    -- * Given a method like this: -+ *

    Given a method like this: -+ * - *

    
    -  *     {@literal @}CachedGauge(name = "queueSize", timeout = 30, timeoutUnit = TimeUnit.SECONDS)
    -  *     public int getQueueSize() {
    -@@ -18,36 +18,34 @@ import java.util.concurrent.TimeUnit;
    -  *     }
    -  *
    -  * 
    -- *

    - * -- * A gauge for the defining class with the name queueSize will be created which uses the annotated method's -- * return value as its value, and which caches the result for 30 seconds. -+ *

    A gauge for the defining class with the name queueSize will be created which uses the -+ * annotated method's return value as its value, and which caches the result for 30 seconds. - * - * @since 3.1 - */ - @Retention(RetentionPolicy.RUNTIME) --@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) -+@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) - public @interface CachedGauge { - -- /** -- * @return The name of the counter. -- */ -- String name() default ""; -- -- /** -- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name -- * relative to the annotated class. -- */ -- boolean absolute() default false; -+ /** -+ * @return The name of the counter. -+ */ -+ String name() default ""; - -- /** -- * @return The amount of time to cache the result -- */ -- long timeout(); -+ /** -+ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the -+ * given name relative to the annotated class. -+ */ -+ boolean absolute() default false; - -- /** -- * @return The unit of timeout -- */ -- TimeUnit timeoutUnit() default TimeUnit.MILLISECONDS; -+ /** -+ * @return The amount of time to cache the result -+ */ -+ long timeout(); - -+ /** -+ * @return The unit of timeout -+ */ -+ TimeUnit timeoutUnit() default TimeUnit.MILLISECONDS; - } ---- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Counted.java -+++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Counted.java -@@ -10,44 +10,47 @@ import java.lang.annotation.Target; - /** - * An annotation for marking a method of an annotated object as counted. - * -- *

    -- * Given a method like this: -+ *

    Given a method like this: -+ * - *

    
    -  *     {@literal @}Counted(name = "fancyName")
    -  *     public String fancyName(String name) {
    -  *         return "Sir Captain " + name;
    -  *     }
    -  * 
    -- *

    -- * A counter for the defining class with the name {@code fancyName} will be created and each time the -- * {@code #fancyName(String)} method is invoked, the counter will be marked. -+ * -+ *

    A counter for the defining class with the name {@code fancyName} will be created and each time -+ * the {@code #fancyName(String)} method is invoked, the counter will be marked. - * - * @since 3.1 - */ - @Inherited - @Documented - @Retention(RetentionPolicy.RUNTIME) --@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) -+@Target({ -+ ElementType.TYPE, -+ ElementType.CONSTRUCTOR, -+ ElementType.METHOD, -+ ElementType.ANNOTATION_TYPE -+}) - public @interface Counted { - -- /** -- * @return The name of the counter. -- */ -- String name() default ""; -- -- /** -- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name -- * relative to the annotated class. When annotating a class, this must be {@code false}. -- */ -- boolean absolute() default false; -+ /** -+ * @return The name of the counter. -+ */ -+ String name() default ""; - -- /** -- * @return -- * If {@code false} (default), the counter is decremented when the annotated -- * method returns, counting current invocations of the annotated method. -- * If {@code true}, the counter increases monotonically, counting total -- * invocations of the annotated method. -- */ -- boolean monotonic() default false; -+ /** -+ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the -+ * given name relative to the annotated class. When annotating a class, this must be {@code -+ * false}. -+ */ -+ boolean absolute() default false; - -+ /** -+ * @return If {@code false} (default), the counter is decremented when the annotated method -+ * returns, counting current invocations of the annotated method. If {@code true}, the counter -+ * increases monotonically, counting total invocations of the annotated method. -+ */ -+ boolean monotonic() default false; - } ---- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ExceptionMetered.java -+++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ExceptionMetered.java -@@ -9,57 +9,63 @@ import java.lang.annotation.Target; - - /** - * An annotation for marking a method of an annotated object as metered. -- *

    -- * Given a method like this: -+ * -+ *

    Given a method like this: -+ * - *

    
    -  *     {@literal @}ExceptionMetered(name = "fancyName", cause=IllegalArgumentException.class)
    -  *     public String fancyName(String name) {
    -  *         return "Sir Captain " + name;
    -  *     }
    -  * 
    -- *

    -- * A meter for the defining class with the name {@code fancyName} will be created and each time the -- * {@code #fancyName(String)} throws an exception of type {@code cause} (or a subclass), the meter -- * will be marked. -- *

    -- * A name for the metric can be specified as an annotation parameter, otherwise, the metric will be -- * named based on the method name. -- *

    -- * For instance, given a declaration of -+ * -+ *

    A meter for the defining class with the name {@code fancyName} will be created and each time -+ * the {@code #fancyName(String)} throws an exception of type {@code cause} (or a subclass), the -+ * meter will be marked. -+ * -+ *

    A name for the metric can be specified as an annotation parameter, otherwise, the metric will -+ * be named based on the method name. -+ * -+ *

    For instance, given a declaration of -+ * - *

    
    -  *     {@literal @}ExceptionMetered
    -  *     public String fancyName(String name) {
    -  *         return "Sir Captain " + name;
    -  *     }
    -  * 
    -- *

    -- * A meter named {@code fancyName.exceptions} will be created and marked every time an exception is -- * thrown. -+ * -+ *

    A meter named {@code fancyName.exceptions} will be created and marked every time an exception -+ * is thrown. - */ - @Inherited - @Documented - @Retention(RetentionPolicy.RUNTIME) --@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) -+@Target({ -+ ElementType.TYPE, -+ ElementType.CONSTRUCTOR, -+ ElementType.METHOD, -+ ElementType.ANNOTATION_TYPE -+}) - public @interface ExceptionMetered { -- /** -- * The default suffix for meter names. -- */ -- String DEFAULT_NAME_SUFFIX = "exceptions"; -+ /** The default suffix for meter names. */ -+ String DEFAULT_NAME_SUFFIX = "exceptions"; - -- /** -- * @return The name of the meter. If not specified, the meter will be given a name based on the method -- * it decorates and the suffix "Exceptions". -- */ -- String name() default ""; -+ /** -+ * @return The name of the meter. If not specified, the meter will be given a name based on the -+ * method it decorates and the suffix "Exceptions". -+ */ -+ String name() default ""; - -- /** -- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name -- * relative to the annotated class. When annotating a class, this must be {@code false}. -- */ -- boolean absolute() default false; -+ /** -+ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the -+ * given name relative to the annotated class. When annotating a class, this must be {@code -+ * false}. -+ */ -+ boolean absolute() default false; - -- /** -- * @return The type of exceptions that the meter will catch and count. -- */ -- Class cause() default Exception.class; -+ /** -+ * @return The type of exceptions that the meter will catch and count. -+ */ -+ Class cause() default Exception.class; - } ---- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Gauge.java -+++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Gauge.java -@@ -7,29 +7,30 @@ import java.lang.annotation.Target; - - /** - * An annotation for marking a method of an annotated object as a gauge. -- *

    -- * Given a method like this: -+ * -+ *

    Given a method like this: -+ * - *

    
    -  *     {@literal @}Gauge(name = "queueSize")
    -  *     public int getQueueSize() {
    -  *         return queue.size;
    -  *     }
    -  * 
    -- *

    -- * A gauge for the defining class with the name {@code queueSize} will be created which uses the -+ * -+ *

    A gauge for the defining class with the name {@code queueSize} will be created which uses the - * annotated method's return value as its value. - */ - @Retention(RetentionPolicy.RUNTIME) --@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE }) -+@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) - public @interface Gauge { -- /** -- * @return The gauge's name. -- */ -- String name() default ""; -+ /** -+ * @return The gauge's name. -+ */ -+ String name() default ""; - -- /** -- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name -- * relative to the annotated class. -- */ -- boolean absolute() default false; -+ /** -+ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the -+ * given name relative to the annotated class. -+ */ -+ boolean absolute() default false; - } ---- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Metered.java -+++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Metered.java -@@ -9,31 +9,38 @@ import java.lang.annotation.Target; - - /** - * An annotation for marking a method of an annotated object as metered. -- *

    -- * Given a method like this: -+ * -+ *

    Given a method like this: -+ * - *

    
    -  *     {@literal @}Metered(name = "fancyName")
    -  *     public String fancyName(String name) {
    -  *         return "Sir Captain " + name;
    -  *     }
    -  * 
    -- *

    -- * A meter for the defining class with the name {@code fancyName} will be created and each time the -- * {@code #fancyName(String)} method is invoked, the meter will be marked. -+ * -+ *

    A meter for the defining class with the name {@code fancyName} will be created and each time -+ * the {@code #fancyName(String)} method is invoked, the meter will be marked. - */ - @Inherited - @Documented - @Retention(RetentionPolicy.RUNTIME) --@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) -+@Target({ -+ ElementType.TYPE, -+ ElementType.CONSTRUCTOR, -+ ElementType.METHOD, -+ ElementType.ANNOTATION_TYPE -+}) - public @interface Metered { -- /** -- * @return The name of the meter. -- */ -- String name() default ""; -+ /** -+ * @return The name of the meter. -+ */ -+ String name() default ""; - -- /** -- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name -- * relative to the annotated class. When annotating a class, this must be {@code false}. -- */ -- boolean absolute() default false; -+ /** -+ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the -+ * given name relative to the annotated class. When annotating a class, this must be {@code -+ * false}. -+ */ -+ boolean absolute() default false; - } ---- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Metric.java -+++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Metric.java -@@ -8,41 +8,41 @@ import java.lang.annotation.Target; - /** - * An annotation requesting that a metric be injected or registered. - * -- *

    -- * Given a field like this: -+ *

    Given a field like this: -+ * - *

    
    -  *     {@literal @}Metric
    -  *     public Histogram histogram;
    -  * 
    -- *

    -- * A meter of the field's type will be created and injected into managed objects. -- * It will be up to the user to interact with the metric. This annotation -- * can be used on fields of type Meter, Timer, Counter, and Histogram. - * -- *

    -- * This may also be used to register a metric, which is useful for creating a histogram with -- * a custom Reservoir. -+ *

    A meter of the field's type will be created and injected into managed objects. It will be up -+ * to the user to interact with the metric. This annotation can be used on fields of type Meter, -+ * Timer, Counter, and Histogram. -+ * -+ *

    This may also be used to register a metric, which is useful for creating a histogram with a -+ * custom Reservoir. -+ * - *

    
    -  *     {@literal @}Metric
    -  *     public Histogram uniformHistogram = new Histogram(new UniformReservoir());
    -  * 
    -+ * - *

    - * - * @since 3.1 - */ - @Retention(RetentionPolicy.RUNTIME) --@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE }) -+@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE}) - public @interface Metric { - -- /** -- * @return The name of the metric. -- */ -- String name() default ""; -- -- /** -- * @return If {@code true}, use the given name as an absolute name. If {@code false}, -- * use the given name relative to the annotated class. -- */ -- boolean absolute() default false; -+ /** -+ * @return The name of the metric. -+ */ -+ String name() default ""; - -+ /** -+ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the -+ * given name relative to the annotated class. -+ */ -+ boolean absolute() default false; - } ---- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ResponseMetered.java -+++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ResponseMetered.java -@@ -9,37 +9,44 @@ import java.lang.annotation.Target; - - /** - * An annotation for marking a method of an annotated object as metered. -- *

    -- * Given a method like this: -+ * -+ *

    Given a method like this: -+ * - *

    
    -  *     {@literal @}ResponseMetered(name = "fancyName", level = ResponseMeteredLevel.ALL)
    -  *     public String fancyName(String name) {
    -  *         return "Sir Captain " + name;
    -  *     }
    -  * 
    -- *

    -- * Meters for the defining class with the name {@code fancyName} will be created for response codes -- * based on the ResponseMeteredLevel selected. Each time the {@code #fancyName(String)} method is invoked, -- * the appropriate response meter will be marked. -+ * -+ *

    Meters for the defining class with the name {@code fancyName} will be created for response -+ * codes based on the ResponseMeteredLevel selected. Each time the {@code #fancyName(String)} method -+ * is invoked, the appropriate response meter will be marked. - */ - @Inherited - @Documented - @Retention(RetentionPolicy.RUNTIME) --@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) -+@Target({ -+ ElementType.TYPE, -+ ElementType.CONSTRUCTOR, -+ ElementType.METHOD, -+ ElementType.ANNOTATION_TYPE -+}) - public @interface ResponseMetered { -- /** -- * @return The name of the meter. -- */ -- String name() default ""; -+ /** -+ * @return The name of the meter. -+ */ -+ String name() default ""; - -- /** -- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name -- * relative to the annotated class. When annotating a class, this must be {@code false}. -- */ -- boolean absolute() default false; -+ /** -+ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the -+ * given name relative to the annotated class. When annotating a class, this must be {@code -+ * false}. -+ */ -+ boolean absolute() default false; - -- /** -- * @return the ResponseMeteredLevel which decides which response code meters are marked. -- */ -- ResponseMeteredLevel level() default ResponseMeteredLevel.COARSE; -+ /** -+ * @return the ResponseMeteredLevel which decides which response code meters are marked. -+ */ -+ ResponseMeteredLevel level() default ResponseMeteredLevel.COARSE; - } ---- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ResponseMeteredLevel.java -+++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/ResponseMeteredLevel.java -@@ -1,23 +1,19 @@ - package io.dropwizard.metrics5.annotation; - - /** -- * {@link ResponseMeteredLevel} is a parameter for the {@link ResponseMetered} annotation. -- * The constants of this enumerated type decide what meters are included when a class -- * or method is annotated with the {@link ResponseMetered} annotation. -+ * {@link ResponseMeteredLevel} is a parameter for the {@link ResponseMetered} annotation. The -+ * constants of this enumerated type decide what meters are included when a class or method is -+ * annotated with the {@link ResponseMetered} annotation. - */ - public enum ResponseMeteredLevel { -- /** -- * Include meters for 1xx/2xx/3xx/4xx/5xx responses -- */ -- COARSE, -+ /** Include meters for 1xx/2xx/3xx/4xx/5xx responses */ -+ COARSE, - -- /** -- * Include meters for every response code (200, 201, 303, 304, 401, 404, 501, etc.) -- */ -- DETAILED, -+ /** Include meters for every response code (200, 201, 303, 304, 401, 404, 501, etc.) */ -+ DETAILED, - -- /** -- * Include meters for every response code in addition to top level 1xx/2xx/3xx/4xx/5xx responses -- */ -- ALL; -+ /** -+ * Include meters for every response code in addition to top level 1xx/2xx/3xx/4xx/5xx responses -+ */ -+ ALL; - } ---- a/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Timed.java -+++ b/metrics-annotation/src/main/java/io/dropwizard/metrics5/annotation/Timed.java -@@ -9,31 +9,38 @@ import java.lang.annotation.Target; - - /** - * An annotation for marking a method of an annotated object as timed. -- *

    -- * Given a method like this: -+ * -+ *

    Given a method like this: -+ * - *

    
    -  *     {@literal @}Timed(name = "fancyName")
    -  *     public String fancyName(String name) {
    -  *         return "Sir Captain " + name;
    -  *     }
    -  * 
    -- *

    -- * A timer for the defining class with the name {@code fancyName} will be created and each time the -- * {@code #fancyName(String)} method is invoked, the method's execution will be timed. -+ * -+ *

    A timer for the defining class with the name {@code fancyName} will be created and each time -+ * the {@code #fancyName(String)} method is invoked, the method's execution will be timed. - */ - @Inherited - @Documented - @Retention(RetentionPolicy.RUNTIME) --@Target({ ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) -+@Target({ -+ ElementType.TYPE, -+ ElementType.CONSTRUCTOR, -+ ElementType.METHOD, -+ ElementType.ANNOTATION_TYPE -+}) - public @interface Timed { -- /** -- * @return The name of the timer. -- */ -- String name() default ""; -+ /** -+ * @return The name of the timer. -+ */ -+ String name() default ""; - -- /** -- * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the given name -- * relative to the annotated class. When annotating a class, this must be {@code false}. -- */ -- boolean absolute() default false; -+ /** -+ * @return If {@code true}, use the given name as an absolute name. If {@code false}, use the -+ * given name relative to the annotated class. When annotating a class, this must be {@code -+ * false}. -+ */ -+ boolean absolute() default false; - } ---- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/CachedGaugeBenchmark.java -+++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/CachedGaugeBenchmark.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics5.benchmarks; - - import io.dropwizard.metrics5.CachedGauge; -+import java.util.concurrent.TimeUnit; - import org.openjdk.jmh.annotations.Benchmark; - import org.openjdk.jmh.annotations.Scope; - import org.openjdk.jmh.annotations.State; -@@ -10,37 +11,37 @@ import org.openjdk.jmh.runner.RunnerException; - import org.openjdk.jmh.runner.options.Options; - import org.openjdk.jmh.runner.options.OptionsBuilder; - --import java.util.concurrent.TimeUnit; -- - @State(Scope.Benchmark) - public class CachedGaugeBenchmark { - -- private CachedGauge cachedGauge = new CachedGauge(100, TimeUnit.MILLISECONDS) { -+ private CachedGauge cachedGauge = -+ new CachedGauge(100, TimeUnit.MILLISECONDS) { - @Override - protected Integer loadValue() { -- try { -- Thread.sleep(10); -- } catch (InterruptedException e) { -- throw new RuntimeException("Thread was interrupted", e); -- } -- return 12345; -+ try { -+ Thread.sleep(10); -+ } catch (InterruptedException e) { -+ throw new RuntimeException("Thread was interrupted", e); -+ } -+ return 12345; - } -- }; -+ }; - -- @Benchmark -- public void perfGetValue(Blackhole blackhole) { -- blackhole.consume(cachedGauge.getValue()); -- } -+ @Benchmark -+ public void perfGetValue(Blackhole blackhole) { -+ blackhole.consume(cachedGauge.getValue()); -+ } - -- public static void main(String[] args) throws RunnerException { -- Options opt = new OptionsBuilder() -- .include(".*" + CachedGaugeBenchmark.class.getSimpleName() + ".*") -- .warmupIterations(3) -- .measurementIterations(5) -- .threads(4) -- .forks(1) -- .build(); -+ public static void main(String[] args) throws RunnerException { -+ Options opt = -+ new OptionsBuilder() -+ .include(".*" + CachedGaugeBenchmark.class.getSimpleName() + ".*") -+ .warmupIterations(3) -+ .measurementIterations(5) -+ .threads(4) -+ .forks(1) -+ .build(); - -- new Runner(opt).run(); -- } -+ new Runner(opt).run(); -+ } - } ---- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/CounterBenchmark.java -+++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/CounterBenchmark.java -@@ -12,27 +12,27 @@ import org.openjdk.jmh.runner.options.OptionsBuilder; - @State(Scope.Benchmark) - public class CounterBenchmark { - -- private final Counter counter = new Counter(); -- -- // It's intentionally not declared as final to avoid constant folding -- private long nextValue = 0xFBFBABBA; -- -- @Benchmark -- public Object perfIncrement() { -- counter.inc(nextValue); -- return counter; -- } -- -- public static void main(String[] args) throws RunnerException { -- Options opt = new OptionsBuilder() -- .include(".*" + CounterBenchmark.class.getSimpleName() + ".*") -- .warmupIterations(3) -- .measurementIterations(5) -- .threads(4) -- .forks(1) -- .build(); -- -- new Runner(opt).run(); -- } -- -+ private final Counter counter = new Counter(); -+ -+ // It's intentionally not declared as final to avoid constant folding -+ private long nextValue = 0xFBFBABBA; -+ -+ @Benchmark -+ public Object perfIncrement() { -+ counter.inc(nextValue); -+ return counter; -+ } -+ -+ public static void main(String[] args) throws RunnerException { -+ Options opt = -+ new OptionsBuilder() -+ .include(".*" + CounterBenchmark.class.getSimpleName() + ".*") -+ .warmupIterations(3) -+ .measurementIterations(5) -+ .threads(4) -+ .forks(1) -+ .build(); -+ -+ new Runner(opt).run(); -+ } - } ---- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/MeterBenchmark.java -+++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/MeterBenchmark.java -@@ -12,27 +12,27 @@ import org.openjdk.jmh.runner.options.OptionsBuilder; - @State(Scope.Benchmark) - public class MeterBenchmark { - -- private final Meter meter = new Meter(); -- -- // It's intentionally not declared as final to avoid constant folding -- private long nextValue = 0xFBFBABBA; -- -- @Benchmark -- public Object perfMark() { -- meter.mark(nextValue); -- return meter; -- } -- -- public static void main(String[] args) throws RunnerException { -- Options opt = new OptionsBuilder() -- .include(".*" + MeterBenchmark.class.getSimpleName() + ".*") -- .warmupIterations(3) -- .measurementIterations(5) -- .threads(4) -- .forks(1) -- .build(); -- -- new Runner(opt).run(); -- } -- -+ private final Meter meter = new Meter(); -+ -+ // It's intentionally not declared as final to avoid constant folding -+ private long nextValue = 0xFBFBABBA; -+ -+ @Benchmark -+ public Object perfMark() { -+ meter.mark(nextValue); -+ return meter; -+ } -+ -+ public static void main(String[] args) throws RunnerException { -+ Options opt = -+ new OptionsBuilder() -+ .include(".*" + MeterBenchmark.class.getSimpleName() + ".*") -+ .warmupIterations(3) -+ .measurementIterations(5) -+ .threads(4) -+ .forks(1) -+ .build(); -+ -+ new Runner(opt).run(); -+ } - } ---- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/ReservoirBenchmark.java -+++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/ReservoirBenchmark.java -@@ -7,6 +7,7 @@ import io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir; - import io.dropwizard.metrics5.SlidingTimeWindowReservoir; - import io.dropwizard.metrics5.SlidingWindowReservoir; - import io.dropwizard.metrics5.UniformReservoir; -+import java.util.concurrent.TimeUnit; - import org.openjdk.jmh.annotations.Benchmark; - import org.openjdk.jmh.annotations.Mode; - import org.openjdk.jmh.annotations.Scope; -@@ -18,59 +19,61 @@ import org.openjdk.jmh.runner.options.Options; - import org.openjdk.jmh.runner.options.OptionsBuilder; - import org.openjdk.jmh.runner.options.TimeValue; - --import java.util.concurrent.TimeUnit; -- - @State(Scope.Benchmark) - public class ReservoirBenchmark { - -- private final UniformReservoir uniform = new UniformReservoir(); -- private final ExponentiallyDecayingReservoir exponential = new ExponentiallyDecayingReservoir(); -- private final Reservoir lockFreeExponential = LockFreeExponentiallyDecayingReservoir.builder().build(); -- private final SlidingWindowReservoir sliding = new SlidingWindowReservoir(1000); -- private final SlidingTimeWindowReservoir slidingTime = new SlidingTimeWindowReservoir(200, TimeUnit.MILLISECONDS); -- private final SlidingTimeWindowArrayReservoir arrTime = new SlidingTimeWindowArrayReservoir(200, TimeUnit.MILLISECONDS); -+ private final UniformReservoir uniform = new UniformReservoir(); -+ private final ExponentiallyDecayingReservoir exponential = new ExponentiallyDecayingReservoir(); -+ private final Reservoir lockFreeExponential = -+ LockFreeExponentiallyDecayingReservoir.builder().build(); -+ private final SlidingWindowReservoir sliding = new SlidingWindowReservoir(1000); -+ private final SlidingTimeWindowReservoir slidingTime = -+ new SlidingTimeWindowReservoir(200, TimeUnit.MILLISECONDS); -+ private final SlidingTimeWindowArrayReservoir arrTime = -+ new SlidingTimeWindowArrayReservoir(200, TimeUnit.MILLISECONDS); - -- // It's intentionally not declared as final to avoid constant folding -- private long nextValue = 0xFBFBABBA; -+ // It's intentionally not declared as final to avoid constant folding -+ private long nextValue = 0xFBFBABBA; - -- @Benchmark -- public Object perfUniformReservoir() { -- uniform.update(nextValue); -- return uniform; -- } -+ @Benchmark -+ public Object perfUniformReservoir() { -+ uniform.update(nextValue); -+ return uniform; -+ } - -- @Benchmark -- public Object perfSlidingTimeWindowArrayReservoir() { -- arrTime.update(nextValue); -- return arrTime; -- } -+ @Benchmark -+ public Object perfSlidingTimeWindowArrayReservoir() { -+ arrTime.update(nextValue); -+ return arrTime; -+ } - -- @Benchmark -- public Object perfExponentiallyDecayingReservoir() { -- exponential.update(nextValue); -- return exponential; -- } -+ @Benchmark -+ public Object perfExponentiallyDecayingReservoir() { -+ exponential.update(nextValue); -+ return exponential; -+ } - -- @Benchmark -- public Object perfSlidingWindowReservoir() { -- sliding.update(nextValue); -- return sliding; -- } -+ @Benchmark -+ public Object perfSlidingWindowReservoir() { -+ sliding.update(nextValue); -+ return sliding; -+ } - -- @Benchmark -- public Object perfSlidingTimeWindowReservoir() { -- slidingTime.update(nextValue); -- return slidingTime; -- } -+ @Benchmark -+ public Object perfSlidingTimeWindowReservoir() { -+ slidingTime.update(nextValue); -+ return slidingTime; -+ } - -- @Benchmark -- public Object perfLockFreeExponentiallyDecayingReservoir() { -- lockFreeExponential.update(nextValue); -- return lockFreeExponential; -- } -+ @Benchmark -+ public Object perfLockFreeExponentiallyDecayingReservoir() { -+ lockFreeExponential.update(nextValue); -+ return lockFreeExponential; -+ } - -- public static void main(String[] args) throws RunnerException { -- Options opt = new OptionsBuilder() -+ public static void main(String[] args) throws RunnerException { -+ Options opt = -+ new OptionsBuilder() - .include(".*" + ReservoirBenchmark.class.getSimpleName() + ".*") - .warmupIterations(10) - .measurementIterations(10) -@@ -82,7 +85,6 @@ public class ReservoirBenchmark { - .forks(1) - .build(); - -- new Runner(opt).run(); -- } -- -+ new Runner(opt).run(); -+ } - } --- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java +++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java -@@ -2,7 +2,7 @@ package io.dropwizard.metrics5.benchmarks; +@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.benchmarks; import io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir; import io.dropwizard.metrics5.SlidingTimeWindowReservoir; -import io.dropwizard.metrics5.Snapshot; -+import java.util.concurrent.TimeUnit; + import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Group; - import org.openjdk.jmh.annotations.GroupThreads; -@@ -16,53 +16,52 @@ import org.openjdk.jmh.runner.options.Options; - import org.openjdk.jmh.runner.options.OptionsBuilder; - import org.openjdk.jmh.runner.options.TimeValue; - --import java.util.concurrent.TimeUnit; -- - /** - * @author bstorozhuk - */ - @State(Scope.Benchmark) - public class SlidingTimeWindowReservoirsBenchmark { -- private final SlidingTimeWindowReservoir slidingTime = new SlidingTimeWindowReservoir(200, TimeUnit.MILLISECONDS); -- private final SlidingTimeWindowArrayReservoir arrTime = new SlidingTimeWindowArrayReservoir(200, TimeUnit.MILLISECONDS); -+ private final SlidingTimeWindowReservoir slidingTime = -+ new SlidingTimeWindowReservoir(200, TimeUnit.MILLISECONDS); -+ private final SlidingTimeWindowArrayReservoir arrTime = -+ new SlidingTimeWindowArrayReservoir(200, TimeUnit.MILLISECONDS); - -- // It's intentionally not declared as final to avoid constant folding -- private long nextValue = 0xFBFBABBA; -+ // It's intentionally not declared as final to avoid constant folding -+ private long nextValue = 0xFBFBABBA; - -- @Benchmark -- @Group("slidingTime") -- @GroupThreads(3) -- public Object slidingTimeAddMeasurement() { -- slidingTime.update(nextValue); -- return slidingTime; -- } -+ @Benchmark -+ @Group("slidingTime") -+ @GroupThreads(3) -+ public Object slidingTimeAddMeasurement() { -+ slidingTime.update(nextValue); -+ return slidingTime; -+ } - -- @Benchmark -- @Group("slidingTime") -- @GroupThreads(1) -- public Object slidingTimeRead() { -- Snapshot snapshot = slidingTime.getSnapshot(); -- return snapshot; -- } -+ @Benchmark -+ @Group("slidingTime") -+ @GroupThreads(1) -+ public Object slidingTimeRead() { +@@ -42,8 +41,7 @@ public class SlidingTimeWindowReservoirsBenchmark { + @Group("slidingTime") + @GroupThreads(1) + public Object slidingTimeRead() { +- Snapshot snapshot = slidingTime.getSnapshot(); +- return snapshot; + return slidingTime.getSnapshot(); -+ } - -- @Benchmark -- @Group("arrTime") -- @GroupThreads(3) -- public Object arrTimeAddMeasurement() { -- arrTime.update(nextValue); -- return slidingTime; -- } -+ @Benchmark -+ @Group("arrTime") -+ @GroupThreads(3) -+ public Object arrTimeAddMeasurement() { -+ arrTime.update(nextValue); -+ return slidingTime; -+ } - -- @Benchmark -- @Group("arrTime") -- @GroupThreads(1) -- public Object arrTimeRead() { -- Snapshot snapshot = arrTime.getSnapshot(); -- return snapshot; -- } -+ @Benchmark -+ @Group("arrTime") -+ @GroupThreads(1) -+ public Object arrTimeRead() { -+ return arrTime.getSnapshot(); -+ } - -- public static void main(String[] args) throws RunnerException { -- Options opt = new OptionsBuilder() -+ public static void main(String[] args) throws RunnerException { -+ Options opt = -+ new OptionsBuilder() - .include(".*" + SlidingTimeWindowReservoirsBenchmark.class.getSimpleName() + ".*") - .warmupIterations(10) - .measurementIterations(10) -@@ -73,7 +72,6 @@ public class SlidingTimeWindowReservoirsBenchmark { - .forks(1) - .build(); - -- new Runner(opt).run(); -- } -+ new Runner(opt).run(); -+ } - } -- ---- a/metrics-caffeine3/src/main/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounter.java -+++ b/metrics-caffeine3/src/main/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounter.java -@@ -15,6 +15,8 @@ - */ - package io.dropwizard.metrics5.caffeine3; - -+import static java.util.Objects.requireNonNull; -+ - import com.github.benmanes.caffeine.cache.RemovalCause; - import com.github.benmanes.caffeine.cache.stats.CacheStats; - import com.github.benmanes.caffeine.cache.stats.StatsCounter; -@@ -22,13 +24,10 @@ import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Histogram; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; --import org.checkerframework.checker.index.qual.NonNegative; -- - import java.util.EnumMap; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.LongAdder; -- --import static java.util.Objects.requireNonNull; -+import org.checkerframework.checker.index.qual.NonNegative; - - /** - * A {@link StatsCounter} instrumented with Dropwizard Metrics. -@@ -64,8 +63,7 @@ public final class MetricsStatsCounter implements StatsCounter { - evictionsWithCause = new EnumMap<>(RemovalCause.class); - for (RemovalCause cause : RemovalCause.values()) { - evictionsWithCause.put( -- cause, -- registry.histogram(MetricRegistry.name(metricsPrefix, "evictions", cause.name()))); -+ cause, registry.histogram(MetricRegistry.name(metricsPrefix, "evictions", cause.name()))); - } } ---- a/metrics-caffeine3/src/test/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounterTest.java -+++ b/metrics-caffeine3/src/test/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounterTest.java -@@ -15,19 +15,18 @@ - */ - package io.dropwizard.metrics5.caffeine3; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.junit.jupiter.api.Assertions.assertEquals; -+ - import com.github.benmanes.caffeine.cache.Caffeine; - import com.github.benmanes.caffeine.cache.LoadingCache; - import com.github.benmanes.caffeine.cache.RemovalCause; --import com.google.errorprone.annotations.CanIgnoreReturnValue; - import io.dropwizard.metrics5.MetricRegistry; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertEquals; -- - /** -- * An example of exporting stats to Dropwizard Metrics. -+ * An example of exporting stats to Dropwizard Metrics. - * - * @author ben.manes@gmail.com (Ben Manes) - * @author John Karp -@@ -47,9 +46,10 @@ final class MetricsStatsCounterTest { + @Benchmark +@@ -58,8 +56,7 @@ public class SlidingTimeWindowReservoirsBenchmark { + @Group("arrTime") + @GroupThreads(1) + public Object arrTimeRead() { +- Snapshot snapshot = arrTime.getSnapshot(); +- return snapshot; ++ return arrTime.getSnapshot(); + } - @Test - void basicUsage() { -- LoadingCache cache = Caffeine.newBuilder() -- .recordStats(() -> new MetricsStatsCounter(registry, PREFIX)) -- .build(key -> key); -+ LoadingCache cache = -+ Caffeine.newBuilder() -+ .recordStats(() -> new MetricsStatsCounter(registry, PREFIX)) -+ .build(key -> key); - - // Perform application work - for (int i = 0; i < 4; i++) { + public static void main(String[] args) throws RunnerException { --- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java +++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java -@@ -1,5 +1,21 @@ +@@ -1,13 +1,12 @@ package io.dropwizard.metrics5.collectd; +import static com.google.common.base.Preconditions.checkArgument; -+import static io.dropwizard.metrics5.MetricAttribute.COUNT; -+import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; -+import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; -+import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; -+import static io.dropwizard.metrics5.MetricAttribute.MEAN; -+import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; -+import static io.dropwizard.metrics5.MetricAttribute.P50; -+import static io.dropwizard.metrics5.MetricAttribute.P75; -+import static io.dropwizard.metrics5.MetricAttribute.P95; -+import static io.dropwizard.metrics5.MetricAttribute.P98; -+import static io.dropwizard.metrics5.MetricAttribute.P99; -+import static io.dropwizard.metrics5.MetricAttribute.P999; -+import static io.dropwizard.metrics5.MetricAttribute.STDDEV; -+ + import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MAX; + import static io.dropwizard.metrics5.MetricAttribute.MEAN; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P75; + import static io.dropwizard.metrics5.MetricAttribute.P95; +@@ -16,6 +15,7 @@ import static io.dropwizard.metrics5.MetricAttribute.P99; + import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; + +import com.google.common.collect.ImmutableSet; import io.dropwizard.metrics5.Clock; import io.dropwizard.metrics5.Counter; import io.dropwizard.metrics5.Gauge; -@@ -12,326 +28,337 @@ import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.ScheduledReporter; - import io.dropwizard.metrics5.Snapshot; +@@ -30,7 +30,6 @@ import io.dropwizard.metrics5.Snapshot; import io.dropwizard.metrics5.Timer; --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -- import java.io.IOException; import java.net.InetAddress; -import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.SortedMap; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.MetricAttribute.COUNT; --import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; --import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; --import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MAX; --import static io.dropwizard.metrics5.MetricAttribute.MEAN; --import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MIN; --import static io.dropwizard.metrics5.MetricAttribute.P50; --import static io.dropwizard.metrics5.MetricAttribute.P75; --import static io.dropwizard.metrics5.MetricAttribute.P95; --import static io.dropwizard.metrics5.MetricAttribute.P98; --import static io.dropwizard.metrics5.MetricAttribute.P99; --import static io.dropwizard.metrics5.MetricAttribute.P999; --import static io.dropwizard.metrics5.MetricAttribute.STDDEV; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; - - /** - * A reporter which publishes metric values to a Collectd server. - * -- * @see collectd – The system statistics -- * collection daemon -+ * @see collectd – The system statistics collection daemon - */ - public class CollectdReporter extends ScheduledReporter { - -- /** -- * Returns a builder for the specified registry. -- *

    -- * The default settings are: -- *

      -- *
    • hostName: InetAddress.getLocalHost().getHostName()
    • -- *
    • executor: default executor created by {@code ScheduledReporter}
    • -- *
    • shutdownExecutorOnStop: true
    • -- *
    • clock: Clock.defaultClock()
    • -- *
    • rateUnit: TimeUnit.SECONDS
    • -- *
    • durationUnit: TimeUnit.MILLISECONDS
    • -- *
    • filter: MetricFilter.ALL
    • -- *
    • securityLevel: NONE
    • -- *
    • username: ""
    • -- *
    • password: ""
    • -- *
    -- */ -- public static Builder forRegistry(MetricRegistry registry) { -- return new Builder(registry); -+ /** -+ * Returns a builder for the specified registry. -+ * -+ *

    The default settings are: -+ * -+ *

      -+ *
    • hostName: InetAddress.getLocalHost().getHostName() -+ *
    • executor: default executor created by {@code ScheduledReporter} -+ *
    • shutdownExecutorOnStop: true -+ *
    • clock: Clock.defaultClock() -+ *
    • rateUnit: TimeUnit.SECONDS -+ *
    • durationUnit: TimeUnit.MILLISECONDS -+ *
    • filter: MetricFilter.ALL -+ *
    • securityLevel: NONE -+ *
    • username: "" -+ *
    • password: "" -+ *
    -+ */ -+ public static Builder forRegistry(MetricRegistry registry) { -+ return new Builder(registry); -+ } -+ -+ public static class Builder { -+ -+ private final MetricRegistry registry; -+ private String hostName; -+ private ScheduledExecutorService executor; -+ private boolean shutdownExecutorOnStop = true; -+ private Clock clock = Clock.defaultClock(); -+ private TimeUnit rateUnit = TimeUnit.SECONDS; -+ private TimeUnit durationUnit = TimeUnit.MILLISECONDS; -+ private MetricFilter filter = MetricFilter.ALL; -+ private SecurityLevel securityLevel = SecurityLevel.NONE; -+ private String username = ""; -+ private String password = ""; +@@ -81,7 +80,7 @@ public class CollectdReporter extends ScheduledReporter { + private SecurityLevel securityLevel = SecurityLevel.NONE; + private String username = ""; + private String password = ""; +- private Set disabledMetricAttributes = Collections.emptySet(); + private Set disabledMetricAttributes = ImmutableSet.of(); -+ private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; -+ -+ private Builder(MetricRegistry registry) { -+ this.registry = registry; - } + private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; -- public static class Builder { -- -- private final MetricRegistry registry; -- private String hostName; -- private ScheduledExecutorService executor; -- private boolean shutdownExecutorOnStop = true; -- private Clock clock = Clock.defaultClock(); -- private TimeUnit rateUnit = TimeUnit.SECONDS; -- private TimeUnit durationUnit = TimeUnit.MILLISECONDS; -- private MetricFilter filter = MetricFilter.ALL; -- private SecurityLevel securityLevel = SecurityLevel.NONE; -- private String username = ""; -- private String password = ""; -- private Set disabledMetricAttributes = Collections.emptySet(); -- private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; -- -- private Builder(MetricRegistry registry) { -- this.registry = registry; -- } -- -- public Builder withHostName(String hostName) { -- this.hostName = hostName; -- return this; -- } -- -- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -- this.shutdownExecutorOnStop = shutdownExecutorOnStop; -- return this; -- } -- -- public Builder scheduleOn(ScheduledExecutorService executor) { -- this.executor = executor; -- return this; -- } -- -- public Builder withClock(Clock clock) { -- this.clock = clock; -- return this; -- } -- -- public Builder convertRatesTo(TimeUnit rateUnit) { -- this.rateUnit = rateUnit; -- return this; -- } -- -- public Builder convertDurationsTo(TimeUnit durationUnit) { -- this.durationUnit = durationUnit; -- return this; -- } -- -- public Builder filter(MetricFilter filter) { -- this.filter = filter; -- return this; -- } -- -- public Builder withUsername(String username) { -- this.username = username; -- return this; -- } -- -- public Builder withPassword(String password) { -- this.password = password; -- return this; -- } -- -- public Builder withSecurityLevel(SecurityLevel securityLevel) { -- this.securityLevel = securityLevel; -- return this; -- } -- -- public Builder disabledMetricAttributes(Set attributes) { -- this.disabledMetricAttributes = attributes; -- return this; -- } -- -- public Builder withMaxLength(int maxLength) { -- this.maxLength = maxLength; -- return this; + private Builder(MetricRegistry registry) { +@@ -150,14 +149,10 @@ public class CollectdReporter extends ScheduledReporter { + + public CollectdReporter build(Sender sender) { + if (securityLevel != SecurityLevel.NONE) { +- if (username.isEmpty()) { +- throw new IllegalArgumentException( +- "username is required for securityLevel: " + securityLevel); - } -- -- public CollectdReporter build(Sender sender) { -- if (securityLevel != SecurityLevel.NONE) { -- if (username.isEmpty()) { -- throw new IllegalArgumentException("username is required for securityLevel: " + securityLevel); -- } -- if (password.isEmpty()) { -- throw new IllegalArgumentException("password is required for securityLevel: " + securityLevel); -- } -- } -- return new CollectdReporter(registry, -- hostName, sender, -- executor, shutdownExecutorOnStop, -- clock, rateUnit, durationUnit, -- filter, disabledMetricAttributes, -- username, password, securityLevel, new Sanitize(maxLength)); +- if (password.isEmpty()) { +- throw new IllegalArgumentException( +- "password is required for securityLevel: " + securityLevel); - } -+ public Builder withHostName(String hostName) { -+ this.hostName = hostName; -+ return this; - } ++ checkArgument( ++ !username.isEmpty(), "username is required for securityLevel: %s", securityLevel); ++ checkArgument( ++ !password.isEmpty(), "password is required for securityLevel: %s", securityLevel); + } + return new CollectdReporter( + registry, +@@ -302,7 +297,7 @@ public class CollectdReporter extends ScheduledReporter { + try { + writer.write(metaData, value); + } catch (RuntimeException e) { +- LOG.warn("Failed to process metric '" + metaData.getPlugin() + "': " + e.getMessage()); ++ LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage()); + } catch (IOException e) { + LOG.error("Failed to send metric to collectd", e); + } +@@ -336,9 +331,9 @@ public class CollectdReporter extends ScheduledReporter { + private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { + final Snapshot snapshot = metric.getSnapshot(); + writeValue(metaData, COUNT, (double) metric.getCount()); +- writeValue(metaData, MAX, (double) snapshot.getMax()); ++ writeValue(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); + writeValue(metaData, MEAN, snapshot.getMean()); +- writeValue(metaData, MIN, (double) snapshot.getMin()); ++ writeValue(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); + writeValue(metaData, STDDEV, snapshot.getStdDev()); + writeValue(metaData, P50, snapshot.getMedian()); + writeValue(metaData, P75, snapshot.get75thPercentile()); +@@ -351,9 +346,9 @@ public class CollectdReporter extends ScheduledReporter { + private void serializeTimer(MetaData.Builder metaData, Timer metric) { + final Snapshot snapshot = metric.getSnapshot(); + writeValue(metaData, COUNT, (double) metric.getCount()); +- writeDuration(metaData, MAX, (double) snapshot.getMax()); ++ writeDuration(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); + writeDuration(metaData, MEAN, snapshot.getMean()); +- writeDuration(metaData, MIN, (double) snapshot.getMin()); ++ writeDuration(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); + writeDuration(metaData, STDDEV, snapshot.getStdDev()); + writeDuration(metaData, P50, snapshot.getMedian()); + writeDuration(metaData, P75, snapshot.get75thPercentile()); +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java +@@ -1,10 +1,14 @@ + package io.dropwizard.metrics5.collectd; -- private static final Logger LOG = LoggerFactory.getLogger(CollectdReporter.class); -- private static final String REPORTER_NAME = "collectd-reporter"; -- private static final String FALLBACK_HOST_NAME = "localhost"; -- private static final String COLLECTD_TYPE_GAUGE = "gauge"; -- -- private String hostName; -- private final Sender sender; -- private final Clock clock; -- private long period; -- private final PacketWriter writer; -- private final Sanitize sanitize; -- -- private CollectdReporter(MetricRegistry registry, -- String hostname, Sender sender, -- ScheduledExecutorService executor, boolean shutdownExecutorOnStop, -- Clock clock, TimeUnit rateUnit, TimeUnit durationUnit, -- MetricFilter filter, Set disabledMetricAttributes, -- String username, String password, -- SecurityLevel securityLevel, Sanitize sanitize) { -- super(registry, REPORTER_NAME, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, -- disabledMetricAttributes); -- this.hostName = (hostname != null) ? hostname : resolveHostName(); -- this.sender = sender; -- this.clock = clock; -- this.sanitize = sanitize; -- writer = new PacketWriter(sender, username, password, securityLevel); -+ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -+ this.shutdownExecutorOnStop = shutdownExecutorOnStop; -+ return this; - } ++import static com.google.common.base.Preconditions.checkState; ++import static java.nio.charset.StandardCharsets.US_ASCII; ++import static java.nio.charset.StandardCharsets.UTF_8; ++ ++import com.google.common.base.Strings; + import java.io.IOException; + import java.nio.BufferOverflowException; + import java.nio.ByteBuffer; + import java.nio.ByteOrder; +-import java.nio.charset.StandardCharsets; + import java.security.InvalidKeyException; + import java.security.MessageDigest; + import java.security.NoSuchAlgorithmException; +@@ -64,8 +68,8 @@ class PacketWriter { + PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { + this.sender = sender; + this.securityLevel = securityLevel; +- this.username = username != null ? username.getBytes(StandardCharsets.UTF_8) : null; +- this.password = password != null ? password.getBytes(StandardCharsets.UTF_8) : null; ++ this.username = username != null ? username.getBytes(UTF_8) : null; ++ this.password = password != null ? password.getBytes(UTF_8) : null; + } -- private String resolveHostName() { -- try { -- return InetAddress.getLocalHost().getHostName(); -- } catch (Exception e) { -- LOG.error("Failed to lookup local host name: {}", e.getMessage(), e); -- return FALLBACK_HOST_NAME; -- } -+ public Builder scheduleOn(ScheduledExecutorService executor) { -+ this.executor = executor; -+ return this; - } + void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { +@@ -119,12 +123,12 @@ class PacketWriter { + } -- @Override -- public void start(long period, TimeUnit unit) { -- this.period = period; -- super.start(period, unit); -+ public Builder withClock(Clock clock) { -+ this.clock = clock; -+ return this; + private void writeString(ByteBuffer buffer, int type, String val) { +- if (val == null || val.length() == 0) { ++ if (Strings.isNullOrEmpty(val)) { + return; } + int len = HEADER_LEN + val.length() + 1; + writeHeader(buffer, type, len); +- buffer.put(val.getBytes(StandardCharsets.US_ASCII)).put(NULL); ++ buffer.put(val.getBytes(US_ASCII)).put(NULL); + } -- @Override -- public void report(SortedMap> gauges, SortedMap counters, -- SortedMap histograms, SortedMap meters, -- SortedMap timers) { -- MetaData.Builder metaData = new MetaData.Builder(sanitize, hostName, clock.getTime() / 1000, period) -- .type(COLLECTD_TYPE_GAUGE); -- try { -- connect(sender); -- for (Map.Entry> entry : gauges.entrySet()) { -- serializeGauge(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -- } -- for (Map.Entry entry : counters.entrySet()) { -- serializeCounter(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -- } -- for (Map.Entry entry : histograms.entrySet()) { -- serializeHistogram(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -- } -- for (Map.Entry entry : meters.entrySet()) { -- serializeMeter(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -- } -- for (Map.Entry entry : timers.entrySet()) { -- serializeTimer(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -- } -- } catch (IOException e) { -- LOG.warn("Unable to report to Collectd", e); -- } finally { -- disconnect(sender); -- } -+ public Builder convertRatesTo(TimeUnit rateUnit) { -+ this.rateUnit = rateUnit; -+ return this; + private void writeNumber(ByteBuffer buffer, int type, long val) { +@@ -236,9 +240,7 @@ class PacketWriter { + } catch (InvalidParameterSpecException e) { + throw new RuntimeException(e); } +- if (iv.length != IV_LENGTH) { +- throw new IllegalStateException("Bad initialization vector"); +- } ++ checkState(iv.length == IV_LENGTH, "Bad initialization vector"); + final ByteBuffer output = ByteBuffer.allocate(input.remaining() * 2); + try { + cipher.doFinal(input, output); +@@ -261,9 +263,7 @@ class PacketWriter { + final MessageDigest digest = MessageDigest.getInstance(SHA_1_ALGORITHM); + digest.update(input); + final byte[] output = digest.digest(); +- if (output.length != SHA1_LENGTH) { +- throw new IllegalStateException("Bad SHA1 hash"); +- } ++ checkState(output.length == SHA1_LENGTH, "Bad SHA1 hash"); + return output; + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.collectd; -- private void connect(Sender sender) throws IOException { -- if (!sender.isConnected()) { -- sender.connect(); -- } -+ public Builder convertDurationsTo(TimeUnit durationUnit) { -+ this.durationUnit = durationUnit; -+ return this; - } ++import static com.google.common.base.Preconditions.checkState; ++ + import java.io.IOException; + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; +@@ -19,9 +21,7 @@ public class Sender { + } -- private void disconnect(Sender sender) { -- try { -- sender.disconnect(); -- } catch (Exception e) { -- LOG.warn("Error disconnecting from Collectd", e); -- } -+ public Builder filter(MetricFilter filter) { -+ this.filter = filter; -+ return this; + public void connect() throws IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); + if (host != null) { + address = new InetSocketAddress(host, port); } +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java +@@ -1,37 +1,37 @@ + package io.dropwizard.metrics5.collectd; -- private void writeValue(MetaData.Builder metaData, MetricAttribute attribute, Number value) { -- if (!getDisabledMetricAttributes().contains(attribute)) { -- write(metaData.typeInstance(attribute.getCode()).get(), value); -- } -+ public Builder withUsername(String username) { -+ this.username = username; -+ return this; - } +-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; -- private void writeRate(MetaData.Builder metaData, MetricAttribute attribute, double rate) { -- writeValue(metaData, attribute, convertRate(rate)); -+ public Builder withPassword(String password) { -+ this.password = password; -+ return this; - } + import io.dropwizard.metrics5.MetricRegistry; + import org.junit.jupiter.api.Test; -- private void writeDuration(MetaData.Builder metaData, MetricAttribute attribute, double duration) { -- writeValue(metaData, attribute, convertDuration(duration)); -+ public Builder withSecurityLevel(SecurityLevel securityLevel) { -+ this.securityLevel = securityLevel; -+ return this; - } - -- private void write(MetaData metaData, Number value) { -- try { -- writer.write(metaData, value); -- } catch (RuntimeException e) { -- LOG.warn("Failed to process metric '" + metaData.getPlugin() + "': " + e.getMessage()); -- } catch (IOException e) { -- LOG.error("Failed to send metric to collectd", e); -- } -+ public Builder disabledMetricAttributes(Set attributes) { -+ this.disabledMetricAttributes = attributes; -+ return this; - } - -- private void serializeGauge(MetaData.Builder metaData, Gauge metric) { -- if (metric.getValue() instanceof Number) { -- write(metaData.typeInstance("value").get(), (Number) metric.getValue()); -- } else if (metric.getValue() instanceof Boolean) { -- write(metaData.typeInstance("value").get(), ((Boolean) metric.getValue()) ? 1 : 0); -- } else { -- LOG.warn("Failed to process metric '{}'. Unsupported gauge of type: {} ", metaData.get().getPlugin(), -- metric.getValue().getClass().getName()); -- } -+ public Builder withMaxLength(int maxLength) { -+ this.maxLength = maxLength; -+ return this; - } - -- private void serializeMeter(MetaData.Builder metaData, Meter metric) { -- writeValue(metaData, COUNT, (double) metric.getCount()); -- writeRate(metaData, M1_RATE, metric.getOneMinuteRate()); -- writeRate(metaData, M5_RATE, metric.getFiveMinuteRate()); -- writeRate(metaData, M15_RATE, metric.getFifteenMinuteRate()); -- writeRate(metaData, MEAN_RATE, metric.getMeanRate()); -+ public CollectdReporter build(Sender sender) { -+ if (securityLevel != SecurityLevel.NONE) { -+ checkArgument( -+ !username.isEmpty(), "username is required for securityLevel: %s", securityLevel); -+ checkArgument( -+ !password.isEmpty(), "password is required for securityLevel: %s", securityLevel); -+ } -+ return new CollectdReporter( -+ registry, -+ hostName, -+ sender, -+ executor, -+ shutdownExecutorOnStop, -+ clock, -+ rateUnit, -+ durationUnit, -+ filter, -+ disabledMetricAttributes, -+ username, -+ password, -+ securityLevel, -+ new Sanitize(maxLength)); -+ } -+ } -+ -+ private static final Logger LOG = LoggerFactory.getLogger(CollectdReporter.class); -+ private static final String REPORTER_NAME = "collectd-reporter"; -+ private static final String FALLBACK_HOST_NAME = "localhost"; -+ private static final String COLLECTD_TYPE_GAUGE = "gauge"; -+ -+ private String hostName; -+ private final Sender sender; -+ private final Clock clock; -+ private long period; -+ private final PacketWriter writer; -+ private final Sanitize sanitize; -+ -+ private CollectdReporter( -+ MetricRegistry registry, -+ String hostname, -+ Sender sender, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Clock clock, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ MetricFilter filter, -+ Set disabledMetricAttributes, -+ String username, -+ String password, -+ SecurityLevel securityLevel, -+ Sanitize sanitize) { -+ super( -+ registry, -+ REPORTER_NAME, -+ filter, -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes); -+ this.hostName = (hostname != null) ? hostname : resolveHostName(); -+ this.sender = sender; -+ this.clock = clock; -+ this.sanitize = sanitize; -+ writer = new PacketWriter(sender, username, password, securityLevel); -+ } -+ -+ private String resolveHostName() { -+ try { -+ return InetAddress.getLocalHost().getHostName(); -+ } catch (Exception e) { -+ LOG.error("Failed to lookup local host name: {}", e.getMessage(), e); -+ return FALLBACK_HOST_NAME; -+ } -+ } -+ -+ @Override -+ public void start(long period, TimeUnit unit) { -+ this.period = period; -+ super.start(period, unit); -+ } -+ -+ @Override -+ public void report( -+ SortedMap> gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ MetaData.Builder metaData = -+ new MetaData.Builder(sanitize, hostName, clock.getTime() / 1000, period) -+ .type(COLLECTD_TYPE_GAUGE); -+ try { -+ connect(sender); -+ for (Map.Entry> entry : gauges.entrySet()) { -+ serializeGauge(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -+ } -+ for (Map.Entry entry : counters.entrySet()) { -+ serializeCounter(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -+ } -+ for (Map.Entry entry : histograms.entrySet()) { -+ serializeHistogram(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -+ } -+ for (Map.Entry entry : meters.entrySet()) { -+ serializeMeter(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -+ } -+ for (Map.Entry entry : timers.entrySet()) { -+ serializeTimer(metaData.plugin(entry.getKey().getKey()), entry.getValue()); -+ } -+ } catch (IOException e) { -+ LOG.warn("Unable to report to Collectd", e); -+ } finally { -+ disconnect(sender); - } -+ } - -- private void serializeCounter(MetaData.Builder metaData, Counter metric) { -- writeValue(metaData, COUNT, (double) metric.getCount()); -+ private void connect(Sender sender) throws IOException { -+ if (!sender.isConnected()) { -+ sender.connect(); - } -+ } - -- private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { -- final Snapshot snapshot = metric.getSnapshot(); -- writeValue(metaData, COUNT, (double) metric.getCount()); -- writeValue(metaData, MAX, (double) snapshot.getMax()); -- writeValue(metaData, MEAN, snapshot.getMean()); -- writeValue(metaData, MIN, (double) snapshot.getMin()); -- writeValue(metaData, STDDEV, snapshot.getStdDev()); -- writeValue(metaData, P50, snapshot.getMedian()); -- writeValue(metaData, P75, snapshot.get75thPercentile()); -- writeValue(metaData, P95, snapshot.get95thPercentile()); -- writeValue(metaData, P98, snapshot.get98thPercentile()); -- writeValue(metaData, P99, snapshot.get99thPercentile()); -- writeValue(metaData, P999, snapshot.get999thPercentile()); -+ private void disconnect(Sender sender) { -+ try { -+ sender.disconnect(); -+ } catch (Exception e) { -+ LOG.warn("Error disconnecting from Collectd", e); - } -+ } - -- private void serializeTimer(MetaData.Builder metaData, Timer metric) { -- final Snapshot snapshot = metric.getSnapshot(); -- writeValue(metaData, COUNT, (double) metric.getCount()); -- writeDuration(metaData, MAX, (double) snapshot.getMax()); -- writeDuration(metaData, MEAN, snapshot.getMean()); -- writeDuration(metaData, MIN, (double) snapshot.getMin()); -- writeDuration(metaData, STDDEV, snapshot.getStdDev()); -- writeDuration(metaData, P50, snapshot.getMedian()); -- writeDuration(metaData, P75, snapshot.get75thPercentile()); -- writeDuration(metaData, P95, snapshot.get95thPercentile()); -- writeDuration(metaData, P98, snapshot.get98thPercentile()); -- writeDuration(metaData, P99, snapshot.get99thPercentile()); -- writeDuration(metaData, P999, snapshot.get999thPercentile()); -- writeRate(metaData, M1_RATE, metric.getOneMinuteRate()); -- writeRate(metaData, M5_RATE, metric.getFiveMinuteRate()); -- writeRate(metaData, M15_RATE, metric.getFifteenMinuteRate()); -- writeRate(metaData, MEAN_RATE, metric.getMeanRate()); -+ private void writeValue(MetaData.Builder metaData, MetricAttribute attribute, Number value) { -+ if (!getDisabledMetricAttributes().contains(attribute)) { -+ write(metaData.typeInstance(attribute.getCode()).get(), value); -+ } -+ } -+ -+ private void writeRate(MetaData.Builder metaData, MetricAttribute attribute, double rate) { -+ writeValue(metaData, attribute, convertRate(rate)); -+ } -+ -+ private void writeDuration( -+ MetaData.Builder metaData, MetricAttribute attribute, double duration) { -+ writeValue(metaData, attribute, convertDuration(duration)); -+ } -+ -+ private void write(MetaData metaData, Number value) { -+ try { -+ writer.write(metaData, value); -+ } catch (RuntimeException e) { -+ LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage()); -+ } catch (IOException e) { -+ LOG.error("Failed to send metric to collectd", e); -+ } -+ } -+ -+ private void serializeGauge(MetaData.Builder metaData, Gauge metric) { -+ if (metric.getValue() instanceof Number) { -+ write(metaData.typeInstance("value").get(), (Number) metric.getValue()); -+ } else if (metric.getValue() instanceof Boolean) { -+ write(metaData.typeInstance("value").get(), ((Boolean) metric.getValue()) ? 1 : 0); -+ } else { -+ LOG.warn( -+ "Failed to process metric '{}'. Unsupported gauge of type: {} ", -+ metaData.get().getPlugin(), -+ metric.getValue().getClass().getName()); - } -+ } -+ -+ private void serializeMeter(MetaData.Builder metaData, Meter metric) { -+ writeValue(metaData, COUNT, (double) metric.getCount()); -+ writeRate(metaData, M1_RATE, metric.getOneMinuteRate()); -+ writeRate(metaData, M5_RATE, metric.getFiveMinuteRate()); -+ writeRate(metaData, M15_RATE, metric.getFifteenMinuteRate()); -+ writeRate(metaData, MEAN_RATE, metric.getMeanRate()); -+ } -+ -+ private void serializeCounter(MetaData.Builder metaData, Counter metric) { -+ writeValue(metaData, COUNT, (double) metric.getCount()); -+ } -+ -+ private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { -+ final Snapshot snapshot = metric.getSnapshot(); -+ writeValue(metaData, COUNT, (double) metric.getCount()); -+ writeValue(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); -+ writeValue(metaData, MEAN, snapshot.getMean()); -+ writeValue(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); -+ writeValue(metaData, STDDEV, snapshot.getStdDev()); -+ writeValue(metaData, P50, snapshot.getMedian()); -+ writeValue(metaData, P75, snapshot.get75thPercentile()); -+ writeValue(metaData, P95, snapshot.get95thPercentile()); -+ writeValue(metaData, P98, snapshot.get98thPercentile()); -+ writeValue(metaData, P99, snapshot.get99thPercentile()); -+ writeValue(metaData, P999, snapshot.get999thPercentile()); -+ } -+ -+ private void serializeTimer(MetaData.Builder metaData, Timer metric) { -+ final Snapshot snapshot = metric.getSnapshot(); -+ writeValue(metaData, COUNT, (double) metric.getCount()); -+ writeDuration(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); -+ writeDuration(metaData, MEAN, snapshot.getMean()); -+ writeDuration(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); -+ writeDuration(metaData, STDDEV, snapshot.getStdDev()); -+ writeDuration(metaData, P50, snapshot.getMedian()); -+ writeDuration(metaData, P75, snapshot.get75thPercentile()); -+ writeDuration(metaData, P95, snapshot.get95thPercentile()); -+ writeDuration(metaData, P98, snapshot.get98thPercentile()); -+ writeDuration(metaData, P99, snapshot.get99thPercentile()); -+ writeDuration(metaData, P999, snapshot.get999thPercentile()); -+ writeRate(metaData, M1_RATE, metric.getOneMinuteRate()); -+ writeRate(metaData, M5_RATE, metric.getFiveMinuteRate()); -+ writeRate(metaData, M15_RATE, metric.getFifteenMinuteRate()); -+ writeRate(metaData, MEAN_RATE, metric.getMeanRate()); -+ } - } ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/MetaData.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/MetaData.java -@@ -2,97 +2,103 @@ package io.dropwizard.metrics5.collectd; - - class MetaData { - -- private final String host; -- private final String plugin; -- private final String pluginInstance; -- private final String type; -- private final String typeInstance; -- private final long timestamp; -- private final long period; -- -- MetaData(String host, String plugin, String pluginInstance, String type, String typeInstance, -- long timestamp, long period) { -- this.host = host; -- this.plugin = plugin; -- this.pluginInstance = pluginInstance; -- this.type = type; -- this.typeInstance = typeInstance; -- this.timestamp = timestamp; -- this.period = period; -+ private final String host; -+ private final String plugin; -+ private final String pluginInstance; -+ private final String type; -+ private final String typeInstance; -+ private final long timestamp; -+ private final long period; -+ -+ MetaData( -+ String host, -+ String plugin, -+ String pluginInstance, -+ String type, -+ String typeInstance, -+ long timestamp, -+ long period) { -+ this.host = host; -+ this.plugin = plugin; -+ this.pluginInstance = pluginInstance; -+ this.type = type; -+ this.typeInstance = typeInstance; -+ this.timestamp = timestamp; -+ this.period = period; -+ } -+ -+ String getHost() { -+ return host; -+ } -+ -+ String getPlugin() { -+ return plugin; -+ } -+ -+ String getPluginInstance() { -+ return pluginInstance; -+ } -+ -+ String getType() { -+ return type; -+ } -+ -+ String getTypeInstance() { -+ return typeInstance; -+ } -+ -+ long getTimestamp() { -+ return timestamp; -+ } -+ -+ long getPeriod() { -+ return period; -+ } -+ -+ static class Builder { -+ -+ private String host; -+ private String plugin; -+ private String pluginInstance; -+ private String type; -+ private String typeInstance; -+ private long timestamp; -+ private long period; -+ private Sanitize sanitize; -+ -+ Builder(String host, long timestamp, long duration) { -+ this(new Sanitize(Sanitize.DEFAULT_MAX_LENGTH), host, timestamp, duration); - } - -- String getHost() { -- return host; -+ Builder(Sanitize sanitize, String host, long timestamp, long duration) { -+ this.sanitize = sanitize; -+ this.host = sanitize.instanceName(host); -+ this.timestamp = timestamp; -+ period = duration; - } - -- String getPlugin() { -- return plugin; -+ Builder plugin(String name) { -+ plugin = sanitize.name(name); -+ return this; - } - -- String getPluginInstance() { -- return pluginInstance; -+ Builder pluginInstance(String name) { -+ pluginInstance = sanitize.instanceName(name); -+ return this; - } - -- String getType() { -- return type; -+ Builder type(String name) { -+ type = sanitize.name(name); -+ return this; - } - -- String getTypeInstance() { -- return typeInstance; -+ Builder typeInstance(String name) { -+ typeInstance = sanitize.instanceName(name); -+ return this; - } - -- long getTimestamp() { -- return timestamp; -- } -- -- long getPeriod() { -- return period; -- } -- -- static class Builder { -- -- private String host; -- private String plugin; -- private String pluginInstance; -- private String type; -- private String typeInstance; -- private long timestamp; -- private long period; -- private Sanitize sanitize; -- -- Builder(String host, long timestamp, long duration) { -- this(new Sanitize(Sanitize.DEFAULT_MAX_LENGTH), host, timestamp, duration); -- } -- -- Builder(Sanitize sanitize, String host, long timestamp, long duration) { -- this.sanitize = sanitize; -- this.host = sanitize.instanceName(host); -- this.timestamp = timestamp; -- period = duration; -- } -- -- Builder plugin(String name) { -- plugin = sanitize.name(name); -- return this; -- } -- -- Builder pluginInstance(String name) { -- pluginInstance = sanitize.instanceName(name); -- return this; -- } -- -- Builder type(String name) { -- type = sanitize.name(name); -- return this; -- } -- -- Builder typeInstance(String name) { -- typeInstance = sanitize.instanceName(name); -- return this; -- } -- -- MetaData get() { -- return new MetaData(host, plugin, pluginInstance, type, typeInstance, timestamp, period); -- } -+ MetaData get() { -+ return new MetaData(host, plugin, pluginInstance, type, typeInstance, timestamp, period); - } -+ } - } ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java -@@ -1,275 +1,283 @@ - package io.dropwizard.metrics5.collectd; - --import javax.crypto.BadPaddingException; --import javax.crypto.Cipher; --import javax.crypto.IllegalBlockSizeException; --import javax.crypto.Mac; --import javax.crypto.NoSuchPaddingException; --import javax.crypto.ShortBufferException; --import javax.crypto.spec.IvParameterSpec; --import javax.crypto.spec.SecretKeySpec; -+import static com.google.common.base.Preconditions.checkState; -+import static java.nio.charset.StandardCharsets.US_ASCII; -+import static java.nio.charset.StandardCharsets.UTF_8; -+ -+import com.google.common.base.Strings; - import java.io.IOException; - import java.nio.BufferOverflowException; - import java.nio.ByteBuffer; - import java.nio.ByteOrder; --import java.nio.charset.StandardCharsets; - import java.security.InvalidKeyException; - import java.security.MessageDigest; - import java.security.NoSuchAlgorithmException; - import java.security.spec.InvalidParameterSpecException; - import java.util.Arrays; -+import javax.crypto.BadPaddingException; -+import javax.crypto.Cipher; -+import javax.crypto.IllegalBlockSizeException; -+import javax.crypto.Mac; -+import javax.crypto.NoSuchPaddingException; -+import javax.crypto.ShortBufferException; -+import javax.crypto.spec.IvParameterSpec; -+import javax.crypto.spec.SecretKeySpec; - - class PacketWriter { - -- private static final int TYPE_HOST = 0; -- private static final int TYPE_TIME = 1; -- private static final int TYPE_PLUGIN = 2; -- private static final int TYPE_PLUGIN_INSTANCE = 3; -- private static final int TYPE_TYPE = 4; -- private static final int TYPE_TYPE_INSTANCE = 5; -- private static final int TYPE_VALUES = 6; -- private static final int TYPE_INTERVAL = 7; -- private static final int TYPE_SIGN_SHA256 = 0x0200; -- private static final int TYPE_ENCR_AES256 = 0x0210; -+ private static final int TYPE_HOST = 0; -+ private static final int TYPE_TIME = 1; -+ private static final int TYPE_PLUGIN = 2; -+ private static final int TYPE_PLUGIN_INSTANCE = 3; -+ private static final int TYPE_TYPE = 4; -+ private static final int TYPE_TYPE_INSTANCE = 5; -+ private static final int TYPE_VALUES = 6; -+ private static final int TYPE_INTERVAL = 7; -+ private static final int TYPE_SIGN_SHA256 = 0x0200; -+ private static final int TYPE_ENCR_AES256 = 0x0210; - -- private static final int UINT16_LEN = 2; -- private static final int UINT32_LEN = UINT16_LEN * 2; -- private static final int UINT64_LEN = UINT32_LEN * 2; -- private static final int HEADER_LEN = UINT16_LEN * 2; -- private static final int BUFFER_SIZE = 1024; -+ private static final int UINT16_LEN = 2; -+ private static final int UINT32_LEN = UINT16_LEN * 2; -+ private static final int UINT64_LEN = UINT32_LEN * 2; -+ private static final int HEADER_LEN = UINT16_LEN * 2; -+ private static final int BUFFER_SIZE = 1024; - -- private static final int VALUE_COUNT_LEN = UINT16_LEN; -- private static final int NUMBER_LEN = HEADER_LEN + UINT64_LEN; -- private static final int SIGNATURE_LEN = 36; // 2b Type + 2b Length + 32b Hash -- private static final int ENCRYPT_DATA_LEN = 22; // 16b IV + 2b Type + 2b Length + 2b Username length -- private static final int IV_LENGTH = 16; -- private static final int SHA1_LENGTH = 20; -+ private static final int VALUE_COUNT_LEN = UINT16_LEN; -+ private static final int NUMBER_LEN = HEADER_LEN + UINT64_LEN; -+ private static final int SIGNATURE_LEN = 36; // 2b Type + 2b Length + 32b Hash -+ private static final int ENCRYPT_DATA_LEN = -+ 22; // 16b IV + 2b Type + 2b Length + 2b Username length -+ private static final int IV_LENGTH = 16; -+ private static final int SHA1_LENGTH = 20; - -- private static final int VALUE_LEN = 9; -- private static final byte DATA_TYPE_GAUGE = (byte) 1; -- private static final byte NULL = (byte) '\0'; -- private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; -- private static final String AES_CYPHER = "AES_256/OFB/NoPadding"; -- private static final String AES = "AES"; -- private static final String SHA_256_ALGORITHM = "SHA-256"; -- private static final String SHA_1_ALGORITHM = "SHA1"; -+ private static final int VALUE_LEN = 9; -+ private static final byte DATA_TYPE_GAUGE = (byte) 1; -+ private static final byte NULL = (byte) '\0'; -+ private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; -+ private static final String AES_CYPHER = "AES_256/OFB/NoPadding"; -+ private static final String AES = "AES"; -+ private static final String SHA_256_ALGORITHM = "SHA-256"; -+ private static final String SHA_1_ALGORITHM = "SHA1"; - -- private final Sender sender; -+ private final Sender sender; - -- private final SecurityLevel securityLevel; -- private final byte[] username; -- private final byte[] password; -+ private final SecurityLevel securityLevel; -+ private final byte[] username; -+ private final byte[] password; - -- PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { -- this.sender = sender; -- this.securityLevel = securityLevel; -- this.username = username != null ? username.getBytes(StandardCharsets.UTF_8) : null; -- this.password = password != null ? password.getBytes(StandardCharsets.UTF_8) : null; -- } -+ PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { -+ this.sender = sender; -+ this.securityLevel = securityLevel; -+ this.username = username != null ? username.getBytes(UTF_8) : null; -+ this.password = password != null ? password.getBytes(UTF_8) : null; -+ } - -- void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { -- final ByteBuffer packet = ByteBuffer.allocate(BUFFER_SIZE); -- write(packet, metaData); -- write(packet, values); -- packet.flip(); -+ void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { -+ final ByteBuffer packet = ByteBuffer.allocate(BUFFER_SIZE); -+ write(packet, metaData); -+ write(packet, values); -+ packet.flip(); - -- switch (securityLevel) { -- case NONE: -- sender.send(packet); -- break; -- case SIGN: -- sender.send(signPacket(packet)); -- break; -- case ENCRYPT: -- sender.send(encryptPacket(packet)); -- break; -- default: -- throw new IllegalArgumentException("Unsupported security level: " + securityLevel); -- } -+ switch (securityLevel) { -+ case NONE: -+ sender.send(packet); -+ break; -+ case SIGN: -+ sender.send(signPacket(packet)); -+ break; -+ case ENCRYPT: -+ sender.send(encryptPacket(packet)); -+ break; -+ default: -+ throw new IllegalArgumentException("Unsupported security level: " + securityLevel); - } -+ } - -+ private void write(ByteBuffer buffer, MetaData metaData) { -+ writeString(buffer, TYPE_HOST, metaData.getHost()); -+ writeNumber(buffer, TYPE_TIME, metaData.getTimestamp()); -+ writeString(buffer, TYPE_PLUGIN, metaData.getPlugin()); -+ writeString(buffer, TYPE_PLUGIN_INSTANCE, metaData.getPluginInstance()); -+ writeString(buffer, TYPE_TYPE, metaData.getType()); -+ writeString(buffer, TYPE_TYPE_INSTANCE, metaData.getTypeInstance()); -+ writeNumber(buffer, TYPE_INTERVAL, metaData.getPeriod()); -+ } - -- private void write(ByteBuffer buffer, MetaData metaData) { -- writeString(buffer, TYPE_HOST, metaData.getHost()); -- writeNumber(buffer, TYPE_TIME, metaData.getTimestamp()); -- writeString(buffer, TYPE_PLUGIN, metaData.getPlugin()); -- writeString(buffer, TYPE_PLUGIN_INSTANCE, metaData.getPluginInstance()); -- writeString(buffer, TYPE_TYPE, metaData.getType()); -- writeString(buffer, TYPE_TYPE_INSTANCE, metaData.getTypeInstance()); -- writeNumber(buffer, TYPE_INTERVAL, metaData.getPeriod()); -+ private void write(ByteBuffer buffer, Number... values) { -+ final int numValues = values.length; -+ final int length = HEADER_LEN + VALUE_COUNT_LEN + numValues * VALUE_LEN; -+ writeHeader(buffer, TYPE_VALUES, length); -+ buffer.putShort((short) numValues); -+ buffer.put(nCopies(numValues, DATA_TYPE_GAUGE)); -+ buffer.order(ByteOrder.LITTLE_ENDIAN); -+ for (Number value : values) { -+ buffer.putDouble(value.doubleValue()); - } -+ buffer.order(ByteOrder.BIG_ENDIAN); -+ } - -- private void write(ByteBuffer buffer, Number... values) { -- final int numValues = values.length; -- final int length = HEADER_LEN + VALUE_COUNT_LEN + numValues * VALUE_LEN; -- writeHeader(buffer, TYPE_VALUES, length); -- buffer.putShort((short) numValues); -- buffer.put(nCopies(numValues, DATA_TYPE_GAUGE)); -- buffer.order(ByteOrder.LITTLE_ENDIAN); -- for (Number value : values) { -- buffer.putDouble(value.doubleValue()); -- } -- buffer.order(ByteOrder.BIG_ENDIAN); -- } -+ private byte[] nCopies(int n, byte value) { -+ final byte[] array = new byte[n]; -+ Arrays.fill(array, value); -+ return array; -+ } - -- private byte[] nCopies(int n, byte value) { -- final byte[] array = new byte[n]; -- Arrays.fill(array, value); -- return array; -+ private void writeString(ByteBuffer buffer, int type, String val) { -+ if (Strings.isNullOrEmpty(val)) { -+ return; - } -+ int len = HEADER_LEN + val.length() + 1; -+ writeHeader(buffer, type, len); -+ buffer.put(val.getBytes(US_ASCII)).put(NULL); -+ } - -- private void writeString(ByteBuffer buffer, int type, String val) { -- if (val == null || val.length() == 0) { -- return; -- } -- int len = HEADER_LEN + val.length() + 1; -- writeHeader(buffer, type, len); -- buffer.put(val.getBytes(StandardCharsets.US_ASCII)).put(NULL); -- } -+ private void writeNumber(ByteBuffer buffer, int type, long val) { -+ writeHeader(buffer, type, NUMBER_LEN); -+ buffer.putLong(val); -+ } - -- private void writeNumber(ByteBuffer buffer, int type, long val) { -- writeHeader(buffer, type, NUMBER_LEN); -- buffer.putLong(val); -- } -+ private void writeHeader(ByteBuffer buffer, int type, int len) { -+ buffer.putShort((short) type); -+ buffer.putShort((short) len); -+ } - -- private void writeHeader(ByteBuffer buffer, int type, int len) { -- buffer.putShort((short) type); -- buffer.putShort((short) len); -- } -+ /** -+ * Signs the provided packet, so a CollectD server can verify that its authenticity. Wire format: -+ * -+ *
    -+   * +-------------------------------+-------------------------------+
    -+   * ! Type (0x0200)                 ! Length                        !
    -+   * +-------------------------------+-------------------------------+
    -+   * ! Signature (SHA2(username + packet))                           \
    -+   * +-------------------------------+-------------------------------+
    -+   * ! Username                      ! Packet                        \
    -+   * +---------------------------------------------------------------+
    -+   * 
    -+ * -+ * @see Binary -+ * protocol - CollectD | Signature part -+ */ -+ private ByteBuffer signPacket(ByteBuffer packet) { -+ final byte[] signature = -+ sign( -+ password, -+ (ByteBuffer) -+ ByteBuffer.allocate(packet.remaining() + username.length) -+ .put(username) -+ .put(packet) -+ .flip()); -+ return (ByteBuffer) -+ ByteBuffer.allocate(BUFFER_SIZE) -+ .putShort((short) TYPE_SIGN_SHA256) -+ .putShort((short) (username.length + SIGNATURE_LEN)) -+ .put(signature) -+ .put(username) -+ .put((ByteBuffer) packet.flip()) -+ .flip(); -+ } - -- /** -- * Signs the provided packet, so a CollectD server can verify that its authenticity. -- * Wire format: -- *
    --     * +-------------------------------+-------------------------------+
    --     * ! Type (0x0200)                 ! Length                        !
    --     * +-------------------------------+-------------------------------+
    --     * ! Signature (SHA2(username + packet))                           \
    --     * +-------------------------------+-------------------------------+
    --     * ! Username                      ! Packet                        \
    --     * +---------------------------------------------------------------+
    --     * 
    -- * -- * @see -- * Binary protocol - CollectD | Signature part -- */ -- private ByteBuffer signPacket(ByteBuffer packet) { -- final byte[] signature = sign(password, (ByteBuffer) ByteBuffer.allocate(packet.remaining() + username.length) -- .put(username) -- .put(packet) -- .flip()); -- return (ByteBuffer) ByteBuffer.allocate(BUFFER_SIZE) -- .putShort((short) TYPE_SIGN_SHA256) -- .putShort((short) (username.length + SIGNATURE_LEN)) -- .put(signature) -- .put(username) -- .put((ByteBuffer) packet.flip()) -- .flip(); -- } -- -- /** -- * Encrypts the provided packet, so it's can't be eavesdropped during a transfer -- * to a CollectD server. Wire format: -- *
    --     * +---------------------------------+-------------------------------+
    --     * ! Type (0x0210)                   ! Length                        !
    --     * +---------------------------------+-------------------------------+
    --     * ! Username length in bytes        ! Username                      \
    --     * +-----------------------------------------------------------------+
    --     * ! Initialization Vector (IV)      !                               \
    --     * +---------------------------------+-------------------------------+
    --     * ! Encrypted bytes (AES (SHA1(packet) + packet))                   \
    --     * +---------------------------------+-------------------------------+
    --     * 
    -- * -- * @see -- * Binary protocol - CollectD | Encrypted part -- */ -- private ByteBuffer encryptPacket(ByteBuffer packet) { -- final ByteBuffer payload = (ByteBuffer) ByteBuffer.allocate(SHA1_LENGTH + packet.remaining()) -+ /** -+ * Encrypts the provided packet, so it's can't be eavesdropped during a transfer to a CollectD -+ * server. Wire format: -+ * -+ *
    -+   * +---------------------------------+-------------------------------+
    -+   * ! Type (0x0210)                   ! Length                        !
    -+   * +---------------------------------+-------------------------------+
    -+   * ! Username length in bytes        ! Username                      \
    -+   * +-----------------------------------------------------------------+
    -+   * ! Initialization Vector (IV)      !                               \
    -+   * +---------------------------------+-------------------------------+
    -+   * ! Encrypted bytes (AES (SHA1(packet) + packet))                   \
    -+   * +---------------------------------+-------------------------------+
    -+   * 
    -+ * -+ * @see Binary -+ * protocol - CollectD | Encrypted part -+ */ -+ private ByteBuffer encryptPacket(ByteBuffer packet) { -+ final ByteBuffer payload = -+ (ByteBuffer) -+ ByteBuffer.allocate(SHA1_LENGTH + packet.remaining()) - .put(sha1(packet)) - .put((ByteBuffer) packet.flip()) - .flip(); -- final EncryptionResult er = encrypt(password, payload); -- return (ByteBuffer) ByteBuffer.allocate(BUFFER_SIZE) -- .putShort((short) TYPE_ENCR_AES256) -- .putShort((short) (ENCRYPT_DATA_LEN + username.length + er.output.remaining())) -- .putShort((short) username.length) -- .put(username) -- .put(er.iv) -- .put(er.output) -- .flip(); -- } -+ final EncryptionResult er = encrypt(password, payload); -+ return (ByteBuffer) -+ ByteBuffer.allocate(BUFFER_SIZE) -+ .putShort((short) TYPE_ENCR_AES256) -+ .putShort((short) (ENCRYPT_DATA_LEN + username.length + er.output.remaining())) -+ .putShort((short) username.length) -+ .put(username) -+ .put(er.iv) -+ .put(er.output) -+ .flip(); -+ } - -- private static byte[] sign(byte[] secret, ByteBuffer input) { -- final Mac mac; -- try { -- mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); -- mac.init(new SecretKeySpec(secret, HMAC_SHA256_ALGORITHM)); -- } catch (NoSuchAlgorithmException | InvalidKeyException e) { -- throw new RuntimeException(e); -- } -- mac.update(input); -- return mac.doFinal(); -+ private static byte[] sign(byte[] secret, ByteBuffer input) { -+ final Mac mac; -+ try { -+ mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); -+ mac.init(new SecretKeySpec(secret, HMAC_SHA256_ALGORITHM)); -+ } catch (NoSuchAlgorithmException | InvalidKeyException e) { -+ throw new RuntimeException(e); - } -+ mac.update(input); -+ return mac.doFinal(); -+ } - -- private static EncryptionResult encrypt(byte[] password, ByteBuffer input) { -- final Cipher cipher; -- try { -- cipher = Cipher.getInstance(AES_CYPHER); -- cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sha256(password), AES)); -- } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { -- throw new RuntimeException(e); -- } -- final byte[] iv; -- try { -- iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); -- } catch (InvalidParameterSpecException e) { -- throw new RuntimeException(e); -- } -- if (iv.length != IV_LENGTH) { -- throw new IllegalStateException("Bad initialization vector"); -- } -- final ByteBuffer output = ByteBuffer.allocate(input.remaining() * 2); -- try { -- cipher.doFinal(input, output); -- } catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException e) { -- throw new RuntimeException(e); -- } -- return new EncryptionResult(iv, (ByteBuffer) output.flip()); -+ private static EncryptionResult encrypt(byte[] password, ByteBuffer input) { -+ final Cipher cipher; -+ try { -+ cipher = Cipher.getInstance(AES_CYPHER); -+ cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sha256(password), AES)); -+ } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { -+ throw new RuntimeException(e); - } -+ final byte[] iv; -+ try { -+ iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); -+ } catch (InvalidParameterSpecException e) { -+ throw new RuntimeException(e); -+ } -+ checkState(iv.length == IV_LENGTH, "Bad initialization vector"); -+ final ByteBuffer output = ByteBuffer.allocate(input.remaining() * 2); -+ try { -+ cipher.doFinal(input, output); -+ } catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException e) { -+ throw new RuntimeException(e); -+ } -+ return new EncryptionResult(iv, (ByteBuffer) output.flip()); -+ } - -- private static byte[] sha256(byte[] input) { -- try { -- return MessageDigest.getInstance(SHA_256_ALGORITHM).digest(input); -- } catch (NoSuchAlgorithmException e) { -- throw new RuntimeException(e); -- } -+ private static byte[] sha256(byte[] input) { -+ try { -+ return MessageDigest.getInstance(SHA_256_ALGORITHM).digest(input); -+ } catch (NoSuchAlgorithmException e) { -+ throw new RuntimeException(e); - } -+ } - -- private static byte[] sha1(ByteBuffer input) { -- try { -- final MessageDigest digest = MessageDigest.getInstance(SHA_1_ALGORITHM); -- digest.update(input); -- final byte[] output = digest.digest(); -- if (output.length != SHA1_LENGTH) { -- throw new IllegalStateException("Bad SHA1 hash"); -- } -- return output; -- } catch (NoSuchAlgorithmException e) { -- throw new RuntimeException(e); -- } -+ private static byte[] sha1(ByteBuffer input) { -+ try { -+ final MessageDigest digest = MessageDigest.getInstance(SHA_1_ALGORITHM); -+ digest.update(input); -+ final byte[] output = digest.digest(); -+ checkState(output.length == SHA1_LENGTH, "Bad SHA1 hash"); -+ return output; -+ } catch (NoSuchAlgorithmException e) { -+ throw new RuntimeException(e); - } -+ } - -- private static class EncryptionResult { -+ private static class EncryptionResult { - -- private final byte[] iv; -- private final ByteBuffer output; -+ private final byte[] iv; -+ private final ByteBuffer output; - -- private EncryptionResult(byte[] iv, ByteBuffer output) { -- this.iv = iv; -- this.output = output; -- } -+ private EncryptionResult(byte[] iv, ByteBuffer output) { -+ this.iv = iv; -+ this.output = output; - } -- -+ } - } ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sanitize.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sanitize.java -@@ -8,39 +8,38 @@ import java.util.List; - */ - class Sanitize { - -- static final int DEFAULT_MAX_LENGTH = 63; -+ static final int DEFAULT_MAX_LENGTH = 63; - -- private static final char DASH = '-'; -- private static final char SLASH = '/'; -- private static final char NULL = '\0'; -- private static final char UNDERSCORE = '_'; -+ private static final char DASH = '-'; -+ private static final char SLASH = '/'; -+ private static final char NULL = '\0'; -+ private static final char UNDERSCORE = '_'; - -- private static final List INSTANCE_RESERVED = Arrays.asList(SLASH, NULL); -- private static final List NAME_RESERVED = Arrays.asList(DASH, SLASH, NULL); -+ private static final List INSTANCE_RESERVED = Arrays.asList(SLASH, NULL); -+ private static final List NAME_RESERVED = Arrays.asList(DASH, SLASH, NULL); - -- private final int maxLength; -+ private final int maxLength; - -- Sanitize(int maxLength) { -- this.maxLength = maxLength; -- } -+ Sanitize(int maxLength) { -+ this.maxLength = maxLength; -+ } - -- String name(String name) { -- return sanitize(name, NAME_RESERVED); -- } -+ String name(String name) { -+ return sanitize(name, NAME_RESERVED); -+ } - -- String instanceName(String instanceName) { -- return sanitize(instanceName, INSTANCE_RESERVED); -- } -+ String instanceName(String instanceName) { -+ return sanitize(instanceName, INSTANCE_RESERVED); -+ } - -- private String sanitize(String string, List reservedChars) { -- final StringBuilder buffer = new StringBuilder(string.length()); -- final int len = Math.min(string.length(), maxLength); -- for (int i = 0; i < len; i++) { -- final char c = string.charAt(i); -- final boolean legal = ((int) c) < 128 && !reservedChars.contains(c); -- buffer.append(legal ? c : UNDERSCORE); -- } -- return buffer.toString(); -+ private String sanitize(String string, List reservedChars) { -+ final StringBuilder buffer = new StringBuilder(string.length()); -+ final int len = Math.min(string.length(), maxLength); -+ for (int i = 0; i < len; i++) { -+ final char c = string.charAt(i); -+ final boolean legal = ((int) c) < 128 && !reservedChars.contains(c); -+ buffer.append(legal ? c : UNDERSCORE); - } -- -+ return buffer.toString(); -+ } - } ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/SecurityConfiguration.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/SecurityConfiguration.java -@@ -2,29 +2,29 @@ package io.dropwizard.metrics5.collectd; - - public class SecurityConfiguration { - -- private final byte[] username; -- private final byte[] password; -- private final SecurityLevel securityLevel; -+ private final byte[] username; -+ private final byte[] password; -+ private final SecurityLevel securityLevel; - -- public SecurityConfiguration(byte[] username, byte[] password, SecurityLevel securityLevel) { -- this.username = username; -- this.password = password; -- this.securityLevel = securityLevel; -- } -+ public SecurityConfiguration(byte[] username, byte[] password, SecurityLevel securityLevel) { -+ this.username = username; -+ this.password = password; -+ this.securityLevel = securityLevel; -+ } - -- public static SecurityConfiguration none() { -- return new SecurityConfiguration(null, null, SecurityLevel.NONE); -- } -+ public static SecurityConfiguration none() { -+ return new SecurityConfiguration(null, null, SecurityLevel.NONE); -+ } - -- public byte[] getUsername() { -- return username; -- } -+ public byte[] getUsername() { -+ return username; -+ } - -- public byte[] getPassword() { -- return password; -- } -+ public byte[] getPassword() { -+ return password; -+ } - -- public SecurityLevel getSecurityLevel() { -- return securityLevel; -- } -+ public SecurityLevel getSecurityLevel() { -+ return securityLevel; -+ } - } ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/SecurityLevel.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/SecurityLevel.java -@@ -1,8 +1,7 @@ - package io.dropwizard.metrics5.collectd; - - public enum SecurityLevel { -- -- NONE, -- SIGN, -- ENCRYPT -+ NONE, -+ SIGN, -+ ENCRYPT - } ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.collectd; - -+import static com.google.common.base.Preconditions.checkState; -+ - import java.io.IOException; - import java.net.InetSocketAddress; - import java.nio.ByteBuffer; -@@ -7,44 +9,41 @@ import java.nio.channels.DatagramChannel; - - public class Sender { - -- private final String host; -- private final int port; -+ private final String host; -+ private final int port; - -- private InetSocketAddress address; -- private DatagramChannel channel; -+ private InetSocketAddress address; -+ private DatagramChannel channel; - -- public Sender(String host, int port) { -- this.host = host; -- this.port = port; -- } -+ public Sender(String host, int port) { -+ this.host = host; -+ this.port = port; -+ } - -- public void connect() throws IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -- if (host != null) { -- address = new InetSocketAddress(host, port); -- } -- channel = DatagramChannel.open(); -+ public void connect() throws IOException { -+ checkState(!isConnected(), "Already connected"); -+ if (host != null) { -+ address = new InetSocketAddress(host, port); - } -+ channel = DatagramChannel.open(); -+ } - -- public boolean isConnected() { -- return channel != null && !channel.socket().isClosed(); -- } -+ public boolean isConnected() { -+ return channel != null && !channel.socket().isClosed(); -+ } - -- public void send(ByteBuffer buffer) throws IOException { -- channel.send(buffer, address); -- } -+ public void send(ByteBuffer buffer) throws IOException { -+ channel.send(buffer, address); -+ } - -- public void disconnect() throws IOException { -- if (channel == null) { -- return; -- } -- try { -- channel.close(); -- } finally { -- channel = null; -- } -+ public void disconnect() throws IOException { -+ if (channel == null) { -+ return; - } -- -+ try { -+ channel.close(); -+ } finally { -+ channel = null; -+ } -+ } - } ---- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java -+++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java -@@ -1,33 +1,37 @@ - package io.dropwizard.metrics5.collectd; - -+import static org.assertj.core.api.Assertions.assertThatThrownBy; -+ - import io.dropwizard.metrics5.MetricRegistry; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -- -class CollectdReporterSecurityTest { +final class CollectdReporterSecurityTest { -- private final MetricRegistry registry = new MetricRegistry(); -+ private final MetricRegistry registry = new MetricRegistry(); + private final MetricRegistry registry = new MetricRegistry(); -- @Test -- void testUnableSetSecurityLevelToSignWithoutUsername() { -- assertThatIllegalArgumentException().isThrownBy(() -> -+ @Test + @Test +- void testUnableSetSecurityLevelToSignWithoutUsername() { +- assertThatIllegalArgumentException() +- .isThrownBy( + void unableSetSecurityLevelToSignWithoutUsername() { + assertThatThrownBy( -+ () -> + () -> CollectdReporter.forRegistry(registry) -- .withHostName("eddie") -- .withSecurityLevel(SecurityLevel.SIGN) -- .withPassword("t1_g3r") -- .build(new Sender("localhost", 25826))) -- .withMessage("username is required for securityLevel: SIGN"); -- } -+ .withHostName("eddie") -+ .withSecurityLevel(SecurityLevel.SIGN) -+ .withPassword("t1_g3r") -+ .build(new Sender("localhost", 25826))) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withPassword("t1_g3r") + .build(new Sender("localhost", 25826))) +- .withMessage("username is required for securityLevel: SIGN"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("username is required for securityLevel: SIGN"); -+ } + } -- @Test -- void testUnableSetSecurityLevelToSignWithoutPassword() { -- assertThatIllegalArgumentException().isThrownBy(() -> -+ @Test + @Test +- void testUnableSetSecurityLevelToSignWithoutPassword() { +- assertThatIllegalArgumentException() +- .isThrownBy( + void unableSetSecurityLevelToSignWithoutPassword() { + assertThatThrownBy( -+ () -> + () -> CollectdReporter.forRegistry(registry) -- .withHostName("eddie") -- .withSecurityLevel(SecurityLevel.SIGN) -- .withUsername("scott") -- .build(new Sender("localhost", 25826))) -- .withMessage("password is required for securityLevel: SIGN"); -- } -+ .withHostName("eddie") -+ .withSecurityLevel(SecurityLevel.SIGN) -+ .withUsername("scott") -+ .build(new Sender("localhost", 25826))) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withUsername("scott") + .build(new Sender("localhost", 25826))) +- .withMessage("password is required for securityLevel: SIGN"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("password is required for securityLevel: SIGN"); -+ } + } } --- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java +++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java -@@ -1,5 +1,14 @@ +@@ -1,11 +1,14 @@ package io.dropwizard.metrics5.collectd; +import static java.util.Collections.emptySortedMap; -+import static java.util.concurrent.TimeUnit.MILLISECONDS; -+import static org.assertj.core.api.Assertions.assertThat; + import static java.util.concurrent.TimeUnit.MILLISECONDS; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import io.dropwizard.metrics5.Counter; import io.dropwizard.metrics5.Histogram; import io.dropwizard.metrics5.Meter; -@@ -8,315 +17,280 @@ import io.dropwizard.metrics5.MetricName; +@@ -14,7 +17,6 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.Snapshot; import io.dropwizard.metrics5.Timer; --import org.collectd.api.ValueList; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; --import org.junit.jupiter.api.extension.RegisterExtension; -- -import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; - import java.util.SortedMap; - import java.util.TreeMap; -+import org.collectd.api.ValueList; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; -+import org.junit.jupiter.api.extension.RegisterExtension; +@@ -25,7 +27,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.junit.jupiter.api.extension.RegisterExtension; --import static java.util.concurrent.TimeUnit.MILLISECONDS; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- -public class CollectdReporterTest { -- @RegisterExtension -- public static Receiver receiver = new Receiver(25826); -- -- private final MetricRegistry registry = new MetricRegistry(); -- private CollectdReporter reporter; -- -- @BeforeEach -- void setUp() { -- reporter = CollectdReporter.forRegistry(registry) -- .withHostName("eddie") -- .build(new Sender("localhost", 25826)); -- } -- -- @Test -- void reportsByteGauges() throws Exception { -- reportsGauges((byte) 128); -- } -- -- @Test -- void reportsShortGauges() throws Exception { -- reportsGauges((short) 2048); -- } -- -- @Test -- void reportsIntegerGauges() throws Exception { -- reportsGauges(42); -- } -- -- @Test -- void reportsLongGauges() throws Exception { -- reportsGauges(Long.MAX_VALUE); -- } -- -- @Test -- void reportsFloatGauges() throws Exception { -- reportsGauges(0.25); -- } -- -- @Test -- void reportsDoubleGauges() throws Exception { -- reportsGauges(0.125d); -- } -- -- private void reportsGauges(T value) throws Exception { -- reporter.report( -- map(MetricName.build("gauge"), () -> value), -- map(), -- map(), -- map(), -- map()); -- -- assertThat(nextValues(receiver)).containsExactly(value.doubleValue()); -- } -- -- @Test -- void reportsBooleanGauges() throws Exception { -- reporter.report( -- map(MetricName.build("gauge"), () -> true), -- map(), -- map(), -- map(), -- map()); -- -- assertThat(nextValues(receiver)).containsExactly(1d); -- -- reporter.report( -- map(MetricName.build("gauge"), () -> false), -- map(), -- map(), -- map(), -- map()); -- -- assertThat(nextValues(receiver)).containsExactly(0d); -- } -- -- @Test -- void doesNotReportStringGauges() throws Exception { -- reporter.report( -- map(MetricName.build("unsupported"), () -> "value"), -- map(), -- map(), -- map(), -- map()); -- -- assertThat(receiver.next()).isNull(); -- } -- -- @Test -- void reportsCounters() throws Exception { -- Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(42L); -- -- reporter.report( -- map(), -- map(MetricName.build("api", "rest", "requests", "count"), counter), -- map(), -- map(), -- map()); -- -- assertThat(nextValues(receiver)).containsExactly(42d); -- } -- -- @Test -- void reportsMeters() throws Exception { -- Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getOneMinuteRate()).thenReturn(2.0); -- when(meter.getFiveMinuteRate()).thenReturn(3.0); -- when(meter.getFifteenMinuteRate()).thenReturn(4.0); -- when(meter.getMeanRate()).thenReturn(5.0); -- -- reporter.report( -- map(), -- map(), -- map(), -- map(MetricName.build("api", "rest", "requests"), meter), -- map()); -- -- assertThat(nextValues(receiver)).containsExactly(1d); -- assertThat(nextValues(receiver)).containsExactly(2d); -- assertThat(nextValues(receiver)).containsExactly(3d); -- assertThat(nextValues(receiver)).containsExactly(4d); -- assertThat(nextValues(receiver)).containsExactly(5d); -- } -- -- @Test -- void reportsHistograms() throws Exception { -- Histogram histogram = mock(Histogram.class); -- Snapshot snapshot = mock(Snapshot.class); -- when(histogram.getCount()).thenReturn(1L); -- when(histogram.getSnapshot()).thenReturn(snapshot); -- when(snapshot.getMax()).thenReturn(2L); -- when(snapshot.getMean()).thenReturn(3.0); -- when(snapshot.getMin()).thenReturn(4L); -- when(snapshot.getStdDev()).thenReturn(5.0); -- when(snapshot.getMedian()).thenReturn(6.0); -- when(snapshot.get75thPercentile()).thenReturn(7.0); -- when(snapshot.get95thPercentile()).thenReturn(8.0); -- when(snapshot.get98thPercentile()).thenReturn(9.0); -- when(snapshot.get99thPercentile()).thenReturn(10.0); -- when(snapshot.get999thPercentile()).thenReturn(11.0); -- -- reporter.report( -- map(), -- map(), -- map(MetricName.build("histogram"), histogram), -- map(), -- map()); -- -- for (int i = 1; i <= 11; i++) { -- assertThat(nextValues(receiver)).containsExactly((double) i); -- } -- } -- -- @Test -- void reportsTimers() throws Exception { -- Timer timer = mock(Timer.class); -- Snapshot snapshot = mock(Snapshot.class); -- when(timer.getSnapshot()).thenReturn(snapshot); -- when(timer.getCount()).thenReturn(1L); -- when(timer.getSnapshot()).thenReturn(snapshot); -- when(snapshot.getMax()).thenReturn(MILLISECONDS.toNanos(100)); -- when(snapshot.getMean()).thenReturn((double) MILLISECONDS.toNanos(200)); -- when(snapshot.getMin()).thenReturn(MILLISECONDS.toNanos(300)); -- when(snapshot.getStdDev()).thenReturn((double) MILLISECONDS.toNanos(400)); -- when(snapshot.getMedian()).thenReturn((double) MILLISECONDS.toNanos(500)); -- when(snapshot.get75thPercentile()).thenReturn((double) MILLISECONDS.toNanos(600)); -- when(snapshot.get95thPercentile()).thenReturn((double) MILLISECONDS.toNanos(700)); -- when(snapshot.get98thPercentile()).thenReturn((double) MILLISECONDS.toNanos(800)); -- when(snapshot.get99thPercentile()).thenReturn((double) MILLISECONDS.toNanos(900)); -- when(snapshot.get999thPercentile()).thenReturn((double) MILLISECONDS.toNanos(1000)); -- when(timer.getOneMinuteRate()).thenReturn(11.0); -- when(timer.getFiveMinuteRate()).thenReturn(12.0); -- when(timer.getFifteenMinuteRate()).thenReturn(13.0); -- when(timer.getMeanRate()).thenReturn(14.0); -- -- reporter.report( -- map(), -- map(), -- map(), -- map(), -- map(MetricName.build("timer"), timer)); -- -- assertThat(nextValues(receiver)).containsExactly(1d); -- assertThat(nextValues(receiver)).containsExactly(100d); -- assertThat(nextValues(receiver)).containsExactly(200d); -- assertThat(nextValues(receiver)).containsExactly(300d); -- assertThat(nextValues(receiver)).containsExactly(400d); -- assertThat(nextValues(receiver)).containsExactly(500d); -- assertThat(nextValues(receiver)).containsExactly(600d); -- assertThat(nextValues(receiver)).containsExactly(700d); -- assertThat(nextValues(receiver)).containsExactly(800d); -- assertThat(nextValues(receiver)).containsExactly(900d); -- assertThat(nextValues(receiver)).containsExactly(1000d); -- assertThat(nextValues(receiver)).containsExactly(11d); -- assertThat(nextValues(receiver)).containsExactly(12d); -- assertThat(nextValues(receiver)).containsExactly(13d); -- assertThat(nextValues(receiver)).containsExactly(14d); -- } -- -- @Test -- void doesNotReportDisabledMetricAttributes() throws Exception { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getOneMinuteRate()).thenReturn(2.0); -- when(meter.getFiveMinuteRate()).thenReturn(3.0); -- when(meter.getFifteenMinuteRate()).thenReturn(4.0); -- when(meter.getMeanRate()).thenReturn(5.0); -- -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(11L); -- -- CollectdReporter reporter = CollectdReporter.forRegistry(registry) -- .withHostName("eddie") -- .disabledMetricAttributes(EnumSet.of(MetricAttribute.M5_RATE, MetricAttribute.M15_RATE)) -- .build(new Sender("localhost", 25826)); -- -- reporter.report( -- map(), -- map(MetricName.build("counter"), counter), -- map(), -- map(MetricName.build("meter"), meter), -- map()); -- -- assertThat(nextValues(receiver)).containsExactly(11d); -- assertThat(nextValues(receiver)).containsExactly(1d); -- assertThat(nextValues(receiver)).containsExactly(2d); -- assertThat(nextValues(receiver)).containsExactly(5d); -- } -- -- @Test -- void sanitizesMetricName() throws Exception { -- Counter counter = registry.counter("dash-illegal.slash/illegal"); -- counter.inc(); -- -- reporter.report(); -- -- ValueList values = receiver.next(); -- assertThat(values.getPlugin()).isEqualTo("dash_illegal.slash_illegal"); +final class CollectdReporterTest { -+ @RegisterExtension public static Receiver receiver = new Receiver(25826); -+ -+ private final MetricRegistry registry = new MetricRegistry(); -+ private CollectdReporter reporter; -+ -+ @BeforeEach -+ void setUp() { -+ reporter = -+ CollectdReporter.forRegistry(registry) -+ .withHostName("eddie") -+ .build(new Sender("localhost", 25826)); -+ } -+ -+ @Test -+ void reportsByteGauges() throws Exception { -+ reportsGauges((byte) 128); -+ } -+ -+ @Test -+ void reportsShortGauges() throws Exception { -+ reportsGauges((short) 2048); -+ } -+ -+ @Test -+ void reportsIntegerGauges() throws Exception { -+ reportsGauges(42); -+ } -+ -+ @Test -+ void reportsLongGauges() throws Exception { -+ reportsGauges(Long.MAX_VALUE); -+ } -+ -+ @Test -+ void reportsFloatGauges() throws Exception { -+ reportsGauges(0.25); -+ } -+ -+ @Test -+ void reportsDoubleGauges() throws Exception { -+ reportsGauges(0.125d); -+ } -+ -+ private void reportsGauges(T value) throws Exception { -+ reporter.report(map(MetricName.build("gauge"), () -> value), map(), map(), map(), map()); -+ -+ assertThat(nextValues(receiver)).containsExactly(value.doubleValue()); -+ } -+ -+ @Test -+ void reportsBooleanGauges() throws Exception { -+ reporter.report(map(MetricName.build("gauge"), () -> true), map(), map(), map(), map()); -+ -+ assertThat(nextValues(receiver)).containsExactly(1d); -+ -+ reporter.report(map(MetricName.build("gauge"), () -> false), map(), map(), map(), map()); -+ -+ assertThat(nextValues(receiver)).containsExactly(0d); -+ } -+ -+ @Test -+ void doesNotReportStringGauges() throws Exception { -+ reporter.report( -+ map(MetricName.build("unsupported"), () -> "value"), map(), map(), map(), map()); -+ -+ assertThat(receiver.next()).isNull(); -+ } -+ -+ @Test -+ void reportsCounters() throws Exception { + @RegisterExtension public static Receiver receiver = new Receiver(25826); + + private final MetricRegistry registry = new MetricRegistry(); +@@ -96,7 +98,7 @@ public class CollectdReporterTest { + + @Test + void reportsCounters() throws Exception { +- Counter counter = mock(Counter.class); + Counter counter = mock(); -+ when(counter.getCount()).thenReturn(42L); -+ -+ reporter.report( -+ map(), -+ map(MetricName.build("api", "rest", "requests", "count"), counter), -+ map(), -+ map(), -+ map()); -+ -+ assertThat(nextValues(receiver)).containsExactly(42d); -+ } -+ -+ @Test -+ void reportsMeters() throws Exception { + when(counter.getCount()).thenReturn(42L); + + reporter.report( +@@ -111,7 +113,7 @@ public class CollectdReporterTest { + + @Test + void reportsMeters() throws Exception { +- Meter meter = mock(Meter.class); + Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getOneMinuteRate()).thenReturn(2.0); -+ when(meter.getFiveMinuteRate()).thenReturn(3.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(4.0); -+ when(meter.getMeanRate()).thenReturn(5.0); -+ -+ reporter.report( -+ map(), map(), map(), map(MetricName.build("api", "rest", "requests"), meter), map()); -+ -+ assertThat(nextValues(receiver)).containsExactly(1d); -+ assertThat(nextValues(receiver)).containsExactly(2d); -+ assertThat(nextValues(receiver)).containsExactly(3d); -+ assertThat(nextValues(receiver)).containsExactly(4d); -+ assertThat(nextValues(receiver)).containsExactly(5d); -+ } -+ -+ @Test -+ void reportsHistograms() throws Exception { + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); +@@ -130,8 +132,8 @@ public class CollectdReporterTest { + + @Test + void reportsHistograms() throws Exception { +- Histogram histogram = mock(Histogram.class); +- Snapshot snapshot = mock(Snapshot.class); + Histogram histogram = mock(); + Snapshot snapshot = mock(); -+ when(histogram.getCount()).thenReturn(1L); -+ when(histogram.getSnapshot()).thenReturn(snapshot); -+ when(snapshot.getMax()).thenReturn(2L); -+ when(snapshot.getMean()).thenReturn(3.0); -+ when(snapshot.getMin()).thenReturn(4L); -+ when(snapshot.getStdDev()).thenReturn(5.0); -+ when(snapshot.getMedian()).thenReturn(6.0); -+ when(snapshot.get75thPercentile()).thenReturn(7.0); -+ when(snapshot.get95thPercentile()).thenReturn(8.0); -+ when(snapshot.get98thPercentile()).thenReturn(9.0); -+ when(snapshot.get99thPercentile()).thenReturn(10.0); -+ when(snapshot.get999thPercentile()).thenReturn(11.0); -+ -+ reporter.report(map(), map(), map(MetricName.build("histogram"), histogram), map(), map()); -+ -+ for (int i = 1; i <= 11; i++) { -+ assertThat(nextValues(receiver)).containsExactly((double) i); - } -- -- @Test -- void testUnableSetSecurityLevelToSignWithoutUsername() { -- assertThatIllegalArgumentException().isThrownBy(() -> -+ } -+ -+ @Test -+ void reportsTimers() throws Exception { + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSnapshot()).thenReturn(snapshot); + when(snapshot.getMax()).thenReturn(2L); +@@ -154,8 +156,8 @@ public class CollectdReporterTest { + + @Test + void reportsTimers() throws Exception { +- Timer timer = mock(Timer.class); +- Snapshot snapshot = mock(Snapshot.class); + Timer timer = mock(); + Snapshot snapshot = mock(); -+ when(timer.getSnapshot()).thenReturn(snapshot); -+ when(timer.getCount()).thenReturn(1L); -+ when(timer.getSnapshot()).thenReturn(snapshot); -+ when(snapshot.getMax()).thenReturn(MILLISECONDS.toNanos(100)); -+ when(snapshot.getMean()).thenReturn((double) MILLISECONDS.toNanos(200)); -+ when(snapshot.getMin()).thenReturn(MILLISECONDS.toNanos(300)); -+ when(snapshot.getStdDev()).thenReturn((double) MILLISECONDS.toNanos(400)); -+ when(snapshot.getMedian()).thenReturn((double) MILLISECONDS.toNanos(500)); -+ when(snapshot.get75thPercentile()).thenReturn((double) MILLISECONDS.toNanos(600)); -+ when(snapshot.get95thPercentile()).thenReturn((double) MILLISECONDS.toNanos(700)); -+ when(snapshot.get98thPercentile()).thenReturn((double) MILLISECONDS.toNanos(800)); -+ when(snapshot.get99thPercentile()).thenReturn((double) MILLISECONDS.toNanos(900)); -+ when(snapshot.get999thPercentile()).thenReturn((double) MILLISECONDS.toNanos(1000)); -+ when(timer.getOneMinuteRate()).thenReturn(11.0); -+ when(timer.getFiveMinuteRate()).thenReturn(12.0); -+ when(timer.getFifteenMinuteRate()).thenReturn(13.0); -+ when(timer.getMeanRate()).thenReturn(14.0); -+ -+ reporter.report(map(), map(), map(), map(), map(MetricName.build("timer"), timer)); -+ -+ assertThat(nextValues(receiver)).containsExactly(1d); -+ assertThat(nextValues(receiver)).containsExactly(100d); -+ assertThat(nextValues(receiver)).containsExactly(200d); -+ assertThat(nextValues(receiver)).containsExactly(300d); -+ assertThat(nextValues(receiver)).containsExactly(400d); -+ assertThat(nextValues(receiver)).containsExactly(500d); -+ assertThat(nextValues(receiver)).containsExactly(600d); -+ assertThat(nextValues(receiver)).containsExactly(700d); -+ assertThat(nextValues(receiver)).containsExactly(800d); -+ assertThat(nextValues(receiver)).containsExactly(900d); -+ assertThat(nextValues(receiver)).containsExactly(1000d); -+ assertThat(nextValues(receiver)).containsExactly(11d); -+ assertThat(nextValues(receiver)).containsExactly(12d); -+ assertThat(nextValues(receiver)).containsExactly(13d); -+ assertThat(nextValues(receiver)).containsExactly(14d); -+ } -+ -+ @Test -+ void doesNotReportDisabledMetricAttributes() throws Exception { + when(timer.getSnapshot()).thenReturn(snapshot); + when(timer.getCount()).thenReturn(1L); + when(timer.getSnapshot()).thenReturn(snapshot); +@@ -195,14 +197,14 @@ public class CollectdReporterTest { + + @Test + void doesNotReportDisabledMetricAttributes() throws Exception { +- final Meter meter = mock(Meter.class); + final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getOneMinuteRate()).thenReturn(2.0); -+ when(meter.getFiveMinuteRate()).thenReturn(3.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(4.0); -+ when(meter.getMeanRate()).thenReturn(5.0); -+ + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); + final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(11L); -+ -+ CollectdReporter reporter = -+ CollectdReporter.forRegistry(registry) -+ .withHostName("eddie") -+ .disabledMetricAttributes(EnumSet.of(MetricAttribute.M5_RATE, MetricAttribute.M15_RATE)) -+ .build(new Sender("localhost", 25826)); -+ -+ reporter.report( -+ map(), -+ map(MetricName.build("counter"), counter), -+ map(), -+ map(MetricName.build("meter"), meter), -+ map()); -+ -+ assertThat(nextValues(receiver)).containsExactly(11d); -+ assertThat(nextValues(receiver)).containsExactly(1d); -+ assertThat(nextValues(receiver)).containsExactly(2d); -+ assertThat(nextValues(receiver)).containsExactly(5d); -+ } -+ -+ @Test -+ void sanitizesMetricName() throws Exception { -+ Counter counter = registry.counter("dash-illegal.slash/illegal"); -+ counter.inc(); -+ -+ reporter.report(); -+ -+ ValueList values = receiver.next(); -+ assertThat(values.getPlugin()).isEqualTo("dash_illegal.slash_illegal"); -+ } -+ -+ @Test + when(counter.getCount()).thenReturn(11L); + + CollectdReporter reporter = +@@ -236,37 +238,37 @@ public class CollectdReporterTest { + } + + @Test +- void testUnableSetSecurityLevelToSignWithoutUsername() { +- assertThatIllegalArgumentException() +- .isThrownBy( + void unableSetSecurityLevelToSignWithoutUsername() { + assertThatThrownBy( -+ () -> + () -> CollectdReporter.forRegistry(registry) -- .withHostName("eddie") -- .withSecurityLevel(SecurityLevel.SIGN) -- .withPassword("t1_g3r") -- .build(new Sender("localhost", 25826))) -- .withMessage("username is required for securityLevel: SIGN"); -- } -- -- @Test -- void testUnableSetSecurityLevelToSignWithoutPassword() { -- assertThatIllegalArgumentException().isThrownBy(() -> -+ .withHostName("eddie") -+ .withSecurityLevel(SecurityLevel.SIGN) -+ .withPassword("t1_g3r") -+ .build(new Sender("localhost", 25826))) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withPassword("t1_g3r") + .build(new Sender("localhost", 25826))) +- .withMessage("username is required for securityLevel: SIGN"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("username is required for securityLevel: SIGN"); -+ } -+ -+ @Test + } + + @Test +- void testUnableSetSecurityLevelToSignWithoutPassword() { +- assertThatIllegalArgumentException() +- .isThrownBy( + void unableSetSecurityLevelToSignWithoutPassword() { + assertThatThrownBy( -+ () -> + () -> CollectdReporter.forRegistry(registry) -- .withHostName("eddie") -- .withSecurityLevel(SecurityLevel.SIGN) -- .withUsername("scott") -- .build(new Sender("localhost", 25826))) -- .withMessage("password is required for securityLevel: SIGN"); -- } -- -- private SortedMap map() { -- return Collections.emptySortedMap(); -- } -- -- private SortedMap map(MetricName name, T metric) { -- final Map map = Collections.singletonMap(name, metric); -- return new TreeMap<>(map); -- } -- -- @Test -- void sanitizesMetricNameWithCustomMaxLength() throws Exception { -- CollectdReporter customReporter = CollectdReporter.forRegistry(registry) -- .withHostName("eddie") -- .withMaxLength(20) -- .build(new Sender("localhost", 25826)); -- -- Counter counter = registry.counter("dash-illegal.slash/illegal"); -- counter.inc(); -- -- customReporter.report(); -- -- ValueList values = receiver.next(); -- assertThat(values.getPlugin()).isEqualTo("dash_illegal.slash_i"); -- } -- -- private List nextValues(Receiver receiver) throws Exception { -- final ValueList valueList = receiver.next(); -- return valueList == null ? Collections.emptyList() : valueList.getValues(); -- } -+ .withHostName("eddie") -+ .withSecurityLevel(SecurityLevel.SIGN) -+ .withUsername("scott") -+ .build(new Sender("localhost", 25826))) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withUsername("scott") + .build(new Sender("localhost", 25826))) +- .withMessage("password is required for securityLevel: SIGN"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("password is required for securityLevel: SIGN"); -+ } -+ -+ private SortedMap map() { + } + + private SortedMap map() { +- return Collections.emptySortedMap(); + return emptySortedMap(); -+ } -+ -+ private SortedMap map(MetricName name, T metric) { + } + + private SortedMap map(MetricName name, T metric) { +- final Map map = Collections.singletonMap(name, metric); + final Map map = ImmutableMap.of(name, metric); -+ return new TreeMap<>(map); -+ } -+ -+ @Test -+ void sanitizesMetricNameWithCustomMaxLength() throws Exception { -+ CollectdReporter customReporter = -+ CollectdReporter.forRegistry(registry) -+ .withHostName("eddie") -+ .withMaxLength(20) -+ .build(new Sender("localhost", 25826)); -+ -+ Counter counter = registry.counter("dash-illegal.slash/illegal"); -+ counter.inc(); -+ -+ customReporter.report(); -+ -+ ValueList values = receiver.next(); -+ assertThat(values.getPlugin()).isEqualTo("dash_illegal.slash_i"); -+ } -+ -+ private List nextValues(Receiver receiver) throws Exception { -+ final ValueList valueList = receiver.next(); + return new TreeMap<>(map); + } + +@@ -289,6 +291,6 @@ public class CollectdReporterTest { + + private List nextValues(Receiver receiver) throws Exception { + final ValueList valueList = receiver.next(); +- return valueList == null ? Collections.emptyList() : valueList.getValues(); + return valueList == null ? ImmutableList.of() : valueList.getValues(); -+ } + } } --- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java +++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java -@@ -1,12 +1,9 @@ - package io.dropwizard.metrics5.collectd; - --import io.dropwizard.metrics5.collectd.SecurityLevel; --import org.junit.jupiter.api.Test; -+import static java.nio.charset.StandardCharsets.UTF_8; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; +@@ -17,7 +17,7 @@ import javax.crypto.spec.IvParameterSpec; + import javax.crypto.spec.SecretKeySpec; + import org.junit.jupiter.api.Test; --import javax.crypto.Cipher; --import javax.crypto.Mac; --import javax.crypto.spec.IvParameterSpec; --import javax.crypto.spec.SecretKeySpec; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.nio.ByteOrder; -@@ -14,182 +11,185 @@ import java.security.InvalidKeyException; - import java.security.MessageDigest; - import java.security.NoSuchAlgorithmException; - import java.util.concurrent.atomic.AtomicBoolean; -+import javax.crypto.Cipher; -+import javax.crypto.Mac; -+import javax.crypto.spec.IvParameterSpec; -+import javax.crypto.spec.SecretKeySpec; -+import org.junit.jupiter.api.Test; - --import static java.nio.charset.StandardCharsets.UTF_8; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.data.Offset.offset; -- -class PacketWriterTest { -- -- private MetaData metaData = new MetaData.Builder("nw-1.alpine.example.com", 1520961345L, 100) -- .type("gauge") -- .typeInstance("value") -- .get(); -- private String username = "scott"; -- private String password = "t1_g$r"; -- -- @Test -- void testSignRequest() throws Exception { -- AtomicBoolean packetVerified = new AtomicBoolean(); -- Sender sender = new Sender("localhost", 4009) { -- @Override -- public void send(ByteBuffer buffer) throws IOException { -- short type = buffer.getShort(); -- assertThat(type).isEqualTo((short) 512); -- short length = buffer.getShort(); -- assertThat(length).isEqualTo((short) 41); -- byte[] packetSignature = new byte[32]; -- buffer.get(packetSignature, 0, 32); -- -- byte[] packetUsername = new byte[length - 36]; -- buffer.get(packetUsername, 0, packetUsername.length); -- assertThat(new String(packetUsername, UTF_8)).isEqualTo(username); -- -- byte[] packet = new byte[buffer.remaining()]; -- buffer.get(packet); -- -- byte[] usernameAndPacket = new byte[username.length() + packet.length]; -- System.arraycopy(packetUsername, 0, usernameAndPacket, 0, packetUsername.length); -- System.arraycopy(packet, 0, usernameAndPacket, packetUsername.length, packet.length); -- assertThat(sign(usernameAndPacket, password)).isEqualTo(packetSignature); -- -- verifyPacket(packet); -- packetVerified.set(true); -- } -- -- private byte[] sign(byte[] input, String password) { -- Mac mac; -- try { -- mac = Mac.getInstance("HmacSHA256"); -- mac.init(new SecretKeySpec(password.getBytes(UTF_8), "HmacSHA256")); -- } catch (NoSuchAlgorithmException | InvalidKeyException e) { -- throw new RuntimeException(e); -- } -- return mac.doFinal(input); +final class PacketWriterTest { -+ -+ private MetaData metaData = -+ new MetaData.Builder("nw-1.alpine.example.com", 1520961345L, 100) -+ .type("gauge") -+ .typeInstance("value") -+ .get(); -+ private String username = "scott"; -+ private String password = "t1_g$r"; -+ -+ @Test -+ void signRequest() throws Exception { -+ AtomicBoolean packetVerified = new AtomicBoolean(); -+ Sender sender = -+ new Sender("localhost", 4009) { -+ @Override -+ public void send(ByteBuffer buffer) throws IOException { -+ short type = buffer.getShort(); -+ assertThat(type).isEqualTo((short) 512); -+ short length = buffer.getShort(); -+ assertThat(length).isEqualTo((short) 41); -+ byte[] packetSignature = new byte[32]; -+ buffer.get(packetSignature, 0, 32); -+ -+ byte[] packetUsername = new byte[length - 36]; -+ buffer.get(packetUsername, 0, packetUsername.length); -+ assertThat(new String(packetUsername, UTF_8)).isEqualTo(username); -+ -+ byte[] packet = new byte[buffer.remaining()]; -+ buffer.get(packet); -+ -+ byte[] usernameAndPacket = new byte[username.length() + packet.length]; -+ System.arraycopy(packetUsername, 0, usernameAndPacket, 0, packetUsername.length); -+ System.arraycopy(packet, 0, usernameAndPacket, packetUsername.length, packet.length); -+ assertThat(sign(usernameAndPacket, password)).isEqualTo(packetSignature); -+ -+ verifyPacket(packet); -+ packetVerified.set(true); -+ } -+ -+ private byte[] sign(byte[] input, String password) { -+ Mac mac; -+ try { -+ mac = Mac.getInstance("HmacSHA256"); -+ mac.init(new SecretKeySpec(password.getBytes(UTF_8), "HmacSHA256")); -+ } catch (NoSuchAlgorithmException | InvalidKeyException e) { -+ throw new RuntimeException(e); - } -- -+ return mac.doFinal(input); -+ } - }; -- PacketWriter packetWriter = new PacketWriter(sender, username, password, SecurityLevel.SIGN); -- packetWriter.write(metaData, 42); -- assertThat(packetVerified).isTrue(); -- } -- -- @Test -- void testEncryptRequest() throws Exception { -- AtomicBoolean packetVerified = new AtomicBoolean(); -- Sender sender = new Sender("localhost", 4009) { -- @Override -- public void send(ByteBuffer buffer) throws IOException { -- short type = buffer.getShort(); -- assertThat(type).isEqualTo((short) 0x0210); -- short length = buffer.getShort(); -- assertThat(length).isEqualTo((short) 134); -- short usernameLength = buffer.getShort(); -- assertThat(usernameLength).isEqualTo((short) 5); -- byte[] packetUsername = new byte[usernameLength]; -- buffer.get(packetUsername, 0, packetUsername.length); -- assertThat(new String(packetUsername, UTF_8)).isEqualTo(username); -- -- byte[] iv = new byte[16]; -- buffer.get(iv, 0, iv.length); -- byte[] encryptedPacket = new byte[buffer.remaining()]; -- buffer.get(encryptedPacket); -- -- byte[] decryptedPacket = decrypt(iv, encryptedPacket); -- byte[] hash = new byte[20]; -- System.arraycopy(decryptedPacket, 0, hash, 0, 20); -- byte[] rawData = new byte[decryptedPacket.length - 20]; -- System.arraycopy(decryptedPacket, 20, rawData, 0, decryptedPacket.length - 20); -- assertThat(sha1(rawData)).isEqualTo(hash); -- -- verifyPacket(rawData); -- packetVerified.set(true); -- } -- -- private byte[] decrypt(byte[] iv, byte[] input) { -- try { -- Cipher cipher = Cipher.getInstance("AES_256/OFB/NoPadding"); -- cipher.init(Cipher.DECRYPT_MODE, -- new SecretKeySpec(sha256(password.getBytes(UTF_8)), "AES"), -- new IvParameterSpec(iv)); -- return cipher.doFinal(input); -- } catch (Exception e) { -- throw new RuntimeException(e); -- } -+ PacketWriter packetWriter = new PacketWriter(sender, username, password, SecurityLevel.SIGN); -+ packetWriter.write(metaData, 42); -+ assertThat(packetVerified).isTrue(); -+ } -+ -+ @Test -+ void encryptRequest() throws Exception { -+ AtomicBoolean packetVerified = new AtomicBoolean(); -+ Sender sender = -+ new Sender("localhost", 4009) { -+ @Override -+ public void send(ByteBuffer buffer) throws IOException { -+ short type = buffer.getShort(); -+ assertThat(type).isEqualTo((short) 0x0210); -+ short length = buffer.getShort(); -+ assertThat(length).isEqualTo((short) 134); -+ short usernameLength = buffer.getShort(); -+ assertThat(usernameLength).isEqualTo((short) 5); -+ byte[] packetUsername = new byte[usernameLength]; -+ buffer.get(packetUsername, 0, packetUsername.length); -+ assertThat(new String(packetUsername, UTF_8)).isEqualTo(username); -+ -+ byte[] iv = new byte[16]; -+ buffer.get(iv, 0, iv.length); -+ byte[] encryptedPacket = new byte[buffer.remaining()]; -+ buffer.get(encryptedPacket); -+ -+ byte[] decryptedPacket = decrypt(iv, encryptedPacket); -+ byte[] hash = new byte[20]; -+ System.arraycopy(decryptedPacket, 0, hash, 0, 20); -+ byte[] rawData = new byte[decryptedPacket.length - 20]; -+ System.arraycopy(decryptedPacket, 20, rawData, 0, decryptedPacket.length - 20); -+ assertThat(sha1(rawData)).isEqualTo(hash); -+ -+ verifyPacket(rawData); -+ packetVerified.set(true); -+ } -+ -+ private byte[] decrypt(byte[] iv, byte[] input) { -+ try { -+ Cipher cipher = Cipher.getInstance("AES_256/OFB/NoPadding"); -+ cipher.init( -+ Cipher.DECRYPT_MODE, -+ new SecretKeySpec(sha256(password.getBytes(UTF_8)), "AES"), -+ new IvParameterSpec(iv)); -+ return cipher.doFinal(input); -+ } catch (Exception e) { -+ throw new RuntimeException(e); - } -+ } - -- private byte[] sha256(byte[] input) { -- try { -- return MessageDigest.getInstance("SHA-256").digest(input); -- } catch (NoSuchAlgorithmException e) { -- throw new RuntimeException(e); -- } -+ private byte[] sha256(byte[] input) { -+ try { -+ return MessageDigest.getInstance("SHA-256").digest(input); -+ } catch (NoSuchAlgorithmException e) { -+ throw new RuntimeException(e); - } -+ } - -- private byte[] sha1(byte[] input) { -- try { -- return MessageDigest.getInstance("SHA-1").digest(input); -- } catch (NoSuchAlgorithmException e) { -- throw new RuntimeException(e); -- } -+ private byte[] sha1(byte[] input) { -+ try { -+ return MessageDigest.getInstance("SHA-1").digest(input); -+ } catch (NoSuchAlgorithmException e) { -+ throw new RuntimeException(e); - } -+ } - }; -- PacketWriter packetWriter = new PacketWriter(sender, username, password, SecurityLevel.ENCRYPT); -- packetWriter.write(metaData, 42); -- assertThat(packetVerified).isTrue(); -- } -- -- private void verifyPacket(byte[] packetArr) { -- ByteBuffer packet = ByteBuffer.wrap(packetArr); -- -- short hostType = packet.getShort(); -- assertThat(hostType).isEqualTo((short) 0); -- short hostLength = packet.getShort(); -- assertThat(hostLength).isEqualTo((short) 28); -- byte[] host = new byte[hostLength - 5]; -- packet.get(host, 0, host.length); -- assertThat(new String(host, UTF_8)).isEqualTo("nw-1.alpine.example.com"); -- assertThat(packet.get()).isEqualTo((byte) 0); -- -- short timestampType = packet.getShort(); -- assertThat(timestampType).isEqualTo((short) 1); -- short timestampLength = packet.getShort(); -- assertThat(timestampLength).isEqualTo((short) 12); -- assertThat(packet.getLong()).isEqualTo(1520961345L); -- -- short typeType = packet.getShort(); -- assertThat(typeType).isEqualTo((short) 4); -- short typeLength = packet.getShort(); -- assertThat(typeLength).isEqualTo((short) 10); -- byte[] type = new byte[typeLength - 5]; -- packet.get(type, 0, type.length); -- assertThat(new String(type, UTF_8)).isEqualTo("gauge"); -- assertThat(packet.get()).isEqualTo((byte) 0); -- -- short typeInstanceType = packet.getShort(); -- assertThat(typeInstanceType).isEqualTo((short) 5); -- short typeInstanceLength = packet.getShort(); -- assertThat(typeInstanceLength).isEqualTo((short) 10); -- byte[] typeInstance = new byte[typeInstanceLength - 5]; -- packet.get(typeInstance, 0, typeInstance.length); -- assertThat(new String(typeInstance, UTF_8)).isEqualTo("value"); -- assertThat(packet.get()).isEqualTo((byte) 0); -- -- short periodType = packet.getShort(); -- assertThat(periodType).isEqualTo((short) 7); -- short periodLength = packet.getShort(); -- assertThat(periodLength).isEqualTo((short) 12); -- assertThat(packet.getLong()).isEqualTo(100); -- -- short valuesType = packet.getShort(); -- assertThat(valuesType).isEqualTo((short) 6); -- short valuesLength = packet.getShort(); -- assertThat(valuesLength).isEqualTo((short) 15); -- short amountOfValues = packet.getShort(); -- assertThat(amountOfValues).isEqualTo((short) 1); -- byte dataType = packet.get(); -- assertThat(dataType).isEqualTo((byte) 1); -- assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isEqualTo(42.0, offset(0.01)); -- } -- --} -\ No newline at end of file -+ PacketWriter packetWriter = new PacketWriter(sender, username, password, SecurityLevel.ENCRYPT); -+ packetWriter.write(metaData, 42); -+ assertThat(packetVerified).isTrue(); -+ } -+ -+ private void verifyPacket(byte[] packetArr) { -+ ByteBuffer packet = ByteBuffer.wrap(packetArr); -+ -+ short hostType = packet.getShort(); -+ assertThat(hostType).isEqualTo((short) 0); -+ short hostLength = packet.getShort(); -+ assertThat(hostLength).isEqualTo((short) 28); -+ byte[] host = new byte[hostLength - 5]; -+ packet.get(host, 0, host.length); -+ assertThat(new String(host, UTF_8)).isEqualTo("nw-1.alpine.example.com"); -+ assertThat(packet.get()).isEqualTo((byte) 0); -+ -+ short timestampType = packet.getShort(); -+ assertThat(timestampType).isEqualTo((short) 1); -+ short timestampLength = packet.getShort(); -+ assertThat(timestampLength).isEqualTo((short) 12); -+ assertThat(packet.getLong()).isEqualTo(1520961345L); -+ -+ short typeType = packet.getShort(); -+ assertThat(typeType).isEqualTo((short) 4); -+ short typeLength = packet.getShort(); -+ assertThat(typeLength).isEqualTo((short) 10); -+ byte[] type = new byte[typeLength - 5]; -+ packet.get(type, 0, type.length); -+ assertThat(new String(type, UTF_8)).isEqualTo("gauge"); -+ assertThat(packet.get()).isEqualTo((byte) 0); -+ -+ short typeInstanceType = packet.getShort(); -+ assertThat(typeInstanceType).isEqualTo((short) 5); -+ short typeInstanceLength = packet.getShort(); -+ assertThat(typeInstanceLength).isEqualTo((short) 10); -+ byte[] typeInstance = new byte[typeInstanceLength - 5]; -+ packet.get(typeInstance, 0, typeInstance.length); -+ assertThat(new String(typeInstance, UTF_8)).isEqualTo("value"); -+ assertThat(packet.get()).isEqualTo((byte) 0); -+ -+ short periodType = packet.getShort(); -+ assertThat(periodType).isEqualTo((short) 7); -+ short periodLength = packet.getShort(); -+ assertThat(periodLength).isEqualTo((short) 12); -+ assertThat(packet.getLong()).isEqualTo(100); -+ -+ short valuesType = packet.getShort(); -+ assertThat(valuesType).isEqualTo((short) 6); -+ short valuesLength = packet.getShort(); -+ assertThat(valuesLength).isEqualTo((short) 15); -+ short amountOfValues = packet.getShort(); -+ assertThat(amountOfValues).isEqualTo((short) 1); -+ byte dataType = packet.get(); -+ assertThat(dataType).isEqualTo((byte) 1); -+ assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01)); -+ } -+} ---- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/Receiver.java -+++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/Receiver.java -@@ -1,5 +1,11 @@ - package io.dropwizard.metrics5.collectd; - -+import java.net.DatagramSocket; -+import java.net.InetAddress; -+import java.net.InetSocketAddress; -+import java.util.concurrent.BlockingQueue; -+import java.util.concurrent.LinkedBlockingQueue; -+import java.util.concurrent.TimeUnit; - import org.collectd.api.Notification; - import org.collectd.api.ValueList; - import org.collectd.protocol.Dispatcher; -@@ -8,59 +14,55 @@ import org.junit.jupiter.api.extension.AfterAllCallback; - import org.junit.jupiter.api.extension.BeforeAllCallback; - import org.junit.jupiter.api.extension.ExtensionContext; - --import java.net.DatagramSocket; --import java.net.InetAddress; --import java.net.InetSocketAddress; --import java.util.concurrent.BlockingQueue; --import java.util.concurrent.LinkedBlockingQueue; --import java.util.concurrent.TimeUnit; -- - public final class Receiver implements BeforeAllCallback, AfterAllCallback { -- private final int port; -- -- private UdpReceiver receiver; -- private DatagramSocket socket; -- private final BlockingQueue queue = new LinkedBlockingQueue<>(); -+ private final int port; + private MetaData metaData = + new MetaData.Builder("nw-1.alpine.example.com", 1520961345L, 100) +@@ -28,7 +28,7 @@ class PacketWriterTest { + private String password = "t1_g$r"; -- public Receiver(int port) { -- this.port = port; -- } -+ private UdpReceiver receiver; -+ private DatagramSocket socket; -+ private final BlockingQueue queue = new LinkedBlockingQueue<>(); - -+ public Receiver(int port) { -+ this.port = port; -+ } - -- @Override -- public void afterAll(ExtensionContext context) throws Exception { -- receiver.shutdown(); -- socket.close(); -- } -+ @Override -+ public void afterAll(ExtensionContext context) throws Exception { -+ receiver.shutdown(); -+ socket.close(); -+ } - -- @Override -- public void beforeAll(ExtensionContext context) throws Exception { -- socket = new DatagramSocket(null); -- socket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), port)); -+ @Override -+ public void beforeAll(ExtensionContext context) throws Exception { -+ socket = new DatagramSocket(null); -+ socket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), port)); - -- receiver = new UdpReceiver(new Dispatcher() { -- @Override -- public void dispatch(ValueList values) { -+ receiver = -+ new UdpReceiver( -+ new Dispatcher() { -+ @Override -+ public void dispatch(ValueList values) { - queue.offer(new ValueList(values)); -- } -+ } - -- @Override -- public void dispatch(Notification notification) { -+ @Override -+ public void dispatch(Notification notification) { - throw new UnsupportedOperationException(); -- } -- }); -- receiver.setPort(port); -- new Thread(() -> { -- try { -+ } -+ }); -+ receiver.setPort(port); -+ new Thread( -+ () -> { -+ try { - receiver.listen(socket); -- } catch (Exception e) { -+ } catch (Exception e) { - e.printStackTrace(); -- } -- }).start(); -- } -+ } -+ }) -+ .start(); -+ } + @Test +- void testSignRequest() throws Exception { ++ void signRequest() throws Exception { + AtomicBoolean packetVerified = new AtomicBoolean(); + Sender sender = + new Sender("localhost", 4009) { +@@ -74,7 +74,7 @@ class PacketWriterTest { + } -- public ValueList next() throws InterruptedException { -- return queue.poll(2, TimeUnit.SECONDS); -- } -+ public ValueList next() throws InterruptedException { -+ return queue.poll(2, TimeUnit.SECONDS); -+ } + @Test +- void testEncryptRequest() throws Exception { ++ void encryptRequest() throws Exception { + AtomicBoolean packetVerified = new AtomicBoolean(); + Sender sender = + new Sender("localhost", 4009) { +@@ -190,6 +190,6 @@ class PacketWriterTest { + assertThat(amountOfValues).isEqualTo((short) 1); + byte dataType = packet.get(); + assertThat(dataType).isEqualTo((byte) 1); +- assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isEqualTo(42.0, offset(0.01)); ++ assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01)); + } } --- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java +++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java -@@ -1,39 +1,41 @@ - package io.dropwizard.metrics5.collectd; +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; -class SanitizeTest { -- -- private Sanitize sanitize = new Sanitize(Sanitize.DEFAULT_MAX_LENGTH); -- -- @Test -- void replacesIllegalCharactersInName() throws Exception { -- assertThat(sanitize.name("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz_quux"); -- } -- -- @Test -- void replacesIllegalCharactersInInstanceName() throws Exception { -- assertThat(sanitize.instanceName("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz-quux"); -- } -- -- @Test -- void truncatesNamesExceedingMaxLength() throws Exception { -- String longName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; -- assertThat(sanitize.name(longName)).isEqualTo(longName.substring(0, (Sanitize.DEFAULT_MAX_LENGTH))); -- } -- -- @Test -- void truncatesNamesExceedingCustomMaxLength() throws Exception { -- Sanitize customSanitize = new Sanitize(70); -- String longName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; -- assertThat(customSanitize.name(longName)).isEqualTo(longName.substring(0, 70)); -- } -- -- @Test -- void replacesNonASCIICharacters() throws Exception { -- assertThat(sanitize.name("M" + '\u00FC' + "nchen")).isEqualTo("M_nchen"); -- } -+import org.junit.jupiter.api.Test; - +final class SanitizeTest { -+ -+ private Sanitize sanitize = new Sanitize(Sanitize.DEFAULT_MAX_LENGTH); -+ -+ @Test -+ void replacesIllegalCharactersInName() throws Exception { -+ assertThat(sanitize.name("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz_quux"); -+ } -+ -+ @Test -+ void replacesIllegalCharactersInInstanceName() throws Exception { -+ assertThat(sanitize.instanceName("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz-quux"); -+ } -+ -+ @Test -+ void truncatesNamesExceedingMaxLength() throws Exception { -+ String longName = -+ "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; -+ assertThat(sanitize.name(longName)) -+ .isEqualTo(longName.substring(0, (Sanitize.DEFAULT_MAX_LENGTH))); -+ } -+ -+ @Test -+ void truncatesNamesExceedingCustomMaxLength() throws Exception { -+ Sanitize customSanitize = new Sanitize(70); -+ String longName = -+ "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; -+ assertThat(customSanitize.name(longName)).isEqualTo(longName.substring(0, 70)); -+ } -+ -+ @Test -+ void replacesNonASCIICharacters() throws Exception { -+ assertThat(sanitize.name("M" + '\u00FC' + "nchen")).isEqualTo("M_nchen"); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/CachedGauge.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/CachedGauge.java -@@ -10,65 +10,65 @@ import java.util.concurrent.atomic.AtomicReference; - * @param the type of the gauge's value - */ - public abstract class CachedGauge implements Gauge { -- private final Clock clock; -- private final AtomicLong reloadAt; -- private final long timeoutNS; -- private final AtomicReference value; -+ private final Clock clock; -+ private final AtomicLong reloadAt; -+ private final long timeoutNS; -+ private final AtomicReference value; - -- /** -- * Creates a new cached gauge with the given timeout period. -- * -- * @param timeout the timeout -- * @param timeoutUnit the unit of {@code timeout} -- */ -- protected CachedGauge(long timeout, TimeUnit timeoutUnit) { -- this(Clock.defaultClock(), timeout, timeoutUnit); -- } -+ /** -+ * Creates a new cached gauge with the given timeout period. -+ * -+ * @param timeout the timeout -+ * @param timeoutUnit the unit of {@code timeout} -+ */ -+ protected CachedGauge(long timeout, TimeUnit timeoutUnit) { -+ this(Clock.defaultClock(), timeout, timeoutUnit); -+ } - -- /** -- * Creates a new cached gauge with the given clock and timeout period. -- * -- * @param clock the clock used to calculate the timeout -- * @param timeout the timeout -- * @param timeoutUnit the unit of {@code timeout} -- */ -- protected CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit) { -- this.clock = clock; -- this.reloadAt = new AtomicLong(clock.getTick()); -- this.timeoutNS = timeoutUnit.toNanos(timeout); -- this.value = new AtomicReference<>(); -- } -+ /** -+ * Creates a new cached gauge with the given clock and timeout period. -+ * -+ * @param clock the clock used to calculate the timeout -+ * @param timeout the timeout -+ * @param timeoutUnit the unit of {@code timeout} -+ */ -+ protected CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit) { -+ this.clock = clock; -+ this.reloadAt = new AtomicLong(clock.getTick()); -+ this.timeoutNS = timeoutUnit.toNanos(timeout); -+ this.value = new AtomicReference<>(); -+ } - -- /** -- * Loads the value and returns it. -- * -- * @return the new value -- */ -- protected abstract T loadValue(); -+ /** -+ * Loads the value and returns it. -+ * -+ * @return the new value -+ */ -+ protected abstract T loadValue(); - -- @Override -- public T getValue() { -- T currentValue = this.value.get(); -- if (shouldLoad() || currentValue == null) { -- T newValue = loadValue(); -- if (!this.value.compareAndSet(currentValue, newValue)) { -- return this.value.get(); -- } -- return newValue; -- } -- return currentValue; -+ @Override -+ public T getValue() { -+ T currentValue = this.value.get(); -+ if (shouldLoad() || currentValue == null) { -+ T newValue = loadValue(); -+ if (!this.value.compareAndSet(currentValue, newValue)) { -+ return this.value.get(); -+ } -+ return newValue; - } -+ return currentValue; -+ } - -- private boolean shouldLoad() { -- for ( ;; ) { -- final long time = clock.getTick(); -- final long current = reloadAt.get(); -- if (current > time) { -- return false; -- } -- if (reloadAt.compareAndSet(current, time + timeoutNS)) { -- return true; -- } -- } -+ private boolean shouldLoad() { -+ for (; ; ) { -+ final long time = clock.getTick(); -+ final long current = reloadAt.get(); -+ if (current > time) { -+ return false; -+ } -+ if (reloadAt.compareAndSet(current, time + timeoutNS)) { -+ return true; -+ } - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/ChunkedAssociativeLongArray.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ChunkedAssociativeLongArray.java -@@ -1,200 +1,211 @@ - package io.dropwizard.metrics5; -+import static java.lang.System.arraycopy; -+import static java.util.Arrays.binarySearch; -+ - import java.lang.ref.SoftReference; - import java.util.ArrayDeque; - import java.util.Deque; - import java.util.Iterator; + private Sanitize sanitize = new Sanitize(Sanitize.DEFAULT_MAX_LENGTH); --import static java.lang.System.arraycopy; --import static java.util.Arrays.binarySearch; -- - class ChunkedAssociativeLongArray { -- private static final long[] EMPTY = new long[0]; -- private static final int DEFAULT_CHUNK_SIZE = 512; -- private static final int MAX_CACHE_SIZE = 128; -- -- private final int defaultChunkSize; -- -- /* -- * We use this ArrayDeque as cache to store chunks that are expired and removed from main data structure. -- * Then instead of allocating new Chunk immediately we are trying to poll one from this deque. -- * So if you have constant or slowly changing load ChunkedAssociativeLongArray will never -- * throw away old chunks or allocate new ones which makes this data structure almost garbage free. -- */ -- private final ArrayDeque> chunksCache = new ArrayDeque<>(); -- -- private final Deque chunks = new ArrayDeque<>(); -- -- ChunkedAssociativeLongArray() { -- this(DEFAULT_CHUNK_SIZE); -+ private static final long[] EMPTY = new long[0]; -+ private static final int DEFAULT_CHUNK_SIZE = 512; -+ private static final int MAX_CACHE_SIZE = 128; -+ -+ private final int defaultChunkSize; -+ -+ /* -+ * We use this ArrayDeque as cache to store chunks that are expired and removed from main data structure. -+ * Then instead of allocating new Chunk immediately we are trying to poll one from this deque. -+ * So if you have constant or slowly changing load ChunkedAssociativeLongArray will never -+ * throw away old chunks or allocate new ones which makes this data structure almost garbage free. -+ */ -+ private final ArrayDeque> chunksCache = new ArrayDeque<>(); -+ -+ private final Deque chunks = new ArrayDeque<>(); -+ -+ ChunkedAssociativeLongArray() { -+ this(DEFAULT_CHUNK_SIZE); -+ } -+ -+ ChunkedAssociativeLongArray(int chunkSize) { -+ this.defaultChunkSize = chunkSize; -+ } -+ -+ private Chunk allocateChunk() { -+ while (true) { -+ final SoftReference chunkRef = chunksCache.pollLast(); -+ if (chunkRef == null) { -+ return new Chunk(defaultChunkSize); -+ } -+ final Chunk chunk = chunkRef.get(); -+ if (chunk != null) { -+ chunk.cursor = 0; -+ chunk.startIndex = 0; -+ chunk.chunkSize = chunk.keys.length; -+ return chunk; -+ } - } -+ } - -- ChunkedAssociativeLongArray(int chunkSize) { -- this.defaultChunkSize = chunkSize; -+ private void freeChunk(Chunk chunk) { -+ if (chunksCache.size() < MAX_CACHE_SIZE) { -+ chunksCache.add(new SoftReference<>(chunk)); - } -- -- private Chunk allocateChunk() { -- while (true) { -- final SoftReference chunkRef = chunksCache.pollLast(); -- if (chunkRef == null) { -- return new Chunk(defaultChunkSize); -- } -- final Chunk chunk = chunkRef.get(); -- if (chunk != null) { -- chunk.cursor = 0; -- chunk.startIndex = 0; -- chunk.chunkSize = chunk.keys.length; -- return chunk; -- } -- } -+ } -+ -+ synchronized boolean put(long key, long value) { -+ Chunk activeChunk = chunks.peekLast(); -+ if (activeChunk != null -+ && activeChunk.cursor != 0 -+ && activeChunk.keys[activeChunk.cursor - 1] > key) { -+ // key should be the same as last inserted or bigger -+ return false; - } -- -- private void freeChunk(Chunk chunk) { -- if (chunksCache.size() < MAX_CACHE_SIZE) { -- chunksCache.add(new SoftReference<>(chunk)); -- } -+ if (activeChunk == null -+ || activeChunk.cursor - activeChunk.startIndex == activeChunk.chunkSize) { -+ // The last chunk doesn't exist or full -+ activeChunk = allocateChunk(); -+ chunks.add(activeChunk); - } -- -- synchronized boolean put(long key, long value) { -- Chunk activeChunk = chunks.peekLast(); -- if (activeChunk != null && activeChunk.cursor != 0 && activeChunk.keys[activeChunk.cursor - 1] > key) { -- // key should be the same as last inserted or bigger -- return false; -- } -- if (activeChunk == null || activeChunk.cursor - activeChunk.startIndex == activeChunk.chunkSize) { -- // The last chunk doesn't exist or full -- activeChunk = allocateChunk(); -- chunks.add(activeChunk); -- } -- activeChunk.append(key, value); -- return true; -+ activeChunk.append(key, value); -+ return true; -+ } -+ -+ synchronized long[] values() { -+ final int valuesSize = size(); -+ if (valuesSize == 0) { -+ return EMPTY; - } - -- synchronized long[] values() { -- final int valuesSize = size(); -- if (valuesSize == 0) { -- return EMPTY; -- } -- -- final long[] values = new long[valuesSize]; -- int valuesIndex = 0; -- for (Chunk chunk : chunks) { -- int length = chunk.cursor - chunk.startIndex; -- int itemsToCopy = Math.min(valuesSize - valuesIndex, length); -- arraycopy(chunk.values, chunk.startIndex, values, valuesIndex, itemsToCopy); -- valuesIndex += length; -- } -- return values; -+ final long[] values = new long[valuesSize]; -+ int valuesIndex = 0; -+ for (Chunk chunk : chunks) { -+ int length = chunk.cursor - chunk.startIndex; -+ int itemsToCopy = Math.min(valuesSize - valuesIndex, length); -+ arraycopy(chunk.values, chunk.startIndex, values, valuesIndex, itemsToCopy); -+ valuesIndex += length; - } -+ return values; -+ } - -- synchronized int size() { -- int result = 0; -- for (Chunk chunk : chunks) { -- result += chunk.cursor - chunk.startIndex; -- } -- return result; -+ synchronized int size() { -+ int result = 0; -+ for (Chunk chunk : chunks) { -+ result += chunk.cursor - chunk.startIndex; - } -- -- synchronized String out() { -- final StringBuilder builder = new StringBuilder(); -- final Iterator iterator = chunks.iterator(); -- while (iterator.hasNext()) { -- final Chunk chunk = iterator.next(); -- builder.append('['); -- for (int i = chunk.startIndex; i < chunk.cursor; i++) { -- builder.append('(').append(chunk.keys[i]).append(": ") -- .append(chunk.values[i]).append(')').append(' '); -- } -- builder.append(']'); -- if (iterator.hasNext()) { -- builder.append("->"); -- } -- } -- return builder.toString(); -+ return result; -+ } -+ -+ synchronized String out() { -+ final StringBuilder builder = new StringBuilder(); -+ final Iterator iterator = chunks.iterator(); -+ while (iterator.hasNext()) { -+ final Chunk chunk = iterator.next(); -+ builder.append('['); -+ for (int i = chunk.startIndex; i < chunk.cursor; i++) { -+ builder -+ .append('(') -+ .append(chunk.keys[i]) -+ .append(": ") -+ .append(chunk.values[i]) -+ .append(')') -+ .append(' '); -+ } -+ builder.append(']'); -+ if (iterator.hasNext()) { -+ builder.append("->"); -+ } - } -- -- /** -- * Try to trim all beyond specified boundaries. -- * -- * @param startKey the start value for which all elements less than it should be removed. -- * @param endKey the end value for which all elements greater/equals than it should be removed. -+ return builder.toString(); -+ } -+ -+ /** -+ * Try to trim all beyond specified boundaries. -+ * -+ * @param startKey the start value for which all elements less than it should be removed. -+ * @param endKey the end value for which all elements greater/equals than it should be removed. -+ */ -+ synchronized void trim(long startKey, long endKey) { -+ /* -+ * [3, 4, 5, 9] -> [10, 13, 14, 15] -> [21, 24, 29, 30] -> [31] :: start layout -+ * |5______________________________23| :: trim(5, 23) -+ * [5, 9] -> [10, 13, 14, 15] -> [21] :: result layout - */ -- synchronized void trim(long startKey, long endKey) { -- /* -- * [3, 4, 5, 9] -> [10, 13, 14, 15] -> [21, 24, 29, 30] -> [31] :: start layout -- * |5______________________________23| :: trim(5, 23) -- * [5, 9] -> [10, 13, 14, 15] -> [21] :: result layout -- */ -- final Iterator descendingIterator = chunks.descendingIterator(); -- while (descendingIterator.hasNext()) { -- final Chunk currentTail = descendingIterator.next(); -- if (isFirstElementIsEmptyOrGreaterEqualThanKey(currentTail, endKey)) { -- freeChunk(currentTail); -- descendingIterator.remove(); -- } else { -- currentTail.cursor = findFirstIndexOfGreaterEqualElements(currentTail.keys, currentTail.startIndex, -- currentTail.cursor, endKey); -- break; -- } -- } -+ final Iterator descendingIterator = chunks.descendingIterator(); -+ while (descendingIterator.hasNext()) { -+ final Chunk currentTail = descendingIterator.next(); -+ if (isFirstElementIsEmptyOrGreaterEqualThanKey(currentTail, endKey)) { -+ freeChunk(currentTail); -+ descendingIterator.remove(); -+ } else { -+ currentTail.cursor = -+ findFirstIndexOfGreaterEqualElements( -+ currentTail.keys, currentTail.startIndex, currentTail.cursor, endKey); -+ break; -+ } -+ } - -- final Iterator iterator = chunks.iterator(); -- while (iterator.hasNext()) { -- final Chunk currentHead = iterator.next(); -- if (isLastElementIsLessThanKey(currentHead, startKey)) { -- freeChunk(currentHead); -- iterator.remove(); -- } else { -- final int newStartIndex = findFirstIndexOfGreaterEqualElements(currentHead.keys, currentHead.startIndex, -- currentHead.cursor, startKey); -- if (currentHead.startIndex != newStartIndex) { -- currentHead.startIndex = newStartIndex; -- currentHead.chunkSize = currentHead.cursor - currentHead.startIndex; -- } -- break; -- } -+ final Iterator iterator = chunks.iterator(); -+ while (iterator.hasNext()) { -+ final Chunk currentHead = iterator.next(); -+ if (isLastElementIsLessThanKey(currentHead, startKey)) { -+ freeChunk(currentHead); -+ iterator.remove(); -+ } else { -+ final int newStartIndex = -+ findFirstIndexOfGreaterEqualElements( -+ currentHead.keys, currentHead.startIndex, currentHead.cursor, startKey); -+ if (currentHead.startIndex != newStartIndex) { -+ currentHead.startIndex = newStartIndex; -+ currentHead.chunkSize = currentHead.cursor - currentHead.startIndex; - } -+ break; -+ } - } -+ } - -- synchronized void clear() { -- chunks.clear(); -- } -+ synchronized void clear() { -+ chunks.clear(); -+ } - -- private boolean isFirstElementIsEmptyOrGreaterEqualThanKey(Chunk chunk, long key) { -- return chunk.cursor == chunk.startIndex || chunk.keys[chunk.startIndex] >= key; -- } -+ private boolean isFirstElementIsEmptyOrGreaterEqualThanKey(Chunk chunk, long key) { -+ return chunk.cursor == chunk.startIndex || chunk.keys[chunk.startIndex] >= key; -+ } - -- private boolean isLastElementIsLessThanKey(Chunk chunk, long key) { -- return chunk.cursor == chunk.startIndex || chunk.keys[chunk.cursor - 1] < key; -- } -+ private boolean isLastElementIsLessThanKey(Chunk chunk, long key) { -+ return chunk.cursor == chunk.startIndex || chunk.keys[chunk.cursor - 1] < key; -+ } - -- private int findFirstIndexOfGreaterEqualElements(long[] array, int startIndex, int endIndex, long minKey) { -- if (endIndex == startIndex || array[startIndex] >= minKey) { -- return startIndex; -- } -- final int keyIndex = binarySearch(array, startIndex, endIndex, minKey); -- return keyIndex < 0 ? -(keyIndex + 1) : keyIndex; -+ private int findFirstIndexOfGreaterEqualElements( -+ long[] array, int startIndex, int endIndex, long minKey) { -+ if (endIndex == startIndex || array[startIndex] >= minKey) { -+ return startIndex; - } -+ final int keyIndex = binarySearch(array, startIndex, endIndex, minKey); -+ return keyIndex < 0 ? -(keyIndex + 1) : keyIndex; -+ } - -- private static class Chunk { -+ private static class Chunk { - -- private final long[] keys; -- private final long[] values; -+ private final long[] keys; -+ private final long[] values; - -- private int chunkSize; // can differ from keys.length after half clear() -- private int startIndex = 0; -- private int cursor = 0; -+ private int chunkSize; // can differ from keys.length after half clear() -+ private int startIndex = 0; -+ private int cursor = 0; - -- private Chunk(int chunkSize) { -- this.chunkSize = chunkSize; -- this.keys = new long[chunkSize]; -- this.values = new long[chunkSize]; -- } -+ private Chunk(int chunkSize) { -+ this.chunkSize = chunkSize; -+ this.keys = new long[chunkSize]; -+ this.values = new long[chunkSize]; -+ } - -- private void append(long key, long value) { -- keys[cursor] = key; -- values[cursor] = value; -- cursor++; -- } -+ private void append(long key, long value) { -+ keys[cursor] = key; -+ values[cursor] = value; -+ cursor++; - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Clock.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Clock.java -@@ -1,46 +1,42 @@ - package io.dropwizard.metrics5; - --/** -- * An abstraction for how time passes. It is passed to {@link Timer} to track timing. -- */ -+/** An abstraction for how time passes. It is passed to {@link Timer} to track timing. */ - public abstract class Clock { -- /** -- * Returns the current time tick. -- * -- * @return time tick in nanoseconds -- */ -- public abstract long getTick(); -+ /** -+ * Returns the current time tick. -+ * -+ * @return time tick in nanoseconds -+ */ -+ public abstract long getTick(); - -- /** -- * Returns the current time in milliseconds. -- * -- * @return time in milliseconds -- */ -- public long getTime() { -- return System.currentTimeMillis(); -- } -+ /** -+ * Returns the current time in milliseconds. -+ * -+ * @return time in milliseconds -+ */ -+ public long getTime() { -+ return System.currentTimeMillis(); -+ } - -- /** -- * The default clock to use. -- * -- * @return the default {@link Clock} instance -- * @see Clock.UserTimeClock -- */ -- public static Clock defaultClock() { -- return UserTimeClockHolder.DEFAULT; -- } -+ /** -+ * The default clock to use. -+ * -+ * @return the default {@link Clock} instance -+ * @see Clock.UserTimeClock -+ */ -+ public static Clock defaultClock() { -+ return UserTimeClockHolder.DEFAULT; -+ } - -- /** -- * A clock implementation which returns the current time in epoch nanoseconds. -- */ -- public static class UserTimeClock extends Clock { -- @Override -- public long getTick() { -- return System.nanoTime(); -- } -+ /** A clock implementation which returns the current time in epoch nanoseconds. */ -+ public static class UserTimeClock extends Clock { -+ @Override -+ public long getTick() { -+ return System.nanoTime(); - } -+ } - -- private static class UserTimeClockHolder { -- private static final Clock DEFAULT = new UserTimeClock(); -- } -+ private static class UserTimeClockHolder { -+ private static final Clock DEFAULT = new UserTimeClock(); -+ } - } --- a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java +++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java @@ -1,8 +1,8 @@ @@ -4430,82126 +467,10672 @@ import java.util.Date; import java.util.Locale; import java.util.Map; -@@ -12,349 +12,491 @@ import java.util.TimeZone; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; - --/** -- * A reporter which outputs measurements to a {@link PrintStream}, like {@code System.out}. -- */ -+/** A reporter which outputs measurements to a {@link PrintStream}, like {@code System.out}. */ - public class ConsoleReporter extends ScheduledReporter { -+ /** -+ * Returns a new {@link Builder} for {@link ConsoleReporter}. -+ * -+ * @param registry the registry to report -+ * @return a {@link Builder} instance for a {@link ConsoleReporter} -+ */ -+ public static Builder forRegistry(MetricRegistry registry) { -+ return new Builder(registry); -+ } -+ -+ /** -+ * A builder for {@link ConsoleReporter} instances. Defaults to using the default locale and time -+ * zone, writing to {@code System.out}, converting rates to events/second, converting durations to -+ * milliseconds, and not filtering metrics. -+ */ -+ public static class Builder { -+ private final MetricRegistry registry; -+ private PrintStream output; -+ private Locale locale; -+ private Clock clock; -+ private TimeZone timeZone; -+ private TimeUnit rateUnit; -+ private TimeUnit durationUnit; -+ private MetricFilter filter; -+ private ScheduledExecutorService executor; -+ private boolean shutdownExecutorOnStop; -+ private Set disabledMetricAttributes; -+ -+ private Builder(MetricRegistry registry) { -+ this.registry = registry; -+ this.output = System.out; -+ this.locale = Locale.getDefault(); -+ this.clock = Clock.defaultClock(); -+ this.timeZone = TimeZone.getDefault(); -+ this.rateUnit = TimeUnit.SECONDS; -+ this.durationUnit = TimeUnit.MILLISECONDS; -+ this.filter = MetricFilter.ALL; -+ this.executor = null; -+ this.shutdownExecutorOnStop = true; +@@ -53,7 +53,7 @@ public class ConsoleReporter extends ScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- disabledMetricAttributes = Collections.emptySet(); + disabledMetricAttributes = ImmutableSet.of(); -+ } -+ - /** -- * Returns a new {@link Builder} for {@link ConsoleReporter}. -+ * Specifies whether or not, the executor (used for reporting) will be stopped with same time -+ * with reporter. Default value is true. Setting this parameter to false, has the sense in -+ * combining with providing external managed executor via {@link -+ * #scheduleOn(ScheduledExecutorService)}. - * -- * @param registry the registry to report -- * @return a {@link Builder} instance for a {@link ConsoleReporter} -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ * @return {@code this} - */ -- public static Builder forRegistry(MetricRegistry registry) { -- return new Builder(registry); -+ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -+ this.shutdownExecutorOnStop = shutdownExecutorOnStop; -+ return this; } /** -- * A builder for {@link ConsoleReporter} instances. Defaults to using the default locale and -- * time zone, writing to {@code System.out}, converting rates to events/second, converting -- * durations to milliseconds, and not filtering metrics. -+ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. -+ * Null value leads to executor will be auto created on start. -+ * -+ * @param executor the executor to use while scheduling reporting of metrics. -+ * @return {@code this} - */ -- public static class Builder { -- private final MetricRegistry registry; -- private PrintStream output; -- private Locale locale; -- private Clock clock; -- private TimeZone timeZone; -- private TimeUnit rateUnit; -- private TimeUnit durationUnit; -- private MetricFilter filter; -- private ScheduledExecutorService executor; -- private boolean shutdownExecutorOnStop; -- private Set disabledMetricAttributes; -- -- private Builder(MetricRegistry registry) { -- this.registry = registry; -- this.output = System.out; -- this.locale = Locale.getDefault(); -- this.clock = Clock.defaultClock(); -- this.timeZone = TimeZone.getDefault(); -- this.rateUnit = TimeUnit.SECONDS; -- this.durationUnit = TimeUnit.MILLISECONDS; -- this.filter = MetricFilter.ALL; -- this.executor = null; -- this.shutdownExecutorOnStop = true; -- disabledMetricAttributes = Collections.emptySet(); -- } -- -- /** -- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. -- * Default value is true. -- * Setting this parameter to false, has the sense in combining with providing external managed executor via {@link #scheduleOn(ScheduledExecutorService)}. -- * -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- * @return {@code this} -- */ -- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -- this.shutdownExecutorOnStop = shutdownExecutorOnStop; -- return this; -- } -- -- /** -- * Specifies the executor to use while scheduling reporting of metrics. -- * Default value is null. -- * Null value leads to executor will be auto created on start. -- * -- * @param executor the executor to use while scheduling reporting of metrics. -- * @return {@code this} -- */ -- public Builder scheduleOn(ScheduledExecutorService executor) { -- this.executor = executor; -- return this; -- } -- -- /** -- * Write to the given {@link PrintStream}. -- * -- * @param output a {@link PrintStream} instance. -- * @return {@code this} -- */ -- public Builder outputTo(PrintStream output) { -- this.output = output; -- return this; -- } -- -- /** -- * Format numbers for the given {@link Locale}. -- * -- * @param locale a {@link Locale} -- * @return {@code this} -- */ -- public Builder formattedFor(Locale locale) { -- this.locale = locale; -- return this; -- } -- -- /** -- * Use the given {@link Clock} instance for the time. -- * -- * @param clock a {@link Clock} instance -- * @return {@code this} -- */ -- public Builder withClock(Clock clock) { -- this.clock = clock; -- return this; -- } -- -- /** -- * Use the given {@link TimeZone} for the time. -- * -- * @param timeZone a {@link TimeZone} -- * @return {@code this} -- */ -- public Builder formattedFor(TimeZone timeZone) { -- this.timeZone = timeZone; -- return this; -- } -- -- /** -- * Convert rates to the given time unit. -- * -- * @param rateUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertRatesTo(TimeUnit rateUnit) { -- this.rateUnit = rateUnit; -- return this; -- } -- -- /** -- * Convert durations to the given time unit. -- * -- * @param durationUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertDurationsTo(TimeUnit durationUnit) { -- this.durationUnit = durationUnit; -- return this; -- } -- -- /** -- * Only report metrics which match the given filter. -- * -- * @param filter a {@link MetricFilter} -- * @return {@code this} -- */ -- public Builder filter(MetricFilter filter) { -- this.filter = filter; -- return this; -- } -- -- /** -- * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). -- * See {@link MetricAttribute}. -- * -- * @param disabledMetricAttributes a {@link MetricFilter} -- * @return {@code this} -- */ -- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -- this.disabledMetricAttributes = disabledMetricAttributes; -- return this; -- } -- -- /** -- * Builds a {@link ConsoleReporter} with the given properties. -- * -- * @return a {@link ConsoleReporter} -- */ -- public ConsoleReporter build() { -- return new ConsoleReporter(registry, -- output, -- locale, -- clock, -- timeZone, -- rateUnit, -- durationUnit, -- filter, -- executor, -- shutdownExecutorOnStop, -- disabledMetricAttributes); -- } -+ public Builder scheduleOn(ScheduledExecutorService executor) { -+ this.executor = executor; -+ return this; +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java +@@ -179,7 +179,7 @@ public class CsvReporter extends ScheduledReporter { } + } -- private static final int CONSOLE_WIDTH = 80; -- -- private final PrintStream output; -- private final Locale locale; -- private final Clock clock; -- private final DateFormat dateFormat; -- -- private ConsoleReporter(MetricRegistry registry, -- PrintStream output, -- Locale locale, -- Clock clock, -- TimeZone timeZone, -- TimeUnit rateUnit, -- TimeUnit durationUnit, -- MetricFilter filter, -- ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop, -- Set disabledMetricAttributes) { -- super(registry, "console-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, disabledMetricAttributes); -- this.output = output; -- this.locale = locale; -- this.clock = clock; -- this.dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, -- DateFormat.MEDIUM, -- locale); -- dateFormat.setTimeZone(timeZone); -+ /** -+ * Write to the given {@link PrintStream}. -+ * -+ * @param output a {@link PrintStream} instance. -+ * @return {@code this} -+ */ -+ public Builder outputTo(PrintStream output) { -+ this.output = output; -+ return this; - } +- private static final Logger LOGGER = LoggerFactory.getLogger(CsvReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(CsvReporter.class); -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap> gauges, -- SortedMap counters, -- SortedMap histograms, -- SortedMap meters, -- SortedMap timers) { -- final String dateTime = dateFormat.format(new Date(clock.getTime())); -- printWithBanner(dateTime, '='); -- output.println(); -- -- if (!gauges.isEmpty()) { -- printWithBanner("-- Gauges", '-'); -- for (Map.Entry> entry : gauges.entrySet()) { -- output.println(entry.getKey()); -- printGauge(entry.getValue()); -- } -- output.println(); -- } -- -- if (!counters.isEmpty()) { -- printWithBanner("-- Counters", '-'); -- for (Map.Entry entry : counters.entrySet()) { -- output.println(entry.getKey()); -- printCounter(entry); -- } -- output.println(); -- } -- -- if (!histograms.isEmpty()) { -- printWithBanner("-- Histograms", '-'); -- for (Map.Entry entry : histograms.entrySet()) { -- output.println(entry.getKey()); -- printHistogram(entry.getValue()); -- } -- output.println(); -- } -- -- if (!meters.isEmpty()) { -- printWithBanner("-- Meters", '-'); -- for (Map.Entry entry : meters.entrySet()) { -- output.println(entry.getKey()); -- printMeter(entry.getValue()); -- } -- output.println(); -- } -- -- if (!timers.isEmpty()) { -- printWithBanner("-- Timers", '-'); -- for (Map.Entry entry : timers.entrySet()) { -- output.println(entry.getKey()); -- printTimer(entry.getValue()); -- } -- output.println(); -- } -- -- output.println(); -- output.flush(); -+ /** -+ * Format numbers for the given {@link Locale}. -+ * -+ * @param locale a {@link Locale} -+ * @return {@code this} -+ */ -+ public Builder formattedFor(Locale locale) { -+ this.locale = locale; -+ return this; + private final File directory; + private final Locale locale; +@@ -391,7 +391,7 @@ public class CsvReporter extends ScheduledReporter { + } + } + } catch (IOException e) { +- LOGGER.warn("Error writing to {}", name, e); ++ LOG.warn("Error writing to {}", name, e); } + } -- private void printMeter(Meter meter) { -- printIfEnabled(MetricAttribute.COUNT, String.format(locale, " count = %d", meter.getCount())); -- printIfEnabled(MetricAttribute.SUM, String.format(locale, " sum = %d", meter.getSum())); -- printIfEnabled(MetricAttribute.MEAN_RATE, String.format(locale, " mean rate = %2.2f events/%s", convertRate(meter.getMeanRate()), getRateUnit())); -- printIfEnabled(MetricAttribute.M1_RATE, String.format(locale, " 1-minute rate = %2.2f events/%s", convertRate(meter.getOneMinuteRate()), getRateUnit())); -- printIfEnabled(MetricAttribute.M5_RATE, String.format(locale, " 5-minute rate = %2.2f events/%s", convertRate(meter.getFiveMinuteRate()), getRateUnit())); -- printIfEnabled(MetricAttribute.M15_RATE, String.format(locale, " 15-minute rate = %2.2f events/%s", convertRate(meter.getFifteenMinuteRate()), getRateUnit())); -+ /** -+ * Use the given {@link Clock} instance for the time. -+ * -+ * @param clock a {@link Clock} instance -+ * @return {@code this} -+ */ -+ public Builder withClock(Clock clock) { -+ this.clock = clock; -+ return this; - } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java +@@ -17,9 +17,9 @@ public class ExponentialMovingAverages implements MovingAverages { + * If ticking would reduce even Long.MAX_VALUE in the 15 minute EWMA below this target then don't + * bother ticking in a loop and instead reset all the EWMAs. + */ +- private static final double maxTickZeroTarget = 0.0001; ++ private static final double MAX_TICK_ZERO_TARGET = 0.0001; -- private void printCounter(Map.Entry entry) { -- output.printf(locale, " count = %d%n", entry.getValue().getCount()); -+ /** -+ * Use the given {@link TimeZone} for the time. -+ * -+ * @param timeZone a {@link TimeZone} -+ * @return {@code this} -+ */ -+ public Builder formattedFor(TimeZone timeZone) { -+ this.timeZone = timeZone; -+ return this; - } +- private static final int maxTicks; ++ private static final int MAX_TICKS; + private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5); + + static { +@@ -29,8 +29,8 @@ public class ExponentialMovingAverages implements MovingAverages { + do { + m3.tick(); + m3Ticks++; +- } while (m3.getRate(TimeUnit.SECONDS) > maxTickZeroTarget); +- maxTicks = m3Ticks; ++ } while (m3.getRate(TimeUnit.SECONDS) > MAX_TICK_ZERO_TARGET); ++ MAX_TICKS = m3Ticks; + } -- private void printGauge(Gauge gauge) { -- output.printf(locale, " value = %s%n", gauge.getValue()); -+ /** -+ * Convert rates to the given time unit. -+ * -+ * @param rateUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertRatesTo(TimeUnit rateUnit) { -+ this.rateUnit = rateUnit; -+ return this; - } + private final EWMA m1Rate = EWMA.oneMinuteEWMA(); +@@ -69,7 +69,7 @@ public class ExponentialMovingAverages implements MovingAverages { + if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) { + sum.add(age); + final long requiredTicks = age / TICK_INTERVAL; +- if (requiredTicks >= maxTicks) { ++ if (requiredTicks >= MAX_TICKS) { + m1Rate.reset(); + m5Rate.reset(); + m15Rate.reset(); +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java +@@ -1,8 +1,10 @@ + package io.dropwizard.metrics5; -- private void printHistogram(Histogram histogram) { -- printIfEnabled(MetricAttribute.COUNT, String.format(locale, " count = %d", histogram.getCount())); -- printIfEnabled(MetricAttribute.SUM, String.format(locale, " sum = %d", histogram.getSum())); -- Snapshot snapshot = histogram.getSnapshot(); -- printIfEnabled(MetricAttribute.MIN, String.format(locale, " min = %d", snapshot.getMin())); -- printIfEnabled(MetricAttribute.MAX, String.format(locale, " max = %d", snapshot.getMax())); -- printIfEnabled(MetricAttribute.MEAN, String.format(locale, " mean = %2.2f", snapshot.getMean())); -- printIfEnabled(MetricAttribute.STDDEV, String.format(locale, " stddev = %2.2f", snapshot.getStdDev())); -- printIfEnabled(MetricAttribute.P50, String.format(locale, " median = %2.2f", snapshot.getMedian())); -- printIfEnabled(MetricAttribute.P75, String.format(locale, " 75%% <= %2.2f", snapshot.get75thPercentile())); -- printIfEnabled(MetricAttribute.P95, String.format(locale, " 95%% <= %2.2f", snapshot.get95thPercentile())); -- printIfEnabled(MetricAttribute.P98, String.format(locale, " 98%% <= %2.2f", snapshot.get98thPercentile())); -- printIfEnabled(MetricAttribute.P99, String.format(locale, " 99%% <= %2.2f", snapshot.get99thPercentile())); -- printIfEnabled(MetricAttribute.P999, String.format(locale, " 99.9%% <= %2.2f", snapshot.get999thPercentile())); -+ /** -+ * Convert durations to the given time unit. -+ * -+ * @param durationUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertDurationsTo(TimeUnit durationUnit) { -+ this.durationUnit = durationUnit; -+ return this; - } ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Objects.requireNonNull; ++ + import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; + import java.time.Duration; +-import java.util.Objects; + import java.util.concurrent.ConcurrentSkipListMap; + import java.util.concurrent.ThreadLocalRandom; + import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +@@ -41,7 +43,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { -- private void printTimer(Timer timer) { -- final Snapshot snapshot = timer.getSnapshot(); -- printIfEnabled(MetricAttribute.COUNT, String.format(locale, " count = %d", timer.getCount())); -- printIfEnabled(MetricAttribute.SUM, String.format(locale, " sum = %2.2f", convertDuration(timer.getSum()))); -- printIfEnabled(MetricAttribute.MEAN_RATE, String.format(locale, " mean rate = %2.2f calls/%s", convertRate(timer.getMeanRate()), getRateUnit())); -- printIfEnabled(MetricAttribute.M1_RATE, String.format(locale, " 1-minute rate = %2.2f calls/%s", convertRate(timer.getOneMinuteRate()), getRateUnit())); -- printIfEnabled(MetricAttribute.M5_RATE, String.format(locale, " 5-minute rate = %2.2f calls/%s", convertRate(timer.getFiveMinuteRate()), getRateUnit())); -- printIfEnabled(MetricAttribute.M15_RATE, String.format(locale, " 15-minute rate = %2.2f calls/%s", convertRate(timer.getFifteenMinuteRate()), getRateUnit())); -- -- printIfEnabled(MetricAttribute.MIN, String.format(locale, " min = %2.2f %s", convertDuration(snapshot.getMin()), getDurationUnit())); -- printIfEnabled(MetricAttribute.MAX, String.format(locale, " max = %2.2f %s", convertDuration(snapshot.getMax()), getDurationUnit())); -- printIfEnabled(MetricAttribute.MEAN, String.format(locale, " mean = %2.2f %s", convertDuration(snapshot.getMean()), getDurationUnit())); -- printIfEnabled(MetricAttribute.STDDEV, String.format(locale, " stddev = %2.2f %s", convertDuration(snapshot.getStdDev()), getDurationUnit())); -- printIfEnabled(MetricAttribute.P50, String.format(locale, " median = %2.2f %s", convertDuration(snapshot.getMedian()), getDurationUnit())); -- printIfEnabled(MetricAttribute.P75, String.format(locale, " 75%% <= %2.2f %s", convertDuration(snapshot.get75thPercentile()), getDurationUnit())); -- printIfEnabled(MetricAttribute.P95, String.format(locale, " 95%% <= %2.2f %s", convertDuration(snapshot.get95thPercentile()), getDurationUnit())); -- printIfEnabled(MetricAttribute.P98, String.format(locale, " 98%% <= %2.2f %s", convertDuration(snapshot.get98thPercentile()), getDurationUnit())); -- printIfEnabled(MetricAttribute.P99, String.format(locale, " 99%% <= %2.2f %s", convertDuration(snapshot.get99thPercentile()), getDurationUnit())); -- printIfEnabled(MetricAttribute.P999, String.format(locale, " 99.9%% <= %2.2f %s", convertDuration(snapshot.get999thPercentile()), getDurationUnit())); -+ /** -+ * Only report metrics which match the given filter. -+ * -+ * @param filter a {@link MetricFilter} -+ * @return {@code this} -+ */ -+ public Builder filter(MetricFilter filter) { -+ this.filter = filter; -+ return this; + private static final double SECONDS_PER_NANO = .000_000_001D; + private static final AtomicReferenceFieldUpdater +- stateUpdater = ++ STATE_UPDATER = + AtomicReferenceFieldUpdater.newUpdater( + LockFreeExponentiallyDecayingReservoir.class, State.class, "state"); + +@@ -53,7 +55,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + + private static final class State { + +- private static final AtomicIntegerFieldUpdater countUpdater = ++ private static final AtomicIntegerFieldUpdater COUNT_UPDATER = + AtomicIntegerFieldUpdater.newUpdater(State.class, "count"); + + private final double alphaNanos; +@@ -89,7 +91,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + private void addSample( + double priority, long value, double itemWeight, boolean bypassIncrement) { + if (values.putIfAbsent(priority, new WeightedSample(value, itemWeight)) == null +- && (bypassIncrement || countUpdater.incrementAndGet(this) > size)) { ++ && (bypassIncrement || COUNT_UPDATER.incrementAndGet(this) > size)) { + values.pollFirstEntry(); + } + } +@@ -126,7 +128,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + // It's possible that more values were added while the map was scanned, those with the + // minimum priorities are removed. + while (newCount > size) { +- Objects.requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); ++ requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); + newCount--; + } + return new State(alphaNanos, size, newTick, newCount, newValues); +@@ -193,7 +195,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + + private State doRescale(long currentTick, State stateSnapshot) { + State newState = stateSnapshot.rescale(currentTick); +- if (stateUpdater.compareAndSet(this, stateSnapshot, newState)) { ++ if (STATE_UPDATER.compareAndSet(this, stateSnapshot, newState)) { + // newState successfully installed + return newState; + } +@@ -235,10 +237,8 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + * are replaced (based on weight, with some amount of random jitter). + */ + public Builder size(int value) { +- if (value <= 0) { +- throw new IllegalArgumentException( +- "LockFreeExponentiallyDecayingReservoir size must be positive: " + value); +- } ++ checkArgument( ++ value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: %s", value); + this.size = value; + return this; } +@@ -254,13 +254,13 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { -- private void printWithBanner(String s, char c) { -- output.print(s); -- output.print(' '); -- for (int i = 0; i < (CONSOLE_WIDTH - s.length() - 1); i++) { -- output.print(c); -- } -- output.println(); -+ /** -+ * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). -+ * See {@link MetricAttribute}. -+ * -+ * @param disabledMetricAttributes a {@link MetricFilter} -+ * @return {@code this} -+ */ -+ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -+ this.disabledMetricAttributes = disabledMetricAttributes; -+ return this; + /** Interval at which this reservoir is rescaled. */ + public Builder rescaleThreshold(Duration value) { +- this.rescaleThreshold = Objects.requireNonNull(value, "rescaleThreshold is required"); ++ this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required"); + return this; } - /** -- * Print only if the attribute is enabled -+ * Builds a {@link ConsoleReporter} with the given properties. - * -- * @param type Metric attribute -- * @param status Status to be logged -+ * @return a {@link ConsoleReporter} - */ -- private void printIfEnabled(MetricAttribute type, String status) { -- if (getDisabledMetricAttributes().contains(type)) { -- return; -- } -+ public ConsoleReporter build() { -+ return new ConsoleReporter( -+ registry, -+ output, -+ locale, -+ clock, -+ timeZone, -+ rateUnit, -+ durationUnit, -+ filter, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes); -+ } -+ } -+ -+ private static final int CONSOLE_WIDTH = 80; -+ -+ private final PrintStream output; -+ private final Locale locale; -+ private final Clock clock; -+ private final DateFormat dateFormat; -+ -+ private ConsoleReporter( -+ MetricRegistry registry, -+ PrintStream output, -+ Locale locale, -+ Clock clock, -+ TimeZone timeZone, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ MetricFilter filter, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes) { -+ super( -+ registry, -+ "console-reporter", -+ filter, -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes); -+ this.output = output; -+ this.locale = locale; -+ this.clock = clock; -+ this.dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale); -+ dateFormat.setTimeZone(timeZone); -+ } -+ -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap> gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ final String dateTime = dateFormat.format(new Date(clock.getTime())); -+ printWithBanner(dateTime, '='); -+ output.println(); -+ -+ if (!gauges.isEmpty()) { -+ printWithBanner("-- Gauges", '-'); -+ for (Map.Entry> entry : gauges.entrySet()) { -+ output.println(entry.getKey()); -+ printGauge(entry.getValue()); -+ } -+ output.println(); -+ } - -- output.println(status); -+ if (!counters.isEmpty()) { -+ printWithBanner("-- Counters", '-'); -+ for (Map.Entry entry : counters.entrySet()) { -+ output.println(entry.getKey()); -+ printCounter(entry); -+ } -+ output.println(); + /** Clock instance used for decay. */ + public Builder clock(Clock value) { +- this.clock = Objects.requireNonNull(value, "clock is required"); ++ this.clock = requireNonNull(value, "clock is required"); + return this; } -+ -+ if (!histograms.isEmpty()) { -+ printWithBanner("-- Histograms", '-'); -+ for (Map.Entry entry : histograms.entrySet()) { -+ output.println(entry.getKey()); -+ printHistogram(entry.getValue()); -+ } -+ output.println(); -+ } -+ -+ if (!meters.isEmpty()) { -+ printWithBanner("-- Meters", '-'); -+ for (Map.Entry entry : meters.entrySet()) { -+ output.println(entry.getKey()); -+ printMeter(entry.getValue()); -+ } -+ output.println(); -+ } -+ -+ if (!timers.isEmpty()) { -+ printWithBanner("-- Timers", '-'); -+ for (Map.Entry entry : timers.entrySet()) { -+ output.println(entry.getKey()); -+ printTimer(entry.getValue()); -+ } -+ output.println(); -+ } -+ -+ output.println(); -+ output.flush(); -+ } -+ -+ private void printMeter(Meter meter) { -+ printIfEnabled( -+ MetricAttribute.COUNT, String.format(locale, " count = %d", meter.getCount())); -+ printIfEnabled( -+ MetricAttribute.SUM, String.format(locale, " sum = %d", meter.getSum())); -+ printIfEnabled( -+ MetricAttribute.MEAN_RATE, -+ String.format( -+ locale, -+ " mean rate = %2.2f events/%s", -+ convertRate(meter.getMeanRate()), -+ getRateUnit())); -+ printIfEnabled( -+ MetricAttribute.M1_RATE, -+ String.format( -+ locale, -+ " 1-minute rate = %2.2f events/%s", -+ convertRate(meter.getOneMinuteRate()), -+ getRateUnit())); -+ printIfEnabled( -+ MetricAttribute.M5_RATE, -+ String.format( -+ locale, -+ " 5-minute rate = %2.2f events/%s", -+ convertRate(meter.getFiveMinuteRate()), -+ getRateUnit())); -+ printIfEnabled( -+ MetricAttribute.M15_RATE, -+ String.format( -+ locale, -+ " 15-minute rate = %2.2f events/%s", -+ convertRate(meter.getFifteenMinuteRate()), -+ getRateUnit())); -+ } -+ -+ private void printCounter(Map.Entry entry) { -+ output.printf(locale, " count = %d%n", entry.getValue().getCount()); -+ } -+ -+ private void printGauge(Gauge gauge) { -+ output.printf(locale, " value = %s%n", gauge.getValue()); -+ } -+ -+ private void printHistogram(Histogram histogram) { -+ printIfEnabled( -+ MetricAttribute.COUNT, -+ String.format(locale, " count = %d", histogram.getCount())); -+ printIfEnabled( -+ MetricAttribute.SUM, String.format(locale, " sum = %d", histogram.getSum())); -+ Snapshot snapshot = histogram.getSnapshot(); -+ printIfEnabled( -+ MetricAttribute.MIN, String.format(locale, " min = %d", snapshot.getMin())); -+ printIfEnabled( -+ MetricAttribute.MAX, String.format(locale, " max = %d", snapshot.getMax())); -+ printIfEnabled( -+ MetricAttribute.MEAN, -+ String.format(locale, " mean = %2.2f", snapshot.getMean())); -+ printIfEnabled( -+ MetricAttribute.STDDEV, -+ String.format(locale, " stddev = %2.2f", snapshot.getStdDev())); -+ printIfEnabled( -+ MetricAttribute.P50, -+ String.format(locale, " median = %2.2f", snapshot.getMedian())); -+ printIfEnabled( -+ MetricAttribute.P75, -+ String.format(locale, " 75%% <= %2.2f", snapshot.get75thPercentile())); -+ printIfEnabled( -+ MetricAttribute.P95, -+ String.format(locale, " 95%% <= %2.2f", snapshot.get95thPercentile())); -+ printIfEnabled( -+ MetricAttribute.P98, -+ String.format(locale, " 98%% <= %2.2f", snapshot.get98thPercentile())); -+ printIfEnabled( -+ MetricAttribute.P99, -+ String.format(locale, " 99%% <= %2.2f", snapshot.get99thPercentile())); -+ printIfEnabled( -+ MetricAttribute.P999, -+ String.format(locale, " 99.9%% <= %2.2f", snapshot.get999thPercentile())); -+ } -+ -+ private void printTimer(Timer timer) { -+ final Snapshot snapshot = timer.getSnapshot(); -+ printIfEnabled( -+ MetricAttribute.COUNT, String.format(locale, " count = %d", timer.getCount())); -+ printIfEnabled( -+ MetricAttribute.SUM, -+ String.format(locale, " sum = %2.2f", convertDuration(timer.getSum()))); -+ printIfEnabled( -+ MetricAttribute.MEAN_RATE, -+ String.format( -+ locale, -+ " mean rate = %2.2f calls/%s", -+ convertRate(timer.getMeanRate()), -+ getRateUnit())); -+ printIfEnabled( -+ MetricAttribute.M1_RATE, -+ String.format( -+ locale, -+ " 1-minute rate = %2.2f calls/%s", -+ convertRate(timer.getOneMinuteRate()), -+ getRateUnit())); -+ printIfEnabled( -+ MetricAttribute.M5_RATE, -+ String.format( -+ locale, -+ " 5-minute rate = %2.2f calls/%s", -+ convertRate(timer.getFiveMinuteRate()), -+ getRateUnit())); -+ printIfEnabled( -+ MetricAttribute.M15_RATE, -+ String.format( -+ locale, -+ " 15-minute rate = %2.2f calls/%s", -+ convertRate(timer.getFifteenMinuteRate()), -+ getRateUnit())); -+ -+ printIfEnabled( -+ MetricAttribute.MIN, -+ String.format( -+ locale, -+ " min = %2.2f %s", -+ convertDuration(snapshot.getMin()), -+ getDurationUnit())); -+ printIfEnabled( -+ MetricAttribute.MAX, -+ String.format( -+ locale, -+ " max = %2.2f %s", -+ convertDuration(snapshot.getMax()), -+ getDurationUnit())); -+ printIfEnabled( -+ MetricAttribute.MEAN, -+ String.format( -+ locale, -+ " mean = %2.2f %s", -+ convertDuration(snapshot.getMean()), -+ getDurationUnit())); -+ printIfEnabled( -+ MetricAttribute.STDDEV, -+ String.format( -+ locale, -+ " stddev = %2.2f %s", -+ convertDuration(snapshot.getStdDev()), -+ getDurationUnit())); -+ printIfEnabled( -+ MetricAttribute.P50, -+ String.format( -+ locale, -+ " median = %2.2f %s", -+ convertDuration(snapshot.getMedian()), -+ getDurationUnit())); -+ printIfEnabled( -+ MetricAttribute.P75, -+ String.format( -+ locale, -+ " 75%% <= %2.2f %s", -+ convertDuration(snapshot.get75thPercentile()), -+ getDurationUnit())); -+ printIfEnabled( -+ MetricAttribute.P95, -+ String.format( -+ locale, -+ " 95%% <= %2.2f %s", -+ convertDuration(snapshot.get95thPercentile()), -+ getDurationUnit())); -+ printIfEnabled( -+ MetricAttribute.P98, -+ String.format( -+ locale, -+ " 98%% <= %2.2f %s", -+ convertDuration(snapshot.get98thPercentile()), -+ getDurationUnit())); -+ printIfEnabled( -+ MetricAttribute.P99, -+ String.format( -+ locale, -+ " 99%% <= %2.2f %s", -+ convertDuration(snapshot.get99thPercentile()), -+ getDurationUnit())); -+ printIfEnabled( -+ MetricAttribute.P999, -+ String.format( -+ locale, -+ " 99.9%% <= %2.2f %s", -+ convertDuration(snapshot.get999thPercentile()), -+ getDurationUnit())); -+ } -+ -+ private void printWithBanner(String s, char c) { -+ output.print(s); -+ output.print(' '); -+ for (int i = 0; i < (CONSOLE_WIDTH - s.length() - 1); i++) { -+ output.print(c); -+ } -+ output.println(); -+ } -+ -+ /** -+ * Print only if the attribute is enabled -+ * -+ * @param type Metric attribute -+ * @param status Status to be logged -+ */ -+ private void printIfEnabled(MetricAttribute type, String status) { -+ if (getDisabledMetricAttributes().contains(type)) { -+ return; -+ } -+ -+ output.println(status); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Counter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Counter.java -@@ -2,55 +2,49 @@ package io.dropwizard.metrics5; - - import java.util.concurrent.atomic.LongAdder; - --/** -- * An incrementing and decrementing counter metric. -- */ -+/** An incrementing and decrementing counter metric. */ - public class Counter implements Metric, Counting { -- private final LongAdder count; -- -- public Counter() { -- this.count = new LongAdder(); -- } -- -- /** -- * Increment the counter by one. -- */ -- public void inc() { -- inc(1); -- } -- -- /** -- * Increment the counter by {@code n}. -- * -- * @param n the amount by which the counter will be increased -- */ -- public void inc(long n) { -- count.add(n); -- } -- -- /** -- * Decrement the counter by one. -- */ -- public void dec() { -- dec(1); -- } -- -- /** -- * Decrement the counter by {@code n}. -- * -- * @param n the amount by which the counter will be decreased -- */ -- public void dec(long n) { -- count.add(-n); -- } -- -- /** -- * Returns the counter's current value. -- * -- * @return the counter's current value -- */ -- @Override -- public long getCount() { -- return count.sum(); -- } -+ private final LongAdder count; -+ -+ public Counter() { -+ this.count = new LongAdder(); -+ } -+ -+ /** Increment the counter by one. */ -+ public void inc() { -+ inc(1); -+ } -+ -+ /** -+ * Increment the counter by {@code n}. -+ * -+ * @param n the amount by which the counter will be increased -+ */ -+ public void inc(long n) { -+ count.add(n); -+ } -+ -+ /** Decrement the counter by one. */ -+ public void dec() { -+ dec(1); -+ } -+ -+ /** -+ * Decrement the counter by {@code n}. -+ * -+ * @param n the amount by which the counter will be decreased -+ */ -+ public void dec(long n) { -+ count.add(-n); -+ } -+ -+ /** -+ * Returns the counter's current value. -+ * -+ * @return the counter's current value -+ */ -+ @Override -+ public long getCount() { -+ return count.sum(); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Counting.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Counting.java -@@ -1,13 +1,11 @@ + +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java +@@ -1,13 +1,19 @@ package io.dropwizard.metrics5; --/** -- * An interface for metric types which have counts. -- */ -+/** An interface for metric types which have counts. */ - public interface Counting { -- /** -- * Returns the current count. -- * -- * @return the current count -- */ -- long getCount(); -+ /** -+ * Returns the current count. -+ * -+ * @return the current count -+ */ -+ long getCount(); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/CsvFileProvider.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/CsvFileProvider.java -@@ -3,10 +3,10 @@ package io.dropwizard.metrics5; - import java.io.File; +-import java.util.Collections; +-import java.util.Comparator; ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Collections.unmodifiableMap; ++import static java.util.Map.Entry.comparingByKey; ++import static java.util.Objects.requireNonNull; ++import static java.util.stream.Collectors.joining; ++ ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableMap; ++import java.util.Arrays; + import java.util.HashMap; + import java.util.Iterator; + import java.util.LinkedHashMap; + import java.util.Map; + import java.util.Objects; +-import java.util.stream.Collectors; + import java.util.stream.Stream; /** -- * This interface allows a pluggable implementation of what file names -- * the {@link CsvReporter} will write to. -+ * This interface allows a pluggable implementation of what file names the {@link CsvReporter} will -+ * write to. - */ - public interface CsvFileProvider { +@@ -17,7 +23,7 @@ import java.util.stream.Stream; + public class MetricName implements Comparable { -- File getFile(File directory, String metricName); -+ File getFile(File directory, String metricName); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5; + private static final String SEPARATOR = "."; +- private static final Map EMPTY_TAGS = Collections.emptyMap(); ++ private static final Map EMPTY_TAGS = ImmutableMap.of(); + static final MetricName EMPTY = new MetricName("", EMPTY_TAGS); --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -+import static java.nio.charset.StandardCharsets.UTF_8; + /** +@@ -33,7 +39,7 @@ public class MetricName implements Comparable { + private final Map tags; - import java.io.File; - import java.io.FileOutputStream; -@@ -13,335 +12,390 @@ import java.util.Map; - import java.util.SortedMap; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; + public MetricName(String key, Map tags) { +- this.key = Objects.requireNonNull(key); ++ this.key = requireNonNull(key); + this.tags = tags.isEmpty() ? EMPTY_TAGS : unmodifiableSortedCopy(tags); + } --import static java.nio.charset.StandardCharsets.UTF_8; -- --/** -- * A reporter which creates a comma-separated values file of the measurements for each metric. -- */ -+/** A reporter which creates a comma-separated values file of the measurements for each metric. */ - public class CsvReporter extends ScheduledReporter { -- private static final String DEFAULT_SEPARATOR = ","; -+ private static final String DEFAULT_SEPARATOR = ","; -+ -+ /** -+ * Returns a new {@link Builder} for {@link CsvReporter}. -+ * -+ * @param registry the registry to report -+ * @return a {@link Builder} instance for a {@link CsvReporter} -+ */ -+ public static Builder forRegistry(MetricRegistry registry) { -+ return new Builder(registry); -+ } -+ -+ /** -+ * A builder for {@link CsvReporter} instances. Defaults to using the default locale, converting -+ * rates to events/second, converting durations to milliseconds, and not filtering metrics. -+ */ -+ public static class Builder { -+ private final MetricRegistry registry; -+ private Locale locale; -+ private String separator; -+ private TimeUnit rateUnit; -+ private TimeUnit durationUnit; -+ private Clock clock; -+ private MetricFilter filter; -+ private ScheduledExecutorService executor; -+ private boolean shutdownExecutorOnStop; -+ private CsvFileProvider csvFileProvider; -+ -+ private Builder(MetricRegistry registry) { -+ this.registry = registry; -+ this.locale = Locale.getDefault(); -+ this.separator = DEFAULT_SEPARATOR; -+ this.rateUnit = TimeUnit.SECONDS; -+ this.durationUnit = TimeUnit.MILLISECONDS; -+ this.clock = Clock.defaultClock(); -+ this.filter = MetricFilter.ALL; -+ this.executor = null; -+ this.shutdownExecutorOnStop = true; -+ this.csvFileProvider = new FixedNameCsvFileProvider(); -+ } +@@ -63,9 +69,9 @@ public class MetricName implements Comparable { + } - /** -- * Returns a new {@link Builder} for {@link CsvReporter}. -+ * Specifies whether or not, the executor (used for reporting) will be stopped with same time -+ * with reporter. Default value is true. Setting this parameter to false, has the sense in -+ * combining with providing external managed executor via {@link -+ * #scheduleOn(ScheduledExecutorService)}. - * -- * @param registry the registry to report -- * @return a {@link Builder} instance for a {@link CsvReporter} -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ * @return {@code this} - */ -- public static Builder forRegistry(MetricRegistry registry) { -- return new Builder(registry); -+ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -+ this.shutdownExecutorOnStop = shutdownExecutorOnStop; -+ return this; + String newKey = +- Stream.concat(Stream.of(key), Stream.of(parts)) +- .filter(s -> s != null && !s.isEmpty()) +- .collect(Collectors.joining(SEPARATOR)); ++ Stream.concat(Stream.of(key), Arrays.stream(parts)) ++ .filter(s -> !Strings.isNullOrEmpty(s)) ++ .collect(joining(SEPARATOR)); + return new MetricName(newKey, tags); + } + +@@ -94,9 +100,7 @@ public class MetricName implements Comparable { + return this; } - /** -- * A builder for {@link CsvReporter} instances. Defaults to using the default locale, converting -- * rates to events/second, converting durations to milliseconds, and not filtering metrics. -+ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. -+ * Null value leads to executor will be auto created on start. -+ * -+ * @param executor the executor to use while scheduling reporting of metrics. -+ * @return {@code this} - */ -- public static class Builder { -- private final MetricRegistry registry; -- private Locale locale; -- private String separator; -- private TimeUnit rateUnit; -- private TimeUnit durationUnit; -- private Clock clock; -- private MetricFilter filter; -- private ScheduledExecutorService executor; -- private boolean shutdownExecutorOnStop; -- private CsvFileProvider csvFileProvider; -- -- private Builder(MetricRegistry registry) { -- this.registry = registry; -- this.locale = Locale.getDefault(); -- this.separator = DEFAULT_SEPARATOR; -- this.rateUnit = TimeUnit.SECONDS; -- this.durationUnit = TimeUnit.MILLISECONDS; -- this.clock = Clock.defaultClock(); -- this.filter = MetricFilter.ALL; -- this.executor = null; -- this.shutdownExecutorOnStop = true; -- this.csvFileProvider = new FixedNameCsvFileProvider(); -- } -- -- /** -- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. -- * Default value is true. -- * Setting this parameter to false, has the sense in combining with providing external managed executor via {@link #scheduleOn(ScheduledExecutorService)}. -- * -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- * @return {@code this} -- */ -- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -- this.shutdownExecutorOnStop = shutdownExecutorOnStop; -- return this; -- } -- -- /** -- * Specifies the executor to use while scheduling reporting of metrics. -- * Default value is null. -- * Null value leads to executor will be auto created on start. -- * -- * @param executor the executor to use while scheduling reporting of metrics. -- * @return {@code this} -- */ -- public Builder scheduleOn(ScheduledExecutorService executor) { -- this.executor = executor; -- return this; -- } -- -- /** -- * Format numbers for the given {@link Locale}. -- * -- * @param locale a {@link Locale} -- * @return {@code this} -- */ -- public Builder formatFor(Locale locale) { -- this.locale = locale; -- return this; -- } -- -- /** -- * Convert rates to the given time unit. -- * -- * @param rateUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertRatesTo(TimeUnit rateUnit) { -- this.rateUnit = rateUnit; -- return this; -- } -- -- /** -- * Convert durations to the given time unit. -- * -- * @param durationUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertDurationsTo(TimeUnit durationUnit) { -- this.durationUnit = durationUnit; -- return this; -- } -- -- /** -- * Use the given string to use as the separator for values. -- * -- * @param separator the string to use for the separator. -- * @return {@code this} -- */ -- public Builder withSeparator(String separator) { -- this.separator = separator; -- return this; -- } -- -- /** -- * Use the given {@link Clock} instance for the time. -- * -- * @param clock a {@link Clock} instance -- * @return {@code this} -- */ -- public Builder withClock(Clock clock) { -- this.clock = clock; -- return this; -- } -- -- /** -- * Only report metrics which match the given filter. -- * -- * @param filter a {@link MetricFilter} -- * @return {@code this} -- */ -- public Builder filter(MetricFilter filter) { -- this.filter = filter; -- return this; -- } -- -- public Builder withCsvFileProvider(CsvFileProvider csvFileProvider) { -- this.csvFileProvider = csvFileProvider; -- return this; -- } -- -- /** -- * Builds a {@link CsvReporter} with the given properties, writing {@code .csv} files to the -- * given directory. -- * -- * @param directory the directory in which the {@code .csv} files will be created -- * @return a {@link CsvReporter} -- */ -- public CsvReporter build(File directory) { -- return new CsvReporter(registry, -- directory, -- locale, -- separator, -- rateUnit, -- durationUnit, -- clock, -- filter, -- executor, -- shutdownExecutorOnStop, -- csvFileProvider); -- } -+ public Builder scheduleOn(ScheduledExecutorService executor) { -+ this.executor = executor; -+ return this; - } - -- private static final Logger LOGGER = LoggerFactory.getLogger(CsvReporter.class); -- -- private final File directory; -- private final Locale locale; -- private final String separator; -- private final Clock clock; -- private final CsvFileProvider csvFileProvider; -- -- private final String histogramFormat; -- private final String meterFormat; -- private final String timerFormat; -- -- private final String timerHeader; -- private final String meterHeader; -- private final String histogramHeader; -- -- private CsvReporter(MetricRegistry registry, -- File directory, -- Locale locale, -- String separator, -- TimeUnit rateUnit, -- TimeUnit durationUnit, -- Clock clock, -- MetricFilter filter, -- ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop, -- CsvFileProvider csvFileProvider) { -- super(registry, "csv-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop); -- this.directory = directory; -- this.locale = locale; -- this.separator = separator; -- this.clock = clock; -- this.csvFileProvider = csvFileProvider; -- -- this.histogramFormat = String.join(separator, "%d", "%d", "%d", "%f", "%d", "%f", "%f", "%f", "%f", "%f", "%f", "%f"); -- this.meterFormat = String.join(separator, "%d", "%d", "%f", "%f", "%f", "%f", "events/%s"); -- this.timerFormat = String.join(separator, "%d", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "%f", "calls/%s", "%s"); -- -- this.timerHeader = String.join(separator, "count", "sum", "max", "mean", "min", "stddev", "p50", "p75", "p95", "p98", "p99", "p999", "mean_rate", "m1_rate", "m5_rate", "m15_rate", "rate_unit", "duration_unit"); -- this.meterHeader = String.join(separator, "count", "sum", "mean_rate", "m1_rate", "m5_rate", "m15_rate", "rate_unit"); -- this.histogramHeader = String.join(separator, "count", "sum", "max", "mean", "min", "stddev", "p50", "p75", "p95", "p98", "p99", "p999"); -+ /** -+ * Format numbers for the given {@link Locale}. -+ * -+ * @param locale a {@link Locale} -+ * @return {@code this} -+ */ -+ public Builder formatFor(Locale locale) { -+ this.locale = locale; -+ return this; - } - -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap> gauges, -- SortedMap counters, -- SortedMap histograms, -- SortedMap meters, -- SortedMap timers) { -- final long timestamp = TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); -- -- for (Map.Entry> entry : gauges.entrySet()) { -- reportGauge(timestamp, entry.getKey(), entry.getValue()); -- } -+ /** -+ * Convert rates to the given time unit. -+ * -+ * @param rateUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertRatesTo(TimeUnit rateUnit) { -+ this.rateUnit = rateUnit; -+ return this; -+ } - -- for (Map.Entry entry : counters.entrySet()) { -- reportCounter(timestamp, entry.getKey(), entry.getValue()); -- } -+ /** -+ * Convert durations to the given time unit. -+ * -+ * @param durationUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertDurationsTo(TimeUnit durationUnit) { -+ this.durationUnit = durationUnit; -+ return this; -+ } - -- for (Map.Entry entry : histograms.entrySet()) { -- reportHistogram(timestamp, entry.getKey(), entry.getValue()); -- } -+ /** -+ * Use the given string to use as the separator for values. -+ * -+ * @param separator the string to use for the separator. -+ * @return {@code this} -+ */ -+ public Builder withSeparator(String separator) { -+ this.separator = separator; -+ return this; -+ } - -- for (Map.Entry entry : meters.entrySet()) { -- reportMeter(timestamp, entry.getKey(), entry.getValue()); -- } -+ /** -+ * Use the given {@link Clock} instance for the time. -+ * -+ * @param clock a {@link Clock} instance -+ * @return {@code this} -+ */ -+ public Builder withClock(Clock clock) { -+ this.clock = clock; -+ return this; -+ } - -- for (Map.Entry entry : timers.entrySet()) { -- reportTimer(timestamp, entry.getKey(), entry.getValue()); -- } -+ /** -+ * Only report metrics which match the given filter. -+ * -+ * @param filter a {@link MetricFilter} -+ * @return {@code this} -+ */ -+ public Builder filter(MetricFilter filter) { -+ this.filter = filter; -+ return this; - } +- if (pairs.length % 2 != 0) { +- throw new IllegalArgumentException("Argument count must be even"); +- } ++ checkArgument(pairs.length % 2 == 0, "Argument count must be even"); -- private void reportTimer(long timestamp, MetricName name, Timer timer) { -- final Snapshot snapshot = timer.getSnapshot(); -- -- report(timestamp, -- name, -- timerHeader, -- timerFormat, -- timer.getCount(), -- convertDuration(timer.getSum()), -- convertDuration(snapshot.getMax()), -- convertDuration(snapshot.getMean()), -- convertDuration(snapshot.getMin()), -- convertDuration(snapshot.getStdDev()), -- convertDuration(snapshot.getMedian()), -- convertDuration(snapshot.get75thPercentile()), -- convertDuration(snapshot.get95thPercentile()), -- convertDuration(snapshot.get98thPercentile()), -- convertDuration(snapshot.get99thPercentile()), -- convertDuration(snapshot.get999thPercentile()), -- convertRate(timer.getMeanRate()), -- convertRate(timer.getOneMinuteRate()), -- convertRate(timer.getFiveMinuteRate()), -- convertRate(timer.getFifteenMinuteRate()), -- getRateUnit(), -- getDurationUnit()); -+ public Builder withCsvFileProvider(CsvFileProvider csvFileProvider) { -+ this.csvFileProvider = csvFileProvider; -+ return this; - } + final Map add = new HashMap<>(); + for (int i = 0; i < pairs.length; i += 2) { +@@ -201,8 +205,8 @@ public class MetricName implements Comparable { + private static , V> Map unmodifiableSortedCopy(Map map) { + LinkedHashMap sorted = new LinkedHashMap<>(); + map.entrySet().stream() +- .sorted(Comparator.comparing(Map.Entry::getKey)) ++ .sorted(comparingByKey()) + .forEach(e -> sorted.put(e.getKey(), e.getValue())); +- return Collections.unmodifiableMap(sorted); ++ return unmodifiableMap(sorted); + } + } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java +@@ -1,6 +1,10 @@ + package io.dropwizard.metrics5; -- private void reportMeter(long timestamp, MetricName name, Meter meter) { -- report(timestamp, -- name, -- meterHeader, -- meterFormat, -- meter.getCount(), -- meter.getSum(), -- convertRate(meter.getMeanRate()), -- convertRate(meter.getOneMinuteRate()), -- convertRate(meter.getFiveMinuteRate()), -- convertRate(meter.getFifteenMinuteRate()), -- getRateUnit()); -+ /** -+ * Builds a {@link CsvReporter} with the given properties, writing {@code .csv} files to the -+ * given directory. -+ * -+ * @param directory the directory in which the {@code .csv} files will be created -+ * @return a {@link CsvReporter} -+ */ -+ public CsvReporter build(File directory) { -+ return new CsvReporter( -+ registry, -+ directory, -+ locale, -+ separator, -+ rateUnit, -+ durationUnit, -+ clock, -+ filter, -+ executor, -+ shutdownExecutorOnStop, -+ csvFileProvider); -+ } -+ } -+ -+ private static final Logger LOG = LoggerFactory.getLogger(CsvReporter.class); -+ -+ private final File directory; -+ private final Locale locale; -+ private final String separator; -+ private final Clock clock; -+ private final CsvFileProvider csvFileProvider; -+ -+ private final String histogramFormat; -+ private final String meterFormat; -+ private final String timerFormat; -+ -+ private final String timerHeader; -+ private final String meterHeader; -+ private final String histogramHeader; -+ -+ private CsvReporter( -+ MetricRegistry registry, -+ File directory, -+ Locale locale, -+ String separator, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ Clock clock, -+ MetricFilter filter, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ CsvFileProvider csvFileProvider) { -+ super( -+ registry, "csv-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop); -+ this.directory = directory; -+ this.locale = locale; -+ this.separator = separator; -+ this.clock = clock; -+ this.csvFileProvider = csvFileProvider; -+ -+ this.histogramFormat = -+ String.join( -+ separator, "%d", "%d", "%d", "%f", "%d", "%f", "%f", "%f", "%f", "%f", "%f", "%f"); -+ this.meterFormat = String.join(separator, "%d", "%d", "%f", "%f", "%f", "%f", "events/%s"); -+ this.timerFormat = -+ String.join( -+ separator, -+ "%d", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "%f", -+ "calls/%s", -+ "%s"); -+ -+ this.timerHeader = -+ String.join( -+ separator, -+ "count", -+ "sum", -+ "max", -+ "mean", -+ "min", -+ "stddev", -+ "p50", -+ "p75", -+ "p95", -+ "p98", -+ "p99", -+ "p999", -+ "mean_rate", -+ "m1_rate", -+ "m5_rate", -+ "m15_rate", -+ "rate_unit", -+ "duration_unit"); -+ this.meterHeader = -+ String.join( -+ separator, "count", "sum", "mean_rate", "m1_rate", "m5_rate", "m15_rate", "rate_unit"); -+ this.histogramHeader = -+ String.join( -+ separator, "count", "sum", "max", "mean", "min", "stddev", "p50", "p75", "p95", "p98", -+ "p99", "p999"); -+ } -+ -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap> gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ final long timestamp = TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); +-import java.util.Collections; ++import static java.util.Collections.unmodifiableMap; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; ++import static java.util.Objects.requireNonNull; + -+ for (Map.Entry> entry : gauges.entrySet()) { -+ reportGauge(timestamp, entry.getKey(), entry.getValue()); - } + import java.util.List; + import java.util.Map; + import java.util.SortedMap; +@@ -91,9 +95,7 @@ public class MetricRegistry implements MetricSet { + * @throws IllegalArgumentException if the name is already registered or metric variable is null + */ + public T register(MetricName name, T metric) throws IllegalArgumentException { +- if (metric == null) { +- throw new NullPointerException("metric == null"); +- } ++ requireNonNull(metric, "metric == null"); -- private void reportHistogram(long timestamp, MetricName name, Histogram histogram) { -- final Snapshot snapshot = histogram.getSnapshot(); -- -- report(timestamp, -- name, -- histogramHeader, -- histogramFormat, -- histogram.getCount(), -- histogram.getSum(), -- snapshot.getMax(), -- snapshot.getMean(), -- snapshot.getMin(), -- snapshot.getStdDev(), -- snapshot.getMedian(), -- snapshot.get75thPercentile(), -- snapshot.get95thPercentile(), -- snapshot.get98thPercentile(), -- snapshot.get99thPercentile(), -- snapshot.get999thPercentile()); -+ for (Map.Entry entry : counters.entrySet()) { -+ reportCounter(timestamp, entry.getKey(), entry.getValue()); - } + if (metric instanceof MetricRegistry) { + final MetricRegistry childRegistry = (MetricRegistry) metric; +@@ -213,7 +215,7 @@ public class MetricRegistry implements MetricSet { -- private void reportCounter(long timestamp, MetricName name, Counter counter) { -- report(timestamp, name, "count", "%d", counter.getCount()); -+ for (Map.Entry entry : histograms.entrySet()) { -+ reportHistogram(timestamp, entry.getKey(), entry.getValue()); - } + @Override + public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); ++ return metric instanceof Counter; + } + }); + } +@@ -253,7 +255,7 @@ public class MetricRegistry implements MetricSet { -- private void reportGauge(long timestamp, MetricName name, Gauge gauge) { -- report(timestamp, name, "value", "%s", gauge.getValue()); -+ for (Map.Entry entry : meters.entrySet()) { -+ reportMeter(timestamp, entry.getKey(), entry.getValue()); - } + @Override + public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); ++ return metric instanceof Histogram; + } + }); + } +@@ -293,7 +295,7 @@ public class MetricRegistry implements MetricSet { -- private void report(long timestamp, MetricName name, String header, String line, Object... values) { -- try { -- final File file = csvFileProvider.getFile(directory, name.getKey()); -- final boolean fileAlreadyExists = file.exists(); -- if (fileAlreadyExists || file.createNewFile()) { -- try (PrintWriter out = new PrintWriter(new OutputStreamWriter( -- new FileOutputStream(file, true), UTF_8))) { -- if (!fileAlreadyExists) { -- out.println("t" + separator + header); -- } -- out.printf(locale, String.format(locale, "%d" + separator + "%s%n", timestamp, line), values); -- } -- } -- } catch (IOException e) { -- LOGGER.warn("Error writing to {}", name, e); -+ for (Map.Entry entry : timers.entrySet()) { -+ reportTimer(timestamp, entry.getKey(), entry.getValue()); -+ } -+ } -+ -+ private void reportTimer(long timestamp, MetricName name, Timer timer) { -+ final Snapshot snapshot = timer.getSnapshot(); -+ -+ report( -+ timestamp, -+ name, -+ timerHeader, -+ timerFormat, -+ timer.getCount(), -+ convertDuration(timer.getSum()), -+ convertDuration(snapshot.getMax()), -+ convertDuration(snapshot.getMean()), -+ convertDuration(snapshot.getMin()), -+ convertDuration(snapshot.getStdDev()), -+ convertDuration(snapshot.getMedian()), -+ convertDuration(snapshot.get75thPercentile()), -+ convertDuration(snapshot.get95thPercentile()), -+ convertDuration(snapshot.get98thPercentile()), -+ convertDuration(snapshot.get99thPercentile()), -+ convertDuration(snapshot.get999thPercentile()), -+ convertRate(timer.getMeanRate()), -+ convertRate(timer.getOneMinuteRate()), -+ convertRate(timer.getFiveMinuteRate()), -+ convertRate(timer.getFifteenMinuteRate()), -+ getRateUnit(), -+ getDurationUnit()); -+ } -+ -+ private void reportMeter(long timestamp, MetricName name, Meter meter) { -+ report( -+ timestamp, -+ name, -+ meterHeader, -+ meterFormat, -+ meter.getCount(), -+ meter.getSum(), -+ convertRate(meter.getMeanRate()), -+ convertRate(meter.getOneMinuteRate()), -+ convertRate(meter.getFiveMinuteRate()), -+ convertRate(meter.getFifteenMinuteRate()), -+ getRateUnit()); -+ } -+ -+ private void reportHistogram(long timestamp, MetricName name, Histogram histogram) { -+ final Snapshot snapshot = histogram.getSnapshot(); -+ -+ report( -+ timestamp, -+ name, -+ histogramHeader, -+ histogramFormat, -+ histogram.getCount(), -+ histogram.getSum(), -+ snapshot.getMax(), -+ snapshot.getMean(), -+ snapshot.getMin(), -+ snapshot.getStdDev(), -+ snapshot.getMedian(), -+ snapshot.get75thPercentile(), -+ snapshot.get95thPercentile(), -+ snapshot.get98thPercentile(), -+ snapshot.get99thPercentile(), -+ snapshot.get999thPercentile()); -+ } -+ -+ private void reportCounter(long timestamp, MetricName name, Counter counter) { -+ report(timestamp, name, "count", "%d", counter.getCount()); -+ } -+ -+ private void reportGauge(long timestamp, MetricName name, Gauge gauge) { -+ report(timestamp, name, "value", "%s", gauge.getValue()); -+ } -+ -+ private void report( -+ long timestamp, MetricName name, String header, String line, Object... values) { -+ try { -+ final File file = csvFileProvider.getFile(directory, name.getKey()); -+ final boolean fileAlreadyExists = file.exists(); -+ if (fileAlreadyExists || file.createNewFile()) { -+ try (PrintWriter out = -+ new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, true), UTF_8))) { -+ if (!fileAlreadyExists) { -+ out.println("t" + separator + header); -+ } -+ out.printf( -+ locale, String.format(locale, "%d" + separator + "%s%n", timestamp, line), values); - } -+ } -+ } catch (IOException e) { -+ LOG.warn("Error writing to {}", name, e); - } -+ } + @Override + public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); ++ return metric instanceof Meter; + } + }); + } +@@ -328,7 +330,7 @@ public class MetricRegistry implements MetricSet { -- protected String sanitize(MetricName name) { -- return name.getKey(); -- } -+ protected String sanitize(MetricName name) { -+ return name.getKey(); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/DefaultSettableGauge.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/DefaultSettableGauge.java -@@ -4,40 +4,35 @@ package io.dropwizard.metrics5; - * Similar to {@link Gauge}, but metric value is updated via calling {@link #setValue(T)} instead. - */ - public class DefaultSettableGauge implements SettableGauge { -- private volatile T value; -+ private volatile T value; - -- /** -- * Create an instance with no default value. -- */ -- public DefaultSettableGauge() { -- this(null); -- } -+ /** Create an instance with no default value. */ -+ public DefaultSettableGauge() { -+ this(null); -+ } - -- /** -- * Create an instance with a default value. -- * -- * @param defaultValue default value -- */ -- public DefaultSettableGauge(T defaultValue) { -- this.value = defaultValue; -- } -+ /** -+ * Create an instance with a default value. -+ * -+ * @param defaultValue default value -+ */ -+ public DefaultSettableGauge(T defaultValue) { -+ this.value = defaultValue; -+ } - -- /** -- * Set the metric to a new value. -- */ -- @Override -- public void setValue(T value) { -- this.value = value; -- } -- -- /** -- * Returns the current value. -- * -- * @return the current value -- */ -- @Override -- public T getValue() { -- return value; -- } -+ /** Set the metric to a new value. */ -+ @Override -+ public void setValue(T value) { -+ this.value = value; -+ } - -+ /** -+ * Returns the current value. -+ * -+ * @return the current value -+ */ -+ @Override -+ public T getValue() { -+ return value; -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/DerivativeGauge.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/DerivativeGauge.java -@@ -7,27 +7,27 @@ package io.dropwizard.metrics5; - * @param the derivative type - */ - public abstract class DerivativeGauge implements Gauge { -- private final Gauge base; -+ private final Gauge base; - -- /** -- * Creates a new derivative with the given base gauge. -- * -- * @param base the gauge from which to derive this gauge's value -- */ -- protected DerivativeGauge(Gauge base) { -- this.base = base; -- } -+ /** -+ * Creates a new derivative with the given base gauge. -+ * -+ * @param base the gauge from which to derive this gauge's value -+ */ -+ protected DerivativeGauge(Gauge base) { -+ this.base = base; -+ } - -- @Override -- public T getValue() { -- return transform(base.getValue()); -- } -+ @Override -+ public T getValue() { -+ return transform(base.getValue()); -+ } - -- /** -- * Transforms the value of the base gauge to the value of this gauge. -- * -- * @param value the value of the base gauge -- * @return this gauge's value -- */ -- protected abstract T transform(F value); -+ /** -+ * Transforms the value of the base gauge to the value of this gauge. -+ * -+ * @param value the value of the base gauge -+ * @return this gauge's value -+ */ -+ protected abstract T transform(F value); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/EWMA.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/EWMA.java -@@ -1,116 +1,115 @@ - package io.dropwizard.metrics5; + @Override + public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); ++ return metric instanceof Timer; + } + }); + } +@@ -366,7 +368,7 @@ public class MetricRegistry implements MetricSet { -+import static java.lang.Math.exp; -+ - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.LongAdder; + @Override + public boolean isInstance(Metric metric) { +- return Gauge.class.isInstance(metric); ++ return metric instanceof Gauge; + } + }); + } +@@ -430,7 +432,7 @@ public class MetricRegistry implements MetricSet { + * @return the names of all the metrics + */ + public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); ++ return unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); + } --import static java.lang.Math.exp; -- - /** - * An exponentially-weighted moving average. - * - * @see UNIX Load Average Part 1: How -- * It Works -+ * It Works - * @see UNIX Load Average Part 2: Not -- * Your Average Average -+ * Your Average Average - * @see EMA - */ - public class EWMA { -- private static final int INTERVAL = 5; -- private static final double SECONDS_PER_MINUTE = 60.0; -- private static final int ONE_MINUTE = 1; -- private static final int FIVE_MINUTES = 5; -- private static final int FIFTEEN_MINUTES = 15; -- private static final double M1_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / ONE_MINUTE); -- private static final double M5_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIVE_MINUTES); -- private static final double M15_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIFTEEN_MINUTES); -+ private static final int INTERVAL = 5; -+ private static final double SECONDS_PER_MINUTE = 60.0; -+ private static final int ONE_MINUTE = 1; -+ private static final int FIVE_MINUTES = 5; -+ private static final int FIFTEEN_MINUTES = 15; -+ private static final double M1_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / ONE_MINUTE); -+ private static final double M5_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIVE_MINUTES); -+ private static final double M15_ALPHA = 1 - exp(-INTERVAL / SECONDS_PER_MINUTE / FIFTEEN_MINUTES); - -- private volatile boolean initialized = false; -- private volatile double rate = 0.0; -+ private volatile boolean initialized = false; -+ private volatile double rate = 0.0; - -- private final LongAdder uncounted = new LongAdder(); -- private final double alpha, interval; -+ private final LongAdder uncounted = new LongAdder(); -+ private final double alpha, interval; - -- /** -- * Creates a new EWMA which is equivalent to the UNIX one minute load average and which expects -- * to be ticked every 5 seconds. -- * -- * @return a one-minute EWMA -- */ -- public static EWMA oneMinuteEWMA() { -- return new EWMA(M1_ALPHA, INTERVAL, TimeUnit.SECONDS); -- } -+ /** -+ * Creates a new EWMA which is equivalent to the UNIX one minute load average and which expects to -+ * be ticked every 5 seconds. -+ * -+ * @return a one-minute EWMA -+ */ -+ public static EWMA oneMinuteEWMA() { -+ return new EWMA(M1_ALPHA, INTERVAL, TimeUnit.SECONDS); -+ } - -- /** -- * Creates a new EWMA which is equivalent to the UNIX five minute load average and which expects -- * to be ticked every 5 seconds. -- * -- * @return a five-minute EWMA -- */ -- public static EWMA fiveMinuteEWMA() { -- return new EWMA(M5_ALPHA, INTERVAL, TimeUnit.SECONDS); -- } -+ /** -+ * Creates a new EWMA which is equivalent to the UNIX five minute load average and which expects -+ * to be ticked every 5 seconds. -+ * -+ * @return a five-minute EWMA -+ */ -+ public static EWMA fiveMinuteEWMA() { -+ return new EWMA(M5_ALPHA, INTERVAL, TimeUnit.SECONDS); -+ } - -- /** -- * Creates a new EWMA which is equivalent to the UNIX fifteen minute load average and which -- * expects to be ticked every 5 seconds. -- * -- * @return a fifteen-minute EWMA -- */ -- public static EWMA fifteenMinuteEWMA() { -- return new EWMA(M15_ALPHA, INTERVAL, TimeUnit.SECONDS); -- } -+ /** -+ * Creates a new EWMA which is equivalent to the UNIX fifteen minute load average and which -+ * expects to be ticked every 5 seconds. -+ * -+ * @return a fifteen-minute EWMA -+ */ -+ public static EWMA fifteenMinuteEWMA() { -+ return new EWMA(M15_ALPHA, INTERVAL, TimeUnit.SECONDS); -+ } - -- /** -- * Create a new EWMA with a specific smoothing constant. -- * -- * @param alpha the smoothing constant -- * @param interval the expected tick interval -- * @param intervalUnit the time unit of the tick interval -- */ -- public EWMA(double alpha, long interval, TimeUnit intervalUnit) { -- this.interval = intervalUnit.toNanos(interval); -- this.alpha = alpha; -- } -+ /** -+ * Create a new EWMA with a specific smoothing constant. -+ * -+ * @param alpha the smoothing constant -+ * @param interval the expected tick interval -+ * @param intervalUnit the time unit of the tick interval -+ */ -+ public EWMA(double alpha, long interval, TimeUnit intervalUnit) { -+ this.interval = intervalUnit.toNanos(interval); -+ this.alpha = alpha; -+ } - -- /** -- * Update the moving average with a new value. -- * -- * @param n the new value -- */ -- public void update(long n) { -- uncounted.add(n); -- } -+ /** -+ * Update the moving average with a new value. -+ * -+ * @param n the new value -+ */ -+ public void update(long n) { -+ uncounted.add(n); -+ } - -- /** -- * Set the rate to the smallest possible positive value. Used to avoid calling tick a large number of times. -- */ -- public void reset() { -- uncounted.reset(); -- rate = Double.MIN_NORMAL; -- } -+ /** -+ * Set the rate to the smallest possible positive value. Used to avoid calling tick a large number -+ * of times. -+ */ -+ public void reset() { -+ uncounted.reset(); -+ rate = Double.MIN_NORMAL; -+ } - -- /** -- * Mark the passage of time and decay the current rate accordingly. -- */ -- public void tick() { -- final long count = uncounted.sumThenReset(); -- final double instantRate = count / interval; -- if (initialized) { -- final double oldRate = this.rate; -- rate = oldRate + (alpha * (instantRate - oldRate)); -- } else { -- rate = instantRate; -- initialized = true; -- } -+ /** Mark the passage of time and decay the current rate accordingly. */ -+ public void tick() { -+ final long count = uncounted.sumThenReset(); -+ final double instantRate = count / interval; -+ if (initialized) { -+ final double oldRate = this.rate; -+ rate = oldRate + (alpha * (instantRate - oldRate)); -+ } else { -+ rate = instantRate; -+ initialized = true; + /** +@@ -455,7 +457,7 @@ public class MetricRegistry implements MetricSet { + timers.put(entry.getKey(), (Gauge) entry.getValue()); + } } -+ } - -- /** -- * Returns the rate in the given units of time. -- * -- * @param rateUnit the unit of time -- * @return the rate -- */ -- public double getRate(TimeUnit rateUnit) { -- return rate * (double) rateUnit.toNanos(1); -- } -+ /** -+ * Returns the rate in the given units of time. -+ * -+ * @param rateUnit the unit of time -+ * @return the rate -+ */ -+ public double getRate(TimeUnit rateUnit) { -+ return rate * (double) rateUnit.toNanos(1); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java -@@ -5,110 +5,102 @@ import java.util.concurrent.atomic.AtomicLong; - import java.util.concurrent.atomic.LongAdder; - - /** -- * A triple (one, five and fifteen minutes) of exponentially-weighted moving average rates as needed by {@link Meter}. -- *

    -- * The rates have the same exponential decay factor as the fifteen-minute load average in the -+ * A triple (one, five and fifteen minutes) of exponentially-weighted moving average rates as needed -+ * by {@link Meter}. -+ * -+ *

    The rates have the same exponential decay factor as the fifteen-minute load average in the - * {@code top} Unix command. - */ - public class ExponentialMovingAverages implements MovingAverages { - -- /** -- * If ticking would reduce even Long.MAX_VALUE in the 15 minute EWMA below this target then don't bother -- * ticking in a loop and instead reset all the EWMAs. -- */ -- private static final double maxTickZeroTarget = 0.0001; -- private static final int maxTicks; -- private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5); -+ /** -+ * If ticking would reduce even Long.MAX_VALUE in the 15 minute EWMA below this target then don't -+ * bother ticking in a loop and instead reset all the EWMAs. -+ */ -+ private static final double MAX_TICK_ZERO_TARGET = 0.0001; +- return Collections.unmodifiableSortedMap(timers); ++ return unmodifiableSortedMap(timers); + } -- static -- { -- int m3Ticks = 1; -- final EWMA m3 = EWMA.fifteenMinuteEWMA(); -- m3.update(Long.MAX_VALUE); -- do -- { -- m3.tick(); -- m3Ticks++; -- } -- while (m3.getRate(TimeUnit.SECONDS) > maxTickZeroTarget); -- maxTicks = m3Ticks; -- } -+ private static final int MAX_TICKS; -+ private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5); - -- private final EWMA m1Rate = EWMA.oneMinuteEWMA(); -- private final EWMA m5Rate = EWMA.fiveMinuteEWMA(); -- private final EWMA m15Rate = EWMA.fifteenMinuteEWMA(); -- private final LongAdder sum = new LongAdder(); -+ static { -+ int m3Ticks = 1; -+ final EWMA m3 = EWMA.fifteenMinuteEWMA(); -+ m3.update(Long.MAX_VALUE); -+ do { -+ m3.tick(); -+ m3Ticks++; -+ } while (m3.getRate(TimeUnit.SECONDS) > MAX_TICK_ZERO_TARGET); -+ MAX_TICKS = m3Ticks; -+ } - -- private final AtomicLong lastTick; -- private final Clock clock; -+ private final EWMA m1Rate = EWMA.oneMinuteEWMA(); -+ private final EWMA m5Rate = EWMA.fiveMinuteEWMA(); -+ private final EWMA m15Rate = EWMA.fifteenMinuteEWMA(); -+ private final LongAdder sum = new LongAdder(); - -- /** -- * Creates a new {@link ExponentialMovingAverages}. -- */ -- public ExponentialMovingAverages() { -- this(Clock.defaultClock()); -- } -+ private final AtomicLong lastTick; -+ private final Clock clock; - -- /** -- * Creates a new {@link ExponentialMovingAverages}. -- */ -- public ExponentialMovingAverages(Clock clock) { -- this.clock = clock; -- this.lastTick = new AtomicLong(this.clock.getTick()); -- } -+ /** Creates a new {@link ExponentialMovingAverages}. */ -+ public ExponentialMovingAverages() { -+ this(Clock.defaultClock()); -+ } - -- @Override -- public void update(long n) { -- m1Rate.update(n); -- m5Rate.update(n); -- m15Rate.update(n); -- } -+ /** Creates a new {@link ExponentialMovingAverages}. */ -+ public ExponentialMovingAverages(Clock clock) { -+ this.clock = clock; -+ this.lastTick = new AtomicLong(this.clock.getTick()); -+ } - -- @Override -- public void tickIfNecessary() { -- final long oldTick = lastTick.get(); -- final long newTick = clock.getTick(); -- final long age = newTick - oldTick; -- if (age > TICK_INTERVAL) { -- final long newIntervalStartTick = newTick - age % TICK_INTERVAL; -- if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) { -- sum.add(age); -- final long requiredTicks = age / TICK_INTERVAL; -- if (requiredTicks >= maxTicks) { -- m1Rate.reset(); -- m5Rate.reset(); -- m15Rate.reset(); -- } -- else -- { -- for (long i = 0; i < requiredTicks; i++) -- { -- m1Rate.tick(); -- m5Rate.tick(); -- m15Rate.tick(); -- } -- } -- } -+ @Override -+ public void update(long n) { -+ m1Rate.update(n); -+ m5Rate.update(n); -+ m15Rate.update(n); -+ } -+ -+ @Override -+ public void tickIfNecessary() { -+ final long oldTick = lastTick.get(); -+ final long newTick = clock.getTick(); -+ final long age = newTick - oldTick; -+ if (age > TICK_INTERVAL) { -+ final long newIntervalStartTick = newTick - age % TICK_INTERVAL; -+ if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) { -+ sum.add(age); -+ final long requiredTicks = age / TICK_INTERVAL; -+ if (requiredTicks >= MAX_TICKS) { -+ m1Rate.reset(); -+ m5Rate.reset(); -+ m15Rate.reset(); -+ } else { -+ for (long i = 0; i < requiredTicks; i++) { -+ m1Rate.tick(); -+ m5Rate.tick(); -+ m15Rate.tick(); -+ } - } -+ } + /** +@@ -562,7 +564,7 @@ public class MetricRegistry implements MetricSet { + timers.put(entry.getKey(), (T) entry.getValue()); + } } -+ } +- return Collections.unmodifiableSortedMap(timers); ++ return unmodifiableSortedMap(timers); + } -- @Override -- public double getM1Rate() { -- return m1Rate.getRate(TimeUnit.SECONDS); -- } -+ @Override -+ public double getM1Rate() { -+ return m1Rate.getRate(TimeUnit.SECONDS); -+ } - -- @Override -- public double getM5Rate() { -- return m5Rate.getRate(TimeUnit.SECONDS); -- } -+ @Override -+ public double getM5Rate() { -+ return m5Rate.getRate(TimeUnit.SECONDS); -+ } - -- @Override -- public double getM15Rate() { -- return m15Rate.getRate(TimeUnit.SECONDS); -- } -+ @Override -+ public double getM15Rate() { -+ return m15Rate.getRate(TimeUnit.SECONDS); -+ } - -- @Override -- public long getSum() { -- return sum.sum(); -- } -+ @Override -+ public long getSum() { -+ return sum.sum(); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoir.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoir.java -@@ -1,6 +1,9 @@ - package io.dropwizard.metrics5; + private void onMetricAdded(MetricName name, Metric metric) { +@@ -627,7 +629,7 @@ public class MetricRegistry implements MetricSet { -+import static java.lang.Math.exp; -+import static java.lang.Math.min; + @Override + public Map getMetrics() { +- return Collections.unmodifiableMap(metrics); ++ return unmodifiableMap(metrics); + } -+import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; - import java.util.ArrayList; - import java.util.concurrent.ConcurrentSkipListMap; - import java.util.concurrent.ThreadLocalRandom; -@@ -8,201 +11,197 @@ import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicLong; - import java.util.concurrent.locks.ReentrantReadWriteLock; + @FunctionalInterface +@@ -646,7 +648,7 @@ public class MetricRegistry implements MetricSet { --import static java.lang.Math.exp; --import static java.lang.Math.min; -- --import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; -- - /** - * An exponentially-decaying random reservoir of {@code long}s. Uses Cormode et al's - * forward-decaying priority reservoir sampling method to produce a statistically representative - * sampling reservoir, exponentially biased towards newer entries. - * -- * @see -- * Cormode et al. Forward Decay: A Practical Time Decay Model for Streaming Systems. ICDE '09: -- * Proceedings of the 2009 IEEE International Conference on Data Engineering (2009) -+ * @see Cormode et al. Forward -+ * Decay: A Practical Time Decay Model for Streaming Systems. ICDE '09: Proceedings of the 2009 -+ * IEEE International Conference on Data Engineering (2009) - */ - public class ExponentiallyDecayingReservoir implements Reservoir { -- private static final int DEFAULT_SIZE = 1028; -- private static final double DEFAULT_ALPHA = 0.015; -- private static final long RESCALE_THRESHOLD = TimeUnit.HOURS.toNanos(1); -- -- private final ConcurrentSkipListMap values; -- private final ReentrantReadWriteLock lock; -- private final double alpha; -- private final int size; -- private final AtomicLong count; -- private volatile long startTime; -- private final AtomicLong lastScaleTick; -- private final Clock clock; -- -- /** -- * Creates a new {@link ExponentiallyDecayingReservoir} of 1028 elements, which offers a 99.9% -- * confidence level with a 5% margin of error assuming a normal distribution, and an alpha -- * factor of 0.015, which heavily biases the reservoir to the past 5 minutes of measurements. -- */ -- public ExponentiallyDecayingReservoir() { -- this(DEFAULT_SIZE, DEFAULT_ALPHA); -- } -- -- /** -- * Creates a new {@link ExponentiallyDecayingReservoir}. -- * -- * @param size the number of samples to keep in the sampling reservoir -- * @param alpha the exponential decay factor; the higher this is, the more biased the reservoir -- * will be towards newer values -- */ -- public ExponentiallyDecayingReservoir(int size, double alpha) { -- this(size, alpha, Clock.defaultClock()); -- } -- -- /** -- * Creates a new {@link ExponentiallyDecayingReservoir}. -- * -- * @param size the number of samples to keep in the sampling reservoir -- * @param alpha the exponential decay factor; the higher this is, the more biased the reservoir -- * will be towards newer values -- * @param clock the clock used to timestamp samples and track rescaling -- */ -- public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock) { -- this.values = new ConcurrentSkipListMap<>(); -- this.lock = new ReentrantReadWriteLock(); -- this.alpha = alpha; -- this.size = size; -- this.clock = clock; -- this.count = new AtomicLong(0); -- this.startTime = currentTimeInSeconds(); -- this.lastScaleTick = new AtomicLong(clock.getTick()); -- } -- -- @Override -- public int size() { -- return (int) min(size, count.get()); -- } -- -- @Override -- public void update(long value) { -- update(value, currentTimeInSeconds()); -- } -- -- /** -- * Adds an old value with a fixed timestamp to the reservoir. -- * -- * @param value the value to be added -- * @param timestamp the epoch timestamp of {@code value} in seconds -- */ -- public void update(long value, long timestamp) { -- rescaleIfNeeded(); -- lockForRegularUsage(); -- try { -- final double itemWeight = weight(timestamp - startTime); -- final WeightedSample sample = new WeightedSample(value, itemWeight); -- final double priority = itemWeight / ThreadLocalRandom.current().nextDouble(); -- -- final long newCount = count.incrementAndGet(); -- if (newCount <= size || values.isEmpty()) { -- values.put(priority, sample); -- } else { -- Double first = values.firstKey(); -- if (first < priority && values.putIfAbsent(priority, sample) == null) { -- // ensure we always remove an item -- while (values.remove(first) == null) { -- first = values.firstKey(); -- } -- } -- } -- } finally { -- unlockForRegularUsage(); -+ private static final int DEFAULT_SIZE = 1028; -+ private static final double DEFAULT_ALPHA = 0.015; -+ private static final long RESCALE_THRESHOLD = TimeUnit.HOURS.toNanos(1); -+ -+ private final ConcurrentSkipListMap values; -+ private final ReentrantReadWriteLock lock; -+ private final double alpha; -+ private final int size; -+ private final AtomicLong count; -+ private volatile long startTime; -+ private final AtomicLong lastScaleTick; -+ private final Clock clock; -+ -+ /** -+ * Creates a new {@link ExponentiallyDecayingReservoir} of 1028 elements, which offers a 99.9% -+ * confidence level with a 5% margin of error assuming a normal distribution, and an alpha factor -+ * of 0.015, which heavily biases the reservoir to the past 5 minutes of measurements. -+ */ -+ public ExponentiallyDecayingReservoir() { -+ this(DEFAULT_SIZE, DEFAULT_ALPHA); -+ } -+ -+ /** -+ * Creates a new {@link ExponentiallyDecayingReservoir}. -+ * -+ * @param size the number of samples to keep in the sampling reservoir -+ * @param alpha the exponential decay factor; the higher this is, the more biased the reservoir -+ * will be towards newer values -+ */ -+ public ExponentiallyDecayingReservoir(int size, double alpha) { -+ this(size, alpha, Clock.defaultClock()); -+ } -+ -+ /** -+ * Creates a new {@link ExponentiallyDecayingReservoir}. -+ * -+ * @param size the number of samples to keep in the sampling reservoir -+ * @param alpha the exponential decay factor; the higher this is, the more biased the reservoir -+ * will be towards newer values -+ * @param clock the clock used to timestamp samples and track rescaling -+ */ -+ public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock) { -+ this.values = new ConcurrentSkipListMap<>(); -+ this.lock = new ReentrantReadWriteLock(); -+ this.alpha = alpha; -+ this.size = size; -+ this.clock = clock; -+ this.count = new AtomicLong(0); -+ this.startTime = currentTimeInSeconds(); -+ this.lastScaleTick = new AtomicLong(clock.getTick()); -+ } -+ -+ @Override -+ public int size() { -+ return (int) min(size, count.get()); -+ } -+ -+ @Override -+ public void update(long value) { -+ update(value, currentTimeInSeconds()); -+ } -+ -+ /** -+ * Adds an old value with a fixed timestamp to the reservoir. -+ * -+ * @param value the value to be added -+ * @param timestamp the epoch timestamp of {@code value} in seconds -+ */ -+ public void update(long value, long timestamp) { -+ rescaleIfNeeded(); -+ lockForRegularUsage(); -+ try { -+ final double itemWeight = weight(timestamp - startTime); -+ final WeightedSample sample = new WeightedSample(value, itemWeight); -+ final double priority = itemWeight / ThreadLocalRandom.current().nextDouble(); -+ -+ final long newCount = count.incrementAndGet(); -+ if (newCount <= size || values.isEmpty()) { -+ values.put(priority, sample); -+ } else { -+ Double first = values.firstKey(); -+ if (first < priority && values.putIfAbsent(priority, sample) == null) { -+ // ensure we always remove an item -+ while (values.remove(first) == null) { -+ first = values.firstKey(); -+ } - } -+ } -+ } finally { -+ unlockForRegularUsage(); - } -+ } + @Override + public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); ++ return metric instanceof Counter; + } + }; -- private void rescaleIfNeeded() { -- final long now = clock.getTick(); -- final long lastScaleTickSnapshot = lastScaleTick.get(); -- if (now - lastScaleTickSnapshot >= RESCALE_THRESHOLD) { -- rescale(now, lastScaleTickSnapshot); -- } -+ private void rescaleIfNeeded() { -+ final long now = clock.getTick(); -+ final long lastScaleTickSnapshot = lastScaleTick.get(); -+ if (now - lastScaleTickSnapshot >= RESCALE_THRESHOLD) { -+ rescale(now, lastScaleTickSnapshot); - } -- -- @Override -- public Snapshot getSnapshot() { -- rescaleIfNeeded(); -- lockForRegularUsage(); -- try { -- return new WeightedSnapshot(values.values()); -- } finally { -- unlockForRegularUsage(); -- } -- } -- -- private long currentTimeInSeconds() { -- return TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ rescaleIfNeeded(); -+ lockForRegularUsage(); -+ try { -+ return new WeightedSnapshot(values.values()); -+ } finally { -+ unlockForRegularUsage(); - } -- -- private double weight(long t) { -- return exp(alpha * t); -- } -- -- /* "A common feature of the above techniques—indeed, the key technique that -- * allows us to track the decayed weights efficiently—is that they maintain -- * counts and other quantities based on g(ti − L), and only scale by g(t − L) -- * at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero -- * and one, the intermediate values of g(ti − L) could become very large. For -- * polynomial functions, these values should not grow too large, and should be -- * effectively represented in practice by floating point values without loss of -- * precision. For exponential functions, these values could grow quite large as -- * new values of (ti − L) become large, and potentially exceed the capacity of -- * common floating point types. However, since the values stored by the -- * algorithms are linear combinations of g values (scaled sums), they can be -- * rescaled relative to a new landmark. That is, by the analysis of exponential -- * decay in Section III-A, the choice of L does not affect the final result. We -- * can therefore multiply each value based on L by a factor of exp(−α(L′ − L)), -- * and obtain the correct value as if we had instead computed relative to a new -- * landmark L′ (and then use this new L′ at query time). This can be done with -- * a linear pass over whatever data structure is being used." -- */ -- private void rescale(long now, long lastTick) { -- lockForRescale(); -- try { -- if (lastScaleTick.compareAndSet(lastTick, now)) { -- final long oldStartTime = startTime; -- this.startTime = currentTimeInSeconds(); -- final double scalingFactor = exp(-alpha * (startTime - oldStartTime)); -- if (Double.compare(scalingFactor, 0) == 0) { -- values.clear(); -- } else { -- final ArrayList keys = new ArrayList<>(values.keySet()); -- for (Double key : keys) { -- final WeightedSample sample = values.remove(key); -- final WeightedSample newSample = new WeightedSample(sample.value, sample.weight * scalingFactor); -- if (Double.compare(newSample.weight, 0) == 0) { -- continue; -- } -- values.put(key * scalingFactor, newSample); -- } -- } -- -- // make sure the counter is in sync with the number of stored samples. -- count.set(values.size()); -+ } -+ -+ private long currentTimeInSeconds() { -+ return TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); -+ } -+ -+ private double weight(long t) { -+ return exp(alpha * t); -+ } -+ -+ /* "A common feature of the above techniques—indeed, the key technique that -+ * allows us to track the decayed weights efficiently—is that they maintain -+ * counts and other quantities based on g(ti − L), and only scale by g(t − L) -+ * at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero -+ * and one, the intermediate values of g(ti − L) could become very large. For -+ * polynomial functions, these values should not grow too large, and should be -+ * effectively represented in practice by floating point values without loss of -+ * precision. For exponential functions, these values could grow quite large as -+ * new values of (ti − L) become large, and potentially exceed the capacity of -+ * common floating point types. However, since the values stored by the -+ * algorithms are linear combinations of g values (scaled sums), they can be -+ * rescaled relative to a new landmark. That is, by the analysis of exponential -+ * decay in Section III-A, the choice of L does not affect the final result. We -+ * can therefore multiply each value based on L by a factor of exp(−α(L′ − L)), -+ * and obtain the correct value as if we had instead computed relative to a new -+ * landmark L′ (and then use this new L′ at query time). This can be done with -+ * a linear pass over whatever data structure is being used." -+ */ -+ private void rescale(long now, long lastTick) { -+ lockForRescale(); -+ try { -+ if (lastScaleTick.compareAndSet(lastTick, now)) { -+ final long oldStartTime = startTime; -+ this.startTime = currentTimeInSeconds(); -+ final double scalingFactor = exp(-alpha * (startTime - oldStartTime)); -+ if (Double.compare(scalingFactor, 0) == 0) { -+ values.clear(); -+ } else { -+ final ArrayList keys = new ArrayList<>(values.keySet()); -+ for (Double key : keys) { -+ final WeightedSample sample = values.remove(key); -+ final WeightedSample newSample = -+ new WeightedSample(sample.value, sample.weight * scalingFactor); -+ if (Double.compare(newSample.weight, 0) == 0) { -+ continue; - } -- } finally { -- unlockForRescale(); -+ values.put(key * scalingFactor, newSample); -+ } - } -- } +@@ -659,7 +661,7 @@ public class MetricRegistry implements MetricSet { -- private void unlockForRescale() { -- lock.writeLock().unlock(); -+ // make sure the counter is in sync with the number of stored samples. -+ count.set(values.size()); -+ } -+ } finally { -+ unlockForRescale(); - } -+ } + @Override + public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); ++ return metric instanceof Histogram; + } + }; -- private void lockForRescale() { -- lock.writeLock().lock(); -- } -+ private void unlockForRescale() { -+ lock.writeLock().unlock(); -+ } +@@ -672,7 +674,7 @@ public class MetricRegistry implements MetricSet { -- private void lockForRegularUsage() { -- lock.readLock().lock(); -- } -+ private void lockForRescale() { -+ lock.writeLock().lock(); -+ } + @Override + public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); ++ return metric instanceof Meter; + } + }; -- private void unlockForRegularUsage() { -- lock.readLock().unlock(); -- } -+ private void lockForRegularUsage() { -+ lock.readLock().lock(); -+ } -+ -+ private void unlockForRegularUsage() { -+ lock.readLock().unlock(); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/FixedNameCsvFileProvider.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/FixedNameCsvFileProvider.java -@@ -3,19 +3,19 @@ package io.dropwizard.metrics5; - import java.io.File; +@@ -685,7 +687,7 @@ public class MetricRegistry implements MetricSet { - /** -- * This implementation of the {@link CsvFileProvider} will always return the same name -- * for the same metric. This means the CSV file will grow indefinitely. -+ * This implementation of the {@link CsvFileProvider} will always return the same name for the same -+ * metric. This means the CSV file will grow indefinitely. - */ - public class FixedNameCsvFileProvider implements CsvFileProvider { + @Override + public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); ++ return metric instanceof Timer; + } + }; -- @Override -- public File getFile(File directory, String metricName) { -- return new File(directory, sanitize(metricName) + ".csv"); -- } -+ @Override -+ public File getFile(File directory, String metricName) { -+ return new File(directory, sanitize(metricName) + ".csv"); -+ } - -- protected String sanitize(String metricName) { -- //Forward slash character is definitely illegal in both Windows and Linux -- //https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx -- return metricName.replaceFirst("^/", "").replaceAll("/", "."); -- } -+ protected String sanitize(String metricName) { -+ // Forward slash character is definitely illegal in both Windows and Linux -+ // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx -+ return metricName.replaceFirst("^/", "").replaceAll("/", "."); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Gauge.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Gauge.java -@@ -1,9 +1,9 @@ - package io.dropwizard.metrics5; +@@ -699,7 +701,7 @@ public class MetricRegistry implements MetricSet { -- - /** - * A gauge metric is an instantaneous reading of a particular value. To instrument a queue's depth, - * for example:
    -+ * - *

    
    -  * final Queue<String> queue = new ConcurrentLinkedQueue<String>();
    -  * final Gauge<Integer> queueDepth = new Gauge<Integer>() {
    -@@ -17,10 +17,10 @@ package io.dropwizard.metrics5;
    -  */
    - @FunctionalInterface
    - public interface Gauge extends Metric {
    --    /**
    --     * Returns the metric's current value.
    --     *
    --     * @return the metric's current value
    --     */
    --    T getValue();
    -+  /**
    -+   * Returns the metric's current value.
    -+   *
    -+   * @return the metric's current value
    -+   */
    -+  T getValue();
    - }
    ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Histogram.java
    -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Histogram.java
    -@@ -6,66 +6,66 @@ import java.util.concurrent.atomic.LongAdder;
    -  * A metric which calculates the distribution of a value.
    -  *
    -  * @see Accurately computing running
    -- * variance
    -+ *     variance
    -  */
    - public class Histogram implements Metric, Sampling, Counting, Summing {
    --    private final Reservoir reservoir;
    --    private final LongAdder count;
    --    private final LongAdder sum;
    -+  private final Reservoir reservoir;
    -+  private final LongAdder count;
    -+  private final LongAdder sum;
    - 
    --    /**
    --     * Creates a new {@link Histogram} with the given reservoir.
    --     *
    --     * @param reservoir the reservoir to create a histogram from
    --     */
    --    public Histogram(Reservoir reservoir) {
    --        this.reservoir = reservoir;
    --        this.count = new LongAdder();
    --        this.sum = new LongAdder();
    --    }
    -+  /**
    -+   * Creates a new {@link Histogram} with the given reservoir.
    -+   *
    -+   * @param reservoir the reservoir to create a histogram from
    -+   */
    -+  public Histogram(Reservoir reservoir) {
    -+    this.reservoir = reservoir;
    -+    this.count = new LongAdder();
    -+    this.sum = new LongAdder();
    -+  }
    - 
    --    /**
    --     * Adds a recorded value.
    --     *
    --     * @param value the length of the value
    --     */
    --    public void update(int value) {
    --        update((long) value);
    --    }
    -+  /**
    -+   * Adds a recorded value.
    -+   *
    -+   * @param value the length of the value
    -+   */
    -+  public void update(int value) {
    -+    update((long) value);
    -+  }
    - 
    --    /**
    --     * Adds a recorded value.
    --     *
    --     * @param value the length of the value
    --     */
    --    public void update(long value) {
    --        count.increment();
    --        sum.add(value);
    --        reservoir.update(value);
    --    }
    -+  /**
    -+   * Adds a recorded value.
    -+   *
    -+   * @param value the length of the value
    -+   */
    -+  public void update(long value) {
    -+    count.increment();
    -+    sum.add(value);
    -+    reservoir.update(value);
    -+  }
    - 
    --    /**
    --     * Returns the number of values recorded.
    --     *
    --     * @return the number of values recorded
    --     */
    --    @Override
    --    public long getCount() {
    --        return count.sum();
    --    }
    -+  /**
    -+   * Returns the number of values recorded.
    -+   *
    -+   * @return the number of values recorded
    -+   */
    -+  @Override
    -+  public long getCount() {
    -+    return count.sum();
    -+  }
    - 
    --    /**
    --     * Returns the sum of values recorded.
    --     *
    --     * @return the sum of values recorded
    --     */
    --    @Override
    --    public long getSum() {
    --        return sum.sum();
    --    }
    -+  /**
    -+   * Returns the sum of values recorded.
    -+   *
    -+   * @return the sum of values recorded
    -+   */
    -+  @Override
    -+  public long getSum() {
    -+    return sum.sum();
    -+  }
    - 
    --    @Override
    --    public Snapshot getSnapshot() {
    --        return reservoir.getSnapshot();
    --    }
    -+  @Override
    -+  public Snapshot getSnapshot() {
    -+    return reservoir.getSnapshot();
    -+  }
    - }
    ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java
    -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java
    -@@ -16,273 +16,259 @@ import java.util.concurrent.TimeoutException;
    - import java.util.concurrent.atomic.AtomicLong;
    +           @Override
    +           public boolean isInstance(Metric metric) {
    +-            return Gauge.class.isInstance(metric);
    ++            return metric instanceof Gauge;
    +           }
    +         };
      
    - /**
    -- * An {@link ExecutorService} that monitors the number of tasks submitted, running,
    -- * completed and also keeps a {@link Timer} for the task duration.
    -- * 

    -- * It will register the metrics using the given (or auto-generated) name as classifier, e.g: -+ * An {@link ExecutorService} that monitors the number of tasks submitted, running, completed and -+ * also keeps a {@link Timer} for the task duration. -+ * -+ *

    It will register the metrics using the given (or auto-generated) name as classifier, e.g: - * "your-executor-service.submitted", "your-executor-service.running", etc. - */ - public class InstrumentedExecutorService implements ExecutorService { -- private static final AtomicLong NAME_COUNTER = new AtomicLong(); -+ private static final AtomicLong NAME_COUNTER = new AtomicLong(); - -- private final ExecutorService delegate; -- private final MetricRegistry registry; -- private final String name; -- private final Meter submitted; -- private final Counter running; -- private final Meter completed; -- private final Counter rejected; -- private final Timer idle; -- private final Timer duration; -+ private final ExecutorService delegate; -+ private final MetricRegistry registry; -+ private final String name; -+ private final Meter submitted; -+ private final Counter running; -+ private final Meter completed; -+ private final Counter rejected; -+ private final Timer idle; -+ private final Timer duration; - -- /** -- * Wraps an {@link ExecutorService} uses an auto-generated default name. -- * -- * @param delegate {@link ExecutorService} to wrap. -- * @param registry {@link MetricRegistry} that will contain the metrics. -- */ -- public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) { -- this(delegate, registry, "instrumented-delegate-" + NAME_COUNTER.incrementAndGet()); -- } -+ /** -+ * Wraps an {@link ExecutorService} uses an auto-generated default name. -+ * -+ * @param delegate {@link ExecutorService} to wrap. -+ * @param registry {@link MetricRegistry} that will contain the metrics. -+ */ -+ public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) { -+ this(delegate, registry, "instrumented-delegate-" + NAME_COUNTER.incrementAndGet()); -+ } - -- /** -- * Wraps an {@link ExecutorService} with an explicit name. -- * -- * @param delegate {@link ExecutorService} to wrap. -- * @param registry {@link MetricRegistry} that will contain the metrics. -- * @param name name for this executor service. -- */ -- public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry, String name) { -- this.delegate = delegate; -- this.registry = registry; -- this.name = name; -- this.submitted = registry.meter(MetricRegistry.name(name, "submitted")); -- this.running = registry.counter(MetricRegistry.name(name, "running")); -- this.completed = registry.meter(MetricRegistry.name(name, "completed")); -- this.rejected = registry.counter(MetricRegistry.name(name, "rejected")); -- this.idle = registry.timer(MetricRegistry.name(name, "idle")); -- this.duration = registry.timer(MetricRegistry.name(name, "duration")); -+ /** -+ * Wraps an {@link ExecutorService} with an explicit name. -+ * -+ * @param delegate {@link ExecutorService} to wrap. -+ * @param registry {@link MetricRegistry} that will contain the metrics. -+ * @param name name for this executor service. -+ */ -+ public InstrumentedExecutorService( -+ ExecutorService delegate, MetricRegistry registry, String name) { -+ this.delegate = delegate; -+ this.registry = registry; -+ this.name = name; -+ this.submitted = registry.meter(MetricRegistry.name(name, "submitted")); -+ this.running = registry.counter(MetricRegistry.name(name, "running")); -+ this.completed = registry.meter(MetricRegistry.name(name, "completed")); -+ this.rejected = registry.counter(MetricRegistry.name(name, "rejected")); -+ this.idle = registry.timer(MetricRegistry.name(name, "idle")); -+ this.duration = registry.timer(MetricRegistry.name(name, "duration")); - -- registerInternalMetrics(); -- } -+ registerInternalMetrics(); -+ } - -- private void registerInternalMetrics() { -- if (delegate instanceof ThreadPoolExecutor) { -- ThreadPoolExecutor executor = (ThreadPoolExecutor) delegate; -- registry.registerGauge(MetricRegistry.name(name, "pool.size"), -- executor::getPoolSize); -- registry.registerGauge(MetricRegistry.name(name, "pool.core"), -- executor::getCorePoolSize); -- registry.registerGauge(MetricRegistry.name(name, "pool.max"), -- executor::getMaximumPoolSize); -- final BlockingQueue queue = executor.getQueue(); -- registry.registerGauge(MetricRegistry.name(name, "tasks.active"), -- executor::getActiveCount); -- registry.registerGauge(MetricRegistry.name(name, "tasks.completed"), -- executor::getCompletedTaskCount); -- registry.registerGauge(MetricRegistry.name(name, "tasks.queued"), -- queue::size); -- registry.registerGauge(MetricRegistry.name(name, "tasks.capacity"), -- queue::remainingCapacity); -- RejectedExecutionHandler delegateHandler = executor.getRejectedExecutionHandler(); -- executor.setRejectedExecutionHandler(new InstrumentedRejectedExecutionHandler(delegateHandler)); -- } else if (delegate instanceof ForkJoinPool) { -- ForkJoinPool forkJoinPool = (ForkJoinPool) delegate; -- registry.registerGauge(MetricRegistry.name(name, "tasks.stolen"), -- forkJoinPool::getStealCount); -- registry.registerGauge(MetricRegistry.name(name, "tasks.queued"), -- forkJoinPool::getQueuedTaskCount); -- registry.registerGauge(MetricRegistry.name(name, "threads.active"), -- forkJoinPool::getActiveThreadCount); -- registry.registerGauge(MetricRegistry.name(name, "threads.running"), -- forkJoinPool::getRunningThreadCount); -- } -+ private void registerInternalMetrics() { -+ if (delegate instanceof ThreadPoolExecutor) { -+ ThreadPoolExecutor executor = (ThreadPoolExecutor) delegate; -+ registry.registerGauge(MetricRegistry.name(name, "pool.size"), executor::getPoolSize); -+ registry.registerGauge(MetricRegistry.name(name, "pool.core"), executor::getCorePoolSize); -+ registry.registerGauge(MetricRegistry.name(name, "pool.max"), executor::getMaximumPoolSize); -+ final BlockingQueue queue = executor.getQueue(); -+ registry.registerGauge(MetricRegistry.name(name, "tasks.active"), executor::getActiveCount); -+ registry.registerGauge( -+ MetricRegistry.name(name, "tasks.completed"), executor::getCompletedTaskCount); -+ registry.registerGauge(MetricRegistry.name(name, "tasks.queued"), queue::size); -+ registry.registerGauge(MetricRegistry.name(name, "tasks.capacity"), queue::remainingCapacity); -+ RejectedExecutionHandler delegateHandler = executor.getRejectedExecutionHandler(); -+ executor.setRejectedExecutionHandler( -+ new InstrumentedRejectedExecutionHandler(delegateHandler)); -+ } else if (delegate instanceof ForkJoinPool) { -+ ForkJoinPool forkJoinPool = (ForkJoinPool) delegate; -+ registry.registerGauge( -+ MetricRegistry.name(name, "tasks.stolen"), forkJoinPool::getStealCount); -+ registry.registerGauge( -+ MetricRegistry.name(name, "tasks.queued"), forkJoinPool::getQueuedTaskCount); -+ registry.registerGauge( -+ MetricRegistry.name(name, "threads.active"), forkJoinPool::getActiveThreadCount); -+ registry.registerGauge( -+ MetricRegistry.name(name, "threads.running"), forkJoinPool::getRunningThreadCount); - } -+ } - -- private void removeInternalMetrics() { -- if (delegate instanceof ThreadPoolExecutor) { -- registry.remove(MetricRegistry.name(name, "pool.size")); -- registry.remove(MetricRegistry.name(name, "pool.core")); -- registry.remove(MetricRegistry.name(name, "pool.max")); -- registry.remove(MetricRegistry.name(name, "tasks.active")); -- registry.remove(MetricRegistry.name(name, "tasks.completed")); -- registry.remove(MetricRegistry.name(name, "tasks.queued")); -- registry.remove(MetricRegistry.name(name, "tasks.capacity")); -- } else if (delegate instanceof ForkJoinPool) { -- registry.remove(MetricRegistry.name(name, "tasks.stolen")); -- registry.remove(MetricRegistry.name(name, "tasks.queued")); -- registry.remove(MetricRegistry.name(name, "threads.active")); -- registry.remove(MetricRegistry.name(name, "threads.running")); -- } -+ private void removeInternalMetrics() { -+ if (delegate instanceof ThreadPoolExecutor) { -+ registry.remove(MetricRegistry.name(name, "pool.size")); -+ registry.remove(MetricRegistry.name(name, "pool.core")); -+ registry.remove(MetricRegistry.name(name, "pool.max")); -+ registry.remove(MetricRegistry.name(name, "tasks.active")); -+ registry.remove(MetricRegistry.name(name, "tasks.completed")); -+ registry.remove(MetricRegistry.name(name, "tasks.queued")); -+ registry.remove(MetricRegistry.name(name, "tasks.capacity")); -+ } else if (delegate instanceof ForkJoinPool) { -+ registry.remove(MetricRegistry.name(name, "tasks.stolen")); -+ registry.remove(MetricRegistry.name(name, "tasks.queued")); -+ registry.remove(MetricRegistry.name(name, "threads.active")); -+ registry.remove(MetricRegistry.name(name, "threads.running")); - } -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void execute(Runnable runnable) { -- submitted.mark(); -- delegate.execute(new InstrumentedRunnable(runnable)); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public void execute(Runnable runnable) { -+ submitted.mark(); -+ delegate.execute(new InstrumentedRunnable(runnable)); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public Future submit(Runnable runnable) { -- submitted.mark(); -- return delegate.submit(new InstrumentedRunnable(runnable)); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public Future submit(Runnable runnable) { -+ submitted.mark(); -+ return delegate.submit(new InstrumentedRunnable(runnable)); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public Future submit(Runnable runnable, T result) { -- submitted.mark(); -- return delegate.submit(new InstrumentedRunnable(runnable), result); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public Future submit(Runnable runnable, T result) { -+ submitted.mark(); -+ return delegate.submit(new InstrumentedRunnable(runnable), result); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public Future submit(Callable task) { -- submitted.mark(); -- return delegate.submit(new InstrumentedCallable<>(task)); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public Future submit(Callable task) { -+ submitted.mark(); -+ return delegate.submit(new InstrumentedCallable<>(task)); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public List> invokeAll(Collection> tasks) throws InterruptedException { -- submitted.mark(tasks.size()); -- Collection> instrumented = instrument(tasks); -- return delegate.invokeAll(instrumented); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public List> invokeAll(Collection> tasks) -+ throws InterruptedException { -+ submitted.mark(tasks.size()); -+ Collection> instrumented = instrument(tasks); -+ return delegate.invokeAll(instrumented); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { -- submitted.mark(tasks.size()); -- Collection> instrumented = instrument(tasks); -- return delegate.invokeAll(instrumented, timeout, unit); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public List> invokeAll( -+ Collection> tasks, long timeout, TimeUnit unit) -+ throws InterruptedException { -+ submitted.mark(tasks.size()); -+ Collection> instrumented = instrument(tasks); -+ return delegate.invokeAll(instrumented, timeout, unit); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public T invokeAny(Collection> tasks) throws ExecutionException, InterruptedException { -- submitted.mark(tasks.size()); -- Collection> instrumented = instrument(tasks); -- return delegate.invokeAny(instrumented); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public T invokeAny(Collection> tasks) -+ throws ExecutionException, InterruptedException { -+ submitted.mark(tasks.size()); -+ Collection> instrumented = instrument(tasks); -+ return delegate.invokeAny(instrumented); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException { -- submitted.mark(tasks.size()); -- Collection> instrumented = instrument(tasks); -- return delegate.invokeAny(instrumented, timeout, unit); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) -+ throws ExecutionException, InterruptedException, TimeoutException { -+ submitted.mark(tasks.size()); -+ Collection> instrumented = instrument(tasks); -+ return delegate.invokeAny(instrumented, timeout, unit); -+ } - -- private Collection> instrument(Collection> tasks) { -- final List> instrumented = new ArrayList<>(tasks.size()); -- for (Callable task : tasks) { -- instrumented.add(new InstrumentedCallable<>(task)); -- } -- return instrumented; -+ private Collection> instrument( -+ Collection> tasks) { -+ final List> instrumented = new ArrayList<>(tasks.size()); -+ for (Callable task : tasks) { -+ instrumented.add(new InstrumentedCallable<>(task)); - } -+ return instrumented; -+ } +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java +@@ -1,11 +1,14 @@ + package io.dropwizard.metrics5; -- @Override -- public void shutdown() { -- delegate.shutdown(); -- removeInternalMetrics(); -- } -+ @Override -+ public void shutdown() { -+ delegate.shutdown(); -+ removeInternalMetrics(); -+ } - -- @Override -- public List shutdownNow() { -- List remainingTasks = delegate.shutdownNow(); -- removeInternalMetrics(); -- return remainingTasks; -- } -+ @Override -+ public List shutdownNow() { -+ List remainingTasks = delegate.shutdownNow(); -+ removeInternalMetrics(); -+ return remainingTasks; -+ } - -- @Override -- public boolean isShutdown() { -- return delegate.isShutdown(); -- } -+ @Override -+ public boolean isShutdown() { -+ return delegate.isShutdown(); -+ } - -- @Override -- public boolean isTerminated() { -- return delegate.isTerminated(); -- } -+ @Override -+ public boolean isTerminated() { -+ return delegate.isTerminated(); -+ } - -- @Override -- public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException { -- return delegate.awaitTermination(l, timeUnit); -- } -+ @Override -+ public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException { -+ return delegate.awaitTermination(l, timeUnit); -+ } - -- private class InstrumentedRejectedExecutionHandler implements RejectedExecutionHandler { -- private final RejectedExecutionHandler delegateHandler; -+ private class InstrumentedRejectedExecutionHandler implements RejectedExecutionHandler { -+ private final RejectedExecutionHandler delegateHandler; - -- public InstrumentedRejectedExecutionHandler(RejectedExecutionHandler delegateHandler) { -- this.delegateHandler = delegateHandler; -- } -+ public InstrumentedRejectedExecutionHandler(RejectedExecutionHandler delegateHandler) { -+ this.delegateHandler = delegateHandler; -+ } - -- @Override -- public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { -- rejected.inc(); -- this.delegateHandler.rejectedExecution(r, executor); -- } -+ @Override -+ public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { -+ rejected.inc(); -+ this.delegateHandler.rejectedExecution(r, executor); - } -+ } - -- private class InstrumentedRunnable implements Runnable { -- private final Runnable task; -- private final Timer.Context idleContext; -+ private class InstrumentedRunnable implements Runnable { -+ private final Runnable task; -+ private final Timer.Context idleContext; - -- InstrumentedRunnable(Runnable task) { -- this.task = task; -- this.idleContext = idle.time(); -- } -+ InstrumentedRunnable(Runnable task) { -+ this.task = task; -+ this.idleContext = idle.time(); -+ } - -- @Override -- public void run() { -- idleContext.stop(); -- running.inc(); -- try (Timer.Context durationContext = duration.time()) { -- task.run(); -- } finally { -- running.dec(); -- completed.mark(); -- } -- } -+ @Override -+ public void run() { -+ idleContext.stop(); -+ running.inc(); -+ try (Timer.Context durationContext = duration.time()) { -+ task.run(); -+ } finally { -+ running.dec(); -+ completed.mark(); -+ } - } -+ } - -- private class InstrumentedCallable implements Callable { -- private final Callable callable; -- private final Timer.Context idleContext; -+ private class InstrumentedCallable implements Callable { -+ private final Callable callable; -+ private final Timer.Context idleContext; - -- InstrumentedCallable(Callable callable) { -- this.callable = callable; -- this.idleContext = idle.time(); -- } -+ InstrumentedCallable(Callable callable) { -+ this.callable = callable; -+ this.idleContext = idle.time(); -+ } - -- @Override -- public T call() throws Exception { -- idleContext.stop(); -- running.inc(); -- try (Timer.Context context = duration.time()) { -- return callable.call(); -- } finally { -- running.dec(); -- completed.mark(); -- } -- } -+ @Override -+ public T call() throws Exception { -+ idleContext.stop(); -+ running.inc(); -+ try (Timer.Context context = duration.time()) { -+ return callable.call(); -+ } finally { -+ running.dec(); -+ completed.mark(); -+ } - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorService.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorService.java -@@ -15,283 +15,266 @@ import java.util.concurrent.atomic.AtomicLong; - /** - * An {@link ScheduledExecutorService} that monitors the number of tasks submitted, running, - * completed and also keeps a {@link Timer} for the task duration. -- *

    -- * It will register the metrics using the given (or auto-generated) name as classifier, e.g: -+ * -+ *

    It will register the metrics using the given (or auto-generated) name as classifier, e.g: - * "your-executor-service.submitted", "your-executor-service.running", etc. - */ - public class InstrumentedScheduledExecutorService implements ScheduledExecutorService { -- private static final AtomicLong NAME_COUNTER = new AtomicLong(); -- -- private final ScheduledExecutorService delegate; -- -- private final Meter submitted; -- private final Counter running; -- private final Meter completed; -- private final Timer duration; -- -- private final Meter scheduledOnce; -- private final Meter scheduledRepetitively; -- private final Counter scheduledOverrun; -- private final Histogram percentOfPeriod; -- -- /** -- * Wraps an {@link ScheduledExecutorService} uses an auto-generated default name. -- * -- * @param delegate {@link ScheduledExecutorService} to wrap. -- * @param registry {@link MetricRegistry} that will contain the metrics. -- */ -- public InstrumentedScheduledExecutorService(ScheduledExecutorService delegate, MetricRegistry registry) { -- this(delegate, registry, "instrumented-scheduled-executor-service-" + NAME_COUNTER.incrementAndGet()); -+ private static final AtomicLong NAME_COUNTER = new AtomicLong(); -+ -+ private final ScheduledExecutorService delegate; -+ -+ private final Meter submitted; -+ private final Counter running; -+ private final Meter completed; -+ private final Timer duration; -+ -+ private final Meter scheduledOnce; -+ private final Meter scheduledRepetitively; -+ private final Counter scheduledOverrun; -+ private final Histogram percentOfPeriod; -+ -+ /** -+ * Wraps an {@link ScheduledExecutorService} uses an auto-generated default name. -+ * -+ * @param delegate {@link ScheduledExecutorService} to wrap. -+ * @param registry {@link MetricRegistry} that will contain the metrics. -+ */ -+ public InstrumentedScheduledExecutorService( -+ ScheduledExecutorService delegate, MetricRegistry registry) { -+ this( -+ delegate, -+ registry, -+ "instrumented-scheduled-executor-service-" + NAME_COUNTER.incrementAndGet()); -+ } -+ -+ /** -+ * Wraps an {@link ScheduledExecutorService} with an explicit name. -+ * -+ * @param delegate {@link ScheduledExecutorService} to wrap. -+ * @param registry {@link MetricRegistry} that will contain the metrics. -+ * @param name name for this executor service. -+ */ -+ public InstrumentedScheduledExecutorService( -+ ScheduledExecutorService delegate, MetricRegistry registry, String name) { -+ this.delegate = delegate; -+ -+ this.submitted = registry.meter(MetricRegistry.name(name, "submitted")); -+ -+ this.running = registry.counter(MetricRegistry.name(name, "running")); -+ this.completed = registry.meter(MetricRegistry.name(name, "completed")); -+ this.duration = registry.timer(MetricRegistry.name(name, "duration")); -+ -+ this.scheduledOnce = registry.meter(MetricRegistry.name(name, "scheduled.once")); -+ this.scheduledRepetitively = -+ registry.meter(MetricRegistry.name(name, "scheduled.repetitively")); -+ this.scheduledOverrun = registry.counter(MetricRegistry.name(name, "scheduled.overrun")); -+ this.percentOfPeriod = -+ registry.histogram(MetricRegistry.name(name, "scheduled.percent-of-period")); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { -+ scheduledOnce.mark(); -+ return delegate.schedule(new InstrumentedRunnable(command), delay, unit); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { -+ scheduledOnce.mark(); -+ return delegate.schedule(new InstrumentedCallable<>(callable), delay, unit); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public ScheduledFuture scheduleAtFixedRate( -+ Runnable command, long initialDelay, long period, TimeUnit unit) { -+ scheduledRepetitively.mark(); -+ return delegate.scheduleAtFixedRate( -+ new InstrumentedPeriodicRunnable(command, period, unit), initialDelay, period, unit); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public ScheduledFuture scheduleWithFixedDelay( -+ Runnable command, long initialDelay, long delay, TimeUnit unit) { -+ scheduledRepetitively.mark(); -+ return delegate.scheduleWithFixedDelay( -+ new InstrumentedRunnable(command), initialDelay, delay, unit); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void shutdown() { -+ delegate.shutdown(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public List shutdownNow() { -+ return delegate.shutdownNow(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public boolean isShutdown() { -+ return delegate.isShutdown(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public boolean isTerminated() { -+ return delegate.isTerminated(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { -+ return delegate.awaitTermination(timeout, unit); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Future submit(Callable task) { -+ submitted.mark(); -+ return delegate.submit(new InstrumentedCallable<>(task)); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Future submit(Runnable task, T result) { -+ submitted.mark(); -+ return delegate.submit(new InstrumentedRunnable(task), result); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Future submit(Runnable task) { -+ submitted.mark(); -+ return delegate.submit(new InstrumentedRunnable(task)); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public List> invokeAll(Collection> tasks) -+ throws InterruptedException { -+ submitted.mark(tasks.size()); -+ Collection> instrumented = instrument(tasks); -+ return delegate.invokeAll(instrumented); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public List> invokeAll( -+ Collection> tasks, long timeout, TimeUnit unit) -+ throws InterruptedException { -+ submitted.mark(tasks.size()); -+ Collection> instrumented = instrument(tasks); -+ return delegate.invokeAll(instrumented, timeout, unit); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public T invokeAny(Collection> tasks) -+ throws InterruptedException, ExecutionException { -+ submitted.mark(tasks.size()); -+ Collection> instrumented = instrument(tasks); -+ return delegate.invokeAny(instrumented); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) -+ throws InterruptedException, ExecutionException, TimeoutException { -+ submitted.mark(tasks.size()); -+ Collection> instrumented = instrument(tasks); -+ return delegate.invokeAny(instrumented, timeout, unit); -+ } -+ -+ private Collection> instrument( -+ Collection> tasks) { -+ final List> instrumented = new ArrayList<>(tasks.size()); -+ for (Callable task : tasks) { -+ instrumented.add(new InstrumentedCallable<>(task)); - } -+ return instrumented; -+ } - -- /** -- * Wraps an {@link ScheduledExecutorService} with an explicit name. -- * -- * @param delegate {@link ScheduledExecutorService} to wrap. -- * @param registry {@link MetricRegistry} that will contain the metrics. -- * @param name name for this executor service. -- */ -- public InstrumentedScheduledExecutorService(ScheduledExecutorService delegate, MetricRegistry registry, String name) { -- this.delegate = delegate; -- -- this.submitted = registry.meter(MetricRegistry.name(name, "submitted")); -- -- this.running = registry.counter(MetricRegistry.name(name, "running")); -- this.completed = registry.meter(MetricRegistry.name(name, "completed")); -- this.duration = registry.timer(MetricRegistry.name(name, "duration")); -- -- this.scheduledOnce = registry.meter(MetricRegistry.name(name, "scheduled.once")); -- this.scheduledRepetitively = registry.meter(MetricRegistry.name(name, "scheduled.repetitively")); -- this.scheduledOverrun = registry.counter(MetricRegistry.name(name, "scheduled.overrun")); -- this.percentOfPeriod = registry.histogram(MetricRegistry.name(name, "scheduled.percent-of-period")); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { -- scheduledOnce.mark(); -- return delegate.schedule(new InstrumentedRunnable(command), delay, unit); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { -- scheduledOnce.mark(); -- return delegate.schedule(new InstrumentedCallable<>(callable), delay, unit); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { -- scheduledRepetitively.mark(); -- return delegate.scheduleAtFixedRate(new InstrumentedPeriodicRunnable(command, period, unit), initialDelay, period, unit); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { -- scheduledRepetitively.mark(); -- return delegate.scheduleWithFixedDelay(new InstrumentedRunnable(command), initialDelay, delay, unit); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public void shutdown() { -- delegate.shutdown(); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public List shutdownNow() { -- return delegate.shutdownNow(); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public boolean isShutdown() { -- return delegate.isShutdown(); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public boolean isTerminated() { -- return delegate.isTerminated(); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { -- return delegate.awaitTermination(timeout, unit); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public void execute(Runnable command) { -+ submitted.mark(); -+ delegate.execute(new InstrumentedRunnable(command)); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public Future submit(Callable task) { -- submitted.mark(); -- return delegate.submit(new InstrumentedCallable<>(task)); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public Future submit(Runnable task, T result) { -- submitted.mark(); -- return delegate.submit(new InstrumentedRunnable(task), result); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public Future submit(Runnable task) { -- submitted.mark(); -- return delegate.submit(new InstrumentedRunnable(task)); -- } -+ private class InstrumentedRunnable implements Runnable { -+ private final Runnable command; - -- /** -- * {@inheritDoc} -- */ -- @Override -- public List> invokeAll(Collection> tasks) throws InterruptedException { -- submitted.mark(tasks.size()); -- Collection> instrumented = instrument(tasks); -- return delegate.invokeAll(instrumented); -+ InstrumentedRunnable(Runnable command) { -+ this.command = command; - } ++import static java.util.Collections.emptySortedMap; ++import static java.util.Collections.emptySortedSet; + import static java.util.Objects.requireNonNull; -- /** -- * {@inheritDoc} -- */ - @Override -- public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { -- submitted.mark(tasks.size()); -- Collection> instrumented = instrument(tasks); -- return delegate.invokeAll(instrumented, timeout, unit); -+ public void run() { -+ running.inc(); -+ final Timer.Context context = duration.time(); -+ try { -+ command.run(); -+ } finally { -+ context.stop(); -+ running.dec(); -+ completed.mark(); -+ } - } -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { -- submitted.mark(tasks.size()); -- Collection> instrumented = instrument(tasks); -- return delegate.invokeAny(instrumented); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { -- submitted.mark(tasks.size()); -- Collection> instrumented = instrument(tasks); -- return delegate.invokeAny(instrumented, timeout, unit); -- } -+ private class InstrumentedPeriodicRunnable implements Runnable { -+ private final Runnable command; -+ private final long periodInNanos; - -- private Collection> instrument(Collection> tasks) { -- final List> instrumented = new ArrayList<>(tasks.size()); -- for (Callable task : tasks) { -- instrumented.add(new InstrumentedCallable<>(task)); -- } -- return instrumented; -+ InstrumentedPeriodicRunnable(Runnable command, long period, TimeUnit unit) { -+ this.command = command; -+ this.periodInNanos = unit.toNanos(period); - } ++import com.google.common.collect.ImmutableMap; ++import com.google.common.collect.ImmutableSet; + import java.io.OutputStream; + import java.time.Duration; + import java.util.Collection; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -158,67 +161,67 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public SortedSet getNames() { +- return Collections.emptySortedSet(); ++ return emptySortedSet(); + } -- /** -- * {@inheritDoc} -- */ - @Override -- public void execute(Runnable command) { -- submitted.mark(); -- delegate.execute(new InstrumentedRunnable(command)); -- } -- -- private class InstrumentedRunnable implements Runnable { -- private final Runnable command; -- -- InstrumentedRunnable(Runnable command) { -- this.command = command; -- } -- -- @Override -- public void run() { -- running.inc(); -- final Timer.Context context = duration.time(); -- try { -- command.run(); -- } finally { -- context.stop(); -- running.dec(); -- completed.mark(); -- } -+ public void run() { -+ running.inc(); -+ final Timer.Context context = duration.time(); -+ try { -+ command.run(); -+ } finally { -+ final long elapsed = context.stop(); -+ running.dec(); -+ completed.mark(); -+ if (elapsed > periodInNanos) { -+ scheduledOverrun.inc(); - } -+ percentOfPeriod.update((100L * elapsed) / periodInNanos); -+ } - } -+ } + /** {@inheritDoc} */ + @Override + public SortedMap> getGauges() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } -- private class InstrumentedPeriodicRunnable implements Runnable { -- private final Runnable command; -- private final long periodInNanos; -- -- InstrumentedPeriodicRunnable(Runnable command, long period, TimeUnit unit) { -- this.command = command; -- this.periodInNanos = unit.toNanos(period); -- } -+ private class InstrumentedCallable implements Callable { -+ private final Callable task; - -- @Override -- public void run() { -- running.inc(); -- final Timer.Context context = duration.time(); -- try { -- command.run(); -- } finally { -- final long elapsed = context.stop(); -- running.dec(); -- completed.mark(); -- if (elapsed > periodInNanos) { -- scheduledOverrun.inc(); -- } -- percentOfPeriod.update((100L * elapsed) / periodInNanos); -- } -- } -+ InstrumentedCallable(Callable task) { -+ this.task = task; - } + /** {@inheritDoc} */ + @Override + public SortedMap> getGauges(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } -- private class InstrumentedCallable implements Callable { -- private final Callable task; -- -- InstrumentedCallable(Callable task) { -- this.task = task; -- } -- -- @Override -- public T call() throws Exception { -- running.inc(); -- final Timer.Context context = duration.time(); -- try { -- return task.call(); -- } finally { -- context.stop(); -- running.dec(); -- completed.mark(); -- } -- } -+ @Override -+ public T call() throws Exception { -+ running.inc(); -+ final Timer.Context context = duration.time(); -+ try { -+ return task.call(); -+ } finally { -+ context.stop(); -+ running.dec(); -+ completed.mark(); -+ } - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedThreadFactory.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedThreadFactory.java -@@ -5,69 +5,67 @@ import java.util.concurrent.atomic.AtomicLong; + /** {@inheritDoc} */ + @Override + public SortedMap getCounters() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } - /** - * A {@link ThreadFactory} that monitors the number of threads created, running and terminated. -- *

    -- * It will register the metrics using the given (or auto-generated) name as classifier, e.g: -+ * -+ *

    It will register the metrics using the given (or auto-generated) name as classifier, e.g: - * "your-thread-delegate.created", "your-thread-delegate.running", etc. - */ - public class InstrumentedThreadFactory implements ThreadFactory { -- private static final AtomicLong NAME_COUNTER = new AtomicLong(); -+ private static final AtomicLong NAME_COUNTER = new AtomicLong(); - -- private final ThreadFactory delegate; -- private final Meter created; -- private final Counter running; -- private final Meter terminated; -+ private final ThreadFactory delegate; -+ private final Meter created; -+ private final Counter running; -+ private final Meter terminated; - -- /** -- * Wraps a {@link ThreadFactory}, uses a default auto-generated name. -- * -- * @param delegate {@link ThreadFactory} to wrap. -- * @param registry {@link MetricRegistry} that will contain the metrics. -- */ -- public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry) { -- this(delegate, registry, "instrumented-thread-delegate-" + NAME_COUNTER.incrementAndGet()); -- } -+ /** -+ * Wraps a {@link ThreadFactory}, uses a default auto-generated name. -+ * -+ * @param delegate {@link ThreadFactory} to wrap. -+ * @param registry {@link MetricRegistry} that will contain the metrics. -+ */ -+ public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry) { -+ this(delegate, registry, "instrumented-thread-delegate-" + NAME_COUNTER.incrementAndGet()); -+ } - -- /** -- * Wraps a {@link ThreadFactory} with an explicit name. -- * -- * @param delegate {@link ThreadFactory} to wrap. -- * @param registry {@link MetricRegistry} that will contain the metrics. -- * @param name name for this delegate. -- */ -- public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry, String name) { -- this.delegate = delegate; -- this.created = registry.meter(MetricRegistry.name(name, "created")); -- this.running = registry.counter(MetricRegistry.name(name, "running")); -- this.terminated = registry.meter(MetricRegistry.name(name, "terminated")); -- } -+ /** -+ * Wraps a {@link ThreadFactory} with an explicit name. -+ * -+ * @param delegate {@link ThreadFactory} to wrap. -+ * @param registry {@link MetricRegistry} that will contain the metrics. -+ * @param name name for this delegate. -+ */ -+ public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry, String name) { -+ this.delegate = delegate; -+ this.created = registry.meter(MetricRegistry.name(name, "created")); -+ this.running = registry.counter(MetricRegistry.name(name, "running")); -+ this.terminated = registry.meter(MetricRegistry.name(name, "terminated")); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public Thread newThread(Runnable runnable) { -- Runnable wrappedRunnable = new InstrumentedRunnable(runnable); -- Thread thread = delegate.newThread(wrappedRunnable); -- created.mark(); -- return thread; -- } -+ /** {@inheritDoc} */ -+ @Override -+ public Thread newThread(Runnable runnable) { -+ Runnable wrappedRunnable = new InstrumentedRunnable(runnable); -+ Thread thread = delegate.newThread(wrappedRunnable); -+ created.mark(); -+ return thread; -+ } - -- private class InstrumentedRunnable implements Runnable { -- private final Runnable task; -+ private class InstrumentedRunnable implements Runnable { -+ private final Runnable task; - -- InstrumentedRunnable(Runnable task) { -- this.task = task; -- } -+ InstrumentedRunnable(Runnable task) { -+ this.task = task; -+ } - -- @Override -- public void run() { -- running.inc(); -- try { -- task.run(); -- } finally { -- running.dec(); -- terminated.mark(); -- } -- } -+ @Override -+ public void run() { -+ running.inc(); -+ try { -+ task.run(); -+ } finally { -+ running.dec(); -+ terminated.mark(); -+ } - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java -@@ -1,9 +1,10 @@ - package io.dropwizard.metrics5; + /** {@inheritDoc} */ + @Override + public SortedMap getCounters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } --import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.util.Objects.requireNonNull; + /** {@inheritDoc} */ + @Override + public SortedMap getHistograms() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } -+import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; - import java.time.Duration; --import java.util.Objects; - import java.util.concurrent.ConcurrentSkipListMap; - import java.util.concurrent.ThreadLocalRandom; - import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -@@ -16,255 +17,255 @@ import java.util.function.BiConsumer; - * sampling reservoir, exponentially biased towards newer entries. - * - * @author Carter Kozak -- * @see -- * Cormode et al. Forward Decay: A Practical Time Decay Model for Streaming Systems. ICDE '09: -- * Proceedings of the 2009 IEEE International Conference on Data Engineering (2009) -- *

    -- * {@link LockFreeExponentiallyDecayingReservoir} is based closely on the {@link ExponentiallyDecayingReservoir}, -- * however it provides looser guarantees while completely avoiding locks. -- *

    -- * Looser guarantees: -- *

      -- *
    • Updates which occur concurrently with rescaling may be discarded if the orphaned state node is updated after -- * rescale has replaced it. This condition has a greater probability as the rescale interval is reduced due to the -- * increased frequency of rescaling. {@link #rescaleThresholdNanos} values below 30 seconds are not recommended. -- *
    • Given a small rescale threshold, updates may attempt to rescale into a new bucket, but lose the CAS race -- * and update into a newer bucket than expected. In these cases the measurement weight is reduced accordingly. -- *
    • In the worst case, all concurrent threads updating the reservoir may attempt to rescale rather than -- * a single thread holding an exclusive write lock. It's expected that the configuration is set such that -- * rescaling is substantially less common than updating at peak load. Even so, when size is reasonably small -- * it can be more efficient to rescale than to park and context switch. -- *
    -+ * @see Cormode et al. Forward -+ * Decay: A Practical Time Decay Model for Streaming Systems. ICDE '09: Proceedings of the 2009 -+ * IEEE International Conference on Data Engineering (2009) -+ *

    {@link LockFreeExponentiallyDecayingReservoir} is based closely on the {@link -+ * ExponentiallyDecayingReservoir}, however it provides looser guarantees while completely -+ * avoiding locks. -+ *

    Looser guarantees: -+ *

      -+ *
    • Updates which occur concurrently with rescaling may be discarded if the orphaned state -+ * node is updated after rescale has replaced it. This condition has a greater probability -+ * as the rescale interval is reduced due to the increased frequency of rescaling. {@link -+ * #rescaleThresholdNanos} values below 30 seconds are not recommended. -+ *
    • Given a small rescale threshold, updates may attempt to rescale into a new bucket, but -+ * lose the CAS race and update into a newer bucket than expected. In these cases the -+ * measurement weight is reduced accordingly. -+ *
    • In the worst case, all concurrent threads updating the reservoir may attempt to rescale -+ * rather than a single thread holding an exclusive write lock. It's expected that the -+ * configuration is set such that rescaling is substantially less common than updating at -+ * peak load. Even so, when size is reasonably small it can be more efficient to rescale -+ * than to park and context switch. -+ *
    - */ - public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + /** {@inheritDoc} */ + @Override + public SortedMap getHistograms(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } -- private static final double SECONDS_PER_NANO = .000_000_001D; -- private static final AtomicReferenceFieldUpdater stateUpdater = -- AtomicReferenceFieldUpdater.newUpdater(LockFreeExponentiallyDecayingReservoir.class, State.class, "state"); -+ private static final double SECONDS_PER_NANO = .000_000_001D; -+ private static final AtomicReferenceFieldUpdater -+ STATE_UPDATER = -+ AtomicReferenceFieldUpdater.newUpdater( -+ LockFreeExponentiallyDecayingReservoir.class, State.class, "state"); -+ -+ private final int size; -+ private final long rescaleThresholdNanos; -+ private final Clock clock; -+ -+ private volatile State state; -+ -+ private static final class State { + /** {@inheritDoc} */ + @Override + public SortedMap getMeters() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } -+ private static final AtomicIntegerFieldUpdater COUNT_UPDATER = -+ AtomicIntegerFieldUpdater.newUpdater(State.class, "count"); -+ -+ private final double alphaNanos; - private final int size; -- private final long rescaleThresholdNanos; -- private final Clock clock; -- -- private volatile State state; -- -- private static final class State { -- -- private static final AtomicIntegerFieldUpdater countUpdater = -- AtomicIntegerFieldUpdater.newUpdater(State.class, "count"); -- -- private final double alphaNanos; -- private final int size; -- private final long startTick; -- // Count is updated after samples are successfully added to the map. -- private final ConcurrentSkipListMap values; -- -- private volatile int count; -- -- State( -- double alphaNanos, -- int size, -- long startTick, -- int count, -- ConcurrentSkipListMap values) { -- this.alphaNanos = alphaNanos; -- this.size = size; -- this.startTick = startTick; -- this.values = values; -- this.count = count; -- } -- -- private void update(long value, long timestampNanos) { -- double itemWeight = weight(timestampNanos - startTick); -- double priority = itemWeight / ThreadLocalRandom.current().nextDouble(); -- boolean mapIsFull = count >= size; -- if (!mapIsFull || values.firstKey() < priority) { -- addSample(priority, value, itemWeight, mapIsFull); -- } -- } -- -- private void addSample(double priority, long value, double itemWeight, boolean bypassIncrement) { -- if (values.putIfAbsent(priority, new WeightedSample(value, itemWeight)) == null -- && (bypassIncrement || countUpdater.incrementAndGet(this) > size)) { -- values.pollFirstEntry(); -- } -- } -- -- /* "A common feature of the above techniques—indeed, the key technique that -- * allows us to track the decayed weights efficiently—is that they maintain -- * counts and other quantities based on g(ti − L), and only scale by g(t − L) -- * at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero -- * and one, the intermediate values of g(ti − L) could become very large. For -- * polynomial functions, these values should not grow too large, and should be -- * effectively represented in practice by floating point values without loss of -- * precision. For exponential functions, these values could grow quite large as -- * new values of (ti − L) become large, and potentially exceed the capacity of -- * common floating point types. However, since the values stored by the -- * algorithms are linear combinations of g values (scaled sums), they can be -- * rescaled relative to a new landmark. That is, by the analysis of exponential -- * decay in Section III-A, the choice of L does not affect the final result. We -- * can therefore multiply each value based on L by a factor of exp(−α(L′ − L)), -- * and obtain the correct value as if we had instead computed relative to a new -- * landmark L′ (and then use this new L′ at query time). This can be done with -- * a linear pass over whatever data structure is being used." -- */ -- State rescale(long newTick) { -- long durationNanos = newTick - startTick; -- double scalingFactor = Math.exp(-alphaNanos * durationNanos); -- int newCount = 0; -- ConcurrentSkipListMap newValues = new ConcurrentSkipListMap<>(); -- if (Double.compare(scalingFactor, 0) != 0) { -- RescalingConsumer consumer = new RescalingConsumer(scalingFactor, newValues); -- values.forEach(consumer); -- // make sure the counter is in sync with the number of stored samples. -- newCount = consumer.count; -- } -- // It's possible that more values were added while the map was scanned, those with the -- // minimum priorities are removed. -- while (newCount > size) { -- Objects.requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); -- newCount--; -- } -- return new State(alphaNanos, size, newTick, newCount, newValues); -- } -- -- private double weight(long durationNanos) { -- return Math.exp(alphaNanos * durationNanos); -- } -+ private final long startTick; -+ // Count is updated after samples are successfully added to the map. -+ private final ConcurrentSkipListMap values; -+ -+ private volatile int count; -+ -+ State( -+ double alphaNanos, -+ int size, -+ long startTick, -+ int count, -+ ConcurrentSkipListMap values) { -+ this.alphaNanos = alphaNanos; -+ this.size = size; -+ this.startTick = startTick; -+ this.values = values; -+ this.count = count; - } + /** {@inheritDoc} */ + @Override + public SortedMap getMeters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } -- private static final class RescalingConsumer implements BiConsumer { -- private final double scalingFactor; -- private final ConcurrentSkipListMap values; -- private int count; -- -- RescalingConsumer(double scalingFactor, ConcurrentSkipListMap values) { -- this.scalingFactor = scalingFactor; -- this.values = values; -- } -- -- @Override -- public void accept(Double priority, WeightedSample sample) { -- double newWeight = sample.weight * scalingFactor; -- if (Double.compare(newWeight, 0) == 0) { -- return; -- } -- WeightedSample newSample = new WeightedSample(sample.value, newWeight); -- if (values.put(priority * scalingFactor, newSample) == null) { -- count++; -- } -- } -+ private void update(long value, long timestampNanos) { -+ double itemWeight = weight(timestampNanos - startTick); -+ double priority = itemWeight / ThreadLocalRandom.current().nextDouble(); -+ boolean mapIsFull = count >= size; -+ if (!mapIsFull || values.firstKey() < priority) { -+ addSample(priority, value, itemWeight, mapIsFull); -+ } - } + /** {@inheritDoc} */ + @Override + public SortedMap getTimers() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } -- private LockFreeExponentiallyDecayingReservoir(int size, double alpha, Duration rescaleThreshold, Clock clock) { -- // Scale alpha to nanoseconds -- double alphaNanos = alpha * SECONDS_PER_NANO; -- this.size = size; -- this.clock = clock; -- this.rescaleThresholdNanos = rescaleThreshold.toNanos(); -- this.state = new State(alphaNanos, size, clock.getTick(), 0, new ConcurrentSkipListMap<>()); -+ private void addSample( -+ double priority, long value, double itemWeight, boolean bypassIncrement) { -+ if (values.putIfAbsent(priority, new WeightedSample(value, itemWeight)) == null -+ && (bypassIncrement || COUNT_UPDATER.incrementAndGet(this) > size)) { -+ values.pollFirstEntry(); -+ } - } + /** {@inheritDoc} */ + @Override + public SortedMap getTimers(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } -- @Override -- public int size() { -- return Math.min(size, state.count); -+ /* "A common feature of the above techniques—indeed, the key technique that -+ * allows us to track the decayed weights efficiently—is that they maintain -+ * counts and other quantities based on g(ti − L), and only scale by g(t − L) -+ * at query time. But while g(ti −L)/g(t−L) is guaranteed to lie between zero -+ * and one, the intermediate values of g(ti − L) could become very large. For -+ * polynomial functions, these values should not grow too large, and should be -+ * effectively represented in practice by floating point values without loss of -+ * precision. For exponential functions, these values could grow quite large as -+ * new values of (ti − L) become large, and potentially exceed the capacity of -+ * common floating point types. However, since the values stored by the -+ * algorithms are linear combinations of g values (scaled sums), they can be -+ * rescaled relative to a new landmark. That is, by the analysis of exponential -+ * decay in Section III-A, the choice of L does not affect the final result. We -+ * can therefore multiply each value based on L by a factor of exp(−α(L′ − L)), -+ * and obtain the correct value as if we had instead computed relative to a new -+ * landmark L′ (and then use this new L′ at query time). This can be done with -+ * a linear pass over whatever data structure is being used." -+ */ -+ State rescale(long newTick) { -+ long durationNanos = newTick - startTick; -+ double scalingFactor = Math.exp(-alphaNanos * durationNanos); -+ int newCount = 0; -+ ConcurrentSkipListMap newValues = new ConcurrentSkipListMap<>(); -+ if (Double.compare(scalingFactor, 0) != 0) { -+ RescalingConsumer consumer = new RescalingConsumer(scalingFactor, newValues); -+ values.forEach(consumer); -+ // make sure the counter is in sync with the number of stored samples. -+ newCount = consumer.count; -+ } -+ // It's possible that more values were added while the map was scanned, those with the -+ // minimum priorities are removed. -+ while (newCount > size) { -+ requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); -+ newCount--; -+ } -+ return new State(alphaNanos, size, newTick, newCount, newValues); - } + /** {@inheritDoc} */ +@@ -236,7 +239,7 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public Map getMetrics() { +- return Collections.emptyMap(); ++ return ImmutableMap.of(); + } -- @Override -- public void update(long value) { -- long now = clock.getTick(); -- rescaleIfNeeded(now).update(value, now); -+ private double weight(long durationNanos) { -+ return Math.exp(alphaNanos * durationNanos); - } -+ } - -- private State rescaleIfNeeded(long currentTick) { -- // This method is optimized for size so the check may be quickly inlined. -- // Rescaling occurs substantially less frequently than the check itself. -- State stateSnapshot = this.state; -- if (currentTick - stateSnapshot.startTick >= rescaleThresholdNanos) { -- return doRescale(currentTick, stateSnapshot); -- } -- return stateSnapshot; -- } -+ private static final class RescalingConsumer implements BiConsumer { -+ private final double scalingFactor; -+ private final ConcurrentSkipListMap values; -+ private int count; - -- private State doRescale(long currentTick, State stateSnapshot) { -- State newState = stateSnapshot.rescale(currentTick); -- if (stateUpdater.compareAndSet(this, stateSnapshot, newState)) { -- // newState successfully installed -- return newState; -- } -- // Otherwise another thread has won the race and we can return the result of a volatile read. -- // It's possible this has taken so long that another update is required, however that's unlikely -- // and no worse than the standard race between a rescale and update. -- return this.state; -+ RescalingConsumer(double scalingFactor, ConcurrentSkipListMap values) { -+ this.scalingFactor = scalingFactor; -+ this.values = values; + static final class NoopMetric implements Metric { +@@ -630,19 +633,19 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public Set keySet() { +- return Collections.emptySet(); ++ return ImmutableSet.of(); } + /** {@inheritDoc} */ @Override -- public Snapshot getSnapshot() { -- State stateSnapshot = rescaleIfNeeded(clock.getTick()); -- return new WeightedSnapshot(stateSnapshot.values.values()); -+ public void accept(Double priority, WeightedSample sample) { -+ double newWeight = sample.weight * scalingFactor; -+ if (Double.compare(newWeight, 0) == 0) { -+ return; -+ } -+ WeightedSample newSample = new WeightedSample(sample.value, newWeight); -+ if (values.put(priority * scalingFactor, newSample) == null) { -+ count++; -+ } - } -+ } -+ -+ private LockFreeExponentiallyDecayingReservoir( -+ int size, double alpha, Duration rescaleThreshold, Clock clock) { -+ // Scale alpha to nanoseconds -+ double alphaNanos = alpha * SECONDS_PER_NANO; -+ this.size = size; -+ this.clock = clock; -+ this.rescaleThresholdNanos = rescaleThreshold.toNanos(); -+ this.state = new State(alphaNanos, size, clock.getTick(), 0, new ConcurrentSkipListMap<>()); -+ } -+ -+ @Override -+ public int size() { -+ return Math.min(size, state.count); -+ } -+ -+ @Override -+ public void update(long value) { -+ long now = clock.getTick(); -+ rescaleIfNeeded(now).update(value, now); -+ } -+ -+ private State rescaleIfNeeded(long currentTick) { -+ // This method is optimized for size so the check may be quickly inlined. -+ // Rescaling occurs substantially less frequently than the check itself. -+ State stateSnapshot = this.state; -+ if (currentTick - stateSnapshot.startTick >= rescaleThresholdNanos) { -+ return doRescale(currentTick, stateSnapshot); -+ } -+ return stateSnapshot; -+ } -+ -+ private State doRescale(long currentTick, State stateSnapshot) { -+ State newState = stateSnapshot.rescale(currentTick); -+ if (STATE_UPDATER.compareAndSet(this, stateSnapshot, newState)) { -+ // newState successfully installed -+ return newState; -+ } -+ // Otherwise another thread has won the race and we can return the result of a volatile read. -+ // It's possible this has taken so long that another update is required, however that's unlikely -+ // and no worse than the standard race between a rescale and update. -+ return this.state; -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ State stateSnapshot = rescaleIfNeeded(clock.getTick()); -+ return new WeightedSnapshot(stateSnapshot.values.values()); -+ } -+ -+ public static Builder builder() { -+ return new Builder(); -+ } -+ -+ /** -+ * By default this uses a size of 1028 elements, which offers a 99.9% confidence level with a 5% -+ * margin of error assuming a normal distribution, and an alpha factor of 0.015, which heavily -+ * biases the reservoir to the past 5 minutes of measurements. -+ */ -+ public static final class Builder { -+ private static final int DEFAULT_SIZE = 1028; -+ private static final double DEFAULT_ALPHA = 0.015D; -+ private static final Duration DEFAULT_RESCALE_THRESHOLD = Duration.ofHours(1); -+ -+ private int size = DEFAULT_SIZE; -+ private double alpha = DEFAULT_ALPHA; -+ private Duration rescaleThreshold = DEFAULT_RESCALE_THRESHOLD; -+ private Clock clock = Clock.defaultClock(); -+ -+ private Builder() {} - -- public static Builder builder() { -- return new Builder(); -+ /** -+ * Maximum number of samples to keep in the reservoir. Once this number is reached older samples -+ * are replaced (based on weight, with some amount of random jitter). -+ */ -+ public Builder size(int value) { -+ checkArgument( -+ value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: %s", value); -+ this.size = value; -+ return this; + public Collection values() { +- return Collections.emptySet(); ++ return ImmutableSet.of(); } - /** -- * By default this uses a size of 1028 elements, which offers a 99.9% -- * confidence level with a 5% margin of error assuming a normal distribution, and an alpha -- * factor of 0.015, which heavily biases the reservoir to the past 5 minutes of measurements. -+ * Alpha is the exponential decay factor. Higher values bias results more heavily toward newer -+ * values. - */ -- public static final class Builder { -- private static final int DEFAULT_SIZE = 1028; -- private static final double DEFAULT_ALPHA = 0.015D; -- private static final Duration DEFAULT_RESCALE_THRESHOLD = Duration.ofHours(1); -- -- private int size = DEFAULT_SIZE; -- private double alpha = DEFAULT_ALPHA; -- private Duration rescaleThreshold = DEFAULT_RESCALE_THRESHOLD; -- private Clock clock = Clock.defaultClock(); -- -- private Builder() { -- } -- -- /** -- * Maximum number of samples to keep in the reservoir. Once this number is reached older samples are -- * replaced (based on weight, with some amount of random jitter). -- */ -- public Builder size(int value) { -- if (value <= 0) { -- throw new IllegalArgumentException( -- "LockFreeExponentiallyDecayingReservoir size must be positive: " + value); -- } -- this.size = value; -- return this; -- } -- -- /** -- * Alpha is the exponential decay factor. Higher values bias results more heavily toward newer values. -- */ -- public Builder alpha(double value) { -- this.alpha = value; -- return this; -- } -- -- /** -- * Interval at which this reservoir is rescaled. -- */ -- public Builder rescaleThreshold(Duration value) { -- this.rescaleThreshold = Objects.requireNonNull(value, "rescaleThreshold is required"); -- return this; -- } -- -- /** -- * Clock instance used for decay. -- */ -- public Builder clock(Clock value) { -- this.clock = Objects.requireNonNull(value, "clock is required"); -- return this; -- } -- -- public Reservoir build() { -- return new LockFreeExponentiallyDecayingReservoir(size, alpha, rescaleThreshold, clock); -- } -+ public Builder alpha(double value) { -+ this.alpha = value; -+ return this; -+ } -+ -+ /** Interval at which this reservoir is rescaled. */ -+ public Builder rescaleThreshold(Duration value) { -+ this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required"); -+ return this; -+ } -+ -+ /** Clock instance used for decay. */ -+ public Builder clock(Clock value) { -+ this.clock = requireNonNull(value, "clock is required"); -+ return this; -+ } -+ -+ public Reservoir build() { -+ return new LockFreeExponentiallyDecayingReservoir(size, alpha, rescaleThreshold, clock); + /** {@inheritDoc} */ + @Override + public Set> entrySet() { +- return Collections.emptySet(); ++ return ImmutableSet.of(); } -+ } + } } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Meter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Meter.java -@@ -4,108 +4,104 @@ import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.LongAdder; +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java +@@ -1,7 +1,10 @@ + package io.dropwizard.metrics5; - /** -- * A meter metric which measures mean throughput and one-, five-, and fifteen-minute -- * moving average throughputs. -+ * A meter metric which measures mean throughput and one-, five-, and fifteen-minute moving average -+ * throughputs. - * - * @see MovingAverages - */ - public class Meter implements Metered { - -- private final MovingAverages movingAverages; -- private final LongAdder count = new LongAdder(); -- private final long startTime; -- private final Clock clock; -+ private final MovingAverages movingAverages; -+ private final LongAdder count = new LongAdder(); -+ private final long startTime; -+ private final Clock clock; - -- /** -- * Creates a new {@link Meter}. -- * -- * @param movingAverages the {@link MovingAverages} implementation to use -- */ -- public Meter(MovingAverages movingAverages) { -- this(movingAverages, Clock.defaultClock()); ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Objects.requireNonNull; ++ ++import com.google.common.collect.ImmutableSet; + import java.io.Closeable; +-import java.util.Collections; + import java.util.Locale; + import java.util.Set; + import java.util.SortedMap; +@@ -128,7 +131,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + durationUnit, + executor, + shutdownExecutorOnStop, +- Collections.emptySet()); ++ ImmutableSet.of()); + } + + protected ScheduledReporter( +@@ -141,9 +144,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + boolean shutdownExecutorOnStop, + Set disabledMetricAttributes) { + +- if (registry == null) { +- throw new NullPointerException("registry == null"); - } -+ /** -+ * Creates a new {@link Meter}. -+ * -+ * @param movingAverages the {@link MovingAverages} implementation to use -+ */ -+ public Meter(MovingAverages movingAverages) { -+ this(movingAverages, Clock.defaultClock()); -+ } - -- /** -- * Creates a new {@link Meter}. -- */ -- public Meter() { -- this(Clock.defaultClock()); ++ requireNonNull(registry, "registry == null"); + + this.registry = registry; + this.filter = filter; +@@ -154,7 +155,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + this.durationFactor = durationUnit.toNanos(1); + this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); + this.disabledMetricAttributes = +- disabledMetricAttributes != null ? disabledMetricAttributes : Collections.emptySet(); ++ disabledMetricAttributes != null ? disabledMetricAttributes : ImmutableSet.of(); + } + + /** +@@ -172,9 +173,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + * for testing. + */ + synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) { +- if (this.scheduledFuture != null) { +- throw new IllegalArgumentException("Reporter already started"); - } -+ /** Creates a new {@link Meter}. */ -+ public Meter() { -+ this(Clock.defaultClock()); -+ } - -- /** -- * Creates a new {@link Meter}. -- * -- * @param clock the clock to use for the meter ticks -- */ -- public Meter(Clock clock) { -- this(new ExponentialMovingAverages(clock), clock); -- } -+ /** -+ * Creates a new {@link Meter}. -+ * -+ * @param clock the clock to use for the meter ticks -+ */ -+ public Meter(Clock clock) { -+ this(new ExponentialMovingAverages(clock), clock); -+ } - -- /** -- * Creates a new {@link Meter}. -- * -- * @param movingAverages the {@link MovingAverages} implementation to use -- * @param clock the clock to use for the meter ticks -- */ -- public Meter(MovingAverages movingAverages, Clock clock) { -- this.movingAverages = movingAverages; -- this.clock = clock; -- this.startTime = this.clock.getTick(); -- } -+ /** -+ * Creates a new {@link Meter}. -+ * -+ * @param movingAverages the {@link MovingAverages} implementation to use -+ * @param clock the clock to use for the meter ticks -+ */ -+ public Meter(MovingAverages movingAverages, Clock clock) { -+ this.movingAverages = movingAverages; -+ this.clock = clock; -+ this.startTime = this.clock.getTick(); -+ } - -- /** -- * Mark the occurrence of an event. -- */ -- public void mark() { -- mark(1); -- } -+ /** Mark the occurrence of an event. */ -+ public void mark() { -+ mark(1); -+ } - -- /** -- * Mark the occurrence of a given number of events. -- * -- * @param n the number of events -- */ -- public void mark(long n) { -- movingAverages.tickIfNecessary(); -- count.add(n); -- movingAverages.update(n); -- } -+ /** -+ * Mark the occurrence of a given number of events. -+ * -+ * @param n the number of events -+ */ -+ public void mark(long n) { -+ movingAverages.tickIfNecessary(); -+ count.add(n); -+ movingAverages.update(n); -+ } - -- @Override -- public long getCount() { -- return count.sum(); -- } -+ @Override -+ public long getCount() { -+ return count.sum(); -+ } - -- @Override -- public long getSum() { -- return movingAverages.getSum(); -- } -+ @Override -+ public long getSum() { -+ return movingAverages.getSum(); -+ } - -- @Override -- public double getFifteenMinuteRate() { -- movingAverages.tickIfNecessary(); -- return movingAverages.getM15Rate(); -- } -+ @Override -+ public double getFifteenMinuteRate() { -+ movingAverages.tickIfNecessary(); -+ return movingAverages.getM15Rate(); -+ } - -- @Override -- public double getFiveMinuteRate() { -- movingAverages.tickIfNecessary(); -- return movingAverages.getM5Rate(); ++ checkArgument(this.scheduledFuture == null, "Reporter already started"); + + this.scheduledFuture = getScheduledFuture(initialDelay, period, unit, runnable); + } +@@ -185,8 +184,8 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, + * ScheduledExecutorService)} instead. + */ +- @SuppressWarnings("DeprecatedIsStillUsed") + @Deprecated ++ @SuppressWarnings("DeprecatedIsStillUsed") + protected ScheduledFuture getScheduledFuture( + long initialDelay, long period, TimeUnit unit, Runnable runnable) { + return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkState; ++ + import java.util.Set; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; +@@ -84,9 +86,7 @@ public class SharedMetricRegistries { + */ + public static MetricRegistry getDefault() { + MetricRegistry metricRegistry = tryGetDefault(); +- if (metricRegistry == null) { +- throw new IllegalStateException("Default registry name has not been set."); - } -+ @Override -+ public double getFiveMinuteRate() { -+ movingAverages.tickIfNecessary(); -+ return movingAverages.getM5Rate(); -+ } - -- @Override -- public double getMeanRate() { -- if (getCount() == 0) { -- return 0.0; -- } else { -- final double elapsed = clock.getTick() - startTime; -- return getCount() / elapsed * TimeUnit.SECONDS.toNanos(1); -- } -+ @Override -+ public double getMeanRate() { -+ if (getCount() == 0) { -+ return 0.0; -+ } else { -+ final double elapsed = clock.getTick() - startTime; -+ return getCount() / elapsed * TimeUnit.SECONDS.toNanos(1); ++ checkState(metricRegistry != null, "Default registry name has not been set."); + return metricRegistry; + } + +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java +@@ -4,10 +4,8 @@ import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MAX; + import static io.dropwizard.metrics5.MetricAttribute.MEAN; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P75; + import static io.dropwizard.metrics5.MetricAttribute.P95; +@@ -16,7 +14,7 @@ import static io.dropwizard.metrics5.MetricAttribute.P99; + import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; + +-import java.util.Collections; ++import com.google.common.collect.ImmutableSet; + import java.util.Map.Entry; + import java.util.Set; + import java.util.SortedMap; +@@ -81,7 +79,7 @@ public class Slf4jReporter extends ScheduledReporter { + this.loggingLevel = LoggingLevel.INFO; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = ImmutableSet.of(); } -+ } -- @Override -- public double getOneMinuteRate() { -- movingAverages.tickIfNecessary(); -- return movingAverages.getM1Rate(); -- } -+ @Override -+ public double getOneMinuteRate() { -+ movingAverages.tickIfNecessary(); -+ return movingAverages.getM1Rate(); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Metered.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Metered.java -@@ -1,56 +1,54 @@ - package io.dropwizard.metrics5; + /** +@@ -306,8 +304,8 @@ public class Slf4jReporter extends ScheduledReporter { + b.append("type=TIMER"); + append(b, "name", prefix(name)); + appendCountIfEnabled(b, timer); +- appendLongDurationIfEnabled(b, MIN, snapshot::getMin); +- appendLongDurationIfEnabled(b, MAX, snapshot::getMax); ++ appendLongDurationIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongDurationIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); + appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); + appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); + appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); +@@ -338,8 +336,8 @@ public class Slf4jReporter extends ScheduledReporter { + b.append("type=HISTOGRAM"); + append(b, "name", prefix(name)); + appendCountIfEnabled(b, histogram); +- appendLongIfEnabled(b, MIN, snapshot::getMin); +- appendLongIfEnabled(b, MAX, snapshot::getMax); ++ appendLongIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); + appendDoubleIfEnabled(b, MEAN, snapshot::getMean); + appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); + appendDoubleIfEnabled(b, P50, snapshot::getMedian); +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java +@@ -186,8 +186,7 @@ public class SlidingTimeWindowMovingAverages implements MovingAverages { + buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); + buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); + } +- long retval = adder.longValue(); +- return retval; ++ return adder.longValue(); + } --/** -- * An object which maintains mean and moving average rates. -- */ -+/** An object which maintains mean and moving average rates. */ - public interface Metered extends Metric, Counting, Summing { -- /** -- * Returns the number of events which have been marked. -- * -- * @return the number of events which have been marked -- */ -- @Override -- long getCount(); -+ /** -+ * Returns the number of events which have been marked. -+ * -+ * @return the number of events which have been marked -+ */ -+ @Override -+ long getCount(); - -- /** -- * Returns the sum of events which have been marked. -- * -- * @return the sum of events which have been marked -- */ -- @Override -- long getSum(); -+ /** -+ * Returns the sum of events which have been marked. -+ * -+ * @return the sum of events which have been marked -+ */ -+ @Override -+ long getSum(); - -- /** -- * Returns the fifteen-minute moving average rate at which events have -- * occurred since the meter was created. -- * -- * @return the fifteen-minute moving average rate at which events have -- * occurred since the meter was created -- */ -- double getFifteenMinuteRate(); -+ /** -+ * Returns the fifteen-minute moving average rate at which events have occurred since the meter -+ * was created. -+ * -+ * @return the fifteen-minute moving average rate at which events have occurred since the meter -+ * was created -+ */ -+ double getFifteenMinuteRate(); - -- /** -- * Returns the five-minute moving average rate at which events have -- * occurred since the meter was created. -- * -- * @return the five-minute moving average rate at which events have -- * occurred since the meter was created -- */ -- double getFiveMinuteRate(); -+ /** -+ * Returns the five-minute moving average rate at which events have occurred since the meter was -+ * created. -+ * -+ * @return the five-minute moving average rate at which events have occurred since the meter was -+ * created -+ */ -+ double getFiveMinuteRate(); - -- /** -- * Returns the mean rate at which events have occurred since the meter was created. -- * -- * @return the mean rate at which events have occurred since the meter was created -- */ -- double getMeanRate(); -+ /** -+ * Returns the mean rate at which events have occurred since the meter was created. -+ * -+ * @return the mean rate at which events have occurred since the meter was created -+ */ -+ double getMeanRate(); - -- /** -- * Returns the one-minute moving average rate at which events have -- * occurred since the meter was created. -- * -- * @return the one-minute moving average rate at which events have -- * occurred since the meter was created -- */ -- double getOneMinuteRate(); -+ /** -+ * Returns the one-minute moving average rate at which events have occurred since the meter was -+ * created. -+ * -+ * @return the one-minute moving average rate at which events have occurred since the meter was -+ * created -+ */ -+ double getOneMinuteRate(); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Metric.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Metric.java -@@ -1,8 +1,4 @@ + @Override +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java +@@ -1,5 +1,6 @@ package io.dropwizard.metrics5; --/** -- * A tag interface to indicate that a class is a metric. -- */ --public interface Metric { -- --} -+/** A tag interface to indicate that a class is a metric. */ -+public interface Metric {} ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricAttribute.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricAttribute.java -@@ -1,34 +1,31 @@ - package io.dropwizard.metrics5; ++import static com.google.common.base.Preconditions.checkArgument; + import static java.lang.Math.floor; + import static java.nio.charset.StandardCharsets.UTF_8; --/** -- * Represents attributes of metrics which can be reported. -- */ -+/** Represents attributes of metrics which can be reported. */ - public enum MetricAttribute { -+ MAX("max"), -+ MEAN("mean"), -+ MIN("min"), -+ STDDEV("stddev"), -+ P50("p50"), -+ P75("p75"), -+ P95("p95"), -+ P98("p98"), -+ P99("p99"), -+ P999("p999"), -+ COUNT("count"), -+ SUM("sum"), -+ M1_RATE("m1_rate"), -+ M5_RATE("m5_rate"), -+ M15_RATE("m15_rate"), -+ MEAN_RATE("mean_rate"); - -- MAX("max"), -- MEAN("mean"), -- MIN("min"), -- STDDEV("stddev"), -- P50("p50"), -- P75("p75"), -- P95("p95"), -- P98("p98"), -- P99("p99"), -- P999("p999"), -- COUNT("count"), -- SUM("sum"), -- M1_RATE("m1_rate"), -- M5_RATE("m5_rate"), -- M15_RATE("m15_rate"), -- MEAN_RATE("mean_rate"); -+ private final String code; - -- private final String code; -+ MetricAttribute(String code) { -+ this.code = code; -+ } - -- MetricAttribute(String code) { -- this.code = code; -- } -- -- public String getCode() { -- return code; +@@ -47,9 +48,10 @@ public class UniformSnapshot extends Snapshot { + */ + @Override + public double getValue(double quantile) { +- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { +- throw new IllegalArgumentException(quantile + " is not in [0..1]"); - } -+ public String getCode() { -+ return code; -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricFilter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricFilter.java -@@ -1,32 +1,28 @@ ++ checkArgument( ++ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), ++ "%s is not in [0..1]", ++ quantile); + + if (values.length == 0) { + return 0.0; +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java +@@ -1,13 +1,14 @@ package io.dropwizard.metrics5; --/** -- * A filter used to determine whether or not a metric should be reported, among other things. -- */ -+/** A filter used to determine whether or not a metric should be reported, among other things. */ - public interface MetricFilter { -- /** -- * Matches all metrics, regardless of type or name. -- */ -- MetricFilter ALL = (name, metric) -> true; -+ /** Matches all metrics, regardless of type or name. */ -+ MetricFilter ALL = (name, metric) -> true; - -- static MetricFilter startsWith(String prefix) { -- return (name, metric) -> name.getKey().startsWith(prefix); -- } -+ static MetricFilter startsWith(String prefix) { -+ return (name, metric) -> name.getKey().startsWith(prefix); -+ } ++import static com.google.common.base.Preconditions.checkArgument; + import static java.nio.charset.StandardCharsets.UTF_8; ++import static java.util.Comparator.comparingLong; -- static MetricFilter endsWith(String suffix) { -- return (name, metric) -> name.getKey().endsWith(suffix); -- } -+ static MetricFilter endsWith(String suffix) { -+ return (name, metric) -> name.getKey().endsWith(suffix); -+ } + import java.io.OutputStream; + import java.io.OutputStreamWriter; + import java.io.PrintWriter; + import java.util.Arrays; + import java.util.Collection; +-import java.util.Comparator; -- static MetricFilter contains(String substring) { -- return (name, metric) -> name.getKey().contains(substring); + /** A statistical snapshot of a {@link WeightedSnapshot}. */ + public class WeightedSnapshot extends Snapshot { +@@ -35,7 +36,7 @@ public class WeightedSnapshot extends Snapshot { + public WeightedSnapshot(Collection values) { + final WeightedSample[] copy = values.toArray(new WeightedSample[] {}); + +- Arrays.sort(copy, Comparator.comparingLong(w -> w.value)); ++ Arrays.sort(copy, comparingLong(w -> w.value)); + + this.values = new long[copy.length]; + this.normWeights = new double[copy.length]; +@@ -64,9 +65,10 @@ public class WeightedSnapshot extends Snapshot { + */ + @Override + public double getValue(double quantile) { +- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { +- throw new IllegalArgumentException(quantile + " is not in [0..1]"); - } -+ static MetricFilter contains(String substring) { -+ return (name, metric) -> name.getKey().contains(substring); -+ } - -- /** -- * Returns {@code true} if the metric matches the filter; {@code false} otherwise. -- * -- * @param name the metric's name -- * @param metric the metric -- * @return {@code true} if the metric matches the filter -- */ -- boolean matches(MetricName name, Metric metric); -+ /** -+ * Returns {@code true} if the metric matches the filter; {@code false} otherwise. -+ * -+ * @param name the metric's name -+ * @param metric the metric -+ * @return {@code true} if the metric matches the filter -+ */ -+ boolean matches(MetricName name, Metric metric); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java -@@ -1,213 +1,212 @@ ++ checkArgument( ++ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), ++ "%s is not in [0..1]", ++ quantile); + + if (values.length == 0) { + return 0.0; +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java +@@ -1,7 +1,6 @@ package io.dropwizard.metrics5; --import java.util.Collections; --import java.util.Comparator; -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.util.Collections.unmodifiableMap; -+import static java.util.Map.Entry.comparingByKey; -+import static java.util.Objects.requireNonNull; -+import static java.util.stream.Collectors.joining; -+ -+import com.google.common.base.Strings; -+import com.google.common.collect.ImmutableMap; -+import java.util.Arrays; - import java.util.HashMap; - import java.util.Iterator; - import java.util.LinkedHashMap; - import java.util.Map; - import java.util.Objects; --import java.util.stream.Collectors; - import java.util.stream.Stream; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertTrue; - /** -- * A metric name with the ability to include semantic tags. -- * This replaces the previous style where metric names where strictly dot-separated strings. -+ * A metric name with the ability to include semantic tags. This replaces the previous style where -+ * metric names where strictly dot-separated strings. - */ - public class MetricName implements Comparable { + import java.util.ArrayList; + import java.util.List; +@@ -15,8 +14,8 @@ import org.junit.jupiter.api.Test; + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; -- private static final String SEPARATOR = "."; -- private static final Map EMPTY_TAGS = Collections.emptyMap(); -- static final MetricName EMPTY = new MetricName("", EMPTY_TAGS); -- -- /** -- * Returns an empty metric name. -- * -- * @return an empty metric name. -- */ -- public static MetricName empty() { -- return EMPTY; -+ private static final String SEPARATOR = "."; -+ private static final Map EMPTY_TAGS = ImmutableMap.of(); -+ static final MetricName EMPTY = new MetricName("", EMPTY_TAGS); -+ -+ /** -+ * Returns an empty metric name. -+ * -+ * @return an empty metric name. -+ */ -+ public static MetricName empty() { -+ return EMPTY; -+ } -+ -+ private final String key; -+ private final Map tags; -+ -+ public MetricName(String key, Map tags) { -+ this.key = requireNonNull(key); -+ this.tags = tags.isEmpty() ? EMPTY_TAGS : unmodifiableSortedCopy(tags); -+ } -+ -+ public String getKey() { -+ return key; -+ } -+ -+ /** -+ * Returns the tags, sorted by key. -+ * -+ * @return the tags (immutable), sorted by key. -+ */ -+ public Map getTags() { -+ return tags; -+ } -+ -+ /** -+ * Build the MetricName that is this with another path appended to it. The new MetricName inherits -+ * the tags of this one. -+ * -+ * @param parts The extra path elements to add to the new metric. -+ * @return A new metric name relative to the original by the path specified in parts. -+ */ -+ public MetricName resolve(String... parts) { -+ if (parts == null || parts.length == 0) { -+ return this; - } +-class CachedGaugeTest { +- private static final Logger LOGGER = LoggerFactory.getLogger(CachedGaugeTest.class); ++final class CachedGaugeTest { ++ private static final Logger LOG = LoggerFactory.getLogger(CachedGaugeTest.class); + private static final int THREAD_COUNT = 10; + private static final long RUNNING_TIME_MILLIS = TimeUnit.SECONDS.toMillis(10); -- private final String key; -- private final Map tags; -- -- public MetricName(String key, Map tags) { -- this.key = Objects.requireNonNull(key); -- this.tags = tags.isEmpty() ? EMPTY_TAGS : unmodifiableSortedCopy(tags); -- } -- -- public String getKey() { -- return key; -- } -- -- /** -- * Returns the tags, sorted by key. -- * -- * @return the tags (immutable), sorted by key. -- */ -- public Map getTags() { -- return tags; -+ String newKey = -+ Stream.concat(Stream.of(key), Arrays.stream(parts)) -+ .filter(s -> !Strings.isNullOrEmpty(s)) -+ .collect(joining(SEPARATOR)); -+ return new MetricName(newKey, tags); -+ } -+ -+ /** -+ * Add tags to a metric name and return the newly created MetricName. -+ * -+ * @param add Tags to add. -+ * @return A newly created metric name with the specified tags associated with it. -+ */ -+ public MetricName tagged(Map add) { -+ final Map newTags = new HashMap<>(); -+ newTags.putAll(tags); -+ newTags.putAll(add); -+ return new MetricName(key, newTags); -+ } -+ -+ /** -+ * Same as {@link #tagged(Map)}, but takes a variadic list of arguments. -+ * -+ * @param pairs An even list of strings acting as key-value pairs. -+ * @return A newly created metric name with the specified tags associated with it. -+ * @see #tagged(Map) -+ */ -+ public MetricName tagged(String... pairs) { -+ if (pairs == null || pairs.length == 0) { -+ return this; - } +@@ -100,12 +99,12 @@ class CachedGaugeTest { + Integer newValue = shortTimeoutGauge.getValue(); -- /** -- * Build the MetricName that is this with another path appended to it. -- * The new MetricName inherits the tags of this one. -- * -- * @param parts The extra path elements to add to the new metric. -- * @return A new metric name relative to the original by the path specified -- * in parts. -- */ -- public MetricName resolve(String... parts) { -- if (parts == null || parts.length == 0) { -- return this; -- } -- -- String newKey = Stream.concat(Stream.of(key), Stream.of(parts)) -- .filter(s -> s != null && !s.isEmpty()) -- .collect(Collectors.joining(SEPARATOR)); -- return new MetricName(newKey, tags); -- } -+ checkArgument(pairs.length % 2 == 0, "Argument count must be even"); + if (newValue == null) { +- LOGGER.warn("Cached gauge returned null value"); ++ LOG.warn("Cached gauge returned null value"); + return false; + } -- /** -- * Add tags to a metric name and return the newly created MetricName. -- * -- * @param add Tags to add. -- * @return A newly created metric name with the specified tags associated with it. -- */ -- public MetricName tagged(Map add) { -- final Map newTags = new HashMap<>(); -- newTags.putAll(tags); -- newTags.putAll(add); -- return new MetricName(key, newTags); -+ final Map add = new HashMap<>(); -+ for (int i = 0; i < pairs.length; i += 2) { -+ add.put(pairs[i], pairs[i + 1]); + if (newValue < lastValue) { +- LOGGER.error( ++ LOG.error( + "Cached gauge returned stale value, last: {}, new: {}", + lastValue, + newValue); +@@ -122,7 +121,7 @@ class CachedGaugeTest { } -- /** -- * Same as {@link #tagged(Map)}, but takes a variadic list of arguments. -- * -- * @param pairs An even list of strings acting as key-value pairs. -- * @return A newly created metric name with the specified tags associated with it. -- * @see #tagged(Map) -- */ -- public MetricName tagged(String... pairs) { -- if (pairs == null || pairs.length == 0) { -- return this; -- } -- -- if (pairs.length % 2 != 0) { -- throw new IllegalArgumentException("Argument count must be even"); -- } -- -- final Map add = new HashMap<>(); -- for (int i = 0; i < pairs.length; i += 2) { -- add.put(pairs[i], pairs[i + 1]); -- } -- -- return tagged(add); -+ return tagged(add); -+ } -+ -+ /** -+ * Build the MetricName that is this with another path and tags appended to it. -+ * -+ *

    Semantically equivalent to:
    -+ * this.resolve(append.getKey()).tagged(append.getTags()); -+ * -+ * @param append The extra name element to add to the new metric. -+ * @return A new metric name with path appended to the original, and tags included from both -+ * names. -+ */ -+ public MetricName append(MetricName append) { -+ return resolve(append.key).tagged(append.tags); -+ } -+ -+ /** -+ * Build a new metric name using the specific path components. -+ * -+ *

    Equivalent to:
    -+ * MetricName.empty().resolve(parts); -+ * -+ * @param parts Path of the new metric name. -+ * @return A newly created metric name with the specified path. -+ */ -+ public static MetricName build(String... parts) { -+ return EMPTY.resolve(parts); -+ } -+ -+ @Override -+ public String toString() { -+ return tags.isEmpty() ? key : key + tags; -+ } -+ -+ @Override -+ public boolean equals(Object o) { -+ if (this == o) { -+ return true; - } -- -- /** -- * Build the MetricName that is this with another path and tags appended to it. -- * -- *

    -- * Semantically equivalent to:
    -- * this.resolve(append.getKey()).tagged(append.getTags()); -- * -- * @param append The extra name element to add to the new metric. -- * @return A new metric name with path appended to the original, -- * and tags included from both names. -- */ -- public MetricName append(MetricName append) { -- return resolve(append.key).tagged(append.tags); -+ if (!(o instanceof MetricName)) { -+ return false; - } -- -- /** -- * Build a new metric name using the specific path components. -- * -- *

    -- * Equivalent to:
    -- * MetricName.empty().resolve(parts); -- * -- * @param parts Path of the new metric name. -- * @return A newly created metric name with the specified path. -- **/ -- public static MetricName build(String... parts) { -- return EMPTY.resolve(parts); -+ MetricName that = (MetricName) o; -+ return Objects.equals(key, that.key) && Objects.equals(tags, that.tags); -+ } -+ -+ @Override -+ public int hashCode() { -+ return Objects.hash(key, tags); -+ } -+ -+ @Override -+ public int compareTo(MetricName o) { -+ int c = key.compareTo(o.getKey()); -+ if (c != 0) { -+ return c; + for (int i = 0; i < futures.size(); i++) { +- assertTrue(futures.get(i).get(), "Future " + i + " failed"); ++ assertThat(futures.get(i).get()).withFailMessage("Future %s failed", i).isTrue(); } -- @Override -- public String toString() { -- return tags.isEmpty() ? key : key + tags; -+ return compareTags(tags, o.getTags()); -+ } -+ -+ private int compareTags(Map left, Map right) { -+ Iterator> lit = left.entrySet().iterator(); -+ Iterator> rit = right.entrySet().iterator(); -+ -+ while (lit.hasNext() && rit.hasNext()) { -+ Map.Entry l = lit.next(); -+ Map.Entry r = rit.next(); -+ int c = l.getKey().compareTo(r.getKey()); -+ if (c != 0) { -+ return c; -+ } -+ if (l.getValue() == null && r.getValue() == null) { -+ return 0; -+ } else if (l.getValue() == null) { -+ return -1; -+ } else if (r.getValue() == null) { -+ return 1; -+ } else { -+ c = l.getValue().compareTo(r.getValue()); -+ } -+ if (c != 0) { -+ return c; -+ } - } -- -- @Override -- public boolean equals(Object o) { -- if (this == o) { -- return true; -- } -- if (!(o instanceof MetricName)) { -- return false; -- } -- MetricName that = (MetricName) o; -- return Objects.equals(key, that.key) && -- Objects.equals(tags, that.tags); -+ if (lit.hasNext()) { -+ return 1; -+ } else if (rit.hasNext()) { -+ return -1; -+ } else { -+ return 0; - } -- -- @Override -- public int hashCode() { -- return Objects.hash(key, tags); -- } -- -- @Override -- public int compareTo(MetricName o) { -- int c = key.compareTo(o.getKey()); -- if (c != 0) { -- return c; -- } -- -- return compareTags(tags, o.getTags()); -- } -- -- private int compareTags(Map left, Map right) { -- Iterator> lit = left.entrySet().iterator(); -- Iterator> rit = right.entrySet().iterator(); -- -- while (lit.hasNext() && rit.hasNext()) { -- Map.Entry l = lit.next(); -- Map.Entry r = rit.next(); -- int c = l.getKey().compareTo(r.getKey()); -- if (c != 0) { -- return c; -- } -- if (l.getValue() == null && r.getValue() == null) { -- return 0; -- } else if (l.getValue() == null) { -- return -1; -- } else if (r.getValue() == null) { -- return 1; -- } else { -- c = l.getValue().compareTo(r.getValue()); -- } -- if (c != 0) { -- return c; -- } -- } -- if (lit.hasNext()) { -- return 1; -- } else if (rit.hasNext()) { -- return -1; -- } else { -- return 0; -- } -- } -- -- private static , V> Map unmodifiableSortedCopy(Map map) { -- LinkedHashMap sorted = new LinkedHashMap<>(); -- map.entrySet() -- .stream() -- .sorted(Comparator.comparing(Map.Entry::getKey)) -- .forEach(e -> sorted.put(e.getKey(), e.getValue())); -- return Collections.unmodifiableMap(sorted); -- } -- -+ } -+ -+ private static , V> Map unmodifiableSortedCopy(Map map) { -+ LinkedHashMap sorted = new LinkedHashMap<>(); -+ map.entrySet().stream() -+ .sorted(comparingByKey()) -+ .forEach(e -> sorted.put(e.getKey(), e.getValue())); -+ return unmodifiableMap(sorted); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java -@@ -1,6 +1,10 @@ - package io.dropwizard.metrics5; + executor.shutdown(); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java +@@ -4,10 +4,10 @@ import static org.assertj.core.api.BDDAssertions.then; --import java.util.Collections; -+import static java.util.Collections.unmodifiableMap; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Collections.unmodifiableSortedSet; -+import static java.util.Objects.requireNonNull; -+ - import java.util.List; - import java.util.Map; - import java.util.SortedMap; -@@ -11,701 +15,698 @@ import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.ConcurrentMap; - import java.util.concurrent.CopyOnWriteArrayList; + import org.junit.jupiter.api.Test; --/** -- * A registry of metric instances. -- */ -+/** A registry of metric instances. */ - public class MetricRegistry implements MetricSet { +-class ChunkedAssociativeLongArrayTest { ++final class ChunkedAssociativeLongArrayTest { -- /** -- * Concatenates elements to form a dotted name, eliding any null values or empty strings. -- * -- * @param name the first element of the name -- * @param names the remaining elements of the name -- * @return {@code name} and {@code names} concatenated by periods -- */ -- public static MetricName name(String name, String... names) { -- if (names == null) { -- return MetricName.build(name); -- } -- -- final String[] parts = new String[names.length + 1]; -- parts[0] = name; -- System.arraycopy(names, 0, parts, 1, names.length); -- return MetricName.build(parts); -- } -- -- /** -- * Concatenates a class name and elements to form a dotted name, eliding any null values or -- * empty strings. -- * -- * @param klass the first element of the name -- * @param names the remaining elements of the name -- * @return {@code klass} and {@code names} concatenated by periods -- */ -- public static MetricName name(Class klass, String... names) { -- return name(klass.getName(), names); -- } -- -- private final ConcurrentMap metrics; -- private final List listeners; -- -- /** -- * Creates a new {@link MetricRegistry}. -- */ -- public MetricRegistry() { -- this.metrics = buildMap(); -- this.listeners = new CopyOnWriteArrayList<>(); -- } -- -- /** -- * Creates a new {@link ConcurrentMap} implementation for use inside the registry. Override this -- * to create a {@link MetricRegistry} with space- or time-bounded metric lifecycles, for -- * example. -- * -- * @return a new {@link ConcurrentMap} -- */ -- protected ConcurrentMap buildMap() { -- return new ConcurrentHashMap<>(); -- } -- -- /** -- * See {@link #registerGauge(MetricName, Gauge)} -- */ -- public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { -- return register(MetricName.build(name), metric); -- } -- -- /** -- * Given a {@link Gauge}, registers it under the given name and returns it -- * -- * @param name the name of the gauge -- * @param the type of the gauge's value -- * @return the registered {@link Gauge} -- * @since 4.2.10 -- */ -- public Gauge registerGauge(MetricName name, Gauge metric) throws IllegalArgumentException { -- return register(name, metric); -- } -- -- /** -- * Given a {@link Metric}, registers it under the given name. -- * -- * @param name the name of the metric -- * @param metric the metric -- * @param the type of the metric -- * @return {@code metric} -- * @throws IllegalArgumentException if the name is already registered or metric variable is null -- */ -- public T register(MetricName name, T metric) throws IllegalArgumentException { -- if (metric == null) { -- throw new NullPointerException("metric == null"); -- } -- -- if (metric instanceof MetricRegistry) { -- final MetricRegistry childRegistry = (MetricRegistry) metric; -- final MetricName childName = name; -- childRegistry.addListener(new MetricRegistryListener() { -- @Override -- public void onGaugeAdded(MetricName name, Gauge gauge) { -- register(childName.append(name), gauge); -- } -- -- @Override -- public void onGaugeRemoved(MetricName name) { -- remove(childName.append(name)); -- } -- -- @Override -- public void onCounterAdded(MetricName name, Counter counter) { -- register(childName.append(name), counter); -- } -- -- @Override -- public void onCounterRemoved(MetricName name) { -- remove(childName.append(name)); -- } -- -- @Override -- public void onHistogramAdded(MetricName name, Histogram histogram) { -- register(childName.append(name), histogram); -- } -- -- @Override -- public void onHistogramRemoved(MetricName name) { -- remove(childName.append(name)); -- } -- -- @Override -- public void onMeterAdded(MetricName name, Meter meter) { -- register(childName.append(name), meter); -- } -- -- @Override -- public void onMeterRemoved(MetricName name) { -- remove(childName.append(name)); -- } -- -- @Override -- public void onTimerAdded(MetricName name, Timer timer) { -- register(childName.append(name), timer); -- } -- -- @Override -- public void onTimerRemoved(MetricName name) { -- remove(childName.append(name)); -- } -- }); -- } else if (metric instanceof MetricSet) { -- registerAll(name, (MetricSet) metric); -- } else { -- final Metric existing = metrics.putIfAbsent(name, metric); -- if (existing == null) { -- onMetricAdded(name, metric); -- } else { -- throw new IllegalArgumentException("A metric named " + name + " already exists"); -- } -- } -- return metric; -- } -- -- /** -- * Given a metric set, registers them. -- * -- * @param metrics a set of metrics -- * @throws IllegalArgumentException if any of the names are already registered -- */ -- public void registerAll(MetricSet metrics) throws IllegalArgumentException { -- registerAll(null, metrics); -- } -- -- /** -- * See {@link #counter(MetricName)} -- */ -- public Counter counter(String name) { -- return getOrAdd(MetricName.build(name), MetricBuilder.COUNTERS); -- } -- -- /** -- * Return the {@link Counter} registered under this name; or create and register -- * a new {@link Counter} if none is registered. -- * -- * @param name the name of the metric -- * @return a new or pre-existing {@link Counter} -- */ -- public Counter counter(MetricName name) { -- return getOrAdd(name, MetricBuilder.COUNTERS); -- } -- -- /** -- * See {@link #histogram(MetricName)} -- */ -- public Histogram histogram(String name) { -- return getOrAdd(MetricName.build(name), MetricBuilder.HISTOGRAMS); -- } -- -- /** -- * Return the {@link Counter} registered under this name; or create and register -- * a new {@link Counter} using the provided MetricSupplier if none is registered. -- * -- * @param name the name of the metric -- * @param supplier a MetricSupplier that can be used to manufacture a counter. -- * @return a new or pre-existing {@link Counter} -- */ -- public T counter(MetricName name, final MetricSupplier supplier) { -- return getOrAdd(name, new MetricBuilder() { -+ /** -+ * Concatenates elements to form a dotted name, eliding any null values or empty strings. -+ * -+ * @param name the first element of the name -+ * @param names the remaining elements of the name -+ * @return {@code name} and {@code names} concatenated by periods -+ */ -+ public static MetricName name(String name, String... names) { -+ if (names == null) { -+ return MetricName.build(name); -+ } -+ -+ final String[] parts = new String[names.length + 1]; -+ parts[0] = name; -+ System.arraycopy(names, 0, parts, 1, names.length); -+ return MetricName.build(parts); -+ } -+ -+ /** -+ * Concatenates a class name and elements to form a dotted name, eliding any null values or empty -+ * strings. -+ * -+ * @param klass the first element of the name -+ * @param names the remaining elements of the name -+ * @return {@code klass} and {@code names} concatenated by periods -+ */ -+ public static MetricName name(Class klass, String... names) { -+ return name(klass.getName(), names); -+ } -+ -+ private final ConcurrentMap metrics; -+ private final List listeners; -+ -+ /** Creates a new {@link MetricRegistry}. */ -+ public MetricRegistry() { -+ this.metrics = buildMap(); -+ this.listeners = new CopyOnWriteArrayList<>(); -+ } -+ -+ /** -+ * Creates a new {@link ConcurrentMap} implementation for use inside the registry. Override this -+ * to create a {@link MetricRegistry} with space- or time-bounded metric lifecycles, for example. -+ * -+ * @return a new {@link ConcurrentMap} -+ */ -+ protected ConcurrentMap buildMap() { -+ return new ConcurrentHashMap<>(); -+ } -+ -+ /** See {@link #registerGauge(MetricName, Gauge)} */ -+ public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { -+ return register(MetricName.build(name), metric); -+ } -+ -+ /** -+ * Given a {@link Gauge}, registers it under the given name and returns it -+ * -+ * @param name the name of the gauge -+ * @param the type of the gauge's value -+ * @return the registered {@link Gauge} -+ * @since 4.2.10 -+ */ -+ public Gauge registerGauge(MetricName name, Gauge metric) -+ throws IllegalArgumentException { -+ return register(name, metric); -+ } -+ -+ /** -+ * Given a {@link Metric}, registers it under the given name. -+ * -+ * @param name the name of the metric -+ * @param metric the metric -+ * @param the type of the metric -+ * @return {@code metric} -+ * @throws IllegalArgumentException if the name is already registered or metric variable is null -+ */ -+ public T register(MetricName name, T metric) throws IllegalArgumentException { -+ requireNonNull(metric, "metric == null"); -+ -+ if (metric instanceof MetricRegistry) { -+ final MetricRegistry childRegistry = (MetricRegistry) metric; -+ final MetricName childName = name; -+ childRegistry.addListener( -+ new MetricRegistryListener() { - @Override -- public T newMetric() { -- return supplier.newMetric(); -+ public void onGaugeAdded(MetricName name, Gauge gauge) { -+ register(childName.append(name), gauge); - } + @Test +- void testTrim() { ++ void trim() { + ChunkedAssociativeLongArray array = new ChunkedAssociativeLongArray(3); + array.put(-3, 3); + array.put(-2, 1); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java +@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat; - @Override -- public boolean isInstance(Metric metric) { -- return Counter.class.isInstance(metric); -+ public void onGaugeRemoved(MetricName name) { -+ remove(childName.append(name)); - } -- }); -- } -- -- /** -- * Return the {@link Histogram} registered under this name; or create and register -- * a new {@link Histogram} if none is registered. -- * -- * @param name the name of the metric -- * @return a new or pre-existing {@link Histogram} -- */ -- public Histogram histogram(MetricName name) { -- return getOrAdd(name, MetricBuilder.HISTOGRAMS); -- } + import org.junit.jupiter.api.Test; -- /** -- * See {@link #meter(MetricName)} -- */ -- public Meter meter(String name) { -- return getOrAdd(MetricName.build(name), MetricBuilder.METERS); -- } -- -- /** -- * Return the {@link Histogram} registered under this name; or create and register -- * a new {@link Histogram} using the provided MetricSupplier if none is registered. -- * -- * @param name the name of the metric -- * @param supplier a MetricSupplier that can be used to manufacture a histogram -- * @return a new or pre-existing {@link Histogram} -- */ -- public Histogram histogram(MetricName name, final MetricSupplier supplier) { -- return getOrAdd(name, new MetricBuilder() { - @Override -- public Histogram newMetric() { -- return supplier.newMetric(); -+ public void onCounterAdded(MetricName name, Counter counter) { -+ register(childName.append(name), counter); - } +-public class ClassMetadataTest { ++final class ClassMetadataTest { + @Test +- public void testParameterMetadataIsAvailable() throws NoSuchMethodException { ++ void parameterMetadataIsAvailable() throws NoSuchMethodException { + assertThat(DefaultSettableGauge.class.getConstructor(Object.class).getParameters()) + .allSatisfy(parameter -> assertThat(parameter.isNamePresent()).isTrue()); + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java +@@ -5,15 +5,15 @@ import static org.assertj.core.api.Assertions.offset; - @Override -- public boolean isInstance(Metric metric) { -- return Histogram.class.isInstance(metric); -+ public void onCounterRemoved(MetricName name) { -+ remove(childName.append(name)); - } -- }); -- } + import org.junit.jupiter.api.Test; -- /** -- * Return the {@link Meter} registered under this name; or create and register -- * a new {@link Meter} if none is registered. -- * -- * @param name the name of the metric -- * @return a new or pre-existing {@link Meter} -- */ -- public Meter meter(MetricName name) { -- return getOrAdd(name, MetricBuilder.METERS); -- } -- -- /** -- * See {@link #timer(MetricName)} -- */ -- public Timer timer(String name) { -- return getOrAdd(MetricName.build(name), MetricBuilder.TIMERS); -- } -- -- /** -- * Return the {@link Meter} registered under this name; or create and register -- * a new {@link Meter} using the provided MetricSupplier if none is registered. -- * -- * @param name the name of the metric -- * @param supplier a MetricSupplier that can be used to manufacture a Meter -- * @return a new or pre-existing {@link Meter} -- */ -- public Meter meter(MetricName name, final MetricSupplier supplier) { -- return getOrAdd(name, new MetricBuilder() { - @Override -- public Meter newMetric() { -- return supplier.newMetric(); -+ public void onHistogramAdded(MetricName name, Histogram histogram) { -+ register(childName.append(name), histogram); - } +-class ClockTest { ++final class ClockTest { - @Override -- public boolean isInstance(Metric metric) { -- return Meter.class.isInstance(metric); -+ public void onHistogramRemoved(MetricName name) { -+ remove(childName.append(name)); - } -- }); -- } -- -- /** -- * Return the {@link Timer} registered under this name; or create and register -- * a new {@link Timer} if none is registered. -- * -- * @param name the name of the metric -- * @return a new or pre-existing {@link Timer} -- */ -- public Timer timer(MetricName name) { -- return getOrAdd(name, MetricBuilder.TIMERS); -- } + @Test + void userTimeClock() { + final Clock.UserTimeClock clock = new Clock.UserTimeClock(); -- /** -- * Return the {@link Timer} registered under this name; or create and register -- * a new {@link Timer} using the provided MetricSupplier if none is registered. -- * -- * @param name the name of the metric -- * @param supplier a MetricSupplier that can be used to manufacture a Timer -- * @return a new or pre-existing {@link Timer} -- */ -- public Timer timer(MetricName name, final MetricSupplier supplier) { -- return getOrAdd(name, new MetricBuilder() { - @Override -- public Timer newMetric() { -- return supplier.newMetric(); -+ public void onMeterAdded(MetricName name, Meter meter) { -+ register(childName.append(name), meter); - } +- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(100.0)); ++ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0)); - @Override -- public boolean isInstance(Metric metric) { -- return Timer.class.isInstance(metric); -+ public void onMeterRemoved(MetricName name) { -+ remove(childName.append(name)); - } -- }); -- } +- assertThat((double) clock.getTick()).isEqualTo(System.nanoTime(), offset(1000000.0)); ++ assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0)); + } -- /** -- * Return the {@link Gauge} registered under this name; or create and register -- * a new {@link SettableGauge} if none is registered. -- * -- * @param name the name of the metric -- * @return a pre-existing {@link Gauge} or a new {@link SettableGauge} -- * @since 4.2 -- */ -- @SuppressWarnings({"rawtypes", "unchecked"}) -- public T gauge(MetricName name) { -- return (T) getOrAdd(name, MetricBuilder.GAUGES); -- } -- -- /** -- * Return the {@link Gauge} registered under this name; or create and register -- * a new {@link Gauge} using the provided MetricSupplier if none is registered. -- * -- * @param name the name of the metric -- * @param supplier a MetricSupplier that can be used to manufacture a Gauge -- * @return a new or pre-existing {@link Gauge} -- */ -- @SuppressWarnings("rawtypes") -- public T gauge(MetricName name, final MetricSupplier supplier) { -- return getOrAdd(name, new MetricBuilder() { - @Override -- public T newMetric() { -- return supplier.newMetric(); -+ public void onTimerAdded(MetricName name, Timer timer) { -+ register(childName.append(name), timer); - } + @Test +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java +@@ -19,12 +19,12 @@ import org.apache.commons.lang3.SystemUtils; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; - @Override -- public boolean isInstance(Metric metric) { -- return Gauge.class.isInstance(metric); -+ public void onTimerRemoved(MetricName name) { -+ remove(childName.append(name)); - } -+ }); -+ } else if (metric instanceof MetricSet) { -+ registerAll(name, (MetricSet) metric); -+ } else { -+ final Metric existing = metrics.putIfAbsent(name, metric); -+ if (existing == null) { -+ onMetricAdded(name, metric); -+ } else { -+ throw new IllegalArgumentException("A metric named " + name + " already exists"); -+ } -+ } -+ return metric; -+ } -+ -+ /** -+ * Given a metric set, registers them. -+ * -+ * @param metrics a set of metrics -+ * @throws IllegalArgumentException if any of the names are already registered -+ */ -+ public void registerAll(MetricSet metrics) throws IllegalArgumentException { -+ registerAll(null, metrics); -+ } -+ -+ /** See {@link #counter(MetricName)} */ -+ public Counter counter(String name) { -+ return getOrAdd(MetricName.build(name), MetricBuilder.COUNTERS); -+ } -+ -+ /** -+ * Return the {@link Counter} registered under this name; or create and register a new {@link -+ * Counter} if none is registered. -+ * -+ * @param name the name of the metric -+ * @return a new or pre-existing {@link Counter} -+ */ -+ public Counter counter(MetricName name) { -+ return getOrAdd(name, MetricBuilder.COUNTERS); -+ } -+ -+ /** See {@link #histogram(MetricName)} */ -+ public Histogram histogram(String name) { -+ return getOrAdd(MetricName.build(name), MetricBuilder.HISTOGRAMS); -+ } -+ -+ /** -+ * Return the {@link Counter} registered under this name; or create and register a new {@link -+ * Counter} using the provided MetricSupplier if none is registered. -+ * -+ * @param name the name of the metric -+ * @param supplier a MetricSupplier that can be used to manufacture a counter. -+ * @return a new or pre-existing {@link Counter} -+ */ -+ public T counter(MetricName name, final MetricSupplier supplier) { -+ return getOrAdd( -+ name, -+ new MetricBuilder() { -+ @Override -+ public T newMetric() { -+ return supplier.newMetric(); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Counter; -+ } - }); -- } -- -- -- /** -- * Removes the metric with the given name. -- * -- * @param name the name of the metric -- * @return whether or not the metric was removed -- */ -- public boolean remove(MetricName name) { -- final Metric metric = metrics.remove(name); -- if (metric != null) { -- onMetricRemoved(name, metric); -- return true; -- } -- return false; -- } -- -- /** -- * Removes all metrics which match the given filter. -- * -- * @param filter a filter -- */ -- public void removeMatching(MetricFilter filter) { -- for (Map.Entry entry : metrics.entrySet()) { -- if (filter.matches(entry.getKey(), entry.getValue())) { -- remove(entry.getKey()); -- } -- } -- } -- -- /** -- * Adds a {@link MetricRegistryListener} to a collection of listeners that will be notified on -- * metric creation. Listeners will be notified in the order in which they are added. -- *

    -- * N.B.: The listener will be notified of all existing metrics when it first registers. -- * -- * @param listener the listener that will be notified -- */ -- public void addListener(MetricRegistryListener listener) { -- listeners.add(listener); -- -- for (Map.Entry entry : metrics.entrySet()) { -- notifyListenerOfAddedMetric(listener, entry.getValue(), entry.getKey()); -- } -- } -- -- /** -- * Removes a {@link MetricRegistryListener} from this registry's collection of listeners. -- * -- * @param listener the listener that will be removed -- */ -- public void removeListener(MetricRegistryListener listener) { -- listeners.remove(listener); -- } -- -- /** -- * Returns a set of the names of all the metrics in the registry. -- * -- * @return the names of all the metrics -- */ -- public SortedSet getNames() { -- return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); -- } -- -- /** -- * Returns a map of all the gauges in the registry and their names. -- * -- * @return all the gauges in the registry -- */ -- public SortedMap> getGauges() { -- return getGauges(MetricFilter.ALL); -- } -- -- /** -- * Returns a map of all the gauges in the registry and their names which match the given filter. -- * -- * @param filter the metric filter to match -- * @return all the gauges in the registry -- */ -- public SortedMap> getGauges(MetricFilter filter) { -- final SortedMap> timers = new TreeMap<>(); -- for (Map.Entry entry : metrics.entrySet()) { -- if (entry.getValue() instanceof Gauge && filter.matches(entry.getKey(), -- entry.getValue())) { -- timers.put(entry.getKey(), (Gauge) entry.getValue()); -- } -- } -- return Collections.unmodifiableSortedMap(timers); -- } -- -- /** -- * Returns a map of all the counters in the registry and their names. -- * -- * @return all the counters in the registry -- */ -- public SortedMap getCounters() { -- return getCounters(MetricFilter.ALL); -- } -- -- /** -- * Returns a map of all the counters in the registry and their names which match the given -- * filter. -- * -- * @param filter the metric filter to match -- * @return all the counters in the registry -- */ -- public SortedMap getCounters(MetricFilter filter) { -- return getMetrics(Counter.class, filter); -- } -- -- /** -- * Returns a map of all the histograms in the registry and their names. -- * -- * @return all the histograms in the registry -- */ -- public SortedMap getHistograms() { -- return getHistograms(MetricFilter.ALL); -- } -- -- /** -- * Returns a map of all the histograms in the registry and their names which match the given -- * filter. -- * -- * @param filter the metric filter to match -- * @return all the histograms in the registry -- */ -- public SortedMap getHistograms(MetricFilter filter) { -- return getMetrics(Histogram.class, filter); -- } -- -- /** -- * Returns a map of all the meters in the registry and their names. -- * -- * @return all the meters in the registry -- */ -- public SortedMap getMeters() { -- return getMeters(MetricFilter.ALL); -- } -- -- /** -- * Returns a map of all the meters in the registry and their names which match the given filter. -- * -- * @param filter the metric filter to match -- * @return all the meters in the registry -- */ -- public SortedMap getMeters(MetricFilter filter) { -- return getMetrics(Meter.class, filter); -- } -- -- /** -- * Returns a map of all the timers in the registry and their names. -- * -- * @return all the timers in the registry -- */ -- public SortedMap getTimers() { -- return getTimers(MetricFilter.ALL); -- } -- -- /** -- * Returns a map of all the timers in the registry and their names which match the given filter. -- * -- * @param filter the metric filter to match -- * @return all the timers in the registry -- */ -- public SortedMap getTimers(MetricFilter filter) { -- return getMetrics(Timer.class, filter); -- } -- -- @SuppressWarnings("unchecked") -- private T getOrAdd(MetricName name, MetricBuilder builder) { -- final Metric metric = metrics.get(name); -- if (builder.isInstance(metric)) { -- return (T) metric; -- } else if (metric == null) { -- try { -- return register(name, builder.newMetric()); -- } catch (IllegalArgumentException e) { -- final Metric added = metrics.get(name); -- if (builder.isInstance(added)) { -- return (T) added; -- } -- } -- } -- throw new IllegalArgumentException(name + " is already used for a different type of metric"); -- } -- -- @SuppressWarnings("unchecked") -- private SortedMap getMetrics(Class klass, MetricFilter filter) { -- final SortedMap timers = new TreeMap<>(); -- for (Map.Entry entry : metrics.entrySet()) { -- if (klass.isInstance(entry.getValue()) && filter.matches(entry.getKey(), -- entry.getValue())) { -- timers.put(entry.getKey(), (T) entry.getValue()); -- } -- } -- return Collections.unmodifiableSortedMap(timers); -- } -- -- private void onMetricAdded(MetricName name, Metric metric) { -- for (MetricRegistryListener listener : listeners) { -- notifyListenerOfAddedMetric(listener, metric, name); -- } -- } -- -- private void notifyListenerOfAddedMetric(MetricRegistryListener listener, Metric metric, MetricName name) { -- if (metric instanceof Gauge) { -- listener.onGaugeAdded(name, (Gauge) metric); -- } else if (metric instanceof Counter) { -- listener.onCounterAdded(name, (Counter) metric); -- } else if (metric instanceof Histogram) { -- listener.onHistogramAdded(name, (Histogram) metric); -- } else if (metric instanceof Meter) { -- listener.onMeterAdded(name, (Meter) metric); -- } else if (metric instanceof Timer) { -- listener.onTimerAdded(name, (Timer) metric); -- } else { -- throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); -- } -- } -- -- private void onMetricRemoved(MetricName name, Metric metric) { -- for (MetricRegistryListener listener : listeners) { -- notifyListenerOfRemovedMetric(name, metric, listener); -- } -- } -- -- private void notifyListenerOfRemovedMetric(MetricName name, Metric metric, MetricRegistryListener listener) { -- if (metric instanceof Gauge) { -- listener.onGaugeRemoved(name); -- } else if (metric instanceof Counter) { -- listener.onCounterRemoved(name); -- } else if (metric instanceof Histogram) { -- listener.onHistogramRemoved(name); -- } else if (metric instanceof Meter) { -- listener.onMeterRemoved(name); -- } else if (metric instanceof Timer) { -- listener.onTimerRemoved(name); -- } else { -- throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); -- } -- } -- -- public void registerAll(MetricName prefix, MetricSet metrics) throws IllegalArgumentException { -- if (prefix == null) { -- prefix = MetricName.EMPTY; -- } -- -- for (Map.Entry entry : metrics.getMetrics().entrySet()) { -- if (entry.getValue() instanceof MetricSet) { -- registerAll(prefix.append(entry.getKey()), (MetricSet) entry.getValue()); -- } else { -- register(prefix.append(entry.getKey()), entry.getValue()); -- } -+ } -+ -+ /** -+ * Return the {@link Histogram} registered under this name; or create and register a new {@link -+ * Histogram} if none is registered. -+ * -+ * @param name the name of the metric -+ * @return a new or pre-existing {@link Histogram} -+ */ -+ public Histogram histogram(MetricName name) { -+ return getOrAdd(name, MetricBuilder.HISTOGRAMS); -+ } -+ -+ /** See {@link #meter(MetricName)} */ -+ public Meter meter(String name) { -+ return getOrAdd(MetricName.build(name), MetricBuilder.METERS); -+ } -+ -+ /** -+ * Return the {@link Histogram} registered under this name; or create and register a new {@link -+ * Histogram} using the provided MetricSupplier if none is registered. -+ * -+ * @param name the name of the metric -+ * @param supplier a MetricSupplier that can be used to manufacture a histogram -+ * @return a new or pre-existing {@link Histogram} -+ */ -+ public Histogram histogram(MetricName name, final MetricSupplier supplier) { -+ return getOrAdd( -+ name, -+ new MetricBuilder() { -+ @Override -+ public Histogram newMetric() { -+ return supplier.newMetric(); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Histogram; -+ } -+ }); -+ } -+ -+ /** -+ * Return the {@link Meter} registered under this name; or create and register a new {@link Meter} -+ * if none is registered. -+ * -+ * @param name the name of the metric -+ * @return a new or pre-existing {@link Meter} -+ */ -+ public Meter meter(MetricName name) { -+ return getOrAdd(name, MetricBuilder.METERS); -+ } -+ -+ /** See {@link #timer(MetricName)} */ -+ public Timer timer(String name) { -+ return getOrAdd(MetricName.build(name), MetricBuilder.TIMERS); -+ } -+ -+ /** -+ * Return the {@link Meter} registered under this name; or create and register a new {@link Meter} -+ * using the provided MetricSupplier if none is registered. -+ * -+ * @param name the name of the metric -+ * @param supplier a MetricSupplier that can be used to manufacture a Meter -+ * @return a new or pre-existing {@link Meter} -+ */ -+ public Meter meter(MetricName name, final MetricSupplier supplier) { -+ return getOrAdd( -+ name, -+ new MetricBuilder() { -+ @Override -+ public Meter newMetric() { -+ return supplier.newMetric(); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Meter; -+ } -+ }); -+ } -+ -+ /** -+ * Return the {@link Timer} registered under this name; or create and register a new {@link Timer} -+ * if none is registered. -+ * -+ * @param name the name of the metric -+ * @return a new or pre-existing {@link Timer} -+ */ -+ public Timer timer(MetricName name) { -+ return getOrAdd(name, MetricBuilder.TIMERS); -+ } -+ -+ /** -+ * Return the {@link Timer} registered under this name; or create and register a new {@link Timer} -+ * using the provided MetricSupplier if none is registered. -+ * -+ * @param name the name of the metric -+ * @param supplier a MetricSupplier that can be used to manufacture a Timer -+ * @return a new or pre-existing {@link Timer} -+ */ -+ public Timer timer(MetricName name, final MetricSupplier supplier) { -+ return getOrAdd( -+ name, -+ new MetricBuilder() { -+ @Override -+ public Timer newMetric() { -+ return supplier.newMetric(); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Timer; -+ } -+ }); -+ } -+ -+ /** -+ * Return the {@link Gauge} registered under this name; or create and register a new {@link -+ * SettableGauge} if none is registered. -+ * -+ * @param name the name of the metric -+ * @return a pre-existing {@link Gauge} or a new {@link SettableGauge} -+ * @since 4.2 -+ */ -+ @SuppressWarnings({"rawtypes", "unchecked"}) -+ public T gauge(MetricName name) { -+ return (T) getOrAdd(name, MetricBuilder.GAUGES); -+ } -+ -+ /** -+ * Return the {@link Gauge} registered under this name; or create and register a new {@link Gauge} -+ * using the provided MetricSupplier if none is registered. -+ * -+ * @param name the name of the metric -+ * @param supplier a MetricSupplier that can be used to manufacture a Gauge -+ * @return a new or pre-existing {@link Gauge} -+ */ -+ @SuppressWarnings("rawtypes") -+ public T gauge(MetricName name, final MetricSupplier supplier) { -+ return getOrAdd( -+ name, -+ new MetricBuilder() { -+ @Override -+ public T newMetric() { -+ return supplier.newMetric(); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Gauge; -+ } -+ }); -+ } -+ -+ /** -+ * Removes the metric with the given name. -+ * -+ * @param name the name of the metric -+ * @return whether or not the metric was removed -+ */ -+ public boolean remove(MetricName name) { -+ final Metric metric = metrics.remove(name); -+ if (metric != null) { -+ onMetricRemoved(name, metric); -+ return true; -+ } -+ return false; -+ } -+ -+ /** -+ * Removes all metrics which match the given filter. -+ * -+ * @param filter a filter -+ */ -+ public void removeMatching(MetricFilter filter) { -+ for (Map.Entry entry : metrics.entrySet()) { -+ if (filter.matches(entry.getKey(), entry.getValue())) { -+ remove(entry.getKey()); -+ } -+ } -+ } -+ -+ /** -+ * Adds a {@link MetricRegistryListener} to a collection of listeners that will be notified on -+ * metric creation. Listeners will be notified in the order in which they are added. -+ * -+ *

    N.B.: The listener will be notified of all existing metrics when it first registers. -+ * -+ * @param listener the listener that will be notified -+ */ -+ public void addListener(MetricRegistryListener listener) { -+ listeners.add(listener); -+ -+ for (Map.Entry entry : metrics.entrySet()) { -+ notifyListenerOfAddedMetric(listener, entry.getValue(), entry.getKey()); -+ } -+ } -+ -+ /** -+ * Removes a {@link MetricRegistryListener} from this registry's collection of listeners. -+ * -+ * @param listener the listener that will be removed -+ */ -+ public void removeListener(MetricRegistryListener listener) { -+ listeners.remove(listener); -+ } -+ -+ /** -+ * Returns a set of the names of all the metrics in the registry. -+ * -+ * @return the names of all the metrics -+ */ -+ public SortedSet getNames() { -+ return unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); -+ } -+ -+ /** -+ * Returns a map of all the gauges in the registry and their names. -+ * -+ * @return all the gauges in the registry -+ */ -+ public SortedMap> getGauges() { -+ return getGauges(MetricFilter.ALL); -+ } -+ -+ /** -+ * Returns a map of all the gauges in the registry and their names which match the given filter. -+ * -+ * @param filter the metric filter to match -+ * @return all the gauges in the registry -+ */ -+ public SortedMap> getGauges(MetricFilter filter) { -+ final SortedMap> timers = new TreeMap<>(); -+ for (Map.Entry entry : metrics.entrySet()) { -+ if (entry.getValue() instanceof Gauge && filter.matches(entry.getKey(), entry.getValue())) { -+ timers.put(entry.getKey(), (Gauge) entry.getValue()); -+ } -+ } -+ return unmodifiableSortedMap(timers); -+ } -+ -+ /** -+ * Returns a map of all the counters in the registry and their names. -+ * -+ * @return all the counters in the registry -+ */ -+ public SortedMap getCounters() { -+ return getCounters(MetricFilter.ALL); -+ } -+ -+ /** -+ * Returns a map of all the counters in the registry and their names which match the given filter. -+ * -+ * @param filter the metric filter to match -+ * @return all the counters in the registry -+ */ -+ public SortedMap getCounters(MetricFilter filter) { -+ return getMetrics(Counter.class, filter); -+ } -+ -+ /** -+ * Returns a map of all the histograms in the registry and their names. -+ * -+ * @return all the histograms in the registry -+ */ -+ public SortedMap getHistograms() { -+ return getHistograms(MetricFilter.ALL); -+ } -+ -+ /** -+ * Returns a map of all the histograms in the registry and their names which match the given -+ * filter. -+ * -+ * @param filter the metric filter to match -+ * @return all the histograms in the registry -+ */ -+ public SortedMap getHistograms(MetricFilter filter) { -+ return getMetrics(Histogram.class, filter); -+ } -+ -+ /** -+ * Returns a map of all the meters in the registry and their names. -+ * -+ * @return all the meters in the registry -+ */ -+ public SortedMap getMeters() { -+ return getMeters(MetricFilter.ALL); -+ } -+ -+ /** -+ * Returns a map of all the meters in the registry and their names which match the given filter. -+ * -+ * @param filter the metric filter to match -+ * @return all the meters in the registry -+ */ -+ public SortedMap getMeters(MetricFilter filter) { -+ return getMetrics(Meter.class, filter); -+ } -+ -+ /** -+ * Returns a map of all the timers in the registry and their names. -+ * -+ * @return all the timers in the registry -+ */ -+ public SortedMap getTimers() { -+ return getTimers(MetricFilter.ALL); -+ } -+ -+ /** -+ * Returns a map of all the timers in the registry and their names which match the given filter. -+ * -+ * @param filter the metric filter to match -+ * @return all the timers in the registry -+ */ -+ public SortedMap getTimers(MetricFilter filter) { -+ return getMetrics(Timer.class, filter); -+ } -+ -+ @SuppressWarnings("unchecked") -+ private T getOrAdd(MetricName name, MetricBuilder builder) { -+ final Metric metric = metrics.get(name); -+ if (builder.isInstance(metric)) { -+ return (T) metric; -+ } else if (metric == null) { -+ try { -+ return register(name, builder.newMetric()); -+ } catch (IllegalArgumentException e) { -+ final Metric added = metrics.get(name); -+ if (builder.isInstance(added)) { -+ return (T) added; - } -- } -- -- @Override -- public Map getMetrics() { -- return Collections.unmodifiableMap(metrics); -- } -- -- @FunctionalInterface -- public interface MetricSupplier { -- T newMetric(); -- } -- -- /** -- * A quick and easy way of capturing the notion of default metrics. -- */ -- private interface MetricBuilder { -- MetricBuilder COUNTERS = new MetricBuilder() { -- @Override -- public Counter newMetric() { -- return new Counter(); -- } -- -- @Override -- public boolean isInstance(Metric metric) { -- return Counter.class.isInstance(metric); -- } -+ } -+ } -+ throw new IllegalArgumentException(name + " is already used for a different type of metric"); -+ } -+ -+ @SuppressWarnings("unchecked") -+ private SortedMap getMetrics( -+ Class klass, MetricFilter filter) { -+ final SortedMap timers = new TreeMap<>(); -+ for (Map.Entry entry : metrics.entrySet()) { -+ if (klass.isInstance(entry.getValue()) && filter.matches(entry.getKey(), entry.getValue())) { -+ timers.put(entry.getKey(), (T) entry.getValue()); -+ } -+ } -+ return unmodifiableSortedMap(timers); -+ } -+ -+ private void onMetricAdded(MetricName name, Metric metric) { -+ for (MetricRegistryListener listener : listeners) { -+ notifyListenerOfAddedMetric(listener, metric, name); -+ } -+ } -+ -+ private void notifyListenerOfAddedMetric( -+ MetricRegistryListener listener, Metric metric, MetricName name) { -+ if (metric instanceof Gauge) { -+ listener.onGaugeAdded(name, (Gauge) metric); -+ } else if (metric instanceof Counter) { -+ listener.onCounterAdded(name, (Counter) metric); -+ } else if (metric instanceof Histogram) { -+ listener.onHistogramAdded(name, (Histogram) metric); -+ } else if (metric instanceof Meter) { -+ listener.onMeterAdded(name, (Meter) metric); -+ } else if (metric instanceof Timer) { -+ listener.onTimerAdded(name, (Timer) metric); -+ } else { -+ throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); -+ } -+ } -+ -+ private void onMetricRemoved(MetricName name, Metric metric) { -+ for (MetricRegistryListener listener : listeners) { -+ notifyListenerOfRemovedMetric(name, metric, listener); -+ } -+ } -+ -+ private void notifyListenerOfRemovedMetric( -+ MetricName name, Metric metric, MetricRegistryListener listener) { -+ if (metric instanceof Gauge) { -+ listener.onGaugeRemoved(name); -+ } else if (metric instanceof Counter) { -+ listener.onCounterRemoved(name); -+ } else if (metric instanceof Histogram) { -+ listener.onHistogramRemoved(name); -+ } else if (metric instanceof Meter) { -+ listener.onMeterRemoved(name); -+ } else if (metric instanceof Timer) { -+ listener.onTimerRemoved(name); -+ } else { -+ throw new IllegalArgumentException("Unknown metric type: " + metric.getClass()); -+ } -+ } -+ -+ public void registerAll(MetricName prefix, MetricSet metrics) throws IllegalArgumentException { -+ if (prefix == null) { -+ prefix = MetricName.EMPTY; -+ } -+ -+ for (Map.Entry entry : metrics.getMetrics().entrySet()) { -+ if (entry.getValue() instanceof MetricSet) { -+ registerAll(prefix.append(entry.getKey()), (MetricSet) entry.getValue()); -+ } else { -+ register(prefix.append(entry.getKey()), entry.getValue()); -+ } -+ } -+ } -+ -+ @Override -+ public Map getMetrics() { -+ return unmodifiableMap(metrics); -+ } -+ -+ @FunctionalInterface -+ public interface MetricSupplier { -+ T newMetric(); -+ } -+ -+ /** A quick and easy way of capturing the notion of default metrics. */ -+ private interface MetricBuilder { -+ MetricBuilder COUNTERS = -+ new MetricBuilder() { -+ @Override -+ public Counter newMetric() { -+ return new Counter(); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Counter; -+ } - }; +-class ConsoleReporterTest { ++final class ConsoleReporterTest { + private final Locale locale = Locale.US; + private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); -- MetricBuilder HISTOGRAMS = new MetricBuilder() { -- @Override -- public Histogram newMetric() { -- return new Histogram(new ExponentiallyDecayingReservoir()); -- } -- -- @Override -- public boolean isInstance(Metric metric) { -- return Histogram.class.isInstance(metric); -- } -+ MetricBuilder HISTOGRAMS = -+ new MetricBuilder() { -+ @Override -+ public Histogram newMetric() { -+ return new Histogram(new ExponentiallyDecayingReservoir()); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Histogram; -+ } - }; +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); + private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + private final PrintStream output = new PrintStream(bytes); + private final ConsoleReporter reporter = +@@ -74,7 +74,7 @@ class ConsoleReporterTest { -- MetricBuilder METERS = new MetricBuilder() { -- @Override -- public Meter newMetric() { -- return new Meter(); -- } -- -- @Override -- public boolean isInstance(Metric metric) { -- return Meter.class.isInstance(metric); -- } -+ MetricBuilder METERS = -+ new MetricBuilder() { -+ @Override -+ public Meter newMetric() { -+ return new Meter(); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Meter; -+ } - }; + @Test + void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); -- MetricBuilder TIMERS = new MetricBuilder() { -- @Override -- public Timer newMetric() { -- return new Timer(); -- } -- -- @Override -- public boolean isInstance(Metric metric) { -- return Timer.class.isInstance(metric); -- } -+ MetricBuilder TIMERS = -+ new MetricBuilder() { -+ @Override -+ public Timer newMetric() { -+ return new Timer(); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Timer; -+ } - }; + reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); +@@ -93,11 +93,11 @@ class ConsoleReporterTest { -- @SuppressWarnings("rawtypes") -- MetricBuilder GAUGES = new MetricBuilder() { -- @Override -- public Gauge newMetric() { -- return new DefaultSettableGauge<>(); -- } -- -- @Override -- public boolean isInstance(Metric metric) { -- return Gauge.class.isInstance(metric); -- } -+ @SuppressWarnings("rawtypes") -+ MetricBuilder GAUGES = -+ new MetricBuilder() { -+ @Override -+ public Gauge newMetric() { -+ return new DefaultSettableGauge<>(); -+ } -+ -+ @Override -+ public boolean isInstance(Metric metric) { -+ return metric instanceof Gauge; -+ } - }; + @Test + void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(4L); -- T newMetric(); -+ T newMetric(); +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -138,7 +138,7 @@ class ConsoleReporterTest { -- boolean isInstance(Metric metric); -- } -+ boolean isInstance(Metric metric); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistryListener.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistryListener.java -@@ -2,127 +2,113 @@ package io.dropwizard.metrics5; - - import java.util.EventListener; - --/** -- * Listeners for events from the registry. Listeners must be thread-safe. -- */ -+/** Listeners for events from the registry. Listeners must be thread-safe. */ - public interface MetricRegistryListener extends EventListener { -- /** -- * A no-op implementation of {@link MetricRegistryListener}. -- */ -- abstract class Base implements MetricRegistryListener { -- @Override -- public void onGaugeAdded(MetricName name, Gauge gauge) { -- } -- -- @Override -- public void onGaugeRemoved(MetricName name) { -- } -- -- @Override -- public void onCounterAdded(MetricName name, Counter counter) { -- } -- -- @Override -- public void onCounterRemoved(MetricName name) { -- } -- -- @Override -- public void onHistogramAdded(MetricName name, Histogram histogram) { -- } -- -- @Override -- public void onHistogramRemoved(MetricName name) { -- } -- -- @Override -- public void onMeterAdded(MetricName name, Meter meter) { -- } -- -- @Override -- public void onMeterRemoved(MetricName name) { -- } -- -- @Override -- public void onTimerAdded(MetricName name, Timer timer) { -- } -- -- @Override -- public void onTimerRemoved(MetricName name) { -- } -- } -- -- /** -- * Called when a {@link Gauge} is added to the registry. -- * -- * @param name the gauge's name -- * @param gauge the gauge -- */ -- void onGaugeAdded(MetricName name, Gauge gauge); -- -- /** -- * Called when a {@link Gauge} is removed from the registry. -- * -- * @param name the gauge's name -- */ -- void onGaugeRemoved(MetricName name); -- -- /** -- * Called when a {@link Counter} is added to the registry. -- * -- * @param name the counter's name -- * @param counter the counter -- */ -- void onCounterAdded(MetricName name, Counter counter); -- -- /** -- * Called when a {@link Counter} is removed from the registry. -- * -- * @param name the counter's name -- */ -- void onCounterRemoved(MetricName name); -- -- /** -- * Called when a {@link Histogram} is added to the registry. -- * -- * @param name the histogram's name -- * @param histogram the histogram -- */ -- void onHistogramAdded(MetricName name, Histogram histogram); -- -- /** -- * Called when a {@link Histogram} is removed from the registry. -- * -- * @param name the histogram's name -- */ -- void onHistogramRemoved(MetricName name); -- -- /** -- * Called when a {@link Meter} is added to the registry. -- * -- * @param name the meter's name -- * @param meter the meter -- */ -- void onMeterAdded(MetricName name, Meter meter); -- -- /** -- * Called when a {@link Meter} is removed from the registry. -- * -- * @param name the meter's name -- */ -- void onMeterRemoved(MetricName name); -- -- /** -- * Called when a {@link Timer} is added to the registry. -- * -- * @param name the timer's name -- * @param timer the timer -- */ -- void onTimerAdded(MetricName name, Timer timer); -- -- /** -- * Called when a {@link Timer} is removed from the registry. -- * -- * @param name the timer's name -- */ -- void onTimerRemoved(MetricName name); -+ /** A no-op implementation of {@link MetricRegistryListener}. */ -+ abstract class Base implements MetricRegistryListener { -+ @Override -+ public void onGaugeAdded(MetricName name, Gauge gauge) {} -+ -+ @Override -+ public void onGaugeRemoved(MetricName name) {} -+ -+ @Override -+ public void onCounterAdded(MetricName name, Counter counter) {} -+ -+ @Override -+ public void onCounterRemoved(MetricName name) {} -+ -+ @Override -+ public void onHistogramAdded(MetricName name, Histogram histogram) {} -+ -+ @Override -+ public void onHistogramRemoved(MetricName name) {} -+ -+ @Override -+ public void onMeterAdded(MetricName name, Meter meter) {} -+ -+ @Override -+ public void onMeterRemoved(MetricName name) {} -+ -+ @Override -+ public void onTimerAdded(MetricName name, Timer timer) {} -+ -+ @Override -+ public void onTimerRemoved(MetricName name) {} -+ } -+ -+ /** -+ * Called when a {@link Gauge} is added to the registry. -+ * -+ * @param name the gauge's name -+ * @param gauge the gauge -+ */ -+ void onGaugeAdded(MetricName name, Gauge gauge); -+ -+ /** -+ * Called when a {@link Gauge} is removed from the registry. -+ * -+ * @param name the gauge's name -+ */ -+ void onGaugeRemoved(MetricName name); -+ -+ /** -+ * Called when a {@link Counter} is added to the registry. -+ * -+ * @param name the counter's name -+ * @param counter the counter -+ */ -+ void onCounterAdded(MetricName name, Counter counter); -+ -+ /** -+ * Called when a {@link Counter} is removed from the registry. -+ * -+ * @param name the counter's name -+ */ -+ void onCounterRemoved(MetricName name); -+ -+ /** -+ * Called when a {@link Histogram} is added to the registry. -+ * -+ * @param name the histogram's name -+ * @param histogram the histogram -+ */ -+ void onHistogramAdded(MetricName name, Histogram histogram); -+ -+ /** -+ * Called when a {@link Histogram} is removed from the registry. -+ * -+ * @param name the histogram's name -+ */ -+ void onHistogramRemoved(MetricName name); -+ -+ /** -+ * Called when a {@link Meter} is added to the registry. -+ * -+ * @param name the meter's name -+ * @param meter the meter -+ */ -+ void onMeterAdded(MetricName name, Meter meter); -+ -+ /** -+ * Called when a {@link Meter} is removed from the registry. -+ * -+ * @param name the meter's name -+ */ -+ void onMeterRemoved(MetricName name); -+ -+ /** -+ * Called when a {@link Timer} is added to the registry. -+ * -+ * @param name the timer's name -+ * @param timer the timer -+ */ -+ void onTimerAdded(MetricName name, Timer timer); -+ -+ /** -+ * Called when a {@link Timer} is removed from the registry. -+ * -+ * @param name the timer's name -+ */ -+ void onTimerRemoved(MetricName name); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricSet.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricSet.java -@@ -8,10 +8,10 @@ import java.util.Map; - * @see MetricRegistry#registerAll(MetricSet) - */ - public interface MetricSet extends Metric { -- /** -- * A map of metric names to metrics. -- * -- * @return the metrics -- */ -- Map getMetrics(); -+ /** -+ * A map of metric names to metrics. -+ * -+ * @return the metrics -+ */ -+ Map getMetrics(); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/MovingAverages.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MovingAverages.java -@@ -1,50 +1,52 @@ - package io.dropwizard.metrics5; + @Test + void reportsMeterValues() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(3L); + when(meter.getMeanRate()).thenReturn(2.0); +@@ -167,7 +167,7 @@ class ConsoleReporterTest { - /** -- * A triple of moving averages (one-, five-, and fifteen-minute -- * moving average) as needed by {@link Meter}. -- *

    -- * Included implementations are: -+ * A triple of moving averages (one-, five-, and fifteen-minute moving average) as needed by {@link -+ * Meter}. -+ * -+ *

    Included implementations are: -+ * - *

      -- *
    • {@link ExponentialMovingAverages} exponential decaying average similar to the {@code top} Unix command. -- *
    • {@link SlidingTimeWindowMovingAverages} simple (unweighted) moving average -+ *
    • {@link ExponentialMovingAverages} exponential decaying average similar to the {@code top} -+ * Unix command. -+ *
    • {@link SlidingTimeWindowMovingAverages} simple (unweighted) moving average - *
    - */ - public interface MovingAverages { - -- /** -- * Tick the internal clock of the MovingAverages implementation if needed -- * (according to the internal ticking interval) -- */ -- void tickIfNecessary(); -+ /** -+ * Tick the internal clock of the MovingAverages implementation if needed (according to the -+ * internal ticking interval) -+ */ -+ void tickIfNecessary(); - -- /** -- * Update all three moving averages with n events having occurred since the last update. -- * -- * @param n -- */ -- void update(long n); -+ /** -+ * Update all three moving averages with n events having occurred since the last update. -+ * -+ * @param n -+ */ -+ void update(long n); - -- /** -- * Returns the one-minute moving average rate -- * -- * @return the one-minute moving average rate -- */ -- double getM1Rate(); -+ /** -+ * Returns the one-minute moving average rate -+ * -+ * @return the one-minute moving average rate -+ */ -+ double getM1Rate(); - -- /** -- * Returns the five-minute moving average rate -- * -- * @return the five-minute moving average rate -- */ -- double getM5Rate(); -+ /** -+ * Returns the five-minute moving average rate -+ * -+ * @return the five-minute moving average rate -+ */ -+ double getM5Rate(); - -- /** -- * Returns the fifteen-minute moving average rate -- * -- * @return the fifteen-minute moving average rate -- */ -- double getM15Rate(); -+ /** -+ * Returns the fifteen-minute moving average rate -+ * -+ * @return the fifteen-minute moving average rate -+ */ -+ double getM15Rate(); - -- long getSum(); -+ long getSum(); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java -@@ -1,9 +1,14 @@ - package io.dropwizard.metrics5; + @Test + void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(5)); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -175,7 +175,7 @@ class ConsoleReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -239,7 +239,7 @@ class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); -+import static java.util.Collections.emptySortedMap; -+import static java.util.Collections.emptySortedSet; -+import static java.util.Objects.requireNonNull; -+ -+import com.google.common.collect.ImmutableMap; -+import com.google.common.collect.ImmutableSet; - import java.io.OutputStream; - import java.time.Duration; - import java.util.Collection; --import java.util.Collections; - import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -13,817 +18,634 @@ import java.util.concurrent.ConcurrentMap; - import java.util.concurrent.TimeUnit; - import java.util.function.Supplier; +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(5L); + when(meter.getMeanRate()).thenReturn(2.0); +@@ -283,7 +283,7 @@ class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); --import static java.util.Objects.requireNonNull; -- - /** -- * A registry of metric instances which never creates or registers any metrics and returns no-op implementations of any metric type. -+ * A registry of metric instances which never creates or registers any metrics and returns no-op -+ * implementations of any metric type. - * - * @since 4.1.17 - */ - public final class NoopMetricRegistry extends MetricRegistry { -- private static final EmptyConcurrentMap EMPTY_CONCURRENT_MAP = new EmptyConcurrentMap<>(); -+ private static final EmptyConcurrentMap EMPTY_CONCURRENT_MAP = -+ new EmptyConcurrentMap<>(); -+ -+ /** -+ * {@inheritDoc} -+ * -+ * @return -+ */ -+ @Override -+ protected ConcurrentMap buildMap() { -+ return EMPTY_CONCURRENT_MAP; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void registerAll(MetricSet metrics) throws IllegalArgumentException { -+ // NOP -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Counter counter(String name) { -+ return NoopCounter.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Counter counter(MetricName name) { -+ return NoopCounter.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ @SuppressWarnings("unchecked") -+ public T counter(MetricName name, final MetricSupplier supplier) { -+ return (T) NoopCounter.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Histogram histogram(String name) { -+ return NoopHistogram.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Histogram histogram(MetricName name) { -+ return NoopHistogram.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Histogram histogram(MetricName name, MetricSupplier supplier) { -+ return NoopHistogram.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Meter meter(String name) { -+ return NoopMeter.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Meter meter(MetricName name) { -+ return NoopMeter.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Meter meter(MetricName name, MetricSupplier supplier) { -+ return NoopMeter.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Timer timer(String name) { -+ return NoopTimer.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Timer timer(MetricName name) { -+ return NoopTimer.INSTANCE; -+ } -+ -+ /** -+ * {@inheritDoc} -+ * -+ * @since 4.2 -+ */ -+ @Override -+ @SuppressWarnings({"rawtypes", "unchecked"}) -+ public T gauge(MetricName name) { -+ return (T) NoopGauge.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Timer timer(MetricName name, MetricSupplier supplier) { -+ return NoopTimer.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @SuppressWarnings({"rawtypes", "unchecked"}) -+ public T gauge(MetricName name, final MetricSupplier supplier) { -+ return (T) NoopGauge.INSTANCE; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public boolean remove(MetricName name) { -+ return false; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void removeMatching(MetricFilter filter) { -+ // NOP -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void addListener(MetricRegistryListener listener) { -+ // NOP -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void removeListener(MetricRegistryListener listener) { -+ // NOP -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedSet getNames() { -+ return emptySortedSet(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap> getGauges() { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap> getGauges(MetricFilter filter) { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap getCounters() { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap getCounters(MetricFilter filter) { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap getHistograms() { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap getHistograms(MetricFilter filter) { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap getMeters() { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap getMeters(MetricFilter filter) { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap getTimers() { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public SortedMap getTimers(MetricFilter filter) { -+ return emptySortedMap(); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void registerAll(MetricName prefix, MetricSet metrics) throws IllegalArgumentException { -+ // NOP -+ } - -- /** -- * {@inheritDoc} -- * @return -- */ -+ /** {@inheritDoc} */ -+ @Override -+ public T register(MetricName name, T metric) throws IllegalArgumentException { -+ return requireNonNull(metric, "metric == null"); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Map getMetrics() { -+ return ImmutableMap.of(); -+ } -+ -+ static final class NoopMetric implements Metric { -+ private static final NoopMetric INSTANCE = new NoopMetric(); -+ } -+ -+ static final class NoopGauge implements Gauge { -+ private static final NoopGauge INSTANCE = new NoopGauge<>(); -+ -+ /** {@inheritDoc} */ - @Override -- protected ConcurrentMap buildMap() { -- return EMPTY_CONCURRENT_MAP; -+ public T getValue() { -+ return null; - } -+ } - -- /** -- * {@inheritDoc} -- */ -+ private static final class EmptySnapshot extends Snapshot { -+ private static final EmptySnapshot INSTANCE = new EmptySnapshot(); -+ private static final long[] EMPTY_LONG_ARRAY = new long[0]; -+ -+ /** {@inheritDoc} */ - @Override -- public void registerAll(MetricSet metrics) throws IllegalArgumentException { -- // NOP -+ public double getValue(double quantile) { -+ return 0D; - } +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -291,7 +291,7 @@ class ConsoleReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -349,11 +349,11 @@ class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Counter counter(String name) { -- return NoopCounter.INSTANCE; -+ public long[] getValues() { -+ return EMPTY_LONG_ARRAY; - } +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(5L); -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Counter counter(MetricName name) { -- return NoopCounter.INSTANCE; -+ public int size() { -+ return 0; - } +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java +@@ -4,12 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- @SuppressWarnings("unchecked") -- public T counter(MetricName name, final MetricSupplier supplier) { -- return (T) NoopCounter.INSTANCE; -+ public long getMax() { -+ return 0L; - } + import org.junit.jupiter.api.Test; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Histogram histogram(String name) { -- return NoopHistogram.INSTANCE; -+ public double getMean() { -+ return 0D; - } +-class CounterTest { ++final class CounterTest { + private final Counter counter = new Counter(); -- -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Histogram histogram(MetricName name) { -- return NoopHistogram.INSTANCE; -+ public long getMin() { -+ return 0L; - } + @Test + void startsAtZero() { +- assertThat(counter.getCount()).isZero(); ++ assertThat(counter.getCount()).isEqualTo(0); + } -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Histogram histogram(MetricName name, MetricSupplier supplier) { -- return NoopHistogram.INSTANCE; -+ public double getStdDev() { -+ return 0D; - } + @Test +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Meter meter(String name) { -- return NoopMeter.INSTANCE; -+ public void dump(OutputStream output) { -+ // NOP - } -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public Meter meter(MetricName name) { -- return NoopMeter.INSTANCE; -+ static final class NoopTimer extends Timer { -+ private static final NoopTimer INSTANCE = new NoopTimer(); -+ private static final Timer.Context CONTEXT = new NoopTimer.Context(); -+ -+ private static class Context extends Timer.Context { -+ private static final Clock CLOCK = -+ new Clock() { -+ /** {@inheritDoc} */ -+ @Override -+ public long getTick() { -+ return 0L; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public long getTime() { -+ return 0L; -+ } -+ }; -+ -+ private Context() { -+ super(INSTANCE, CLOCK); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public long stop() { -+ return 0L; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void close() { -+ // NOP -+ } - } ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; +@@ -7,7 +8,6 @@ import static org.mockito.Mockito.when; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Meter meter(MetricName name, MetricSupplier supplier) { -- return NoopMeter.INSTANCE; -+ public void update(long duration, TimeUnit unit) { -+ // NOP - } + import java.io.File; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.nio.file.Files; + import java.util.Locale; + import java.util.SortedMap; +@@ -17,11 +17,11 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.junit.jupiter.api.io.TempDir; -- -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Timer timer(String name) { -- return NoopTimer.INSTANCE; -+ public void update(Duration duration) { -+ // NOP - } +-public class CsvReporterTest { ++final class CsvReporterTest { + @TempDir public File folder; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Timer timer(MetricName name) { -- return NoopTimer.INSTANCE; -+ public T time(Callable event) throws Exception { -+ return event.call(); - } +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); -- /** -- * {@inheritDoc} -- * -- * @since 4.2 -- */ -+ /** {@inheritDoc} */ - @Override -- @SuppressWarnings({"rawtypes", "unchecked"}) -- public T gauge(MetricName name) { -- return (T) NoopGauge.INSTANCE; -+ public T timeSupplier(Supplier event) { -+ return event.get(); - } + private File dataDirectory; + private CsvReporter reporter; +@@ -53,7 +53,7 @@ public class CsvReporterTest { -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Timer timer(MetricName name, MetricSupplier supplier) { -- return NoopTimer.INSTANCE; -+ public void time(Runnable event) { -+ // NOP - } + @Test + void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); -- /** -- * {@inheritDoc} -- */ -- @SuppressWarnings({"rawtypes", "unchecked"}) -- public T gauge(MetricName name, final MetricSupplier supplier) { -- return (T) NoopGauge.INSTANCE; -+ /** {@inheritDoc} */ -+ @Override -+ public Timer.Context time() { -+ return CONTEXT; - } + reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); +@@ -63,11 +63,11 @@ public class CsvReporterTest { -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public boolean remove(MetricName name) { -- return false; -+ public long getCount() { -+ return 0L; - } + @Test + void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(12L); -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public void removeMatching(MetricFilter filter) { -- // NOP -+ public double getFifteenMinuteRate() { -+ return 0D; - } +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -105,7 +105,7 @@ public class CsvReporterTest { -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public void addListener(MetricRegistryListener listener) { -- // NOP -+ public double getFiveMinuteRate() { -+ return 0D; - } + @Test + void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -113,7 +113,7 @@ public class CsvReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -137,8 +137,8 @@ public class CsvReporterTest { + } -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public void removeListener(MetricRegistryListener listener) { -- // NOP -+ public double getMeanRate() { -+ return 0D; - } + @Test +- void testCsvFileProviderIsUsed() { +- CsvFileProvider fileProvider = mock(CsvFileProvider.class); ++ void csvFileProviderIsUsed() { ++ CsvFileProvider fileProvider = mock(); + when(fileProvider.getFile(dataDirectory, "gauge")) + .thenReturn(new File(dataDirectory, "guage.csv")); -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedSet getNames() { -- return Collections.emptySortedSet(); -+ public double getOneMinuteRate() { -+ return 0D; - } +@@ -177,7 +177,7 @@ public class CsvReporterTest { + } -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedMap> getGauges() { -- return Collections.emptySortedMap(); -+ public Snapshot getSnapshot() { -+ return EmptySnapshot.INSTANCE; - } -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public SortedMap> getGauges(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ static final class NoopHistogram extends Histogram { -+ private static final NoopHistogram INSTANCE = new NoopHistogram(); -+ private static final Reservoir EMPTY_RESERVOIR = -+ new Reservoir() { -+ /** {@inheritDoc} */ -+ @Override -+ public int size() { -+ return 0; -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void update(long value) { -+ // NOP -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public Snapshot getSnapshot() { -+ return EmptySnapshot.INSTANCE; -+ } -+ }; -+ -+ private NoopHistogram() { -+ super(EMPTY_RESERVOIR); - } + private Meter mockMeter() { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getMeanRate()).thenReturn(2.0); +@@ -198,8 +198,7 @@ public class CsvReporterTest { + + @SuppressWarnings("FilesReadStringWithCharset") + private String fileContents(String filename) throws IOException { +- return new String( +- Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); ++ return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), UTF_8); + } -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedMap getCounters() { -- return Collections.emptySortedMap(); -+ public void update(int value) { -+ // NOP - } + private SortedMap map() { +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedMap getCounters(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ public void update(long value) { -+ // NOP - } + import org.junit.jupiter.api.Test; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedMap getHistograms() { -- return Collections.emptySortedMap(); -+ public long getCount() { -+ return 0L; - } +-class DefaultSettableGaugeTest { ++final class DefaultSettableGaugeTest { + @Test + void newSettableGaugeWithoutDefaultReturnsNull() { + DefaultSettableGauge gauge = new DefaultSettableGauge<>(); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedMap getHistograms(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ public Snapshot getSnapshot() { -+ return EmptySnapshot.INSTANCE; - } -+ } -+ -+ static final class NoopCounter extends Counter { -+ private static final NoopCounter INSTANCE = new NoopCounter(); + import org.junit.jupiter.api.Test; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedMap getMeters() { -- return Collections.emptySortedMap(); -+ public void inc() { -+ // NOP - } +-class DerivativeGaugeTest { ++final class DerivativeGaugeTest { + private final Gauge gauge1 = () -> "woo"; + private final Gauge gauge2 = + new DerivativeGauge(gauge1) { +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java +@@ -6,74 +6,74 @@ import static org.assertj.core.api.Assertions.offset; + import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedMap getMeters(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ public void inc(long n) { -+ // NOP - } +-class EWMATest { ++final class EWMATest { + @Test + void aOneMinuteEWMAWithAValueOfThree() { + final EWMA ewma = EWMA.oneMinuteEWMA(); + ewma.update(3); + ewma.tick(); -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedMap getTimers() { -- return Collections.emptySortedMap(); -+ public void dec() { -+ // NOP - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public SortedMap getTimers(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ public void dec(long n) { -+ // NOP - } + elapseMinute(ewma); -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public void registerAll(MetricName prefix, MetricSet metrics) throws IllegalArgumentException { -- // NOP -+ public long getCount() { -+ return 0L; - } -+ } -+ -+ static final class NoopMeter extends Meter { -+ private static final NoopMeter INSTANCE = new NoopMeter(); +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public T register(MetricName name, T metric) throws IllegalArgumentException { -- return requireNonNull(metric, "metric == null"); -+ public void mark() { -+ // NOP - } + elapseMinute(ewma); -- /** -- * {@inheritDoc} -- */ -+ /** {@inheritDoc} */ - @Override -- public Map getMetrics() { -- return Collections.emptyMap(); -+ public void mark(long n) { -+ // NOP - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); -- static final class NoopMetric implements Metric { -- private static final NoopMetric INSTANCE = new NoopMetric(); -+ /** {@inheritDoc} */ -+ @Override -+ public long getCount() { -+ return 0L; - } + elapseMinute(ewma); -- static final class NoopGauge implements Gauge { -- private static final NoopGauge INSTANCE = new NoopGauge<>(); -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public T getValue() { -- return null; -- } -+ /** {@inheritDoc} */ -+ @Override -+ public double getFifteenMinuteRate() { -+ return 0D; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); -- private static final class EmptySnapshot extends Snapshot { -- private static final EmptySnapshot INSTANCE = new EmptySnapshot(); -- private static final long[] EMPTY_LONG_ARRAY = new long[0]; -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getValue(double quantile) { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public long[] getValues() { -- return EMPTY_LONG_ARRAY; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public int size() { -- return 0; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public long getMax() { -- return 0L; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getMean() { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public long getMin() { -- return 0L; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getStdDev() { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public void dump(OutputStream output) { -- // NOP -- } -- } -- -- static final class NoopTimer extends Timer { -- private static final NoopTimer INSTANCE = new NoopTimer(); -- private static final Timer.Context CONTEXT = new NoopTimer.Context(); -- -- private static class Context extends Timer.Context { -- private static final Clock CLOCK = new Clock() { -- /** -- * {@inheritDoc} -- */ -- @Override -- public long getTick() { -- return 0L; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public long getTime() { -- return 0L; -- } -- }; -- -- private Context() { -- super(INSTANCE, CLOCK); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public long stop() { -- return 0L; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public void close() { -- // NOP -- } -- } -+ /** {@inheritDoc} */ -+ @Override -+ public double getFiveMinuteRate() { -+ return 0D; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void update(long duration, TimeUnit unit) { -- // NOP -- } -+ /** {@inheritDoc} */ -+ @Override -+ public double getMeanRate() { -+ return 0D; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void update(Duration duration) { -- // NOP -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public T time(Callable event) throws Exception { -- return event.call(); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public T timeSupplier(Supplier event) { -- return event.get(); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public void time(Runnable event) { -- // NOP -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public Timer.Context time() { -- return CONTEXT; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public long getCount() { -- return 0L; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getFifteenMinuteRate() { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getFiveMinuteRate() { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getMeanRate() { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getOneMinuteRate() { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public Snapshot getSnapshot() { -- return EmptySnapshot.INSTANCE; -- } -+ /** {@inheritDoc} */ -+ @Override -+ public double getOneMinuteRate() { -+ return 0D; - } -+ } - -- static final class NoopHistogram extends Histogram { -- private static final NoopHistogram INSTANCE = new NoopHistogram(); -- private static final Reservoir EMPTY_RESERVOIR = new Reservoir() { -- /** -- * {@inheritDoc} -- */ -- @Override -- public int size() { -- return 0; -- } -+ private static final class EmptyConcurrentMap implements ConcurrentMap { -+ /** {@inheritDoc} */ -+ @Override -+ public V putIfAbsent(K key, V value) { -+ return null; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void update(long value) { -- // NOP -- } -+ /** {@inheritDoc} */ -+ @Override -+ public boolean remove(Object key, Object value) { -+ return false; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public Snapshot getSnapshot() { -- return EmptySnapshot.INSTANCE; -- } -- }; -+ /** {@inheritDoc} */ -+ @Override -+ public boolean replace(K key, V oldValue, V newValue) { -+ return false; -+ } - -- private NoopHistogram() { -- super(EMPTY_RESERVOIR); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public V replace(K key, V value) { -+ return null; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void update(int value) { -- // NOP -- } -+ /** {@inheritDoc} */ -+ @Override -+ public int size() { -+ return 0; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void update(long value) { -- // NOP -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public long getCount() { -- return 0L; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public Snapshot getSnapshot() { -- return EmptySnapshot.INSTANCE; -- } -+ /** {@inheritDoc} */ -+ @Override -+ public boolean isEmpty() { -+ return true; - } + elapseMinute(ewma); -- static final class NoopCounter extends Counter { -- private static final NoopCounter INSTANCE = new NoopCounter(); -+ /** {@inheritDoc} */ -+ @Override -+ public boolean containsKey(Object key) { -+ return false; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void inc() { -- // NOP -- } -+ /** {@inheritDoc} */ -+ @Override -+ public boolean containsValue(Object value) { -+ return false; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void inc(long n) { -- // NOP -- } -+ /** {@inheritDoc} */ -+ @Override -+ public V get(Object key) { -+ return null; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void dec() { -- // NOP -- } -+ /** {@inheritDoc} */ -+ @Override -+ public V put(K key, V value) { -+ return null; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void dec(long n) { -- // NOP -- } -+ /** {@inheritDoc} */ -+ @Override -+ public V remove(Object key) { -+ return null; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public long getCount() { -- return 0L; -- } -+ /** {@inheritDoc} */ -+ @Override -+ public void putAll(Map m) { -+ // NOP - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.01098938, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001)); -- static final class NoopMeter extends Meter { -- private static final NoopMeter INSTANCE = new NoopMeter(); -+ /** {@inheritDoc} */ -+ @Override -+ public void clear() { -+ // NOP -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void mark() { -- // NOP -- } -+ /** {@inheritDoc} */ -+ @Override -+ public Set keySet() { -+ return ImmutableSet.of(); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void mark(long n) { -- // NOP -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public long getCount() { -- return 0L; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getFifteenMinuteRate() { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getFiveMinuteRate() { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getMeanRate() { -- return 0D; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public double getOneMinuteRate() { -- return 0D; -- } -- } -- -- private static final class EmptyConcurrentMap implements ConcurrentMap { -- /** -- * {@inheritDoc} -- */ -- @Override -- public V putIfAbsent(K key, V value) { -- return null; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public boolean remove(Object key, Object value) { -- return false; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public boolean replace(K key, V oldValue, V newValue) { -- return false; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public V replace(K key, V value) { -- return null; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public int size() { -- return 0; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public boolean isEmpty() { -- return true; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public boolean containsKey(Object key) { -- return false; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public boolean containsValue(Object value) { -- return false; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public V get(Object key) { -- return null; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public V put(K key, V value) { -- return null; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public V remove(Object key) { -- return null; -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public void putAll(Map m) { -- // NOP -- } -+ /** {@inheritDoc} */ -+ @Override -+ public Collection values() { -+ return ImmutableSet.of(); -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void clear() { -- // NOP -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public Set keySet() { -- return Collections.emptySet(); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public Collection values() { -- return Collections.emptySet(); -- } -- -- /** -- * {@inheritDoc} -- */ -- @Override -- public Set> entrySet() { -- return Collections.emptySet(); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public Set> entrySet() { -+ return ImmutableSet.of(); - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/RatioGauge.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/RatioGauge.java -@@ -5,62 +5,60 @@ import static java.lang.Double.isNaN; + elapseMinute(ewma); - /** - * A gauge which measures the ratio of one value to another. -- *

    -- * If the denominator is zero, not a number, or infinite, the resulting ratio is not a number. -+ * -+ *

    If the denominator is zero, not a number, or infinite, the resulting ratio is not a number. - */ - public abstract class RatioGauge implements Gauge { -+ /** A ratio of one quantity to another. */ -+ public static class Ratio { - /** -- * A ratio of one quantity to another. -+ * Creates a new ratio with the given numerator and denominator. -+ * -+ * @param numerator the numerator of the ratio -+ * @param denominator the denominator of the ratio -+ * @return {@code numerator:denominator} - */ -- public static class Ratio { -- /** -- * Creates a new ratio with the given numerator and denominator. -- * -- * @param numerator the numerator of the ratio -- * @param denominator the denominator of the ratio -- * @return {@code numerator:denominator} -- */ -- public static Ratio of(double numerator, double denominator) { -- return new Ratio(numerator, denominator); -- } -- -- private final double numerator; -- private final double denominator; -- -- private Ratio(double numerator, double denominator) { -- this.numerator = numerator; -- this.denominator = denominator; -- } -+ public static Ratio of(double numerator, double denominator) { -+ return new Ratio(numerator, denominator); -+ } - -- /** -- * Returns the ratio, which is either a {@code double} between 0 and 1 (inclusive) or -- * {@code NaN}. -- * -- * @return the ratio -- */ -- public double getValue() { -- final double d = denominator; -- if (isNaN(d) || isInfinite(d) || d == 0) { -- return Double.NaN; -- } -- return numerator / d; -- } -+ private final double numerator; -+ private final double denominator; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00404277, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001)); -- @Override -- public String toString() { -- return numerator + ":" + denominator; -- } -+ private Ratio(double numerator, double denominator) { -+ this.numerator = numerator; -+ this.denominator = denominator; - } + elapseMinute(ewma); - /** -- * Returns the {@link Ratio} which is the gauge's current value. -+ * Returns the ratio, which is either a {@code double} between 0 and 1 (inclusive) or {@code -+ * NaN}. - * -- * @return the {@link Ratio} which is the gauge's current value -+ * @return the ratio - */ -- protected abstract Ratio getRatio(); -+ public double getValue() { -+ final double d = denominator; -+ if (isNaN(d) || isInfinite(d) || d == 0) { -+ return Double.NaN; -+ } -+ return numerator / d; -+ } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00148725, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001)); - @Override -- public Double getValue() { -- return getRatio().getValue(); -+ public String toString() { -+ return numerator + ":" + denominator; - } -+ } -+ -+ /** -+ * Returns the {@link Ratio} which is the gauge's current value. -+ * -+ * @return the {@link Ratio} which is the gauge's current value -+ */ -+ protected abstract Ratio getRatio(); -+ -+ @Override -+ public Double getValue() { -+ return getRatio().getValue(); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Reporter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Reporter.java -@@ -5,6 +5,4 @@ import java.io.Closeable; - /* - * A tag interface to indicate that a class is a Reporter. - */ --public interface Reporter extends Closeable { -- --} -+public interface Reporter extends Closeable {} ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Reservoir.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Reservoir.java -@@ -1,27 +1,25 @@ - package io.dropwizard.metrics5; + elapseMinute(ewma); --/** -- * A statistically representative reservoir of a data stream. -- */ -+/** A statistically representative reservoir of a data stream. */ - public interface Reservoir { -- /** -- * Returns the number of values recorded. -- * -- * @return the number of values recorded -- */ -- int size(); -+ /** -+ * Returns the number of values recorded. -+ * -+ * @return the number of values recorded -+ */ -+ int size(); - -- /** -- * Adds a new recorded value to the reservoir. -- * -- * @param value a new recorded value -- */ -- void update(long value); -+ /** -+ * Adds a new recorded value to the reservoir. -+ * -+ * @param value a new recorded value -+ */ -+ void update(long value); - -- /** -- * Returns a snapshot of the reservoir's values. -- * -- * @return a snapshot of the reservoir's values -- */ -- Snapshot getSnapshot(); -+ /** -+ * Returns a snapshot of the reservoir's values. -+ * -+ * @return a snapshot of the reservoir's values -+ */ -+ Snapshot getSnapshot(); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Sampling.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Sampling.java -@@ -1,13 +1,11 @@ - package io.dropwizard.metrics5; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00054713, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001)); --/** -- * An object which samples values. -- */ -+/** An object which samples values. */ - public interface Sampling { -- /** -- * Returns a snapshot of the values. -- * -- * @return a snapshot of the values -- */ -- Snapshot getSnapshot(); -+ /** -+ * Returns a snapshot of the values. -+ * -+ * @return a snapshot of the values -+ */ -+ Snapshot getSnapshot(); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java -@@ -1,20 +1,21 @@ - package io.dropwizard.metrics5; + elapseMinute(ewma); --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.util.Objects.requireNonNull; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00020128, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001)); -+import com.google.common.collect.ImmutableSet; - import java.io.Closeable; --import java.util.Collections; - import java.util.Locale; - import java.util.Set; - import java.util.SortedMap; --import java.util.concurrent.Executor; - import java.util.concurrent.Executors; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.ScheduledFuture; - import java.util.concurrent.ThreadFactory; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicInteger; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; + elapseMinute(ewma); - /** - * The abstract base class for all scheduled reporters (i.e., reporters which process a registry's -@@ -26,312 +27,333 @@ import java.util.concurrent.atomic.AtomicInteger; - */ - public abstract class ScheduledReporter implements Closeable, Reporter { +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00007405, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001)); -- private static final Logger LOG = LoggerFactory.getLogger(ScheduledReporter.class); -- -- /** -- * A simple named thread factory. -- */ -- @SuppressWarnings("NullableProblems") -- private static class NamedThreadFactory implements ThreadFactory { -- private final ThreadGroup group; -- private final AtomicInteger threadNumber = new AtomicInteger(1); -- private final String namePrefix; -- -- private NamedThreadFactory(String name) { -- final SecurityManager s = System.getSecurityManager(); -- this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); -- this.namePrefix = "metrics-" + name + "-thread-"; -- } -- -- @Override -- public Thread newThread(Runnable r) { -- final Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); -- t.setDaemon(true); -- if (t.getPriority() != Thread.NORM_PRIORITY) { -- t.setPriority(Thread.NORM_PRIORITY); -- } -- return t; -- } -- } -- -- private static final AtomicInteger FACTORY_ID = new AtomicInteger(); -- -- private final MetricRegistry registry; -- private final ScheduledExecutorService executor; -- private final boolean shutdownExecutorOnStop; -- private final Set disabledMetricAttributes; -- private ScheduledFuture scheduledFuture; -- private final MetricFilter filter; -- private final long durationFactor; -- private final String durationUnit; -- private final long rateFactor; -- private final String rateUnit; -- -- /** -- * Creates a new {@link ScheduledReporter} instance. -- * -- * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this -- * reporter will report -- * @param name the reporter's name -- * @param filter the filter for which metrics to report -- * @param rateUnit a unit of time -- * @param durationUnit a unit of time -- */ -- protected ScheduledReporter(MetricRegistry registry, -- String name, -- MetricFilter filter, -- TimeUnit rateUnit, -- TimeUnit durationUnit) { -- this(registry, name, filter, rateUnit, durationUnit, createDefaultExecutor(name)); -- } -- -- /** -- * Creates a new {@link ScheduledReporter} instance. -- * -- * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this -- * reporter will report -- * @param name the reporter's name -- * @param filter the filter for which metrics to report -- * @param executor the executor to use while scheduling reporting of metrics. -- */ -- protected ScheduledReporter(MetricRegistry registry, -- String name, -- MetricFilter filter, -- TimeUnit rateUnit, -- TimeUnit durationUnit, -- ScheduledExecutorService executor) { -- this(registry, name, filter, rateUnit, durationUnit, executor, true); -- } -- -- /** -- * Creates a new {@link ScheduledReporter} instance. -- * -- * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this -- * reporter will report -- * @param name the reporter's name -- * @param filter the filter for which metrics to report -- * @param executor the executor to use while scheduling reporting of metrics. -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- */ -- protected ScheduledReporter(MetricRegistry registry, -- String name, -- MetricFilter filter, -- TimeUnit rateUnit, -- TimeUnit durationUnit, -- ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop) { -- this(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, Collections.emptySet()); -- } -- -- protected ScheduledReporter(MetricRegistry registry, -- String name, -- MetricFilter filter, -- TimeUnit rateUnit, -- TimeUnit durationUnit, -- ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop, -- Set disabledMetricAttributes) { -- -- if (registry == null) { -- throw new NullPointerException("registry == null"); -- } -+ private static final Logger LOG = LoggerFactory.getLogger(ScheduledReporter.class); - -- this.registry = registry; -- this.filter = filter; -- this.executor = executor == null ? createDefaultExecutor(name) : executor; -- this.shutdownExecutorOnStop = shutdownExecutorOnStop; -- this.rateFactor = rateUnit.toSeconds(1); -- this.rateUnit = calculateRateUnit(rateUnit); -- this.durationFactor = durationUnit.toNanos(1); -- this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); -- this.disabledMetricAttributes = disabledMetricAttributes != null ? disabledMetricAttributes : -- Collections.emptySet(); -- } -+ /** A simple named thread factory. */ -+ @SuppressWarnings("NullableProblems") -+ private static class NamedThreadFactory implements ThreadFactory { -+ private final ThreadGroup group; -+ private final AtomicInteger threadNumber = new AtomicInteger(1); -+ private final String namePrefix; - -- /** -- * Starts the reporter polling at the given period. -- * -- * @param period the amount of time between polls -- * @param unit the unit for {@code period} -- */ -- public void start(long period, TimeUnit unit) { -- start(period, period, unit); -+ private NamedThreadFactory(String name) { -+ final SecurityManager s = System.getSecurityManager(); -+ this.group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); -+ this.namePrefix = "metrics-" + name + "-thread-"; - } + elapseMinute(ewma); -- /** -- * Starts the reporter polling at the given period with the specific runnable action. -- * Visible only for testing. -- */ -- synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) { -- if (this.scheduledFuture != null) { -- throw new IllegalArgumentException("Reporter already started"); -- } -- -- this.scheduledFuture = getScheduledFuture(initialDelay, period, unit, runnable); -- } -- -- -- /** -- * Schedule the task, and return a future. -- * -- * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, ScheduledExecutorService)} instead. -- */ -- @SuppressWarnings("DeprecatedIsStillUsed") -- @Deprecated -- protected ScheduledFuture getScheduledFuture(long initialDelay, long period, TimeUnit unit, Runnable runnable) { -- return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); -- } -- -- /** -- * Schedule the task, and return a future. -- * The current implementation uses scheduleWithFixedDelay, replacing scheduleWithFixedRate. This avoids queueing issues, but may -- * cause some reporters to skip metrics, as scheduleWithFixedDelay introduces a growing delta from the original start point. -- * -- * Overriding this in a subclass to revert to the old behavior is permitted. -- */ -- protected ScheduledFuture getScheduledFuture(long initialDelay, long period, TimeUnit unit, Runnable runnable, ScheduledExecutorService executor) { -- return executor.scheduleWithFixedDelay(runnable, initialDelay, period, unit); -+ @Override -+ public Thread newThread(Runnable r) { -+ final Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); -+ t.setDaemon(true); -+ if (t.getPriority() != Thread.NORM_PRIORITY) { -+ t.setPriority(Thread.NORM_PRIORITY); -+ } -+ return t; - } -- -- /** -- * Starts the reporter polling at the given period. -- * -- * @param initialDelay the time to delay the first execution -- * @param period the amount of time between polls -- * @param unit the unit for {@code period} and {@code initialDelay} -- */ -- synchronized public void start(long initialDelay, long period, TimeUnit unit) { -- start(initialDelay, period, unit, () -> { -- try { -- report(); -- } catch (Throwable ex) { -- LOG.error("Exception thrown from {}#report. Exception was suppressed.", ScheduledReporter.this.getClass().getSimpleName(), ex); -- } -+ } -+ -+ private static final AtomicInteger FACTORY_ID = new AtomicInteger(); -+ -+ private final MetricRegistry registry; -+ private final ScheduledExecutorService executor; -+ private final boolean shutdownExecutorOnStop; -+ private final Set disabledMetricAttributes; -+ private ScheduledFuture scheduledFuture; -+ private final MetricFilter filter; -+ private final long durationFactor; -+ private final String durationUnit; -+ private final long rateFactor; -+ private final String rateUnit; -+ -+ /** -+ * Creates a new {@link ScheduledReporter} instance. -+ * -+ * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this -+ * reporter will report -+ * @param name the reporter's name -+ * @param filter the filter for which metrics to report -+ * @param rateUnit a unit of time -+ * @param durationUnit a unit of time -+ */ -+ protected ScheduledReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit) { -+ this(registry, name, filter, rateUnit, durationUnit, createDefaultExecutor(name)); -+ } -+ -+ /** -+ * Creates a new {@link ScheduledReporter} instance. -+ * -+ * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this -+ * reporter will report -+ * @param name the reporter's name -+ * @param filter the filter for which metrics to report -+ * @param executor the executor to use while scheduling reporting of metrics. -+ */ -+ protected ScheduledReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor) { -+ this(registry, name, filter, rateUnit, durationUnit, executor, true); -+ } -+ -+ /** -+ * Creates a new {@link ScheduledReporter} instance. -+ * -+ * @param registry the {@link io.dropwizard.metrics5.MetricRegistry} containing the metrics this -+ * reporter will report -+ * @param name the reporter's name -+ * @param filter the filter for which metrics to report -+ * @param executor the executor to use while scheduling reporting of metrics. -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ */ -+ protected ScheduledReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop) { -+ this( -+ registry, -+ name, -+ filter, -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop, -+ ImmutableSet.of()); -+ } -+ -+ protected ScheduledReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes) { -+ -+ requireNonNull(registry, "registry == null"); -+ -+ this.registry = registry; -+ this.filter = filter; -+ this.executor = executor == null ? createDefaultExecutor(name) : executor; -+ this.shutdownExecutorOnStop = shutdownExecutorOnStop; -+ this.rateFactor = rateUnit.toSeconds(1); -+ this.rateUnit = calculateRateUnit(rateUnit); -+ this.durationFactor = durationUnit.toNanos(1); -+ this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); -+ this.disabledMetricAttributes = -+ disabledMetricAttributes != null ? disabledMetricAttributes : ImmutableSet.of(); -+ } -+ -+ /** -+ * Starts the reporter polling at the given period. -+ * -+ * @param period the amount of time between polls -+ * @param unit the unit for {@code period} -+ */ -+ public void start(long period, TimeUnit unit) { -+ start(period, period, unit); -+ } -+ -+ /** -+ * Starts the reporter polling at the given period with the specific runnable action. Visible only -+ * for testing. -+ */ -+ synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) { -+ checkArgument(this.scheduledFuture == null, "Reporter already started"); -+ -+ this.scheduledFuture = getScheduledFuture(initialDelay, period, unit, runnable); -+ } -+ -+ /** -+ * Schedule the task, and return a future. -+ * -+ * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, -+ * ScheduledExecutorService)} instead. -+ */ -+ @Deprecated -+ @SuppressWarnings("DeprecatedIsStillUsed") -+ protected ScheduledFuture getScheduledFuture( -+ long initialDelay, long period, TimeUnit unit, Runnable runnable) { -+ return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); -+ } -+ -+ /** -+ * Schedule the task, and return a future. The current implementation uses scheduleWithFixedDelay, -+ * replacing scheduleWithFixedRate. This avoids queueing issues, but may cause some reporters to -+ * skip metrics, as scheduleWithFixedDelay introduces a growing delta from the original start -+ * point. -+ * -+ *

    Overriding this in a subclass to revert to the old behavior is permitted. -+ */ -+ protected ScheduledFuture getScheduledFuture( -+ long initialDelay, -+ long period, -+ TimeUnit unit, -+ Runnable runnable, -+ ScheduledExecutorService executor) { -+ return executor.scheduleWithFixedDelay(runnable, initialDelay, period, unit); -+ } -+ -+ /** -+ * Starts the reporter polling at the given period. -+ * -+ * @param initialDelay the time to delay the first execution -+ * @param period the amount of time between polls -+ * @param unit the unit for {@code period} and {@code initialDelay} -+ */ -+ public synchronized void start(long initialDelay, long period, TimeUnit unit) { -+ start( -+ initialDelay, -+ period, -+ unit, -+ () -> { -+ try { -+ report(); -+ } catch (Throwable ex) { -+ LOG.error( -+ "Exception thrown from {}#report. Exception was suppressed.", -+ ScheduledReporter.this.getClass().getSimpleName(), -+ ex); -+ } - }); -+ } -+ -+ /** -+ * Stops the reporter and if shutdownExecutorOnStop is true then shuts down its thread of -+ * execution. -+ * -+ *

    Uses the shutdown pattern from -+ * http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html -+ */ -+ public void stop() { -+ if (shutdownExecutorOnStop) { -+ executor.shutdown(); // Disable new tasks from being submitted - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00002724, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001)); -- /** -- * Stops the reporter and if shutdownExecutorOnStop is true then shuts down its thread of execution. -- *

    -- * Uses the shutdown pattern from http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html -- */ -- public void stop() { -- if (shutdownExecutorOnStop) { -- executor.shutdown(); // Disable new tasks from being submitted -- } -- -- if (this.scheduledFuture != null) { -- // Reporter started, try to report metrics one last time -- try { -- report(); -- } catch (Exception e) { -- LOG.warn("Final reporting of metrics failed.", e); -- } -- } -- -- if (shutdownExecutorOnStop) { -- try { -- // Wait a while for existing tasks to terminate -- if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { -- executor.shutdownNow(); // Cancel currently executing tasks -- // Wait a while for tasks to respond to being cancelled -- if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { -- LOG.warn("ScheduledExecutorService did not terminate."); -- } -- } -- } catch (InterruptedException ie) { -- // (Re-)Cancel if current thread also interrupted -- executor.shutdownNow(); -- // Preserve interrupt status -- Thread.currentThread().interrupt(); -- } -- } else { -- // The external manager (like JEE container) responsible for lifecycle of executor -- cancelScheduledFuture(); -- } -+ if (this.scheduledFuture != null) { -+ // Reporter started, try to report metrics one last time -+ try { -+ report(); -+ } catch (Exception e) { -+ LOG.warn("Final reporting of metrics failed.", e); -+ } - } + elapseMinute(ewma); -- private synchronized void cancelScheduledFuture() { -- if (this.scheduledFuture == null) { -- // was never started -- return; -- } -- if (this.scheduledFuture.isCancelled()) { -- // already cancelled -- return; -+ if (shutdownExecutorOnStop) { -+ try { -+ // Wait a while for existing tasks to terminate -+ if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { -+ executor.shutdownNow(); // Cancel currently executing tasks -+ // Wait a while for tasks to respond to being cancelled -+ if (!executor.awaitTermination(1, TimeUnit.SECONDS)) { -+ LOG.warn("ScheduledExecutorService did not terminate."); -+ } - } -- // just cancel the scheduledFuture and exit -- this.scheduledFuture.cancel(false); -+ } catch (InterruptedException ie) { -+ // (Re-)Cancel if current thread also interrupted -+ executor.shutdownNow(); -+ // Preserve interrupt status -+ Thread.currentThread().interrupt(); -+ } -+ } else { -+ // The external manager (like JEE container) responsible for lifecycle of executor -+ cancelScheduledFuture(); - } -+ } - -- /** -- * Stops the reporter and shuts down its thread of execution. -- */ -- @Override -- public void close() { -- stop(); -+ private synchronized void cancelScheduledFuture() { -+ if (this.scheduledFuture == null) { -+ // was never started -+ return; - } -- -- /** -- * Report the current values of all metrics in the registry. -- */ -- public void report() { -- synchronized (this) { -- report(registry.getGauges(filter), -- registry.getCounters(filter), -- registry.getHistograms(filter), -- registry.getMeters(filter), -- registry.getTimers(filter)); -- } -- } -- -- /** -- * Called periodically by the polling thread. Subclasses should report all the given metrics. -- * -- * @param gauges all of the gauges in the registry -- * @param counters all of the counters in the registry -- * @param histograms all of the histograms in the registry -- * @param meters all of the meters in the registry -- * @param timers all of the timers in the registry -- */ -- @SuppressWarnings("rawtypes") -- public abstract void report(SortedMap> gauges, -- SortedMap counters, -- SortedMap histograms, -- SortedMap meters, -- SortedMap timers); -- -- public String getRateUnit() { -- return rateUnit; -+ if (this.scheduledFuture.isCancelled()) { -+ // already cancelled -+ return; - } -- -- public String getDurationUnit() { -- return durationUnit; -+ // just cancel the scheduledFuture and exit -+ this.scheduledFuture.cancel(false); -+ } -+ -+ /** Stops the reporter and shuts down its thread of execution. */ -+ @Override -+ public void close() { -+ stop(); -+ } -+ -+ /** Report the current values of all metrics in the registry. */ -+ public void report() { -+ synchronized (this) { -+ report( -+ registry.getGauges(filter), -+ registry.getCounters(filter), -+ registry.getHistograms(filter), -+ registry.getMeters(filter), -+ registry.getTimers(filter)); - } -- -- public double convertDuration(double duration) { -- return duration / durationFactor; -- } -- -- public double convertRate(double rate) { -- return rate * rateFactor; -- } -- -- public boolean isShutdownExecutorOnStop() { -- return shutdownExecutorOnStop; -- } -- -- public Set getDisabledMetricAttributes() { -- return disabledMetricAttributes; -- } -- -- private String calculateRateUnit(TimeUnit unit) { -- final String s = unit.toString().toLowerCase(Locale.US); -- return s.substring(0, s.length() - 1); -- } -- -- private static ScheduledExecutorService createDefaultExecutor(String name) { -- return Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet())); -- } -- -+ } -+ -+ /** -+ * Called periodically by the polling thread. Subclasses should report all the given metrics. -+ * -+ * @param gauges all of the gauges in the registry -+ * @param counters all of the counters in the registry -+ * @param histograms all of the histograms in the registry -+ * @param meters all of the meters in the registry -+ * @param timers all of the timers in the registry -+ */ -+ @SuppressWarnings("rawtypes") -+ public abstract void report( -+ SortedMap> gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers); -+ -+ public String getRateUnit() { -+ return rateUnit; -+ } -+ -+ public String getDurationUnit() { -+ return durationUnit; -+ } -+ -+ public double convertDuration(double duration) { -+ return duration / durationFactor; -+ } -+ -+ public double convertRate(double rate) { -+ return rate * rateFactor; -+ } -+ -+ public boolean isShutdownExecutorOnStop() { -+ return shutdownExecutorOnStop; -+ } -+ -+ public Set getDisabledMetricAttributes() { -+ return disabledMetricAttributes; -+ } -+ -+ private String calculateRateUnit(TimeUnit unit) { -+ final String s = unit.toString().toLowerCase(Locale.US); -+ return s.substring(0, s.length() - 1); -+ } -+ -+ private static ScheduledExecutorService createDefaultExecutor(String name) { -+ return Executors.newSingleThreadScheduledExecutor( -+ new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet())); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/SettableGauge.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SettableGauge.java -@@ -1,14 +1,10 @@ - package io.dropwizard.metrics5; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00001002, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001)); - /** -- *

    - * Similar to {@link Gauge}, but metric value is updated via calling {@link #setValue(T)} instead. - * See {@link DefaultSettableGauge}. -- *

    - */ - public interface SettableGauge extends Gauge { -- /** -- * Set the metric to a new value. -- */ -- void setValue(T value); -+ /** Set the metric to a new value. */ -+ void setValue(T value); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java -@@ -1,107 +1,106 @@ - package io.dropwizard.metrics5; + elapseMinute(ewma); -+import static com.google.common.base.Preconditions.checkState; -+ - import java.util.Set; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.ConcurrentMap; - import java.util.concurrent.atomic.AtomicReference; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000369, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001)); --/** -- * A map of shared, named metric registries. -- */ -+/** A map of shared, named metric registries. */ - public class SharedMetricRegistries { -- private static final ConcurrentMap REGISTRIES = -- new ConcurrentHashMap<>(); -+ private static final ConcurrentMap REGISTRIES = new ConcurrentHashMap<>(); - -- private static AtomicReference defaultRegistryName = new AtomicReference<>(); -+ private static AtomicReference defaultRegistryName = new AtomicReference<>(); - -- /* Visible for testing */ -- static void setDefaultRegistryName(AtomicReference defaultRegistryName) { -- SharedMetricRegistries.defaultRegistryName = defaultRegistryName; -- } -+ /* Visible for testing */ -+ static void setDefaultRegistryName(AtomicReference defaultRegistryName) { -+ SharedMetricRegistries.defaultRegistryName = defaultRegistryName; -+ } - -- private SharedMetricRegistries() { /* singleton */ } -+ private SharedMetricRegistries() { -+ /* singleton */ -+ } - -- public static void clear() { -- REGISTRIES.clear(); -- } -+ public static void clear() { -+ REGISTRIES.clear(); -+ } + elapseMinute(ewma); -- public static Set names() { -- return REGISTRIES.keySet(); -- } -+ public static Set names() { -+ return REGISTRIES.keySet(); -+ } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000136, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001)); -- public static void remove(String key) { -- REGISTRIES.remove(key); -- } -+ public static void remove(String key) { -+ REGISTRIES.remove(key); -+ } + elapseMinute(ewma); -- public static MetricRegistry add(String name, MetricRegistry registry) { -- return REGISTRIES.putIfAbsent(name, registry); -- } -+ public static MetricRegistry add(String name, MetricRegistry registry) { -+ return REGISTRIES.putIfAbsent(name, registry); -+ } - -- public static MetricRegistry getOrCreate(String name) { -- final MetricRegistry existing = REGISTRIES.get(name); -- if (existing == null) { -- final MetricRegistry created = new MetricRegistry(); -- final MetricRegistry raced = add(name, created); -- if (raced == null) { -- return created; -- } -- return raced; -- } -- return existing; -+ public static MetricRegistry getOrCreate(String name) { -+ final MetricRegistry existing = REGISTRIES.get(name); -+ if (existing == null) { -+ final MetricRegistry created = new MetricRegistry(); -+ final MetricRegistry raced = add(name, created); -+ if (raced == null) { -+ return created; -+ } -+ return raced; - } -+ return existing; -+ } - -- /** -- * Creates a new registry and sets it as the default one under the provided name. -- * -- * @param name the registry name -- * @return the default registry -- * @throws IllegalStateException if the name has already been set -- */ -- public synchronized static MetricRegistry setDefault(String name) { -- final MetricRegistry registry = getOrCreate(name); -- return setDefault(name, registry); -- } -+ /** -+ * Creates a new registry and sets it as the default one under the provided name. -+ * -+ * @param name the registry name -+ * @return the default registry -+ * @throws IllegalStateException if the name has already been set -+ */ -+ public static synchronized MetricRegistry setDefault(String name) { -+ final MetricRegistry registry = getOrCreate(name); -+ return setDefault(name, registry); -+ } - -- /** -- * Sets the provided registry as the default one under the provided name -- * -- * @param name the default registry name -- * @param metricRegistry the default registry -- * @throws IllegalStateException if the default registry has already been set -- */ -- public static MetricRegistry setDefault(String name, MetricRegistry metricRegistry) { -- if (defaultRegistryName.compareAndSet(null, name)) { -- add(name, metricRegistry); -- return metricRegistry; -- } -- throw new IllegalStateException("Default metric registry name is already set."); -+ /** -+ * Sets the provided registry as the default one under the provided name -+ * -+ * @param name the default registry name -+ * @param metricRegistry the default registry -+ * @throws IllegalStateException if the default registry has already been set -+ */ -+ public static MetricRegistry setDefault(String name, MetricRegistry metricRegistry) { -+ if (defaultRegistryName.compareAndSet(null, name)) { -+ add(name, metricRegistry); -+ return metricRegistry; - } -+ throw new IllegalStateException("Default metric registry name is already set."); -+ } - -- /** -- * Gets the name of the default registry, if it has been set -- * -- * @return the default registry -- * @throws IllegalStateException if the default has not been set -- */ -- public static MetricRegistry getDefault() { -- MetricRegistry metricRegistry = tryGetDefault(); -- if (metricRegistry == null) { -- throw new IllegalStateException("Default registry name has not been set."); -- } -- return metricRegistry; -- } -+ /** -+ * Gets the name of the default registry, if it has been set -+ * -+ * @return the default registry -+ * @throws IllegalStateException if the default has not been set -+ */ -+ public static MetricRegistry getDefault() { -+ MetricRegistry metricRegistry = tryGetDefault(); -+ checkState(metricRegistry != null, "Default registry name has not been set."); -+ return metricRegistry; -+ } - -- /** -- * Same as {@link #getDefault()} except returns null when the default registry has not been set. -- * -- * @return the default registry or null -- */ -- public static MetricRegistry tryGetDefault() { -- final String name = defaultRegistryName.get(); -- if (name != null) { -- return getOrCreate(name); -- } else { -- return null; -- } -+ /** -+ * Same as {@link #getDefault()} except returns null when the default registry has not been set. -+ * -+ * @return the default registry or null -+ */ -+ public static MetricRegistry tryGetDefault() { -+ final String name = defaultRegistryName.get(); -+ if (name != null) { -+ return getOrCreate(name); -+ } else { -+ return null; - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java -@@ -1,25 +1,11 @@ - package io.dropwizard.metrics5; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000050, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001)); --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; --import org.slf4j.Marker; -- --import java.util.Collections; --import java.util.Map.Entry; --import java.util.Set; --import java.util.SortedMap; --import java.util.concurrent.ScheduledExecutorService; --import java.util.concurrent.TimeUnit; --import java.util.function.Supplier; -- - import static io.dropwizard.metrics5.MetricAttribute.COUNT; - import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; - import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; - import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MAX; - import static io.dropwizard.metrics5.MetricAttribute.MEAN; - import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MIN; - import static io.dropwizard.metrics5.MetricAttribute.P50; - import static io.dropwizard.metrics5.MetricAttribute.P75; - import static io.dropwizard.metrics5.MetricAttribute.P95; -@@ -28,6 +14,17 @@ import static io.dropwizard.metrics5.MetricAttribute.P99; - import static io.dropwizard.metrics5.MetricAttribute.P999; - import static io.dropwizard.metrics5.MetricAttribute.STDDEV; + elapseMinute(ewma); -+import com.google.common.collect.ImmutableSet; -+import java.util.Map.Entry; -+import java.util.Set; -+import java.util.SortedMap; -+import java.util.concurrent.ScheduledExecutorService; -+import java.util.concurrent.TimeUnit; -+import java.util.function.Supplier; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; -+import org.slf4j.Marker; -+ - /** - * A reporter class for logging metrics values to a SLF4J {@link Logger} periodically, similar to - * {@link ConsoleReporter} or {@link CsvReporter}, but using the SLF4J framework instead. It also -@@ -35,482 +32,507 @@ import static io.dropwizard.metrics5.MetricAttribute.STDDEV; - * for the bound logging toolkit to further process metrics reports. - */ - public class Slf4jReporter extends ScheduledReporter { -+ /** -+ * Returns a new {@link Builder} for {@link Slf4jReporter}. -+ * -+ * @param registry the registry to report -+ * @return a {@link Builder} instance for a {@link Slf4jReporter} -+ */ -+ public static Builder forRegistry(MetricRegistry registry) { -+ return new Builder(registry); -+ } -+ -+ public enum LoggingLevel { -+ TRACE, -+ DEBUG, -+ INFO, -+ WARN, -+ ERROR -+ } -+ -+ /** -+ * A builder for {@link Slf4jReporter} instances. Defaults to logging to {@code metrics}, not -+ * using a marker, converting rates to events/second, converting durations to milliseconds, and -+ * not filtering metrics. -+ */ -+ public static class Builder { -+ private final MetricRegistry registry; -+ private Logger logger; -+ private LoggingLevel loggingLevel; -+ private Marker marker; -+ private String prefix; -+ private TimeUnit rateUnit; -+ private TimeUnit durationUnit; -+ private MetricFilter filter; -+ private ScheduledExecutorService executor; -+ private boolean shutdownExecutorOnStop; -+ private Set disabledMetricAttributes; -+ -+ private Builder(MetricRegistry registry) { -+ this.registry = registry; -+ this.logger = LoggerFactory.getLogger("metrics"); -+ this.marker = null; -+ this.prefix = ""; -+ this.rateUnit = TimeUnit.SECONDS; -+ this.durationUnit = TimeUnit.MILLISECONDS; -+ this.filter = MetricFilter.ALL; -+ this.loggingLevel = LoggingLevel.INFO; -+ this.executor = null; -+ this.shutdownExecutorOnStop = true; -+ this.disabledMetricAttributes = ImmutableSet.of(); -+ } -+ - /** -- * Returns a new {@link Builder} for {@link Slf4jReporter}. -+ * Specifies whether or not, the executor (used for reporting) will be stopped with same time -+ * with reporter. Default value is true. Setting this parameter to false, has the sense in -+ * combining with providing external managed executor via {@link -+ * #scheduleOn(ScheduledExecutorService)}. - * -- * @param registry the registry to report -- * @return a {@link Builder} instance for a {@link Slf4jReporter} -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ * @return {@code this} - */ -- public static Builder forRegistry(MetricRegistry registry) { -- return new Builder(registry); -+ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -+ this.shutdownExecutorOnStop = shutdownExecutorOnStop; -+ return this; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000018, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001)); + } -- public enum LoggingLevel { TRACE, DEBUG, INFO, WARN, ERROR } -+ /** -+ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. -+ * Null value leads to executor will be auto created on start. -+ * -+ * @param executor the executor to use while scheduling reporting of metrics. -+ * @return {@code this} -+ */ -+ public Builder scheduleOn(ScheduledExecutorService executor) { -+ this.executor = executor; -+ return this; -+ } + @Test +@@ -82,67 +82,67 @@ class EWMATest { + ewma.update(3); + ewma.tick(); - /** -- * A builder for {@link Slf4jReporter} instances. Defaults to logging to {@code metrics}, not -- * using a marker, converting rates to events/second, converting durations to milliseconds, and -- * not filtering metrics. -+ * Log metrics to the given logger. -+ * -+ * @param logger an SLF4J {@link Logger} -+ * @return {@code this} - */ -- public static class Builder { -- private final MetricRegistry registry; -- private Logger logger; -- private LoggingLevel loggingLevel; -- private Marker marker; -- private String prefix; -- private TimeUnit rateUnit; -- private TimeUnit durationUnit; -- private MetricFilter filter; -- private ScheduledExecutorService executor; -- private boolean shutdownExecutorOnStop; -- private Set disabledMetricAttributes; -- -- private Builder(MetricRegistry registry) { -- this.registry = registry; -- this.logger = LoggerFactory.getLogger("metrics"); -- this.marker = null; -- this.prefix = ""; -- this.rateUnit = TimeUnit.SECONDS; -- this.durationUnit = TimeUnit.MILLISECONDS; -- this.filter = MetricFilter.ALL; -- this.loggingLevel = LoggingLevel.INFO; -- this.executor = null; -- this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -- } -- -- /** -- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. -- * Default value is true. -- * Setting this parameter to false, has the sense in combining with providing external managed executor via {@link #scheduleOn(ScheduledExecutorService)}. -- * -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- * @return {@code this} -- */ -- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -- this.shutdownExecutorOnStop = shutdownExecutorOnStop; -- return this; -- } -- -- /** -- * Specifies the executor to use while scheduling reporting of metrics. -- * Default value is null. -- * Null value leads to executor will be auto created on start. -- * -- * @param executor the executor to use while scheduling reporting of metrics. -- * @return {@code this} -- */ -- public Builder scheduleOn(ScheduledExecutorService executor) { -- this.executor = executor; -- return this; -- } -- -- /** -- * Log metrics to the given logger. -- * -- * @param logger an SLF4J {@link Logger} -- * @return {@code this} -- */ -- public Builder outputTo(Logger logger) { -- this.logger = logger; -- return this; -- } -- -- /** -- * Mark all logged metrics with the given marker. -- * -- * @param marker an SLF4J {@link Marker} -- * @return {@code this} -- */ -- public Builder markWith(Marker marker) { -- this.marker = marker; -- return this; -- } -- -- /** -- * Prefix all metric names with the given string. -- * -- * @param prefix the prefix for all metric names -- * @return {@code this} -- */ -- public Builder prefixedWith(String prefix) { -- this.prefix = prefix; -- return this; -- } -- -- /** -- * Convert rates to the given time unit. -- * -- * @param rateUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertRatesTo(TimeUnit rateUnit) { -- this.rateUnit = rateUnit; -- return this; -- } -- -- /** -- * Convert durations to the given time unit. -- * -- * @param durationUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertDurationsTo(TimeUnit durationUnit) { -- this.durationUnit = durationUnit; -- return this; -- } -- -- /** -- * Only report metrics which match the given filter. -- * -- * @param filter a {@link MetricFilter} -- * @return {@code this} -- */ -- public Builder filter(MetricFilter filter) { -- this.filter = filter; -- return this; -- } -- -- /** -- * Use Logging Level when reporting. -- * -- * @param loggingLevel a (@link Slf4jReporter.LoggingLevel} -- * @return {@code this} -- */ -- public Builder withLoggingLevel(LoggingLevel loggingLevel) { -- this.loggingLevel = loggingLevel; -- return this; -- } -- -- /** -- * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). -- * See {@link MetricAttribute}. -- * -- * @param disabledMetricAttributes a set of {@link MetricAttribute} -- * @return {@code this} -- */ -- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -- this.disabledMetricAttributes = disabledMetricAttributes; -- return this; -- } -- -- /** -- * Builds a {@link Slf4jReporter} with the given properties. -- * -- * @return a {@link Slf4jReporter} -- */ -- public Slf4jReporter build() { -- LoggerProxy loggerProxy; -- switch (loggingLevel) { -- case TRACE: -- loggerProxy = new TraceLoggerProxy(logger); -- break; -- case INFO: -- loggerProxy = new InfoLoggerProxy(logger); -- break; -- case WARN: -- loggerProxy = new WarnLoggerProxy(logger); -- break; -- case ERROR: -- loggerProxy = new ErrorLoggerProxy(logger); -- break; -- default: -- case DEBUG: -- loggerProxy = new DebugLoggerProxy(logger); -- break; -- } -- return new Slf4jReporter(registry, loggerProxy, marker, prefix, rateUnit, durationUnit, filter, executor, -- shutdownExecutorOnStop, disabledMetricAttributes); -- } -- } -- -- private final LoggerProxy loggerProxy; -- private final Marker marker; -- private final MetricName prefix; -- -- private Slf4jReporter(MetricRegistry registry, -- LoggerProxy loggerProxy, -- Marker marker, -- String prefix, -- TimeUnit rateUnit, -- TimeUnit durationUnit, -- MetricFilter filter, -- ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop, -- Set disabledMetricAttributes) { -- super(registry, "logger-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, -- disabledMetricAttributes); -- this.loggerProxy = loggerProxy; -- this.marker = marker; -- this.prefix = MetricName.build(prefix); -+ public Builder outputTo(Logger logger) { -+ this.logger = logger; -+ return this; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap> gauges, -- SortedMap counters, -- SortedMap histograms, -- SortedMap meters, -- SortedMap timers) { -- if (loggerProxy.isEnabled(marker)) { -- StringBuilder b = new StringBuilder(); -- for (Entry> entry : gauges.entrySet()) { -- logGauge(b, entry.getKey(), entry.getValue()); -- } -- -- for (Entry entry : counters.entrySet()) { -- logCounter(b, entry.getKey(), entry.getValue()); -- } -- -- for (Entry entry : histograms.entrySet()) { -- logHistogram(b, entry.getKey(), entry.getValue()); -- } -- -- for (Entry entry : meters.entrySet()) { -- logMeter(b, entry.getKey(), entry.getValue()); -- } -- -- for (Entry entry : timers.entrySet()) { -- logTimer(b, entry.getKey(), entry.getValue()); -- } -- } -- } -- -- private void logTimer(StringBuilder b, MetricName name, Timer timer) { -- final Snapshot snapshot = timer.getSnapshot(); -- b.setLength(0); -- b.append("type=TIMER"); -- append(b, "name", prefix(name)); -- appendCountIfEnabled(b, timer); -- appendLongDurationIfEnabled(b, MIN, snapshot::getMin); -- appendLongDurationIfEnabled(b, MAX, snapshot::getMax); -- appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); -- appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); -- appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); -- appendDoubleDurationIfEnabled(b, P75, snapshot::get75thPercentile); -- appendDoubleDurationIfEnabled(b, P95, snapshot::get95thPercentile); -- appendDoubleDurationIfEnabled(b, P98, snapshot::get98thPercentile); -- appendDoubleDurationIfEnabled(b, P99, snapshot::get99thPercentile); -- appendDoubleDurationIfEnabled(b, P999, snapshot::get999thPercentile); -- appendMetered(b, timer); -- append(b, "rate_unit", getRateUnit()); -- append(b, "duration_unit", getDurationUnit()); -- loggerProxy.log(marker, b.toString()); -- } -- -- private void logMeter(StringBuilder b, MetricName name, Meter meter) { -- b.setLength(0); -- b.append("type=METER"); -- append(b, "name", prefix(name)); -- appendCountIfEnabled(b, meter); -- appendMetered(b, meter); -- append(b, "rate_unit", getRateUnit()); -- loggerProxy.log(marker, b.toString()); -- } -- -- private void logHistogram(StringBuilder b, MetricName name, Histogram histogram) { -- final Snapshot snapshot = histogram.getSnapshot(); -- b.setLength(0); -- b.append("type=HISTOGRAM"); -- append(b, "name", prefix(name)); -- appendCountIfEnabled(b, histogram); -- appendLongIfEnabled(b, MIN, snapshot::getMin); -- appendLongIfEnabled(b, MAX, snapshot::getMax); -- appendDoubleIfEnabled(b, MEAN, snapshot::getMean); -- appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); -- appendDoubleIfEnabled(b, P50, snapshot::getMedian); -- appendDoubleIfEnabled(b, P75, snapshot::get75thPercentile); -- appendDoubleIfEnabled(b, P95, snapshot::get95thPercentile); -- appendDoubleIfEnabled(b, P98, snapshot::get98thPercentile); -- appendDoubleIfEnabled(b, P99, snapshot::get99thPercentile); -- appendDoubleIfEnabled(b, P999, snapshot::get999thPercentile); -- loggerProxy.log(marker, b.toString()); -- } -- -- private void logCounter(StringBuilder b, MetricName name, Counter counter) { -- b.setLength(0); -- b.append("type=COUNTER"); -- append(b, "name", prefix(name)); -- append(b, COUNT.getCode(), counter.getCount()); -- loggerProxy.log(marker, b.toString()); -- } -- -- private void logGauge(StringBuilder b, MetricName name, Gauge gauge) { -- b.setLength(0); -- b.append("type=GAUGE"); -- append(b, "name", prefix(name)); -- append(b, "value", gauge.getValue()); -- loggerProxy.log(marker, b.toString()); -- } -- -- private void appendLongDurationIfEnabled(StringBuilder b, MetricAttribute metricAttribute, -- Supplier durationSupplier) { -- if (!getDisabledMetricAttributes().contains(metricAttribute)) { -- append(b, metricAttribute.getCode(), convertDuration(durationSupplier.get())); -- } -- } -- -- private void appendDoubleDurationIfEnabled(StringBuilder b, MetricAttribute metricAttribute, -- Supplier durationSupplier) { -- if (!getDisabledMetricAttributes().contains(metricAttribute)) { -- append(b, metricAttribute.getCode(), convertDuration(durationSupplier.get())); -- } -+ /** -+ * Mark all logged metrics with the given marker. -+ * -+ * @param marker an SLF4J {@link Marker} -+ * @return {@code this} -+ */ -+ public Builder markWith(Marker marker) { -+ this.marker = marker; -+ return this; - } + elapseMinute(ewma); -- private void appendLongIfEnabled(StringBuilder b, MetricAttribute metricAttribute, -- Supplier valueSupplier) { -- if (!getDisabledMetricAttributes().contains(metricAttribute)) { -- append(b, metricAttribute.getCode(), valueSupplier.get()); -- } -+ /** -+ * Prefix all metric names with the given string. -+ * -+ * @param prefix the prefix for all metric names -+ * @return {@code this} -+ */ -+ public Builder prefixedWith(String prefix) { -+ this.prefix = prefix; -+ return this; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); -- private void appendDoubleIfEnabled(StringBuilder b, MetricAttribute metricAttribute, -- Supplier valueSupplier) { -- if (!getDisabledMetricAttributes().contains(metricAttribute)) { -- append(b, metricAttribute.getCode(), valueSupplier.get()); -- } -+ /** -+ * Convert rates to the given time unit. -+ * -+ * @param rateUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertRatesTo(TimeUnit rateUnit) { -+ this.rateUnit = rateUnit; -+ return this; - } + elapseMinute(ewma); -- private void appendCountIfEnabled(StringBuilder b, Counting counting) { -- if (!getDisabledMetricAttributes().contains(COUNT)) { -- append(b, COUNT.getCode(), counting.getCount()); -- } -+ /** -+ * Convert durations to the given time unit. -+ * -+ * @param durationUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertDurationsTo(TimeUnit durationUnit) { -+ this.durationUnit = durationUnit; -+ return this; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); -- private void appendMetered(StringBuilder b, Metered meter) { -- appendRateIfEnabled(b, M1_RATE, meter::getOneMinuteRate); -- appendRateIfEnabled(b, M5_RATE, meter::getFiveMinuteRate); -- appendRateIfEnabled(b, M15_RATE, meter::getFifteenMinuteRate); -- appendRateIfEnabled(b, MEAN_RATE, meter::getMeanRate); -+ /** -+ * Only report metrics which match the given filter. -+ * -+ * @param filter a {@link MetricFilter} -+ * @return {@code this} -+ */ -+ public Builder filter(MetricFilter filter) { -+ this.filter = filter; -+ return this; - } + elapseMinute(ewma); -- private void appendRateIfEnabled(StringBuilder b, MetricAttribute metricAttribute, Supplier rateSupplier) { -- if (!getDisabledMetricAttributes().contains(metricAttribute)) { -- append(b, metricAttribute.getCode(), convertRate(rateSupplier.get())); -- } -+ /** -+ * Use Logging Level when reporting. -+ * -+ * @param loggingLevel a (@link Slf4jReporter.LoggingLevel} -+ * @return {@code this} -+ */ -+ public Builder withLoggingLevel(LoggingLevel loggingLevel) { -+ this.loggingLevel = loggingLevel; -+ return this; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); -- private void append(StringBuilder b, String key, long value) { -- b.append(", ").append(key).append('=').append(value); -+ /** -+ * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). -+ * See {@link MetricAttribute}. -+ * -+ * @param disabledMetricAttributes a set of {@link MetricAttribute} -+ * @return {@code this} -+ */ -+ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -+ this.disabledMetricAttributes = disabledMetricAttributes; -+ return this; - } + elapseMinute(ewma); -- private void append(StringBuilder b, String key, double value) { -- b.append(", ").append(key).append('=').append(value); -+ /** -+ * Builds a {@link Slf4jReporter} with the given properties. -+ * -+ * @return a {@link Slf4jReporter} -+ */ -+ public Slf4jReporter build() { -+ LoggerProxy loggerProxy; -+ switch (loggingLevel) { -+ case TRACE: -+ loggerProxy = new TraceLoggerProxy(logger); -+ break; -+ case INFO: -+ loggerProxy = new InfoLoggerProxy(logger); -+ break; -+ case WARN: -+ loggerProxy = new WarnLoggerProxy(logger); -+ break; -+ case ERROR: -+ loggerProxy = new ErrorLoggerProxy(logger); -+ break; -+ default: -+ case DEBUG: -+ loggerProxy = new DebugLoggerProxy(logger); -+ break; -+ } -+ return new Slf4jReporter( -+ registry, -+ loggerProxy, -+ marker, -+ prefix, -+ rateUnit, -+ durationUnit, -+ filter, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes); -+ } -+ } -+ -+ private final LoggerProxy loggerProxy; -+ private final Marker marker; -+ private final MetricName prefix; -+ -+ private Slf4jReporter( -+ MetricRegistry registry, -+ LoggerProxy loggerProxy, -+ Marker marker, -+ String prefix, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ MetricFilter filter, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes) { -+ super( -+ registry, -+ "logger-reporter", -+ filter, -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes); -+ this.loggerProxy = loggerProxy; -+ this.marker = marker; -+ this.prefix = MetricName.build(prefix); -+ } -+ -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap> gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ if (loggerProxy.isEnabled(marker)) { -+ StringBuilder b = new StringBuilder(); -+ for (Entry> entry : gauges.entrySet()) { -+ logGauge(b, entry.getKey(), entry.getValue()); -+ } -+ -+ for (Entry entry : counters.entrySet()) { -+ logCounter(b, entry.getKey(), entry.getValue()); -+ } -+ -+ for (Entry entry : histograms.entrySet()) { -+ logHistogram(b, entry.getKey(), entry.getValue()); -+ } -+ -+ for (Entry entry : meters.entrySet()) { -+ logMeter(b, entry.getKey(), entry.getValue()); -+ } -+ -+ for (Entry entry : timers.entrySet()) { -+ logTimer(b, entry.getKey(), entry.getValue()); -+ } -+ } -+ } -+ -+ private void logTimer(StringBuilder b, MetricName name, Timer timer) { -+ final Snapshot snapshot = timer.getSnapshot(); -+ b.setLength(0); -+ b.append("type=TIMER"); -+ append(b, "name", prefix(name)); -+ appendCountIfEnabled(b, timer); -+ appendLongDurationIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); -+ appendLongDurationIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); -+ appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); -+ appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); -+ appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); -+ appendDoubleDurationIfEnabled(b, P75, snapshot::get75thPercentile); -+ appendDoubleDurationIfEnabled(b, P95, snapshot::get95thPercentile); -+ appendDoubleDurationIfEnabled(b, P98, snapshot::get98thPercentile); -+ appendDoubleDurationIfEnabled(b, P99, snapshot::get99thPercentile); -+ appendDoubleDurationIfEnabled(b, P999, snapshot::get999thPercentile); -+ appendMetered(b, timer); -+ append(b, "rate_unit", getRateUnit()); -+ append(b, "duration_unit", getDurationUnit()); -+ loggerProxy.log(marker, b.toString()); -+ } -+ -+ private void logMeter(StringBuilder b, MetricName name, Meter meter) { -+ b.setLength(0); -+ b.append("type=METER"); -+ append(b, "name", prefix(name)); -+ appendCountIfEnabled(b, meter); -+ appendMetered(b, meter); -+ append(b, "rate_unit", getRateUnit()); -+ loggerProxy.log(marker, b.toString()); -+ } -+ -+ private void logHistogram(StringBuilder b, MetricName name, Histogram histogram) { -+ final Snapshot snapshot = histogram.getSnapshot(); -+ b.setLength(0); -+ b.append("type=HISTOGRAM"); -+ append(b, "name", prefix(name)); -+ appendCountIfEnabled(b, histogram); -+ appendLongIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); -+ appendLongIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); -+ appendDoubleIfEnabled(b, MEAN, snapshot::getMean); -+ appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); -+ appendDoubleIfEnabled(b, P50, snapshot::getMedian); -+ appendDoubleIfEnabled(b, P75, snapshot::get75thPercentile); -+ appendDoubleIfEnabled(b, P95, snapshot::get95thPercentile); -+ appendDoubleIfEnabled(b, P98, snapshot::get98thPercentile); -+ appendDoubleIfEnabled(b, P99, snapshot::get99thPercentile); -+ appendDoubleIfEnabled(b, P999, snapshot::get999thPercentile); -+ loggerProxy.log(marker, b.toString()); -+ } -+ -+ private void logCounter(StringBuilder b, MetricName name, Counter counter) { -+ b.setLength(0); -+ b.append("type=COUNTER"); -+ append(b, "name", prefix(name)); -+ append(b, COUNT.getCode(), counter.getCount()); -+ loggerProxy.log(marker, b.toString()); -+ } -+ -+ private void logGauge(StringBuilder b, MetricName name, Gauge gauge) { -+ b.setLength(0); -+ b.append("type=GAUGE"); -+ append(b, "name", prefix(name)); -+ append(b, "value", gauge.getValue()); -+ loggerProxy.log(marker, b.toString()); -+ } -+ -+ private void appendLongDurationIfEnabled( -+ StringBuilder b, MetricAttribute metricAttribute, Supplier durationSupplier) { -+ if (!getDisabledMetricAttributes().contains(metricAttribute)) { -+ append(b, metricAttribute.getCode(), convertDuration(durationSupplier.get())); - } -+ } - -- private void append(StringBuilder b, String key, String value) { -- b.append(", ").append(key).append('=').append(value); -+ private void appendDoubleDurationIfEnabled( -+ StringBuilder b, MetricAttribute metricAttribute, Supplier durationSupplier) { -+ if (!getDisabledMetricAttributes().contains(metricAttribute)) { -+ append(b, metricAttribute.getCode(), convertDuration(durationSupplier.get())); - } -+ } - -- private void append(StringBuilder b, String key, Object value) { -- b.append(", ").append(key).append('=').append(value); -+ private void appendLongIfEnabled( -+ StringBuilder b, MetricAttribute metricAttribute, Supplier valueSupplier) { -+ if (!getDisabledMetricAttributes().contains(metricAttribute)) { -+ append(b, metricAttribute.getCode(), valueSupplier.get()); - } -+ } - -- @Override -- public String getRateUnit() { -- return "events/" + super.getRateUnit(); -+ private void appendDoubleIfEnabled( -+ StringBuilder b, MetricAttribute metricAttribute, Supplier valueSupplier) { -+ if (!getDisabledMetricAttributes().contains(metricAttribute)) { -+ append(b, metricAttribute.getCode(), valueSupplier.get()); - } -+ } - -- private String prefix(MetricName metricName) { -- return prefix.append(metricName).toString(); -+ private void appendCountIfEnabled(StringBuilder b, Counting counting) { -+ if (!getDisabledMetricAttributes().contains(COUNT)) { -+ append(b, COUNT.getCode(), counting.getCount()); -+ } -+ } -+ -+ private void appendMetered(StringBuilder b, Metered meter) { -+ appendRateIfEnabled(b, M1_RATE, meter::getOneMinuteRate); -+ appendRateIfEnabled(b, M5_RATE, meter::getFiveMinuteRate); -+ appendRateIfEnabled(b, M15_RATE, meter::getFifteenMinuteRate); -+ appendRateIfEnabled(b, MEAN_RATE, meter::getMeanRate); -+ } -+ -+ private void appendRateIfEnabled( -+ StringBuilder b, MetricAttribute metricAttribute, Supplier rateSupplier) { -+ if (!getDisabledMetricAttributes().contains(metricAttribute)) { -+ append(b, metricAttribute.getCode(), convertRate(rateSupplier.get())); - } -+ } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); -- /* private class to allow logger configuration */ -- static abstract class LoggerProxy { -- protected final Logger logger; -+ private void append(StringBuilder b, String key, long value) { -+ b.append(", ").append(key).append('=').append(value); -+ } + elapseMinute(ewma); -- public LoggerProxy(Logger logger) { -- this.logger = logger; -- } -+ private void append(StringBuilder b, String key, double value) { -+ b.append(", ").append(key).append('=').append(value); -+ } - -- abstract void log(Marker marker, String format); -+ private void append(StringBuilder b, String key, String value) { -+ b.append(", ").append(key).append('=').append(value); -+ } - -- abstract boolean isEnabled(Marker marker); -+ private void append(StringBuilder b, String key, Object value) { -+ b.append(", ").append(key).append('=').append(value); -+ } -+ -+ @Override -+ public String getRateUnit() { -+ return "events/" + super.getRateUnit(); -+ } -+ -+ private String prefix(MetricName metricName) { -+ return prefix.append(metricName).toString(); -+ } -+ -+ /* private class to allow logger configuration */ -+ abstract static class LoggerProxy { -+ protected final Logger logger; -+ -+ public LoggerProxy(Logger logger) { -+ this.logger = logger; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); -- /* private class to allow logger configuration */ -- private static class DebugLoggerProxy extends LoggerProxy { -- public DebugLoggerProxy(Logger logger) { -- super(logger); -- } -+ abstract void log(Marker marker, String format); + elapseMinute(ewma); -- @Override -- public void log(Marker marker, String format) { -- logger.debug(marker, format); -- } -+ abstract boolean isEnabled(Marker marker); -+ } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.18071653, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001)); -- @Override -- public boolean isEnabled(Marker marker) { -- return logger.isDebugEnabled(marker); -- } -+ /* private class to allow logger configuration */ -+ private static class DebugLoggerProxy extends LoggerProxy { -+ public DebugLoggerProxy(Logger logger) { -+ super(logger); - } + elapseMinute(ewma); -- /* private class to allow logger configuration */ -- private static class TraceLoggerProxy extends LoggerProxy { -- public TraceLoggerProxy(Logger logger) { -- super(logger); -- } -+ @Override -+ public void log(Marker marker, String format) { -+ logger.debug(marker, format); -+ } - -- @Override -- public void log(Marker marker, String format) { -- logger.trace(marker, format); -- } -+ @Override -+ public boolean isEnabled(Marker marker) { -+ return logger.isDebugEnabled(marker); -+ } -+ } -+ -+ /* private class to allow logger configuration */ -+ private static class TraceLoggerProxy extends LoggerProxy { -+ public TraceLoggerProxy(Logger logger) { -+ super(logger); -+ } - -- @Override -- public boolean isEnabled(Marker marker) { -- return logger.isTraceEnabled(marker); -- } -+ @Override -+ public void log(Marker marker, String format) { -+ logger.trace(marker, format); - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.14795818, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001)); -- /* private class to allow logger configuration */ -- private static class InfoLoggerProxy extends LoggerProxy { -- public InfoLoggerProxy(Logger logger) { -- super(logger); -- } -+ @Override -+ public boolean isEnabled(Marker marker) { -+ return logger.isTraceEnabled(marker); -+ } -+ } - -- @Override -- public void log(Marker marker, String format) { -- logger.info(marker, format); -- } -+ /* private class to allow logger configuration */ -+ private static class InfoLoggerProxy extends LoggerProxy { -+ public InfoLoggerProxy(Logger logger) { -+ super(logger); -+ } - -- @Override -- public boolean isEnabled(Marker marker) { -- return logger.isInfoEnabled(marker); -- } -+ @Override -+ public void log(Marker marker, String format) { -+ logger.info(marker, format); - } + elapseMinute(ewma); -- /* private class to allow logger configuration */ -- private static class WarnLoggerProxy extends LoggerProxy { -- public WarnLoggerProxy(Logger logger) { -- super(logger); -- } -+ @Override -+ public boolean isEnabled(Marker marker) { -+ return logger.isInfoEnabled(marker); -+ } -+ } - -- @Override -- public void log(Marker marker, String format) { -- logger.warn(marker, format); -- } -+ /* private class to allow logger configuration */ -+ private static class WarnLoggerProxy extends LoggerProxy { -+ public WarnLoggerProxy(Logger logger) { -+ super(logger); -+ } - -- @Override -- public boolean isEnabled(Marker marker) { -- return logger.isWarnEnabled(marker); -- } -+ @Override -+ public void log(Marker marker, String format) { -+ logger.warn(marker, format); - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.12113791, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001)); -- /* private class to allow logger configuration */ -- private static class ErrorLoggerProxy extends LoggerProxy { -- public ErrorLoggerProxy(Logger logger) { -- super(logger); -- } -+ @Override -+ public boolean isEnabled(Marker marker) { -+ return logger.isWarnEnabled(marker); -+ } -+ } - -- @Override -- public void log(Marker marker, String format) { -- logger.error(marker, format); -- } -+ /* private class to allow logger configuration */ -+ private static class ErrorLoggerProxy extends LoggerProxy { -+ public ErrorLoggerProxy(Logger logger) { -+ super(logger); -+ } - -- @Override -- public boolean isEnabled(Marker marker) { -- return logger.isErrorEnabled(marker); -- } -+ @Override -+ public void log(Marker marker, String format) { -+ logger.error(marker, format); - } + elapseMinute(ewma); -+ @Override -+ public boolean isEnabled(Marker marker) { -+ return logger.isErrorEnabled(marker); -+ } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoir.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoir.java -@@ -4,98 +4,98 @@ import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicLong; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.09917933, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001)); - /** -- * A {@link Reservoir} implementation backed by a sliding window that stores only the measurements made -- * in the last {@code N} seconds (or other time unit). -+ * A {@link Reservoir} implementation backed by a sliding window that stores only the measurements -+ * made in the last {@code N} seconds (or other time unit). - */ - public class SlidingTimeWindowArrayReservoir implements Reservoir { -- // allow for this many duplicate ticks before overwriting measurements -- private static final long COLLISION_BUFFER = 256L; -- // only trim on updating once every N -- private static final long TRIM_THRESHOLD = 256L; -- private static final long CLEAR_BUFFER = TimeUnit.HOURS.toNanos(1) * COLLISION_BUFFER; -+ // allow for this many duplicate ticks before overwriting measurements -+ private static final long COLLISION_BUFFER = 256L; -+ // only trim on updating once every N -+ private static final long TRIM_THRESHOLD = 256L; -+ private static final long CLEAR_BUFFER = TimeUnit.HOURS.toNanos(1) * COLLISION_BUFFER; - -- private final Clock clock; -- private final ChunkedAssociativeLongArray measurements; -- private final long window; -- private final AtomicLong lastTick; -- private final AtomicLong count; -- private final long startTick; -+ private final Clock clock; -+ private final ChunkedAssociativeLongArray measurements; -+ private final long window; -+ private final AtomicLong lastTick; -+ private final AtomicLong count; -+ private final long startTick; - -- /** -- * Creates a new {@link SlidingTimeWindowArrayReservoir} with the given window of time. -- * -- * @param window the window of time -- * @param windowUnit the unit of {@code window} -- */ -- public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit) { -- this(window, windowUnit, Clock.defaultClock()); -- } -- -- /** -- * Creates a new {@link SlidingTimeWindowArrayReservoir} with the given clock and window of time. -- * -- * @param window the window of time -- * @param windowUnit the unit of {@code window} -- * @param clock the {@link Clock} to use -- */ -- public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit, Clock clock) { -- this.startTick = clock.getTick(); -- this.clock = clock; -- this.measurements = new ChunkedAssociativeLongArray(); -- this.window = windowUnit.toNanos(window) * COLLISION_BUFFER; -- this.lastTick = new AtomicLong((clock.getTick() - startTick) * COLLISION_BUFFER); -- this.count = new AtomicLong(); -- } -+ /** -+ * Creates a new {@link SlidingTimeWindowArrayReservoir} with the given window of time. -+ * -+ * @param window the window of time -+ * @param windowUnit the unit of {@code window} -+ */ -+ public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit) { -+ this(window, windowUnit, Clock.defaultClock()); -+ } - -- @Override -- public int size() { -- trim(); -- return measurements.size(); -- } -+ /** -+ * Creates a new {@link SlidingTimeWindowArrayReservoir} with the given clock and window of time. -+ * -+ * @param window the window of time -+ * @param windowUnit the unit of {@code window} -+ * @param clock the {@link Clock} to use -+ */ -+ public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit, Clock clock) { -+ this.startTick = clock.getTick(); -+ this.clock = clock; -+ this.measurements = new ChunkedAssociativeLongArray(); -+ this.window = windowUnit.toNanos(window) * COLLISION_BUFFER; -+ this.lastTick = new AtomicLong((clock.getTick() - startTick) * COLLISION_BUFFER); -+ this.count = new AtomicLong(); -+ } - -- @Override -- public void update(long value) { -- long newTick; -- do { -- if (count.incrementAndGet() % TRIM_THRESHOLD == 0L) { -- trim(); -- } -- long lastTick = this.lastTick.get(); -- newTick = getTick(); -- boolean longOverflow = newTick < lastTick; -- if (longOverflow) { -- measurements.clear(); -- } -- } while (!measurements.put(newTick, value)); -- } -+ @Override -+ public int size() { -+ trim(); -+ return measurements.size(); -+ } - -- @Override -- public Snapshot getSnapshot() { -+ @Override -+ public void update(long value) { -+ long newTick; -+ do { -+ if (count.incrementAndGet() % TRIM_THRESHOLD == 0L) { - trim(); -- return new UniformSnapshot(measurements.values()); -- } -+ } -+ long lastTick = this.lastTick.get(); -+ newTick = getTick(); -+ boolean longOverflow = newTick < lastTick; -+ if (longOverflow) { -+ measurements.clear(); -+ } -+ } while (!measurements.put(newTick, value)); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ trim(); -+ return new UniformSnapshot(measurements.values()); -+ } - -- private long getTick() { -- for ( ;; ) { -- final long oldTick = lastTick.get(); -- final long tick = (clock.getTick() - startTick) * COLLISION_BUFFER; -- // ensure the tick is strictly incrementing even if there are duplicate ticks -- final long newTick = tick - oldTick > 0L ? tick : oldTick + 1L; -- if (lastTick.compareAndSet(oldTick, newTick)) { -- return newTick; -- } -- } -+ private long getTick() { -+ for (; ; ) { -+ final long oldTick = lastTick.get(); -+ final long tick = (clock.getTick() - startTick) * COLLISION_BUFFER; -+ // ensure the tick is strictly incrementing even if there are duplicate ticks -+ final long newTick = tick - oldTick > 0L ? tick : oldTick + 1L; -+ if (lastTick.compareAndSet(oldTick, newTick)) { -+ return newTick; -+ } - } -+ } - -- void trim() { -- final long now = getTick(); -- final long windowStart = now - window; -- final long windowEnd = now + CLEAR_BUFFER; -- if (windowStart < windowEnd) { -- measurements.trim(windowStart, windowEnd); -- } else { -- // long overflow handling that can happen only after 1 year after class loading -- measurements.clear(); -- } -+ void trim() { -+ final long now = getTick(); -+ final long windowStart = now - window; -+ final long windowEnd = now + CLEAR_BUFFER; -+ if (windowStart < windowEnd) { -+ measurements.trim(windowStart, windowEnd); -+ } else { -+ // long overflow handling that can happen only after 1 year after class loading -+ measurements.clear(); - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java -@@ -8,197 +8,189 @@ import java.util.concurrent.atomic.AtomicLong; - import java.util.concurrent.atomic.LongAdder; + elapseMinute(ewma); - /** -- * A triple of simple moving average rates (one, five and fifteen minutes rates) as needed by {@link Meter}. -- *

    -- * The averages are unweighted, i.e. they include strictly only the events in the -- * sliding time window, every event having the same weight. Unlike the -- * the more widely used {@link ExponentialMovingAverages} implementation, -- * with this class the moving average rate drops immediately to zero if the last -- * marked event is older than the time window. -- *

    -- * A {@link Meter} with {@link SlidingTimeWindowMovingAverages} works similarly to -- * a {@link Histogram} with an {@link SlidingTimeWindowArrayReservoir}, but as a Meter -- * needs to keep track only of the count of events (not the events itself), the memory -- * overhead is much smaller. SlidingTimeWindowMovingAverages uses buckets with just one -- * counter to accumulate the number of events (one bucket per seconds, giving 900 buckets -- * for the 15 minutes time window). -+ * A triple of simple moving average rates (one, five and fifteen minutes rates) as needed by {@link -+ * Meter}. -+ * -+ *

    The averages are unweighted, i.e. they include strictly only the events in the sliding time -+ * window, every event having the same weight. Unlike the the more widely used {@link -+ * ExponentialMovingAverages} implementation, with this class the moving average rate drops -+ * immediately to zero if the last marked event is older than the time window. -+ * -+ *

    A {@link Meter} with {@link SlidingTimeWindowMovingAverages} works similarly to a {@link -+ * Histogram} with an {@link SlidingTimeWindowArrayReservoir}, but as a Meter needs to keep track -+ * only of the count of events (not the events itself), the memory overhead is much smaller. -+ * SlidingTimeWindowMovingAverages uses buckets with just one counter to accumulate the number of -+ * events (one bucket per seconds, giving 900 buckets for the 15 minutes time window). - */ - public class SlidingTimeWindowMovingAverages implements MovingAverages { +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); -- private static final long TIME_WINDOW_DURATION_MINUTES = 15; -- private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(1); -- private static final Duration TIME_WINDOW_DURATION = Duration.ofMinutes(TIME_WINDOW_DURATION_MINUTES); -- -- // package private for the benefit of the unit test -- static final int NUMBER_OF_BUCKETS = (int) (TIME_WINDOW_DURATION.toNanos() / TICK_INTERVAL); -- -- private final AtomicLong lastTick; -- private final Clock clock; -- private final LongAdder sum = new LongAdder(); -- -- /** -- * One counter per time bucket/slot (i.e. per second, see TICK_INTERVAL) for the entire -- * time window (i.e. 15 minutes, see TIME_WINDOW_DURATION_MINUTES) -- */ -- private ArrayList buckets; -- -- /** -- * Index into buckets, pointing at the bucket containing the oldest counts -- */ -- private int oldestBucketIndex; -- -- /** -- * Index into buckets, pointing at the bucket with the count for the current time (tick) -- */ -- private int currentBucketIndex; -- -- /** -- * Instant at creation time of the time window. Used to calculate the currentBucketIndex -- * for the instant of a given tick (instant modulo time window duration) -- */ -- private final Instant bucketBaseTime; -- -- /** -- * Instant of the bucket with index oldestBucketIndex -- */ -- Instant oldestBucketTime; -- -- /** -- * Creates a new {@link SlidingTimeWindowMovingAverages}. -- */ -- public SlidingTimeWindowMovingAverages() { -- this(Clock.defaultClock()); -+ private static final long TIME_WINDOW_DURATION_MINUTES = 15; -+ private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(1); -+ private static final Duration TIME_WINDOW_DURATION = -+ Duration.ofMinutes(TIME_WINDOW_DURATION_MINUTES); -+ -+ // package private for the benefit of the unit test -+ static final int NUMBER_OF_BUCKETS = (int) (TIME_WINDOW_DURATION.toNanos() / TICK_INTERVAL); -+ -+ private final AtomicLong lastTick; -+ private final Clock clock; -+ private final LongAdder sum = new LongAdder(); -+ -+ /** -+ * One counter per time bucket/slot (i.e. per second, see TICK_INTERVAL) for the entire time -+ * window (i.e. 15 minutes, see TIME_WINDOW_DURATION_MINUTES) -+ */ -+ private ArrayList buckets; -+ -+ /** Index into buckets, pointing at the bucket containing the oldest counts */ -+ private int oldestBucketIndex; -+ -+ /** Index into buckets, pointing at the bucket with the count for the current time (tick) */ -+ private int currentBucketIndex; -+ -+ /** -+ * Instant at creation time of the time window. Used to calculate the currentBucketIndex for the -+ * instant of a given tick (instant modulo time window duration) -+ */ -+ private final Instant bucketBaseTime; -+ -+ /** Instant of the bucket with index oldestBucketIndex */ -+ Instant oldestBucketTime; -+ -+ /** Creates a new {@link SlidingTimeWindowMovingAverages}. */ -+ public SlidingTimeWindowMovingAverages() { -+ this(Clock.defaultClock()); -+ } -+ -+ /** -+ * Creates a new {@link SlidingTimeWindowMovingAverages}. -+ * -+ * @param clock the clock to use for the meter ticks -+ */ -+ public SlidingTimeWindowMovingAverages(Clock clock) { -+ this.clock = clock; -+ final long startTime = clock.getTick(); -+ lastTick = new AtomicLong(startTime); -+ -+ buckets = new ArrayList<>(NUMBER_OF_BUCKETS); -+ for (int i = 0; i < NUMBER_OF_BUCKETS; i++) { -+ buckets.add(new LongAdder()); - } -- -- /** -- * Creates a new {@link SlidingTimeWindowMovingAverages}. -- * -- * @param clock the clock to use for the meter ticks -- */ -- public SlidingTimeWindowMovingAverages(Clock clock) { -- this.clock = clock; -- final long startTime = clock.getTick(); -- lastTick = new AtomicLong(startTime); -- -- buckets = new ArrayList<>(NUMBER_OF_BUCKETS); -- for (int i = 0; i < NUMBER_OF_BUCKETS; i++) { -- buckets.add(new LongAdder()); -- } -- bucketBaseTime = Instant.ofEpochSecond(0L, startTime); -- oldestBucketTime = bucketBaseTime; -- oldestBucketIndex = 0; -- currentBucketIndex = 0; -- } -- -- @Override -- public void update(long n) { -- buckets.get(currentBucketIndex).add(n); -- } -- -- @Override -- public void tickIfNecessary() { -- final long oldTick = lastTick.get(); -- final long newTick = clock.getTick(); -- final long age = newTick - oldTick; -- if (age >= TICK_INTERVAL) { -- // - the newTick doesn't fall into the same slot as the oldTick anymore -- // - newLastTick is the lower border time of the new currentBucketIndex slot -- final long newLastTick = newTick - age % TICK_INTERVAL; -- if (lastTick.compareAndSet(oldTick, newLastTick)) { -- sum.add(age); -- Instant currentInstant = Instant.ofEpochSecond(0L, newLastTick); -- currentBucketIndex = normalizeIndex(calculateIndexOfTick(currentInstant)); -- cleanOldBuckets(currentInstant); -- } -- } -- } -- -- @Override -- public double getM15Rate() { -- return getMinuteRate(15); -- } -- -- @Override -- public double getM5Rate() { -- return getMinuteRate(5); -- } -- -- @Override -- public double getM1Rate() { -- return getMinuteRate(1); -- } -- -- private double getMinuteRate(int minutes) { -- Instant now = Instant.ofEpochSecond(0L, lastTick.get()); -- return sumBuckets(now, (int) (TimeUnit.MINUTES.toNanos(minutes) / TICK_INTERVAL)); -- } -- -- int calculateIndexOfTick(Instant tickTime) { -- return (int) (Duration.between(bucketBaseTime, tickTime).toNanos() / TICK_INTERVAL); -+ bucketBaseTime = Instant.ofEpochSecond(0L, startTime); -+ oldestBucketTime = bucketBaseTime; -+ oldestBucketIndex = 0; -+ currentBucketIndex = 0; -+ } -+ -+ @Override -+ public void update(long n) { -+ buckets.get(currentBucketIndex).add(n); -+ } -+ -+ @Override -+ public void tickIfNecessary() { -+ final long oldTick = lastTick.get(); -+ final long newTick = clock.getTick(); -+ final long age = newTick - oldTick; -+ if (age >= TICK_INTERVAL) { -+ // - the newTick doesn't fall into the same slot as the oldTick anymore -+ // - newLastTick is the lower border time of the new currentBucketIndex slot -+ final long newLastTick = newTick - age % TICK_INTERVAL; -+ if (lastTick.compareAndSet(oldTick, newLastTick)) { -+ sum.add(age); -+ Instant currentInstant = Instant.ofEpochSecond(0L, newLastTick); -+ currentBucketIndex = normalizeIndex(calculateIndexOfTick(currentInstant)); -+ cleanOldBuckets(currentInstant); -+ } - } -- -- int normalizeIndex(int index) { -- int mod = index % NUMBER_OF_BUCKETS; -- return mod >= 0 ? mod : mod + NUMBER_OF_BUCKETS; -+ } -+ -+ @Override -+ public double getM15Rate() { -+ return getMinuteRate(15); -+ } -+ -+ @Override -+ public double getM5Rate() { -+ return getMinuteRate(5); -+ } -+ -+ @Override -+ public double getM1Rate() { -+ return getMinuteRate(1); -+ } -+ -+ private double getMinuteRate(int minutes) { -+ Instant now = Instant.ofEpochSecond(0L, lastTick.get()); -+ return sumBuckets(now, (int) (TimeUnit.MINUTES.toNanos(minutes) / TICK_INTERVAL)); -+ } -+ -+ int calculateIndexOfTick(Instant tickTime) { -+ return (int) (Duration.between(bucketBaseTime, tickTime).toNanos() / TICK_INTERVAL); -+ } -+ -+ int normalizeIndex(int index) { -+ int mod = index % NUMBER_OF_BUCKETS; -+ return mod >= 0 ? mod : mod + NUMBER_OF_BUCKETS; -+ } -+ -+ private void cleanOldBuckets(Instant currentTick) { -+ int newOldestIndex; -+ Instant oldestStillNeededTime = -+ currentTick.minus(TIME_WINDOW_DURATION).plusNanos(TICK_INTERVAL); -+ Instant youngestNotInWindow = oldestBucketTime.plus(TIME_WINDOW_DURATION); -+ if (oldestStillNeededTime.isAfter(youngestNotInWindow)) { -+ // there was no update() call for more than two whole TIME_WINDOW_DURATION -+ newOldestIndex = oldestBucketIndex; -+ oldestBucketTime = currentTick; -+ } else if (oldestStillNeededTime.isAfter(oldestBucketTime)) { -+ newOldestIndex = normalizeIndex(calculateIndexOfTick(oldestStillNeededTime)); -+ oldestBucketTime = oldestStillNeededTime; -+ } else { -+ return; - } + elapseMinute(ewma); -- private void cleanOldBuckets(Instant currentTick) { -- int newOldestIndex; -- Instant oldestStillNeededTime = currentTick.minus(TIME_WINDOW_DURATION).plusNanos(TICK_INTERVAL); -- Instant youngestNotInWindow = oldestBucketTime.plus(TIME_WINDOW_DURATION); -- if (oldestStillNeededTime.isAfter(youngestNotInWindow)) { -- // there was no update() call for more than two whole TIME_WINDOW_DURATION -- newOldestIndex = oldestBucketIndex; -- oldestBucketTime = currentTick; -- } else if (oldestStillNeededTime.isAfter(oldestBucketTime)) { -- newOldestIndex = normalizeIndex(calculateIndexOfTick(oldestStillNeededTime)); -- oldestBucketTime = oldestStillNeededTime; -- } else { -- return; -- } -- -- cleanBucketRange(oldestBucketIndex, newOldestIndex); -- oldestBucketIndex = newOldestIndex; -+ cleanBucketRange(oldestBucketIndex, newOldestIndex); -+ oldestBucketIndex = newOldestIndex; -+ } -+ -+ private void cleanBucketRange(int fromIndex, int toIndex) { -+ if (fromIndex < toIndex) { -+ for (int i = fromIndex; i < toIndex; i++) { -+ buckets.get(i).reset(); -+ } -+ } else { -+ for (int i = fromIndex; i < NUMBER_OF_BUCKETS; i++) { -+ buckets.get(i).reset(); -+ } -+ for (int i = 0; i < toIndex; i++) { -+ buckets.get(i).reset(); -+ } - } -- -- private void cleanBucketRange(int fromIndex, int toIndex) { -- if (fromIndex < toIndex) { -- for (int i = fromIndex; i < toIndex; i++) { -- buckets.get(i).reset(); -- } -- } else { -- for (int i = fromIndex; i < NUMBER_OF_BUCKETS; i++) { -- buckets.get(i).reset(); -- } -- for (int i = 0; i < toIndex; i++) { -- buckets.get(i).reset(); -- } -- } -+ } -+ -+ private long sumBuckets(Instant toTime, int numberOfBuckets) { -+ -+ // increment toIndex to include the current bucket into the sum -+ int toIndex = normalizeIndex(calculateIndexOfTick(toTime) + 1); -+ int fromIndex = normalizeIndex(toIndex - numberOfBuckets); -+ LongAdder adder = new LongAdder(); -+ -+ if (fromIndex < toIndex) { -+ buckets.stream() -+ .skip(fromIndex) -+ .limit(toIndex - fromIndex) -+ .mapToLong(LongAdder::longValue) -+ .forEach(adder::add); -+ } else { -+ buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); -+ buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); - } -+ return adder.longValue(); -+ } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.06648190, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001)); -- private long sumBuckets(Instant toTime, int numberOfBuckets) { -- -- // increment toIndex to include the current bucket into the sum -- int toIndex = normalizeIndex(calculateIndexOfTick(toTime) + 1); -- int fromIndex = normalizeIndex(toIndex - numberOfBuckets); -- LongAdder adder = new LongAdder(); -- -- if (fromIndex < toIndex) { -- buckets.stream() -- .skip(fromIndex) -- .limit(toIndex - fromIndex) -- .mapToLong(LongAdder::longValue) -- .forEach(adder::add); -- } else { -- buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); -- buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); -- } -- long retval = adder.longValue(); -- return retval; -- } -- -- @Override -- public long getSum() { -- return sum.sum(); -- } -+ @Override -+ public long getSum() { -+ return sum.sum(); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowReservoir.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowReservoir.java -@@ -5,91 +5,91 @@ import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicLong; + elapseMinute(ewma); - /** -- * A {@link Reservoir} implementation backed by a sliding window that stores only the measurements made -- * in the last {@code N} seconds (or other time unit). -+ * A {@link Reservoir} implementation backed by a sliding window that stores only the measurements -+ * made in the last {@code N} seconds (or other time unit). - */ - public class SlidingTimeWindowReservoir implements Reservoir { -- // allow for this many duplicate ticks before overwriting measurements -- private static final int COLLISION_BUFFER = 256; -- // only trim on updating once every N -- private static final int TRIM_THRESHOLD = 256; -- // offsets the front of the time window for the purposes of clearing the buffer in trim -- private static final long CLEAR_BUFFER = TimeUnit.HOURS.toNanos(1) * COLLISION_BUFFER; -+ // allow for this many duplicate ticks before overwriting measurements -+ private static final int COLLISION_BUFFER = 256; -+ // only trim on updating once every N -+ private static final int TRIM_THRESHOLD = 256; -+ // offsets the front of the time window for the purposes of clearing the buffer in trim -+ private static final long CLEAR_BUFFER = TimeUnit.HOURS.toNanos(1) * COLLISION_BUFFER; - -- private final Clock clock; -- private final ConcurrentSkipListMap measurements; -- private final long window; -- private final AtomicLong lastTick; -- private final AtomicLong count; -- private final long startTick; -+ private final Clock clock; -+ private final ConcurrentSkipListMap measurements; -+ private final long window; -+ private final AtomicLong lastTick; -+ private final AtomicLong count; -+ private final long startTick; - -- /** -- * Creates a new {@link SlidingTimeWindowReservoir} with the given window of time. -- * -- * @param window the window of time -- * @param windowUnit the unit of {@code window} -- */ -- public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit) { -- this(window, windowUnit, Clock.defaultClock()); -- } -+ /** -+ * Creates a new {@link SlidingTimeWindowReservoir} with the given window of time. -+ * -+ * @param window the window of time -+ * @param windowUnit the unit of {@code window} -+ */ -+ public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit) { -+ this(window, windowUnit, Clock.defaultClock()); -+ } - -- /** -- * Creates a new {@link SlidingTimeWindowReservoir} with the given clock and window of time. -- * -- * @param window the window of time -- * @param windowUnit the unit of {@code window} -- * @param clock the {@link Clock} to use -- */ -- public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) { -- this.startTick = clock.getTick(); -- this.clock = clock; -- this.measurements = new ConcurrentSkipListMap<>(); -- this.window = windowUnit.toNanos(window) * COLLISION_BUFFER; -- this.lastTick = new AtomicLong((clock.getTick() - startTick) * COLLISION_BUFFER); -- this.count = new AtomicLong(); -- } -+ /** -+ * Creates a new {@link SlidingTimeWindowReservoir} with the given clock and window of time. -+ * -+ * @param window the window of time -+ * @param windowUnit the unit of {@code window} -+ * @param clock the {@link Clock} to use -+ */ -+ public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) { -+ this.startTick = clock.getTick(); -+ this.clock = clock; -+ this.measurements = new ConcurrentSkipListMap<>(); -+ this.window = windowUnit.toNanos(window) * COLLISION_BUFFER; -+ this.lastTick = new AtomicLong((clock.getTick() - startTick) * COLLISION_BUFFER); -+ this.count = new AtomicLong(); -+ } - -- @Override -- public int size() { -- trim(); -- return measurements.size(); -- } -+ @Override -+ public int size() { -+ trim(); -+ return measurements.size(); -+ } - -- @Override -- public void update(long value) { -- if (count.incrementAndGet() % TRIM_THRESHOLD == 0) { -- trim(); -- } -- measurements.put(getTick(), value); -+ @Override -+ public void update(long value) { -+ if (count.incrementAndGet() % TRIM_THRESHOLD == 0) { -+ trim(); - } -+ measurements.put(getTick(), value); -+ } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.05443077, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001)); -- @Override -- public Snapshot getSnapshot() { -- trim(); -- return new UniformSnapshot(measurements.values()); -- } -+ @Override -+ public Snapshot getSnapshot() { -+ trim(); -+ return new UniformSnapshot(measurements.values()); -+ } - -- private long getTick() { -- for ( ;; ) { -- final long oldTick = lastTick.get(); -- final long tick = (clock.getTick() - startTick) * COLLISION_BUFFER; -- // ensure the tick is strictly incrementing even if there are duplicate ticks -- final long newTick = tick - oldTick > 0 ? tick : oldTick + 1; -- if (lastTick.compareAndSet(oldTick, newTick)) { -- return newTick; -- } -- } -+ private long getTick() { -+ for (; ; ) { -+ final long oldTick = lastTick.get(); -+ final long tick = (clock.getTick() - startTick) * COLLISION_BUFFER; -+ // ensure the tick is strictly incrementing even if there are duplicate ticks -+ final long newTick = tick - oldTick > 0 ? tick : oldTick + 1; -+ if (lastTick.compareAndSet(oldTick, newTick)) { -+ return newTick; -+ } - } -+ } - -- private void trim() { -- final long now = getTick(); -- final long windowStart = now - window; -- final long windowEnd = now + CLEAR_BUFFER; -- if (windowStart < windowEnd) { -- measurements.headMap(windowStart).clear(); -- measurements.tailMap(windowEnd).clear(); -- } else { -- measurements.subMap(windowEnd, windowStart).clear(); -- } -+ private void trim() { -+ final long now = getTick(); -+ final long windowStart = now - window; -+ final long windowEnd = now + CLEAR_BUFFER; -+ if (windowStart < windowEnd) { -+ measurements.headMap(windowStart).clear(); -+ measurements.tailMap(windowEnd).clear(); -+ } else { -+ measurements.subMap(windowEnd, windowStart).clear(); - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingWindowReservoir.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingWindowReservoir.java -@@ -7,37 +7,37 @@ import static java.lang.Math.min; - * measurements. - */ - public class SlidingWindowReservoir implements Reservoir { -- private final long[] measurements; -- private long count; -+ private final long[] measurements; -+ private long count; - -- /** -- * Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements. -- * -- * @param size the number of measurements to store -- */ -- public SlidingWindowReservoir(int size) { -- this.measurements = new long[size]; -- this.count = 0; -- } -+ /** -+ * Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements. -+ * -+ * @param size the number of measurements to store -+ */ -+ public SlidingWindowReservoir(int size) { -+ this.measurements = new long[size]; -+ this.count = 0; -+ } - -- @Override -- public synchronized int size() { -- return (int) min(count, measurements.length); -- } -+ @Override -+ public synchronized int size() { -+ return (int) min(count, measurements.length); -+ } - -- @Override -- public synchronized void update(long value) { -- measurements[(int) (count++ % measurements.length)] = value; -- } -+ @Override -+ public synchronized void update(long value) { -+ measurements[(int) (count++ % measurements.length)] = value; -+ } - -- @Override -- public Snapshot getSnapshot() { -- final long[] values = new long[size()]; -- for (int i = 0; i < values.length; i++) { -- synchronized (this) { -- values[i] = measurements[i]; -- } -- } -- return new UniformSnapshot(values); -+ @Override -+ public Snapshot getSnapshot() { -+ final long[] values = new long[size()]; -+ for (int i = 0; i < values.length; i++) { -+ synchronized (this) { -+ values[i] = measurements[i]; -+ } - } -+ return new UniformSnapshot(values); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Snapshot.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Snapshot.java -@@ -2,120 +2,117 @@ package io.dropwizard.metrics5; + elapseMinute(ewma); - import java.io.OutputStream; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.04456415, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001)); --/** -- * A statistical snapshot of a {@link Snapshot}. -- */ -+/** A statistical snapshot of a {@link Snapshot}. */ - public abstract class Snapshot { - -- /** -- * Returns the value at the given quantile. -- * -- * @param quantile a given quantile, in {@code [0..1]} -- * @return the value in the distribution at {@code quantile} -- */ -- public abstract double getValue(double quantile); -- -- /** -- * Returns the entire set of values in the snapshot. -- * -- * @return the entire set of values -- */ -- public abstract long[] getValues(); -- -- /** -- * Returns the number of values in the snapshot. -- * -- * @return the number of values -- */ -- public abstract int size(); -- -- /** -- * Returns the median value in the distribution. -- * -- * @return the median value -- */ -- public double getMedian() { -- return getValue(0.5); -- } -- -- /** -- * Returns the value at the 75th percentile in the distribution. -- * -- * @return the value at the 75th percentile -- */ -- public double get75thPercentile() { -- return getValue(0.75); -- } -- -- /** -- * Returns the value at the 95th percentile in the distribution. -- * -- * @return the value at the 95th percentile -- */ -- public double get95thPercentile() { -- return getValue(0.95); -- } -- -- /** -- * Returns the value at the 98th percentile in the distribution. -- * -- * @return the value at the 98th percentile -- */ -- public double get98thPercentile() { -- return getValue(0.98); -- } -- -- /** -- * Returns the value at the 99th percentile in the distribution. -- * -- * @return the value at the 99th percentile -- */ -- public double get99thPercentile() { -- return getValue(0.99); -- } -- -- /** -- * Returns the value at the 99.9th percentile in the distribution. -- * -- * @return the value at the 99.9th percentile -- */ -- public double get999thPercentile() { -- return getValue(0.999); -- } -- -- /** -- * Returns the highest value in the snapshot. -- * -- * @return the highest value -- */ -- public abstract long getMax(); -- -- /** -- * Returns the arithmetic mean of the values in the snapshot. -- * -- * @return the arithmetic mean -- */ -- public abstract double getMean(); -- -- /** -- * Returns the lowest value in the snapshot. -- * -- * @return the lowest value -- */ -- public abstract long getMin(); -- -- /** -- * Returns the standard deviation of the values in the snapshot. -- * -- * @return the standard value -- */ -- public abstract double getStdDev(); -- -- /** -- * Writes the values of the snapshot to the given stream. -- * -- * @param output an output stream -- */ -- public abstract void dump(OutputStream output); -- -+ /** -+ * Returns the value at the given quantile. -+ * -+ * @param quantile a given quantile, in {@code [0..1]} -+ * @return the value in the distribution at {@code quantile} -+ */ -+ public abstract double getValue(double quantile); -+ -+ /** -+ * Returns the entire set of values in the snapshot. -+ * -+ * @return the entire set of values -+ */ -+ public abstract long[] getValues(); -+ -+ /** -+ * Returns the number of values in the snapshot. -+ * -+ * @return the number of values -+ */ -+ public abstract int size(); -+ -+ /** -+ * Returns the median value in the distribution. -+ * -+ * @return the median value -+ */ -+ public double getMedian() { -+ return getValue(0.5); -+ } -+ -+ /** -+ * Returns the value at the 75th percentile in the distribution. -+ * -+ * @return the value at the 75th percentile -+ */ -+ public double get75thPercentile() { -+ return getValue(0.75); -+ } -+ -+ /** -+ * Returns the value at the 95th percentile in the distribution. -+ * -+ * @return the value at the 95th percentile -+ */ -+ public double get95thPercentile() { -+ return getValue(0.95); -+ } -+ -+ /** -+ * Returns the value at the 98th percentile in the distribution. -+ * -+ * @return the value at the 98th percentile -+ */ -+ public double get98thPercentile() { -+ return getValue(0.98); -+ } -+ -+ /** -+ * Returns the value at the 99th percentile in the distribution. -+ * -+ * @return the value at the 99th percentile -+ */ -+ public double get99thPercentile() { -+ return getValue(0.99); -+ } -+ -+ /** -+ * Returns the value at the 99.9th percentile in the distribution. -+ * -+ * @return the value at the 99.9th percentile -+ */ -+ public double get999thPercentile() { -+ return getValue(0.999); -+ } -+ -+ /** -+ * Returns the highest value in the snapshot. -+ * -+ * @return the highest value -+ */ -+ public abstract long getMax(); -+ -+ /** -+ * Returns the arithmetic mean of the values in the snapshot. -+ * -+ * @return the arithmetic mean -+ */ -+ public abstract double getMean(); -+ -+ /** -+ * Returns the lowest value in the snapshot. -+ * -+ * @return the lowest value -+ */ -+ public abstract long getMin(); -+ -+ /** -+ * Returns the standard deviation of the values in the snapshot. -+ * -+ * @return the standard value -+ */ -+ public abstract double getStdDev(); -+ -+ /** -+ * Writes the values of the snapshot to the given stream. -+ * -+ * @param output an output stream -+ */ -+ public abstract void dump(OutputStream output); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Summing.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Summing.java -@@ -1,14 +1,12 @@ - package io.dropwizard.metrics5; + elapseMinute(ewma); --/** -- * An interface for metric types which aggregate a sum -- */ -+/** An interface for metric types which aggregate a sum */ - public interface Summing { - -- /** -- * Return the current sum. -- * -- * @return the current sum -- */ -- long getSum(); -+ /** -+ * Return the current sum. -+ * -+ * @return the current sum -+ */ -+ long getSum(); - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Timer.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Timer.java -@@ -10,199 +10,197 @@ import java.util.function.Supplier; - * throughput statistics via {@link Meter}. - */ - public class Timer implements Metered, Sampling { -- /** -- * A timing context. -- * -- * @see Timer#time() -- */ -- public static class Context implements AutoCloseable { -- private final Timer timer; -- private final Clock clock; -- private final long startTime; -- -- Context(Timer timer, Clock clock) { -- this.timer = timer; -- this.clock = clock; -- this.startTime = clock.getTick(); -- } -- -- /** -- * Updates the timer with the difference between current and start time. Call to this method will -- * not reset the start time. Multiple calls result in multiple updates. -- * -- * @return the elapsed time in nanoseconds -- */ -- public long stop() { -- final long elapsed = clock.getTick() - startTime; -- timer.update(elapsed, TimeUnit.NANOSECONDS); -- return elapsed; -- } -- -- /** -- * Equivalent to calling {@link #stop()}. -- */ -- @Override -- public void close() { -- stop(); -- } -- } -- -- private final Meter meter; -- private final Histogram histogram; -+ /** -+ * A timing context. -+ * -+ * @see Timer#time() -+ */ -+ public static class Context implements AutoCloseable { -+ private final Timer timer; - private final Clock clock; -+ private final long startTime; - -- /** -- * Creates a new {@link Timer} using an {@link ExponentiallyDecayingReservoir} and the default -- * {@link Clock}. -- */ -- public Timer() { -- this(new ExponentiallyDecayingReservoir()); -+ Context(Timer timer, Clock clock) { -+ this.timer = timer; -+ this.clock = clock; -+ this.startTime = clock.getTick(); - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.03648604, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001)); - /** -- * Creates a new {@link Timer} that uses the given {@link Reservoir}. -+ * Updates the timer with the difference between current and start time. Call to this method -+ * will not reset the start time. Multiple calls result in multiple updates. - * -- * @param reservoir the {@link Reservoir} implementation the timer should use -+ * @return the elapsed time in nanoseconds - */ -- public Timer(Reservoir reservoir) { -- this(reservoir, Clock.defaultClock()); -- } -- -- /** -- * Creates a new {@link Timer} that uses the given {@link Reservoir} and {@link Clock}. -- * -- * @param reservoir the {@link Reservoir} implementation the timer should use -- * @param clock the {@link Clock} implementation the timer should use -- */ -- public Timer(Reservoir reservoir, Clock clock) { -- this(new Meter(clock), new Histogram(reservoir), clock); -- } -- -- public Timer(Meter meter, Histogram histogram, Clock clock) { -- this.meter = meter; -- this.histogram = histogram; -- this.clock = clock; -- } -- -- /** -- * Adds a recorded duration. -- * -- * @param duration the length of the duration -- * @param unit the scale unit of {@code duration} -- */ -- public void update(long duration, TimeUnit unit) { -- update(unit.toNanos(duration)); -- } -- -- /** -- * Adds a recorded duration. -- * -- * @param duration the {@link Duration} to add to the timer. Negative or zero value are ignored. -- */ -- public void update(Duration duration) { -- update(duration.toNanos()); -- } -- -- /** -- * Times and records the duration of event. -- * -- * @param event a {@link Callable} whose {@link Callable#call()} method implements a process -- * whose duration should be timed -- * @param the type of the value returned by {@code event} -- * @return the value returned by {@code event} -- * @throws Exception if {@code event} throws an {@link Exception} -- */ -- public T time(Callable event) throws Exception { -- final long startTime = clock.getTick(); -- try { -- return event.call(); -- } finally { -- update(clock.getTick() - startTime); -- } -- } -- -- /** -- * Times and records the duration of event. Should not throw exceptions, for that use the -- * {@link #time(Callable)} method. -- * -- * @param event a {@link Supplier} whose {@link Supplier#get()} method implements a process -- * whose duration should be timed -- * @param the type of the value returned by {@code event} -- * @return the value returned by {@code event} -- */ -- public T timeSupplier(Supplier event) { -- final long startTime = clock.getTick(); -- try { -- return event.get(); -- } finally { -- update(clock.getTick() - startTime); -- } -- } -- -- /** -- * Times and records the duration of event. -- * -- * @param event a {@link Runnable} whose {@link Runnable#run()} method implements a process -- * whose duration should be timed -- */ -- public void time(Runnable event) { -- final long startTime = clock.getTick(); -- try { -- event.run(); -- } finally { -- update(clock.getTick() - startTime); -- } -- } -- -- /** -- * Returns a new {@link Context}. -- * -- * @return a new {@link Context} -- * @see Context -- */ -- public Context time() { -- return new Context(this, clock); -- } -- -- @Override -- public long getCount() { -- return histogram.getCount(); -- } -- -- @Override -- public long getSum() { -- return histogram.getSum(); -- } -- -- @Override -- public double getFifteenMinuteRate() { -- return meter.getFifteenMinuteRate(); -- } -- -- @Override -- public double getFiveMinuteRate() { -- return meter.getFiveMinuteRate(); -- } -- -- @Override -- public double getMeanRate() { -- return meter.getMeanRate(); -- } -- -- @Override -- public double getOneMinuteRate() { -- return meter.getOneMinuteRate(); -+ public long stop() { -+ final long elapsed = clock.getTick() - startTime; -+ timer.update(elapsed, TimeUnit.NANOSECONDS); -+ return elapsed; - } + elapseMinute(ewma); -+ /** Equivalent to calling {@link #stop()}. */ - @Override -- public Snapshot getSnapshot() { -- return histogram.getSnapshot(); -- } -- -- private void update(long duration) { -- if (duration >= 0) { -- histogram.update(duration); -- meter.mark(); -- } -- } -+ public void close() { -+ stop(); -+ } -+ } -+ -+ private final Meter meter; -+ private final Histogram histogram; -+ private final Clock clock; -+ -+ /** -+ * Creates a new {@link Timer} using an {@link ExponentiallyDecayingReservoir} and the default -+ * {@link Clock}. -+ */ -+ public Timer() { -+ this(new ExponentiallyDecayingReservoir()); -+ } -+ -+ /** -+ * Creates a new {@link Timer} that uses the given {@link Reservoir}. -+ * -+ * @param reservoir the {@link Reservoir} implementation the timer should use -+ */ -+ public Timer(Reservoir reservoir) { -+ this(reservoir, Clock.defaultClock()); -+ } -+ -+ /** -+ * Creates a new {@link Timer} that uses the given {@link Reservoir} and {@link Clock}. -+ * -+ * @param reservoir the {@link Reservoir} implementation the timer should use -+ * @param clock the {@link Clock} implementation the timer should use -+ */ -+ public Timer(Reservoir reservoir, Clock clock) { -+ this(new Meter(clock), new Histogram(reservoir), clock); -+ } -+ -+ public Timer(Meter meter, Histogram histogram, Clock clock) { -+ this.meter = meter; -+ this.histogram = histogram; -+ this.clock = clock; -+ } -+ -+ /** -+ * Adds a recorded duration. -+ * -+ * @param duration the length of the duration -+ * @param unit the scale unit of {@code duration} -+ */ -+ public void update(long duration, TimeUnit unit) { -+ update(unit.toNanos(duration)); -+ } -+ -+ /** -+ * Adds a recorded duration. -+ * -+ * @param duration the {@link Duration} to add to the timer. Negative or zero value are ignored. -+ */ -+ public void update(Duration duration) { -+ update(duration.toNanos()); -+ } -+ -+ /** -+ * Times and records the duration of event. -+ * -+ * @param event a {@link Callable} whose {@link Callable#call()} method implements a process whose -+ * duration should be timed -+ * @param the type of the value returned by {@code event} -+ * @return the value returned by {@code event} -+ * @throws Exception if {@code event} throws an {@link Exception} -+ */ -+ public T time(Callable event) throws Exception { -+ final long startTime = clock.getTick(); -+ try { -+ return event.call(); -+ } finally { -+ update(clock.getTick() - startTime); -+ } -+ } -+ -+ /** -+ * Times and records the duration of event. Should not throw exceptions, for that use the {@link -+ * #time(Callable)} method. -+ * -+ * @param event a {@link Supplier} whose {@link Supplier#get()} method implements a process whose -+ * duration should be timed -+ * @param the type of the value returned by {@code event} -+ * @return the value returned by {@code event} -+ */ -+ public T timeSupplier(Supplier event) { -+ final long startTime = clock.getTick(); -+ try { -+ return event.get(); -+ } finally { -+ update(clock.getTick() - startTime); -+ } -+ } -+ -+ /** -+ * Times and records the duration of event. -+ * -+ * @param event a {@link Runnable} whose {@link Runnable#run()} method implements a process whose -+ * duration should be timed -+ */ -+ public void time(Runnable event) { -+ final long startTime = clock.getTick(); -+ try { -+ event.run(); -+ } finally { -+ update(clock.getTick() - startTime); -+ } -+ } -+ -+ /** -+ * Returns a new {@link Context}. -+ * -+ * @return a new {@link Context} -+ * @see Context -+ */ -+ public Context time() { -+ return new Context(this, clock); -+ } -+ -+ @Override -+ public long getCount() { -+ return histogram.getCount(); -+ } -+ -+ @Override -+ public long getSum() { -+ return histogram.getSum(); -+ } -+ -+ @Override -+ public double getFifteenMinuteRate() { -+ return meter.getFifteenMinuteRate(); -+ } -+ -+ @Override -+ public double getFiveMinuteRate() { -+ return meter.getFiveMinuteRate(); -+ } -+ -+ @Override -+ public double getMeanRate() { -+ return meter.getMeanRate(); -+ } -+ -+ @Override -+ public double getOneMinuteRate() { -+ return meter.getOneMinuteRate(); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ return histogram.getSnapshot(); -+ } -+ -+ private void update(long duration) { -+ if (duration >= 0) { -+ histogram.update(duration); -+ meter.mark(); -+ } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformReservoir.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformReservoir.java -@@ -11,60 +11,60 @@ import java.util.concurrent.atomic.AtomicLongArray; - * @see Random Sampling with a Reservoir - */ - public class UniformReservoir implements Reservoir { -- private static final int DEFAULT_SIZE = 1028; -- private final AtomicLong count = new AtomicLong(); -- private final AtomicLongArray values; -+ private static final int DEFAULT_SIZE = 1028; -+ private final AtomicLong count = new AtomicLong(); -+ private final AtomicLongArray values; - -- /** -- * Creates a new {@link UniformReservoir} of 1028 elements, which offers a 99.9% confidence level -- * with a 5% margin of error assuming a normal distribution. -- */ -- public UniformReservoir() { -- this(DEFAULT_SIZE); -- } -+ /** -+ * Creates a new {@link UniformReservoir} of 1028 elements, which offers a 99.9% confidence level -+ * with a 5% margin of error assuming a normal distribution. -+ */ -+ public UniformReservoir() { -+ this(DEFAULT_SIZE); -+ } - -- /** -- * Creates a new {@link UniformReservoir}. -- * -- * @param size the number of samples to keep in the sampling reservoir -- */ -- public UniformReservoir(int size) { -- this.values = new AtomicLongArray(size); -- for (int i = 0; i < values.length(); i++) { -- values.set(i, 0); -- } -- count.set(0); -+ /** -+ * Creates a new {@link UniformReservoir}. -+ * -+ * @param size the number of samples to keep in the sampling reservoir -+ */ -+ public UniformReservoir(int size) { -+ this.values = new AtomicLongArray(size); -+ for (int i = 0; i < values.length(); i++) { -+ values.set(i, 0); - } -+ count.set(0); -+ } - -- @Override -- public int size() { -- final long c = count.get(); -- if (c > values.length()) { -- return values.length(); -- } -- return (int) c; -+ @Override -+ public int size() { -+ final long c = count.get(); -+ if (c > values.length()) { -+ return values.length(); - } -+ return (int) c; -+ } - -- @Override -- public void update(long value) { -- final long c = count.incrementAndGet(); -- if (c <= values.length()) { -- values.set((int) c - 1, value); -- } else { -- final long r = ThreadLocalRandom.current().nextLong(c); -- if (r < values.length()) { -- values.set((int) r, value); -- } -- } -+ @Override -+ public void update(long value) { -+ final long c = count.incrementAndGet(); -+ if (c <= values.length()) { -+ values.set((int) c - 1, value); -+ } else { -+ final long r = ThreadLocalRandom.current().nextLong(c); -+ if (r < values.length()) { -+ values.set((int) r, value); -+ } - } -+ } - -- @Override -- public Snapshot getSnapshot() { -- final int s = size(); -- long[] copy = new long[s]; -- for (int i = 0; i < s; i++) { -- copy[i] = values.get(i); -- } -- return new UniformSnapshot(copy); -+ @Override -+ public Snapshot getSnapshot() { -+ final int s = size(); -+ long[] copy = new long[s]; -+ for (int i = 0; i < s; i++) { -+ copy[i] = values.get(i); - } -+ return new UniformSnapshot(copy); -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java -@@ -1,177 +1,178 @@ - package io.dropwizard.metrics5; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); + } -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.lang.Math.floor; -+import static java.nio.charset.StandardCharsets.UTF_8; -+ - import java.io.OutputStream; - import java.io.OutputStreamWriter; - import java.io.PrintWriter; - import java.util.Arrays; - import java.util.Collection; + @Test +@@ -151,67 +151,67 @@ class EWMATest { + ewma.update(3); + ewma.tick(); --import static java.lang.Math.floor; --import static java.nio.charset.StandardCharsets.UTF_8; -- --/** -- * A statistical snapshot of a {@link UniformSnapshot}. -- */ -+/** A statistical snapshot of a {@link UniformSnapshot}. */ - public class UniformSnapshot extends Snapshot { +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); -- private final long[] values; -- -- /** -- * Create a new {@link Snapshot} with the given values. -- * -- * @param values an unordered set of values in the reservoir -- */ -- public UniformSnapshot(Collection values) { -- final Object[] copy = values.toArray(); -- this.values = new long[copy.length]; -- for (int i = 0; i < copy.length; i++) { -- this.values[i] = (Long) copy[i]; -- } -- Arrays.sort(this.values); -+ private final long[] values; -+ -+ /** -+ * Create a new {@link Snapshot} with the given values. -+ * -+ * @param values an unordered set of values in the reservoir -+ */ -+ public UniformSnapshot(Collection values) { -+ final Object[] copy = values.toArray(); -+ this.values = new long[copy.length]; -+ for (int i = 0; i < copy.length; i++) { -+ this.values[i] = (Long) copy[i]; - } -- -- /** -- * Create a new {@link Snapshot} with the given values. -- * -- * @param values an unordered set of values in the reservoir that can be used by this class directly -- */ -- public UniformSnapshot(long[] values) { -- this.values = Arrays.copyOf(values, values.length); -- Arrays.sort(this.values); -+ Arrays.sort(this.values); -+ } -+ -+ /** -+ * Create a new {@link Snapshot} with the given values. -+ * -+ * @param values an unordered set of values in the reservoir that can be used by this class -+ * directly -+ */ -+ public UniformSnapshot(long[] values) { -+ this.values = Arrays.copyOf(values, values.length); -+ Arrays.sort(this.values); -+ } -+ -+ /** -+ * Returns the value at the given quantile. -+ * -+ * @param quantile a given quantile, in {@code [0..1]} -+ * @return the value in the distribution at {@code quantile} -+ */ -+ @Override -+ public double getValue(double quantile) { -+ checkArgument( -+ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), -+ "%s is not in [0..1]", -+ quantile); -+ -+ if (values.length == 0) { -+ return 0.0; - } + elapseMinute(ewma); -- /** -- * Returns the value at the given quantile. -- * -- * @param quantile a given quantile, in {@code [0..1]} -- * @return the value in the distribution at {@code quantile} -- */ -- @Override -- public double getValue(double quantile) { -- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { -- throw new IllegalArgumentException(quantile + " is not in [0..1]"); -- } -- -- if (values.length == 0) { -- return 0.0; -- } -- -- final double pos = quantile * (values.length + 1); -- final int index = (int) pos; -- -- if (index < 1) { -- return values[0]; -- } -- -- if (index >= values.length) { -- return values[values.length - 1]; -- } -- -- final double lower = values[index - 1]; -- final double upper = values[index]; -- return lower + (pos - floor(pos)) * (upper - lower); -- } -+ final double pos = quantile * (values.length + 1); -+ final int index = (int) pos; - -- /** -- * Returns the number of values in the snapshot. -- * -- * @return the number of values -- */ -- @Override -- public int size() { -- return values.length; -+ if (index < 1) { -+ return values[0]; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.56130419, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001)); -- /** -- * Returns the entire set of values in the snapshot. -- * -- * @return the entire set of values -- */ -- @Override -- public long[] getValues() { -- return Arrays.copyOf(values, values.length); -+ if (index >= values.length) { -+ return values[values.length - 1]; - } + elapseMinute(ewma); -- /** -- * Returns the highest value in the snapshot. -- * -- * @return the highest value -- */ -- @Override -- public long getMax() { -- if (values.length == 0) { -- return 0; -- } -- return values[values.length - 1]; -+ final double lower = values[index - 1]; -+ final double upper = values[index]; -+ return lower + (pos - floor(pos)) * (upper - lower); -+ } -+ -+ /** -+ * Returns the number of values in the snapshot. -+ * -+ * @return the number of values -+ */ -+ @Override -+ public int size() { -+ return values.length; -+ } -+ -+ /** -+ * Returns the entire set of values in the snapshot. -+ * -+ * @return the entire set of values -+ */ -+ @Override -+ public long[] getValues() { -+ return Arrays.copyOf(values, values.length); -+ } -+ -+ /** -+ * Returns the highest value in the snapshot. -+ * -+ * @return the highest value -+ */ -+ @Override -+ public long getMax() { -+ if (values.length == 0) { -+ return 0; - } -- -- /** -- * Returns the lowest value in the snapshot. -- * -- * @return the lowest value -- */ -- @Override -- public long getMin() { -- if (values.length == 0) { -- return 0; -- } -- return values[0]; -+ return values[values.length - 1]; -+ } -+ -+ /** -+ * Returns the lowest value in the snapshot. -+ * -+ * @return the lowest value -+ */ -+ @Override -+ public long getMin() { -+ if (values.length == 0) { -+ return 0; -+ } -+ return values[0]; -+ } -+ -+ /** -+ * Returns the arithmetic mean of the values in the snapshot. -+ * -+ * @return the arithmetic mean -+ */ -+ @Override -+ public double getMean() { -+ if (values.length == 0) { -+ return 0; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.52510399, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001)); -- /** -- * Returns the arithmetic mean of the values in the snapshot. -- * -- * @return the arithmetic mean -- */ -- @Override -- public double getMean() { -- if (values.length == 0) { -- return 0; -- } -- -- double sum = 0; -- for (long value : values) { -- sum += value; -- } -- return sum / values.length; -+ double sum = 0; -+ for (long value : values) { -+ sum += value; -+ } -+ return sum / values.length; -+ } -+ -+ /** -+ * Returns the standard deviation of the values in the snapshot. -+ * -+ * @return the standard deviation value -+ */ -+ @Override -+ public double getStdDev() { -+ // two-pass algorithm for variance, avoids numeric overflow -+ -+ if (values.length <= 1) { -+ return 0; - } + elapseMinute(ewma); -- /** -- * Returns the standard deviation of the values in the snapshot. -- * -- * @return the standard deviation value -- */ -- @Override -- public double getStdDev() { -- // two-pass algorithm for variance, avoids numeric overflow -- -- if (values.length <= 1) { -- return 0; -- } -- -- final double mean = getMean(); -- double sum = 0; -- -- for (long value : values) { -- final double diff = value - mean; -- sum += diff * diff; -- } -- -- final double variance = sum / (values.length - 1); -- return Math.sqrt(variance); -+ final double mean = getMean(); -+ double sum = 0; -+ -+ for (long value : values) { -+ final double diff = value - mean; -+ sum += diff * diff; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); -- /** -- * Writes the values of the snapshot to the given stream. -- * -- * @param output an output stream -- */ -- @Override -- public void dump(OutputStream output) { -- try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { -- for (long value : values) { -- out.printf("%d%n", value); -- } -- } -+ final double variance = sum / (values.length - 1); -+ return Math.sqrt(variance); -+ } -+ -+ /** -+ * Writes the values of the snapshot to the given stream. -+ * -+ * @param output an output stream -+ */ -+ @Override -+ public void dump(OutputStream output) { -+ try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { -+ for (long value : values) { -+ out.printf("%d%n", value); -+ } - } -+ } - } ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java -@@ -1,195 +1,192 @@ - package io.dropwizard.metrics5; + elapseMinute(ewma); -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.nio.charset.StandardCharsets.UTF_8; -+import static java.util.Comparator.comparingLong; -+ - import java.io.OutputStream; - import java.io.OutputStreamWriter; - import java.io.PrintWriter; - import java.util.Arrays; - import java.util.Collection; --import java.util.Comparator; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.45955700, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001)); --import static java.nio.charset.StandardCharsets.UTF_8; -- --/** -- * A statistical snapshot of a {@link WeightedSnapshot}. -- */ -+/** A statistical snapshot of a {@link WeightedSnapshot}. */ - public class WeightedSnapshot extends Snapshot { + elapseMinute(ewma); -- /** -- * A single sample item with value and its weights for {@link WeightedSnapshot}. -- */ -- public static class WeightedSample { -- public final long value; -- public final double weight; -- -- public WeightedSample(long value, double weight) { -- this.value = value; -- this.weight = weight; -- } -- } -+ /** A single sample item with value and its weights for {@link WeightedSnapshot}. */ -+ public static class WeightedSample { -+ public final long value; -+ public final double weight; - -- private final long[] values; -- private final double[] normWeights; -- private final double[] quantiles; -- -- /** -- * Create a new {@link Snapshot} with the given values. -- * -- * @param values an unordered set of values in the reservoir -- */ -- public WeightedSnapshot(Collection values) { -- final WeightedSample[] copy = values.toArray(new WeightedSample[]{}); -- -- Arrays.sort(copy, Comparator.comparingLong(w -> w.value)); -- -- this.values = new long[copy.length]; -- this.normWeights = new double[copy.length]; -- this.quantiles = new double[copy.length]; -- -- double sumWeight = 0; -- for (WeightedSample sample : copy) { -- sumWeight += sample.weight; -- } -- -- for (int i = 0; i < copy.length; i++) { -- this.values[i] = copy[i].value; -- this.normWeights[i] = sumWeight != 0 ? copy[i].weight / sumWeight : 0; -- } -- -- for (int i = 1; i < copy.length; i++) { -- this.quantiles[i] = this.quantiles[i - 1] + this.normWeights[i - 1]; -- } -+ public WeightedSample(long value, double weight) { -+ this.value = value; -+ this.weight = weight; - } -+ } - -- /** -- * Returns the value at the given quantile. -- * -- * @param quantile a given quantile, in {@code [0..1]} -- * @return the value in the distribution at {@code quantile} -- */ -- @Override -- public double getValue(double quantile) { -- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { -- throw new IllegalArgumentException(quantile + " is not in [0..1]"); -- } -- -- if (values.length == 0) { -- return 0.0; -- } -- -- int posx = Arrays.binarySearch(quantiles, quantile); -- if (posx < 0) -- posx = ((-posx) - 1) - 1; -- -- if (posx < 1) { -- return values[0]; -- } -- -- if (posx >= values.length) { -- return values[values.length - 1]; -- } -- -- return values[posx]; -- } -+ private final long[] values; -+ private final double[] normWeights; -+ private final double[] quantiles; - -- /** -- * Returns the number of values in the snapshot. -- * -- * @return the number of values -- */ -- @Override -- public int size() { -- return values.length; -- } -+ /** -+ * Create a new {@link Snapshot} with the given values. -+ * -+ * @param values an unordered set of values in the reservoir -+ */ -+ public WeightedSnapshot(Collection values) { -+ final WeightedSample[] copy = values.toArray(new WeightedSample[] {}); -+ -+ Arrays.sort(copy, comparingLong(w -> w.value)); -+ -+ this.values = new long[copy.length]; -+ this.normWeights = new double[copy.length]; -+ this.quantiles = new double[copy.length]; - -- /** -- * Returns the entire set of values in the snapshot. -- * -- * @return the entire set of values -- */ -- @Override -- public long[] getValues() { -- return Arrays.copyOf(values, values.length); -+ double sumWeight = 0; -+ for (WeightedSample sample : copy) { -+ sumWeight += sample.weight; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.42991879, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001)); -- /** -- * Returns the highest value in the snapshot. -- * -- * @return the highest value -- */ -- @Override -- public long getMax() { -- if (values.length == 0) { -- return 0; -- } -- return values[values.length - 1]; -+ for (int i = 0; i < copy.length; i++) { -+ this.values[i] = copy[i].value; -+ this.normWeights[i] = sumWeight != 0 ? copy[i].weight / sumWeight : 0; - } + elapseMinute(ewma); -- /** -- * Returns the lowest value in the snapshot. -- * -- * @return the lowest value -- */ -- @Override -- public long getMin() { -- if (values.length == 0) { -- return 0; -- } -- return values[0]; -+ for (int i = 1; i < copy.length; i++) { -+ this.quantiles[i] = this.quantiles[i - 1] + this.normWeights[i - 1]; - } -+ } -+ -+ /** -+ * Returns the value at the given quantile. -+ * -+ * @param quantile a given quantile, in {@code [0..1]} -+ * @return the value in the distribution at {@code quantile} -+ */ -+ @Override -+ public double getValue(double quantile) { -+ checkArgument( -+ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), -+ "%s is not in [0..1]", -+ quantile); -+ -+ if (values.length == 0) { -+ return 0.0; -+ } -+ -+ int posx = Arrays.binarySearch(quantiles, quantile); -+ if (posx < 0) posx = ((-posx) - 1) - 1; - -- /** -- * Returns the weighted arithmetic mean of the values in the snapshot. -- * -- * @return the weighted arithmetic mean -- */ -- @Override -- public double getMean() { -- if (values.length == 0) { -- return 0; -- } -- -- double sum = 0; -- for (int i = 0; i < values.length; i++) { -- sum += values[i] * normWeights[i]; -- } -- return sum; -+ if (posx < 1) { -+ return values[0]; - } +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); -- /** -- * Returns the weighted standard deviation of the values in the snapshot. -- * -- * @return the weighted standard deviation value -- */ -- @Override -- public double getStdDev() { -- // two-pass algorithm for variance, avoids numeric overflow -+ if (posx >= values.length) { -+ return values[values.length - 1]; -+ } - -- if (values.length <= 1) { -- return 0; -- } -+ return values[posx]; -+ } -+ -+ /** -+ * Returns the number of values in the snapshot. -+ * -+ * @return the number of values -+ */ -+ @Override -+ public int size() { -+ return values.length; -+ } -+ -+ /** -+ * Returns the entire set of values in the snapshot. -+ * -+ * @return the entire set of values -+ */ -+ @Override -+ public long[] getValues() { -+ return Arrays.copyOf(values, values.length); -+ } -+ -+ /** -+ * Returns the highest value in the snapshot. -+ * -+ * @return the highest value -+ */ -+ @Override -+ public long getMax() { -+ if (values.length == 0) { -+ return 0; -+ } -+ return values[values.length - 1]; -+ } -+ -+ /** -+ * Returns the lowest value in the snapshot. -+ * -+ * @return the lowest value -+ */ -+ @Override -+ public long getMin() { -+ if (values.length == 0) { -+ return 0; -+ } -+ return values[0]; -+ } -+ -+ /** -+ * Returns the weighted arithmetic mean of the values in the snapshot. -+ * -+ * @return the weighted arithmetic mean -+ */ -+ @Override -+ public double getMean() { -+ if (values.length == 0) { -+ return 0; -+ } - -- final double mean = getMean(); -- double variance = 0; -+ double sum = 0; -+ for (int i = 0; i < values.length; i++) { -+ sum += values[i] * normWeights[i]; -+ } -+ return sum; -+ } -+ -+ /** -+ * Returns the weighted standard deviation of the values in the snapshot. -+ * -+ * @return the weighted standard deviation value -+ */ -+ @Override -+ public double getStdDev() { -+ // two-pass algorithm for variance, avoids numeric overflow -+ -+ if (values.length <= 1) { -+ return 0; -+ } + elapseMinute(ewma); -- for (int i = 0; i < values.length; i++) { -- final double diff = values[i] - mean; -- variance += normWeights[i] * diff * diff; -- } -+ final double mean = getMean(); -+ double variance = 0; +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.37625345, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001)); -- return Math.sqrt(variance); -+ for (int i = 0; i < values.length; i++) { -+ final double diff = values[i] - mean; -+ variance += normWeights[i] * diff * diff; - } + elapseMinute(ewma); -- /** -- * Writes the values of the snapshot to the given stream. -- * -- * @param output an output stream -- */ -- @Override -- public void dump(OutputStream output) { -- try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { -- for (long value : values) { -- out.printf("%d%n", value); -- } -- } -+ return Math.sqrt(variance); -+ } -+ -+ /** -+ * Writes the values of the snapshot to the given stream. -+ * -+ * @param output an output stream -+ */ -+ @Override -+ public void dump(OutputStream output) { -+ try (PrintWriter out = new PrintWriter(new OutputStreamWriter(output, UTF_8))) { -+ for (long value : values) { -+ out.printf("%d%n", value); -+ } - } -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java -@@ -1,8 +1,6 @@ +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.35198773, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.30805027, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.28818318, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.25221023, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.23594443, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + } + + private void elapseMinute(EWMA ewma) { +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java +@@ -7,10 +7,10 @@ import static org.mockito.Mockito.when; + import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + +-public class ExponentialMovingAveragesTest { ++final class ExponentialMovingAveragesTest { + @Test +- public void testMaxTicks() { +- final Clock clock = mock(Clock.class); ++ void maxTicks() { ++ final Clock clock = mock(); + when(clock.getTick()).thenReturn(0L, Long.MAX_VALUE); + final ExponentialMovingAverages ema = new ExponentialMovingAverages(clock); + ema.update(Long.MAX_VALUE); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java +@@ -1,5 +1,6 @@ package io.dropwizard.metrics5; --import org.junit.jupiter.api.Test; --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -+import static org.assertj.core.api.Assertions.assertThat; ++import static com.google.common.collect.ImmutableList.toImmutableList; + import static org.assertj.core.api.Assertions.assertThat; - import java.util.ArrayList; - import java.util.List; -@@ -12,120 +10,120 @@ import java.util.concurrent.Future; + import java.util.Arrays; +@@ -7,11 +8,10 @@ import java.util.Collection; import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; - import java.util.concurrent.atomic.AtomicLong; -+import org.junit.jupiter.api.Test; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; +-import java.util.stream.Collectors; + import org.junit.jupiter.params.ParameterizedTest; + import org.junit.jupiter.params.provider.MethodSource; --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertTrue; -- --class CachedGaugeTest { -- private static final Logger LOGGER = LoggerFactory.getLogger(CachedGaugeTest.class); -- private static final int THREAD_COUNT = 10; -- private static final long RUNNING_TIME_MILLIS = TimeUnit.SECONDS.toMillis(10); -+final class CachedGaugeTest { -+ private static final Logger LOG = LoggerFactory.getLogger(CachedGaugeTest.class); -+ private static final int THREAD_COUNT = 10; -+ private static final long RUNNING_TIME_MILLIS = TimeUnit.SECONDS.toMillis(10); - -- private final AtomicInteger value = new AtomicInteger(0); -- private final Gauge gauge = new CachedGauge(100, TimeUnit.MILLISECONDS) { -+ private final AtomicInteger value = new AtomicInteger(0); -+ private final Gauge gauge = -+ new CachedGauge(100, TimeUnit.MILLISECONDS) { - @Override - protected Integer loadValue() { -- return value.incrementAndGet(); -+ return value.incrementAndGet(); - } -- }; -- private final Gauge shortTimeoutGauge = new CachedGauge(1, TimeUnit.MILLISECONDS) { -+ }; -+ private final Gauge shortTimeoutGauge = -+ new CachedGauge(1, TimeUnit.MILLISECONDS) { - @Override - protected Integer loadValue() { -- try { -- Thread.sleep(5); -- } catch (InterruptedException e) { -- throw new RuntimeException("Thread was interrupted", e); -- } -- return value.incrementAndGet(); -+ try { -+ Thread.sleep(5); -+ } catch (InterruptedException e) { -+ throw new RuntimeException("Thread was interrupted", e); -+ } -+ return value.incrementAndGet(); - } -- }; -- private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); -- -- @Test -- void cachesTheValueForTheGivenPeriod() { -- assertThat(gauge.getValue()) -- .isEqualTo(1); -- assertThat(gauge.getValue()) -- .isEqualTo(1); -- } -- -- @Test -- void reloadsTheCachedValueAfterTheGivenPeriod() throws Exception { -- assertThat(gauge.getValue()) -- .isEqualTo(1); -- -- Thread.sleep(150); -- -- assertThat(gauge.getValue()) -- .isEqualTo(2); -- -- assertThat(gauge.getValue()) -- .isEqualTo(2); -- } -- -- @Test -- void reloadsCachedValueInNegativeTime() throws Exception { -- AtomicLong time = new AtomicLong(-2L); -- Clock clock = new Clock() { -- @Override -- public long getTick() { -- return time.get(); -- } -+ }; -+ private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); -+ -+ @Test -+ void cachesTheValueForTheGivenPeriod() { -+ assertThat(gauge.getValue()).isEqualTo(1); -+ assertThat(gauge.getValue()).isEqualTo(1); -+ } -+ -+ @Test -+ void reloadsTheCachedValueAfterTheGivenPeriod() throws Exception { -+ assertThat(gauge.getValue()).isEqualTo(1); -+ -+ Thread.sleep(150); -+ -+ assertThat(gauge.getValue()).isEqualTo(2); -+ -+ assertThat(gauge.getValue()).isEqualTo(2); -+ } -+ -+ @Test -+ void reloadsCachedValueInNegativeTime() throws Exception { -+ AtomicLong time = new AtomicLong(-2L); -+ Clock clock = -+ new Clock() { -+ @Override -+ public long getTick() { -+ return time.get(); -+ } - }; -- Gauge clockGauge = new CachedGauge(clock, 1, TimeUnit.NANOSECONDS) { -- @Override -- protected Integer loadValue() { -- return value.incrementAndGet(); -- } -+ Gauge clockGauge = -+ new CachedGauge(clock, 1, TimeUnit.NANOSECONDS) { -+ @Override -+ protected Integer loadValue() { -+ return value.incrementAndGet(); -+ } - }; -- assertThat(clockGauge.getValue()) -- .isEqualTo(1); -- assertThat(clockGauge.getValue()) -- .isEqualTo(1); -+ assertThat(clockGauge.getValue()).isEqualTo(1); -+ assertThat(clockGauge.getValue()).isEqualTo(1); - -- time.set(-1L); -+ time.set(-1L); - -- assertThat(clockGauge.getValue()) -- .isEqualTo(2); -- assertThat(clockGauge.getValue()) -- .isEqualTo(2); -- } -+ assertThat(clockGauge.getValue()).isEqualTo(2); -+ assertThat(clockGauge.getValue()).isEqualTo(2); -+ } +-public class ExponentiallyDecayingReservoirTest { ++final class ExponentiallyDecayingReservoirTest { -- @Test -- void multipleThreadAccessReturnsConsistentResults() throws Exception { -- List> futures = new ArrayList<>(THREAD_COUNT); -+ @Test -+ void multipleThreadAccessReturnsConsistentResults() throws Exception { -+ List> futures = new ArrayList<>(THREAD_COUNT); - -- for (int i = 0; i < THREAD_COUNT; i++) { -- Future future = executor.submit(() -> { -+ for (int i = 0; i < THREAD_COUNT; i++) { -+ Future future = -+ executor.submit( -+ () -> { - long startTime = System.currentTimeMillis(); - int lastValue = 0; - - do { -- Integer newValue = shortTimeoutGauge.getValue(); -- -- if (newValue == null) { -- LOGGER.warn("Cached gauge returned null value"); -- return false; -- } -- -- if (newValue < lastValue) { -- LOGGER.error("Cached gauge returned stale value, last: {}, new: {}", lastValue, newValue); -- return false; -- } -- -- lastValue = newValue; -+ Integer newValue = shortTimeoutGauge.getValue(); -+ -+ if (newValue == null) { -+ LOG.warn("Cached gauge returned null value"); -+ return false; -+ } -+ -+ if (newValue < lastValue) { -+ LOG.error( -+ "Cached gauge returned stale value, last: {}, new: {}", -+ lastValue, -+ newValue); -+ return false; -+ } -+ -+ lastValue = newValue; - } while (System.currentTimeMillis() - startTime <= RUNNING_TIME_MILLIS); + public enum ReservoirFactory { + EXPONENTIALLY_DECAYING() { +@@ -42,7 +42,7 @@ public class ExponentiallyDecayingReservoirTest { + public static Collection reservoirs() { + return Arrays.stream(ReservoirFactory.values()) + .map(value -> new Object[] {value}) +- .collect(Collectors.toList()); ++ .collect(toImmutableList()); + } - return true; -- }); -- -- futures.add(future); -- } -+ }); + private ReservoirFactory reservoirFactory; +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java +@@ -8,7 +8,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.junit.jupiter.api.io.TempDir; -- for (int i = 0; i < futures.size(); i++) { -- assertTrue(futures.get(i).get(), "Future " + i + " failed"); -- } -+ futures.add(future); -+ } +-public class FixedNameCsvFileProviderTest { ++final class FixedNameCsvFileProviderTest { + @TempDir public File folder; -- executor.shutdown(); -+ for (int i = 0; i < futures.size(); i++) { -+ assertThat(futures.get(i).get()).withFailMessage("Future %s failed", i).isTrue(); - } -+ -+ executor.shutdown(); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java -@@ -4,37 +4,32 @@ import static org.assertj.core.api.BDDAssertions.then; + private File dataDirectory; +@@ -19,7 +19,7 @@ public class FixedNameCsvFileProviderTest { + } + + @Test +- void testGetFile() { ++ void getFile() { + FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); + File file = provider.getFile(dataDirectory, "test"); + assertThat(file.getParentFile()).isEqualTo(dataDirectory); +@@ -27,7 +27,7 @@ public class FixedNameCsvFileProviderTest { + } + + @Test +- void testGetFileSanitize() { ++ void getFileSanitize() { + FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); + File file = provider.getFile(dataDirectory, "/myfake/uri"); + assertThat(file.getParentFile()).isEqualTo(dataDirectory); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java +@@ -7,14 +7,14 @@ import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; --class ChunkedAssociativeLongArrayTest { -- -- @Test -- void testTrim() { -- ChunkedAssociativeLongArray array = new ChunkedAssociativeLongArray(3); -- array.put(-3, 3); -- array.put(-2, 1); -- array.put(0, 5); -- array.put(3, 0); -- array.put(9, 8); -- array.put(15, 0); -- array.put(19, 5); -- array.put(21, 5); -- array.put(34, -9); -- array.put(109, 5); -- -- then(array.out()) -- .isEqualTo("[(-3: 3) (-2: 1) (0: 5) ]->[(3: 0) (9: 8) (15: 0) ]->[(19: 5) (21: 5) (34: -9) ]->[(109: 5) ]"); -- then(array.values()) -- .isEqualTo(new long[]{3, 1, 5, 0, 8, 0, 5, 5, -9, 5}); -- then(array.size()) -- .isEqualTo(10); -- -- array.trim(-2, 20); -- -- then(array.out()) -- .isEqualTo("[(-2: 1) (0: 5) ]->[(3: 0) (9: 8) (15: 0) ]->[(19: 5) ]"); -- then(array.values()) -- .isEqualTo(new long[]{1, 5, 0, 8, 0, 5}); -- then(array.size()) -- .isEqualTo(6); -- -- } -+final class ChunkedAssociativeLongArrayTest { -+ -+ @Test -+ void trim() { -+ ChunkedAssociativeLongArray array = new ChunkedAssociativeLongArray(3); -+ array.put(-3, 3); -+ array.put(-2, 1); -+ array.put(0, 5); -+ array.put(3, 0); -+ array.put(9, 8); -+ array.put(15, 0); -+ array.put(19, 5); -+ array.put(21, 5); -+ array.put(34, -9); -+ array.put(109, 5); -+ -+ then(array.out()) -+ .isEqualTo( -+ "[(-3: 3) (-2: 1) (0: 5) ]->[(3: 0) (9: 8) (15: 0) ]->[(19: 5) (21: 5) (34: -9) ]->[(109: 5) ]"); -+ then(array.values()).isEqualTo(new long[] {3, 1, 5, 0, 8, 0, 5, 5, -9, 5}); -+ then(array.size()).isEqualTo(10); -+ -+ array.trim(-2, 20); -+ -+ then(array.out()).isEqualTo("[(-2: 1) (0: 5) ]->[(3: 0) (9: 8) (15: 0) ]->[(19: 5) ]"); -+ then(array.values()).isEqualTo(new long[] {1, 5, 0, 8, 0, 5}); -+ then(array.size()).isEqualTo(6); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java -@@ -1,13 +1,13 @@ - package io.dropwizard.metrics5; +-class HistogramTest { +- private final Reservoir reservoir = mock(Reservoir.class); ++final class HistogramTest { ++ private final Reservoir reservoir = mock(); + private final Histogram histogram = new Histogram(reservoir); --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; + @Test + void updatesTheCountAndSumOnUpdates() { +- assertThat(histogram.getCount()).isZero(); +- assertThat(histogram.getSum()).isZero(); ++ assertThat(histogram.getCount()).isEqualTo(0); ++ assertThat(histogram.getSum()).isEqualTo(0); --public class ClassMetadataTest { -- @Test -- public void testParameterMetadataIsAvailable() throws NoSuchMethodException { -- assertThat(DefaultSettableGauge.class.getConstructor(Object.class).getParameters()) -- .allSatisfy(parameter -> assertThat(parameter.isNamePresent()).isTrue()); -- } --} -\ No newline at end of file -+import org.junit.jupiter.api.Test; -+ -+final class ClassMetadataTest { -+ @Test -+ void parameterMetadataIsAvailable() throws NoSuchMethodException { -+ assertThat(DefaultSettableGauge.class.getConstructor(Object.class).getParameters()) -+ .allSatisfy(parameter -> assertThat(parameter.isNamePresent()).isTrue()); -+ } -+} ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java -@@ -1,28 +1,23 @@ - package io.dropwizard.metrics5; + histogram.update(1); + histogram.update(5); +@@ -25,7 +25,7 @@ class HistogramTest { --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.offset; + @Test + void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(reservoir.getSnapshot()).thenReturn(snapshot); --class ClockTest { -+import org.junit.jupiter.api.Test; -+ -+final class ClockTest { + assertThat(histogram.getSnapshot()).isEqualTo(snapshot); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java +@@ -19,10 +19,9 @@ import org.junit.jupiter.api.Test; + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; -- @Test -- void userTimeClock() { -- final Clock.UserTimeClock clock = new Clock.UserTimeClock(); -+ @Test -+ void userTimeClock() { -+ final Clock.UserTimeClock clock = new Clock.UserTimeClock(); +-class InstrumentedExecutorServiceTest { ++final class InstrumentedExecutorServiceTest { -- assertThat((double) clock.getTime()) -- .isEqualTo(System.currentTimeMillis(), -- offset(100.0)); -+ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0)); +- private static final Logger LOGGER = +- LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); ++ private static final Logger LOG = LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); + private ExecutorService executor; + private MetricRegistry registry; + private InstrumentedExecutorService instrumentedExecutorService; +@@ -48,7 +47,7 @@ class InstrumentedExecutorServiceTest { + void tearDown() throws Exception { + instrumentedExecutorService.shutdown(); + if (!instrumentedExecutorService.awaitTermination(2, TimeUnit.SECONDS)) { +- LOGGER.error("InstrumentedExecutorService did not terminate."); ++ LOG.error("InstrumentedExecutorService did not terminate."); + } + } -- assertThat((double) clock.getTick()) -- .isEqualTo(System.nanoTime(), -- offset(1000000.0)); -- } -+ assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0)); -+ } +@@ -115,8 +114,8 @@ class InstrumentedExecutorServiceTest { + assertThat(idle.getSnapshot().size()).isEqualTo(1); + } -- @Test -- void defaultsToUserTime() { -- assertThat(Clock.defaultClock()) -- .isInstanceOf(Clock.UserTimeClock.class); -- } +- @Test + @SuppressWarnings("unchecked") + @Test -+ void defaultsToUserTime() { -+ assertThat(Clock.defaultClock()).isInstanceOf(Clock.UserTimeClock.class); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java -@@ -1,9 +1,8 @@ - package io.dropwizard.metrics5; + void reportsTasksInformationForThreadPoolExecutor() throws Exception { + executor = + new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); +@@ -180,7 +179,7 @@ class InstrumentedExecutorServiceTest { + } --import org.apache.commons.lang3.JavaVersion; --import org.apache.commons.lang3.SystemUtils; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; + @Test +- public void reportsRejectedTasksForThreadPoolExecutor() throws Exception { ++ void reportsRejectedTasksForThreadPoolExecutor() throws Exception { + executor = + new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1)); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); +@@ -207,7 +206,7 @@ class InstrumentedExecutorServiceTest { + } - import java.io.ByteArrayOutputStream; - import java.io.PrintStream; -@@ -15,20 +14,221 @@ import java.util.SortedMap; - import java.util.TimeZone; - import java.util.TreeMap; - import java.util.concurrent.TimeUnit; -+import org.apache.commons.lang3.JavaVersion; -+import org.apache.commons.lang3.SystemUtils; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- --class ConsoleReporterTest { -- private final Locale locale = Locale.US; -- private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); -- -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final Clock clock = mock(Clock.class); -- private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); -- private final PrintStream output = new PrintStream(bytes); -- private final ConsoleReporter reporter = ConsoleReporter.forRegistry(registry) -+final class ConsoleReporterTest { -+ private final Locale locale = Locale.US; -+ private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); -+ -+ private final MetricRegistry registry = mock(); -+ private final Clock clock = mock(); -+ private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); -+ private final PrintStream output = new PrintStream(bytes); -+ private final ConsoleReporter reporter = -+ ConsoleReporter.forRegistry(registry) -+ .outputTo(output) -+ .formattedFor(locale) -+ .withClock(clock) -+ .formattedFor(timeZone) -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .build(); -+ private String dateHeader; -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ when(clock.getTime()).thenReturn(1363568676000L); -+ // JDK9 has changed the java.text.DateFormat API implementation according to Unicode. -+ // See http://mail.openjdk.java.net/pipermail/jdk9-dev/2017-April/005732.html -+ dateHeader = -+ SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8) -+ ? "3/17/13 6:04:36 PM =============================================================" -+ : -+ // https://bugs.openjdk.org/browse/JDK-8304925 -+ SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_20) -+ ? "3/17/13, 6:04:36\u202FPM ============================================================" -+ : "3/17/13, 6:04:36 PM ============================================================"; -+ } -+ -+ @Test -+ void reportsGaugeValues() throws Exception { -+ final Gauge gauge = () -> 1; -+ -+ reporter.report(map(MetricName.build("gauge"), gauge), map(), map(), map(), map()); -+ -+ assertThat(consoleOutput()) -+ .isEqualTo( -+ lines( -+ dateHeader, -+ "", -+ "-- Gauges ----------------------------------------------------------------------", -+ "gauge", -+ " value = 1", -+ "", -+ "")); -+ } -+ -+ @Test -+ void reportsCounterValues() throws Exception { -+ final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(100L); -+ -+ reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); -+ -+ assertThat(consoleOutput()) -+ .isEqualTo( -+ lines( -+ dateHeader, -+ "", -+ "-- Counters --------------------------------------------------------------------", -+ "test.counter", -+ " count = 100", -+ "", -+ "")); -+ } -+ + @Test +- public void removesMetricsAfterShutdownForThreadPoolExecutor() { ++ void removesMetricsAfterShutdownForThreadPoolExecutor() { + executor = + new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "stp"); +@@ -236,8 +235,8 @@ class InstrumentedExecutorServiceTest { + MetricRegistry.name("stp", "tasks.capacity")); + } + +- @Test + @SuppressWarnings("unchecked") + @Test -+ void reportsHistogramValues() throws Exception { -+ final Histogram histogram = mock(); -+ when(histogram.getCount()).thenReturn(1L); -+ when(histogram.getSum()).thenReturn(4L); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(2L); -+ when(snapshot.getMean()).thenReturn(3.0); -+ when(snapshot.getMin()).thenReturn(4L); -+ when(snapshot.getStdDev()).thenReturn(5.0); -+ when(snapshot.getMedian()).thenReturn(6.0); -+ when(snapshot.get75thPercentile()).thenReturn(7.0); -+ when(snapshot.get95thPercentile()).thenReturn(8.0); -+ when(snapshot.get98thPercentile()).thenReturn(9.0); -+ when(snapshot.get99thPercentile()).thenReturn(10.0); -+ when(snapshot.get999thPercentile()).thenReturn(11.0); -+ -+ when(histogram.getSnapshot()).thenReturn(snapshot); -+ -+ reporter.report(map(), map(), map(MetricName.build("test.histogram"), histogram), map(), map()); -+ -+ assertThat(consoleOutput()) -+ .isEqualTo( -+ lines( -+ dateHeader, -+ "", -+ "-- Histograms ------------------------------------------------------------------", -+ "test.histogram", -+ " count = 1", -+ " sum = 4", -+ " min = 4", -+ " max = 2", -+ " mean = 3.00", -+ " stddev = 5.00", -+ " median = 6.00", -+ " 75% <= 7.00", -+ " 95% <= 8.00", -+ " 98% <= 9.00", -+ " 99% <= 10.00", -+ " 99.9% <= 11.00", -+ "", -+ "")); -+ } -+ -+ @Test -+ void reportsMeterValues() throws Exception { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(3L); -+ when(meter.getMeanRate()).thenReturn(2.0); -+ when(meter.getOneMinuteRate()).thenReturn(3.0); -+ when(meter.getFiveMinuteRate()).thenReturn(4.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ reporter.report(map(), map(), map(), map(MetricName.build("test.meter"), meter), map()); -+ -+ assertThat(consoleOutput()) -+ .isEqualTo( -+ lines( -+ dateHeader, -+ "", -+ "-- Meters ----------------------------------------------------------------------", -+ "test.meter", -+ " count = 1", -+ " sum = 3", -+ " mean rate = 2.00 events/second", -+ " 1-minute rate = 3.00 events/second", -+ " 5-minute rate = 4.00 events/second", -+ " 15-minute rate = 5.00 events/second", -+ "", -+ "")); -+ } -+ -+ @Test -+ void reportsTimerValues() throws Exception { -+ final Timer timer = mock(); -+ when(timer.getCount()).thenReturn(1L); -+ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(5)); -+ when(timer.getMeanRate()).thenReturn(2.0); -+ when(timer.getOneMinuteRate()).thenReturn(3.0); -+ when(timer.getFiveMinuteRate()).thenReturn(4.0); -+ when(timer.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -+ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -+ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -+ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -+ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -+ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -+ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -+ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -+ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -+ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -+ -+ when(timer.getSnapshot()).thenReturn(snapshot); -+ -+ reporter.report(map(), map(), map(), map(), map(MetricName.build("test.another.timer"), timer)); -+ -+ assertThat(consoleOutput()) -+ .isEqualTo( -+ lines( -+ dateHeader, -+ "", -+ "-- Timers ----------------------------------------------------------------------", -+ "test.another.timer", -+ " count = 1", -+ " sum = 5.00", -+ " mean rate = 2.00 calls/second", -+ " 1-minute rate = 3.00 calls/second", -+ " 5-minute rate = 4.00 calls/second", -+ " 15-minute rate = 5.00 calls/second", -+ " min = 300.00 milliseconds", -+ " max = 100.00 milliseconds", -+ " mean = 200.00 milliseconds", -+ " stddev = 400.00 milliseconds", -+ " median = 500.00 milliseconds", -+ " 75% <= 600.00 milliseconds", -+ " 95% <= 700.00 milliseconds", -+ " 98% <= 800.00 milliseconds", -+ " 99% <= 900.00 milliseconds", -+ " 99.9% <= 1000.00 milliseconds", -+ "", -+ "")); -+ } -+ -+ @Test -+ void reportMeterWithDisabledAttributes() throws Exception { -+ Set disabledMetricAttributes = -+ EnumSet.of( -+ MetricAttribute.M15_RATE, -+ MetricAttribute.M5_RATE, -+ MetricAttribute.COUNT, -+ MetricAttribute.SUM); -+ -+ final ConsoleReporter customReporter = -+ ConsoleReporter.forRegistry(registry) - .outputTo(output) - .formattedFor(locale) - .withClock(clock) -@@ -36,393 +236,178 @@ class ConsoleReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(disabledMetricAttributes) - .build(); -- private String dateHeader; -- -- @BeforeEach -- void setUp() throws Exception { -- when(clock.getTime()).thenReturn(1363568676000L); -- // JDK9 has changed the java.text.DateFormat API implementation according to Unicode. -- // See http://mail.openjdk.java.net/pipermail/jdk9-dev/2017-April/005732.html -- dateHeader = SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8) ? -- "3/17/13 6:04:36 PM =============================================================" : -- // https://bugs.openjdk.org/browse/JDK-8304925 -- SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_20) ? -- "3/17/13, 6:04:36\u202FPM ============================================================" : -- "3/17/13, 6:04:36 PM ============================================================"; -- } -- -- @Test -- void reportsGaugeValues() throws Exception { -- final Gauge gauge = () -> 1; -- -- reporter.report(map(MetricName.build("gauge"), gauge), -- map(), -- map(), -- map(), -- map()); -- -- assertThat(consoleOutput()) -- .isEqualTo(lines( -- dateHeader, -- "", -- "-- Gauges ----------------------------------------------------------------------", -- "gauge", -- " value = 1", -- "", -- "" -- )); -- } -- -- @Test -- void reportsCounterValues() throws Exception { -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(100L); -- -- reporter.report(map(), -- map(MetricName.build("test.counter"), counter), -- map(), -- map(), -- map()); -- -- assertThat(consoleOutput()) -- .isEqualTo(lines( -- dateHeader, -- "", -- "-- Counters --------------------------------------------------------------------", -- "test.counter", -- " count = 100", -- "", -- "" -- )); -- } -- -- @Test -- void reportsHistogramValues() throws Exception { -- final Histogram histogram = mock(Histogram.class); -- when(histogram.getCount()).thenReturn(1L); -- when(histogram.getSum()).thenReturn(4L); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(2L); -- when(snapshot.getMean()).thenReturn(3.0); -- when(snapshot.getMin()).thenReturn(4L); -- when(snapshot.getStdDev()).thenReturn(5.0); -- when(snapshot.getMedian()).thenReturn(6.0); -- when(snapshot.get75thPercentile()).thenReturn(7.0); -- when(snapshot.get95thPercentile()).thenReturn(8.0); -- when(snapshot.get98thPercentile()).thenReturn(9.0); -- when(snapshot.get99thPercentile()).thenReturn(10.0); -- when(snapshot.get999thPercentile()).thenReturn(11.0); -- -- when(histogram.getSnapshot()).thenReturn(snapshot); -- -- reporter.report(map(), -- map(), -- map(MetricName.build("test.histogram"), histogram), -- map(), -- map()); -- -- assertThat(consoleOutput()) -- .isEqualTo(lines( -- dateHeader, -- "", -- "-- Histograms ------------------------------------------------------------------", -- "test.histogram", -- " count = 1", -- " sum = 4", -- " min = 4", -- " max = 2", -- " mean = 3.00", -- " stddev = 5.00", -- " median = 6.00", -- " 75% <= 7.00", -- " 95% <= 8.00", -- " 98% <= 9.00", -- " 99% <= 10.00", -- " 99.9% <= 11.00", -- "", -- "" -- )); -- } -- -- @Test -- void reportsMeterValues() throws Exception { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(3L); -- when(meter.getMeanRate()).thenReturn(2.0); -- when(meter.getOneMinuteRate()).thenReturn(3.0); -- when(meter.getFiveMinuteRate()).thenReturn(4.0); -- when(meter.getFifteenMinuteRate()).thenReturn(5.0); -- -- reporter.report(map(), -- map(), -- map(), -- map(MetricName.build("test.meter"), meter), -- map()); -- -- assertThat(consoleOutput()) -- .isEqualTo(lines( -- dateHeader, -- "", -- "-- Meters ----------------------------------------------------------------------", -- "test.meter", -- " count = 1", -- " sum = 3", -- " mean rate = 2.00 events/second", -- " 1-minute rate = 3.00 events/second", -- " 5-minute rate = 4.00 events/second", -- " 15-minute rate = 5.00 events/second", -- "", -- "" -- )); -- } -- -- @Test -- void reportsTimerValues() throws Exception { -- final Timer timer = mock(Timer.class); -- when(timer.getCount()).thenReturn(1L); -- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(5)); -- when(timer.getMeanRate()).thenReturn(2.0); -- when(timer.getOneMinuteRate()).thenReturn(3.0); -- when(timer.getFiveMinuteRate()).thenReturn(4.0); -- when(timer.getFifteenMinuteRate()).thenReturn(5.0); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS -- .toNanos(1000)); -- -- when(timer.getSnapshot()).thenReturn(snapshot); -- -- reporter.report(map(), -- map(), -- map(), -- map(), -- map(MetricName.build("test.another.timer"), timer)); -- -- assertThat(consoleOutput()) -- .isEqualTo(lines( -- dateHeader, -- "", -- "-- Timers ----------------------------------------------------------------------", -- "test.another.timer", -- " count = 1", -- " sum = 5.00", -- " mean rate = 2.00 calls/second", -- " 1-minute rate = 3.00 calls/second", -- " 5-minute rate = 4.00 calls/second", -- " 15-minute rate = 5.00 calls/second", -- " min = 300.00 milliseconds", -- " max = 100.00 milliseconds", -- " mean = 200.00 milliseconds", -- " stddev = 400.00 milliseconds", -- " median = 500.00 milliseconds", -- " 75% <= 600.00 milliseconds", -- " 95% <= 700.00 milliseconds", -- " 98% <= 800.00 milliseconds", -- " 99% <= 900.00 milliseconds", -- " 99.9% <= 1000.00 milliseconds", -- "", -- "" -- )); -- } + void reportsTasksInformationForForkJoinPool() throws Exception { + executor = Executors.newWorkStealingPool(4); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); +@@ -291,7 +290,7 @@ class InstrumentedExecutorServiceTest { + } -- @Test -- void reportMeterWithDisabledAttributes() throws Exception { -- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE, MetricAttribute.COUNT, MetricAttribute.SUM); -- -- final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) -- .outputTo(output) -- .formattedFor(locale) -- .withClock(clock) -- .formattedFor(timeZone) -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(disabledMetricAttributes) -- .build(); -- -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(5L); -- when(meter.getMeanRate()).thenReturn(2.0); -- when(meter.getOneMinuteRate()).thenReturn(3.0); -- when(meter.getFiveMinuteRate()).thenReturn(4.0); -- when(meter.getFifteenMinuteRate()).thenReturn(5.0); -- -- customReporter.report(map(), -- map(), -- map(), -- map(MetricName.build("test.meter"), meter), -- map()); -- -- assertThat(consoleOutput()) -- .isEqualTo(lines( -- dateHeader, -- "", -- "-- Meters ----------------------------------------------------------------------", -- "test.meter", -- " mean rate = 2.00 events/second", -- " 1-minute rate = 3.00 events/second", -- "", -- "" -- )); -- } -- -- @Test -- void reportTimerWithDisabledAttributes() throws Exception { -- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.P50, MetricAttribute.P999, MetricAttribute.M5_RATE, MetricAttribute.MAX); -- -- final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) -- .outputTo(output) -- .formattedFor(locale) -- .withClock(clock) -- .formattedFor(timeZone) -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(disabledMetricAttributes) -- .build(); -- -- final Timer timer = mock(Timer.class); -- when(timer.getCount()).thenReturn(1L); -- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); -- when(timer.getMeanRate()).thenReturn(2.0); -- when(timer.getOneMinuteRate()).thenReturn(3.0); -- when(timer.getFiveMinuteRate()).thenReturn(4.0); -- when(timer.getFifteenMinuteRate()).thenReturn(5.0); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS -- .toNanos(1000)); -- -- when(timer.getSnapshot()).thenReturn(snapshot); -- -- customReporter.report(map(), -- map(), -- map(), -- map(), -- map(MetricName.build("test.another.timer"), timer)); -- -- assertThat(consoleOutput()) -- .isEqualTo(lines( -- dateHeader, -- "", -- "-- Timers ----------------------------------------------------------------------", -- "test.another.timer", -- " count = 1", -- " sum = 6.00", -- " mean rate = 2.00 calls/second", -- " 1-minute rate = 3.00 calls/second", -- " 15-minute rate = 5.00 calls/second", -- " min = 300.00 milliseconds", -- " mean = 200.00 milliseconds", -- " stddev = 400.00 milliseconds", -- " 75% <= 600.00 milliseconds", -- " 95% <= 700.00 milliseconds", -- " 98% <= 800.00 milliseconds", -- " 99% <= 900.00 milliseconds", -- "", -- "" -- )); -- } -- -- @Test -- void reportHistogramWithDisabledAttributes() throws Exception { -- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, MetricAttribute.MAX, MetricAttribute.STDDEV, MetricAttribute.P95); -- -- final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) -- .outputTo(output) -- .formattedFor(locale) -- .withClock(clock) -- .formattedFor(timeZone) -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(disabledMetricAttributes) -- .build(); -- -- final Histogram histogram = mock(Histogram.class); -- when(histogram.getCount()).thenReturn(1L); -- when(histogram.getSum()).thenReturn(5L); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(2L); -- when(snapshot.getMean()).thenReturn(3.0); -- when(snapshot.getMin()).thenReturn(4L); -- when(snapshot.getStdDev()).thenReturn(5.0); -- when(snapshot.getMedian()).thenReturn(6.0); -- when(snapshot.get75thPercentile()).thenReturn(7.0); -- when(snapshot.get95thPercentile()).thenReturn(8.0); -- when(snapshot.get98thPercentile()).thenReturn(9.0); -- when(snapshot.get99thPercentile()).thenReturn(10.0); -- when(snapshot.get999thPercentile()).thenReturn(11.0); -- -- when(histogram.getSnapshot()).thenReturn(snapshot); -- -- customReporter.report(map(), -- map(), -- map(MetricName.build("test.histogram"), histogram), -- map(), -- map()); -- -- assertThat(consoleOutput()) -- .isEqualTo(lines( -- dateHeader, -- "", -- "-- Histograms ------------------------------------------------------------------", -- "test.histogram", -- " count = 1", -- " sum = 5", -- " mean = 3.00", -- " median = 6.00", -- " 75% <= 7.00", -- " 98% <= 9.00", -- " 99% <= 10.00", -- " 99.9% <= 11.00", -- "", -- "" -- )); -- } -- -- private String lines(String... lines) { -- final StringBuilder builder = new StringBuilder(); -- for (String line : lines) { -- builder.append(line).append(String.format("%n")); -- } -- return builder.toString(); -- } -- -- private String consoleOutput() throws UnsupportedEncodingException { -- return bytes.toString("UTF-8"); -- } -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(5L); -+ when(meter.getMeanRate()).thenReturn(2.0); -+ when(meter.getOneMinuteRate()).thenReturn(3.0); -+ when(meter.getFiveMinuteRate()).thenReturn(4.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ customReporter.report(map(), map(), map(), map(MetricName.build("test.meter"), meter), map()); -+ -+ assertThat(consoleOutput()) -+ .isEqualTo( -+ lines( -+ dateHeader, -+ "", -+ "-- Meters ----------------------------------------------------------------------", -+ "test.meter", -+ " mean rate = 2.00 events/second", -+ " 1-minute rate = 3.00 events/second", -+ "", -+ "")); -+ } -+ -+ @Test -+ void reportTimerWithDisabledAttributes() throws Exception { -+ Set disabledMetricAttributes = -+ EnumSet.of( -+ MetricAttribute.P50, -+ MetricAttribute.P999, -+ MetricAttribute.M5_RATE, -+ MetricAttribute.MAX); -+ -+ final ConsoleReporter customReporter = -+ ConsoleReporter.forRegistry(registry) -+ .outputTo(output) -+ .formattedFor(locale) -+ .withClock(clock) -+ .formattedFor(timeZone) -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(disabledMetricAttributes) -+ .build(); - -- private SortedMap map() { -- return new TreeMap<>(); -- } -+ final Timer timer = mock(); -+ when(timer.getCount()).thenReturn(1L); -+ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); -+ when(timer.getMeanRate()).thenReturn(2.0); -+ when(timer.getOneMinuteRate()).thenReturn(3.0); -+ when(timer.getFiveMinuteRate()).thenReturn(4.0); -+ when(timer.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -+ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -+ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -+ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -+ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -+ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -+ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -+ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -+ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -+ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -+ -+ when(timer.getSnapshot()).thenReturn(snapshot); -+ -+ customReporter.report( -+ map(), map(), map(), map(), map(MetricName.build("test.another.timer"), timer)); -+ -+ assertThat(consoleOutput()) -+ .isEqualTo( -+ lines( -+ dateHeader, -+ "", -+ "-- Timers ----------------------------------------------------------------------", -+ "test.another.timer", -+ " count = 1", -+ " sum = 6.00", -+ " mean rate = 2.00 calls/second", -+ " 1-minute rate = 3.00 calls/second", -+ " 15-minute rate = 5.00 calls/second", -+ " min = 300.00 milliseconds", -+ " mean = 200.00 milliseconds", -+ " stddev = 400.00 milliseconds", -+ " 75% <= 600.00 milliseconds", -+ " 95% <= 700.00 milliseconds", -+ " 98% <= 800.00 milliseconds", -+ " 99% <= 900.00 milliseconds", -+ "", -+ "")); -+ } -+ -+ @Test -+ void reportHistogramWithDisabledAttributes() throws Exception { -+ Set disabledMetricAttributes = -+ EnumSet.of( -+ MetricAttribute.MIN, MetricAttribute.MAX, MetricAttribute.STDDEV, MetricAttribute.P95); -+ -+ final ConsoleReporter customReporter = -+ ConsoleReporter.forRegistry(registry) -+ .outputTo(output) -+ .formattedFor(locale) -+ .withClock(clock) -+ .formattedFor(timeZone) -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(disabledMetricAttributes) -+ .build(); - -- private SortedMap map(MetricName name, T metric) { -- final TreeMap map = new TreeMap<>(); -- map.put(name, metric); -- return map; -+ final Histogram histogram = mock(); -+ when(histogram.getCount()).thenReturn(1L); -+ when(histogram.getSum()).thenReturn(5L); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(2L); -+ when(snapshot.getMean()).thenReturn(3.0); -+ when(snapshot.getMin()).thenReturn(4L); -+ when(snapshot.getStdDev()).thenReturn(5.0); -+ when(snapshot.getMedian()).thenReturn(6.0); -+ when(snapshot.get75thPercentile()).thenReturn(7.0); -+ when(snapshot.get95thPercentile()).thenReturn(8.0); -+ when(snapshot.get98thPercentile()).thenReturn(9.0); -+ when(snapshot.get99thPercentile()).thenReturn(10.0); -+ when(snapshot.get999thPercentile()).thenReturn(11.0); -+ -+ when(histogram.getSnapshot()).thenReturn(snapshot); -+ -+ customReporter.report( -+ map(), map(), map(MetricName.build("test.histogram"), histogram), map(), map()); -+ -+ assertThat(consoleOutput()) -+ .isEqualTo( -+ lines( -+ dateHeader, -+ "", -+ "-- Histograms ------------------------------------------------------------------", -+ "test.histogram", -+ " count = 1", -+ " sum = 5", -+ " mean = 3.00", -+ " median = 6.00", -+ " 75% <= 7.00", -+ " 98% <= 9.00", -+ " 99% <= 10.00", -+ " 99.9% <= 11.00", -+ "", -+ "")); -+ } -+ -+ private String lines(String... lines) { -+ final StringBuilder builder = new StringBuilder(); -+ for (String line : lines) { -+ builder.append(line).append(String.format("%n")); - } -+ return builder.toString(); -+ } -+ -+ private String consoleOutput() throws UnsupportedEncodingException { -+ return bytes.toString("UTF-8"); -+ } -+ -+ private SortedMap map() { -+ return new TreeMap<>(); -+ } -+ -+ private SortedMap map(MetricName name, T metric) { -+ final TreeMap map = new TreeMap<>(); -+ map.put(name, metric); -+ return map; -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java -@@ -1,63 +1,56 @@ - package io.dropwizard.metrics5; + @Test +- public void removesMetricsAfterShutdownForForkJoinPool() { ++ void removesMetricsAfterShutdownForForkJoinPool() { + executor = Executors.newWorkStealingPool(4); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "sfjp"); --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java +@@ -13,8 +13,8 @@ import org.junit.jupiter.api.Test; + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; --class CounterTest { -- private final Counter counter = new Counter(); -+import org.junit.jupiter.api.Test; -+ -+final class CounterTest { -+ private final Counter counter = new Counter(); +-class InstrumentedScheduledExecutorServiceTest { +- private static final Logger LOGGER = ++final class InstrumentedScheduledExecutorServiceTest { ++ private static final Logger LOG = + LoggerFactory.getLogger(InstrumentedScheduledExecutorServiceTest.class); -- @Test -- void startsAtZero() { -- assertThat(counter.getCount()) -- .isZero(); -- } -+ @Test -+ void startsAtZero() { -+ assertThat(counter.getCount()).isEqualTo(0); -+ } + private final ScheduledExecutorService scheduledExecutor = +@@ -35,17 +35,17 @@ class InstrumentedScheduledExecutorServiceTest { + private final Histogram percentOfPeriod = registry.histogram("xs.scheduled.percent-of-period"); -- @Test -- void incrementsByOne() { -- counter.inc(); -+ @Test -+ void incrementsByOne() { -+ counter.inc(); + @Test +- void testSubmitRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void submitRunnable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); -- assertThat(counter.getCount()) -- .isEqualTo(1); -- } -+ assertThat(counter.getCount()).isEqualTo(1); -+ } +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); -- @Test -- void incrementsByAnArbitraryDelta() { -- counter.inc(12); -+ @Test -+ void incrementsByAnArbitraryDelta() { -+ counter.inc(12); +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -- assertThat(counter.getCount()) -- .isEqualTo(12); -- } -+ assertThat(counter.getCount()).isEqualTo(12); -+ } + Future theFuture = + instrumentedScheduledExecutor.submit( +@@ -53,87 +53,87 @@ class InstrumentedScheduledExecutorServiceTest { + assertThat(submitted.getCount()).isEqualTo(1); -- @Test -- void decrementsByOne() { -- counter.dec(); -+ @Test -+ void decrementsByOne() { -+ counter.dec(); + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); -- assertThat(counter.getCount()) -- .isEqualTo(-1); -- } -+ assertThat(counter.getCount()).isEqualTo(-1); -+ } +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + }); -- @Test -- void decrementsByAnArbitraryDelta() { -- counter.dec(12); -+ @Test -+ void decrementsByAnArbitraryDelta() { -+ counter.dec(12); + theFuture.get(); -- assertThat(counter.getCount()) -- .isEqualTo(-12); -- } -+ assertThat(counter.getCount()).isEqualTo(-12); -+ } + assertThat(submitted.getCount()).isEqualTo(1); -- @Test -- void incrementByNegativeDelta() { -- counter.inc(-12); -+ @Test -+ void incrementByNegativeDelta() { -+ counter.inc(-12); +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } -- assertThat(counter.getCount()) -- .isEqualTo(-12); -- } -+ assertThat(counter.getCount()).isEqualTo(-12); -+ } + @Test +- void testScheduleRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void scheduleRunnable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); -- @Test -- void decrementByNegativeDelta() { -- counter.dec(-12); -+ @Test -+ void decrementByNegativeDelta() { -+ counter.dec(-12); +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); -- assertThat(counter.getCount()) -- .isEqualTo(12); -- } -+ assertThat(counter.getCount()).isEqualTo(12); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java -@@ -1,257 +1,222 @@ - package io.dropwizard.metrics5; +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; --import org.junit.jupiter.api.io.TempDir; -+import static java.nio.charset.StandardCharsets.UTF_8; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; + ScheduledFuture theFuture = + instrumentedScheduledExecutor.schedule( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); - import java.io.File; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.nio.file.Files; - import java.util.Locale; - import java.util.SortedMap; - import java.util.TreeMap; - import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; -+import org.junit.jupiter.api.io.TempDir; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- --public class CsvReporterTest { -- @TempDir -- public File folder; -- -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final Clock clock = mock(Clock.class); -- -- private File dataDirectory; -- private CsvReporter reporter; -- -- @BeforeEach -- void setUp() throws Exception { -- when(clock.getTime()).thenReturn(19910191000L); -- -- this.dataDirectory = newFolder(folder, "junit"); -- -- this.reporter = CsvReporter.forRegistry(registry) -- .formatFor(Locale.US) -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .withClock(clock) -- .filter(MetricFilter.ALL) -- .build(dataDirectory); -- } -- -- @Test -- void reportsGaugeValues() throws Exception { -- final Gauge gauge = () -> 1; -- -- reporter.report(map(MetricName.build("gauge"), gauge), -- map(), -- map(), -- map(), -- map()); -- -- assertThat(fileContents("gauge.csv")) -- .isEqualTo(csv( -- "t,value", -- "19910191,1" -- )); -- } -- -- @Test -- void reportsCounterValues() throws Exception { -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(100L); -- -- reporter.report(map(), -- map(MetricName.build("test.counter"), counter), -- map(), -- map(), -- map()); -- -- assertThat(fileContents("test.counter.csv")) -- .isEqualTo(csv( -- "t,count", -- "19910191,100" -- )); -- } -- -- @Test -- void reportsHistogramValues() throws Exception { -- final Histogram histogram = mock(Histogram.class); -- when(histogram.getCount()).thenReturn(1L); -- when(histogram.getSum()).thenReturn(12L); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(2L); -- when(snapshot.getMean()).thenReturn(3.0); -- when(snapshot.getMin()).thenReturn(4L); -- when(snapshot.getStdDev()).thenReturn(5.0); -- when(snapshot.getMedian()).thenReturn(6.0); -- when(snapshot.get75thPercentile()).thenReturn(7.0); -- when(snapshot.get95thPercentile()).thenReturn(8.0); -- when(snapshot.get98thPercentile()).thenReturn(9.0); -- when(snapshot.get99thPercentile()).thenReturn(10.0); -- when(snapshot.get999thPercentile()).thenReturn(11.0); -- -- when(histogram.getSnapshot()).thenReturn(snapshot); -- -- reporter.report(map(), -- map(), -- map(MetricName.build("test.histogram"), histogram), -- map(), -- map()); -- -- assertThat(fileContents("test.histogram.csv")) -- .isEqualTo(csv( -- "t,count,sum,max,mean,min,stddev,p50,p75,p95,p98,p99,p999", -- "19910191,1,12,2,3.000000,4,5.000000,6.000000,7.000000,8.000000,9.000000,10.000000,11.000000" -- )); -- } -- -- @Test -- void reportsMeterValues() throws Exception { -- final Meter meter = mockMeter(); -- -- reporter.report(map(), -- map(), -- map(), -- map(MetricName.build("test.meter"), meter), -- map()); -- -- assertThat(fileContents("test.meter.csv")) -- .isEqualTo(csv( -- "t,count,sum,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit", -- "19910191,1,6,2.000000,3.000000,4.000000,5.000000,events/second" -- )); -- } -- -- @Test -- void reportsTimerValues() throws Exception { -- final Timer timer = mock(Timer.class); -- when(timer.getCount()).thenReturn(1L); -- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); -- when(timer.getMeanRate()).thenReturn(2.0); -- when(timer.getOneMinuteRate()).thenReturn(3.0); -- when(timer.getFiveMinuteRate()).thenReturn(4.0); -- when(timer.getFifteenMinuteRate()).thenReturn(5.0); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -- -- when(timer.getSnapshot()).thenReturn(snapshot); -- -- reporter.report(map(), -- map(), -- map(), -- map(), -- map(MetricName.build("test.another.timer"), timer)); -- -- assertThat(fileContents("test.another.timer.csv")) -- .isEqualTo(csv( -- "t,count,sum,max,mean,min,stddev,p50,p75,p95,p98,p99,p999,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit,duration_unit", -- "19910191,1,6.000000,100.000000,200.000000,300.000000,400.000000,500.000000,600.000000,700.000000,800.000000,900.000000,1000.000000,2.000000,3.000000,4.000000,5.000000,calls/second,milliseconds" -- )); -- } -- -- @Test -- void testCsvFileProviderIsUsed() { -- CsvFileProvider fileProvider = mock(CsvFileProvider.class); -- when(fileProvider.getFile(dataDirectory, "gauge")).thenReturn(new File(dataDirectory, "guage.csv")); -- -- CsvReporter reporter = CsvReporter.forRegistry(registry) -- .withCsvFileProvider(fileProvider) -- .build(dataDirectory); -- -- final Gauge gauge = () -> 1; -- -- reporter.report(map(MetricName.build("gauge"), gauge), -- map(), -- map(), -- map(), -- map()); -- -- verify(fileProvider).getFile(dataDirectory, "gauge"); -- } -- -- @Test -- void itFormatsWithCustomSeparator() throws Exception { -- final Meter meter = mockMeter(); -- -- CsvReporter customSeparatorReporter = CsvReporter.forRegistry(registry) -- .formatFor(Locale.US) -- .withSeparator("|") -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .withClock(clock) -- .filter(MetricFilter.ALL) -- .build(dataDirectory); -- -- customSeparatorReporter.report(map(), -- map(), -- map(), -- map(MetricName.build("test.meter"), meter), -- map()); -- -- assertThat(fileContents("test.meter.csv")) -- .isEqualTo(csv( -- "t|count|sum|mean_rate|m1_rate|m5_rate|m15_rate|rate_unit", -- "19910191|1|6|2.000000|3.000000|4.000000|5.000000|events/second" -- )); -- } -- -- private Meter mockMeter() { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(6L); -- when(meter.getMeanRate()).thenReturn(2.0); -- when(meter.getOneMinuteRate()).thenReturn(3.0); -- when(meter.getFiveMinuteRate()).thenReturn(4.0); -- when(meter.getFifteenMinuteRate()).thenReturn(5.0); -- -- return meter; -- } -- -- private String csv(String... lines) { -- final StringBuilder builder = new StringBuilder(); -- for (String line : lines) { -- builder.append(line).append(String.format("%n")); -- } -- return builder.toString(); -- } -- -- @SuppressWarnings("FilesReadStringWithCharset") -- private String fileContents(String filename) throws IOException { -- return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); -- } -- -- private SortedMap map() { -- return new TreeMap<>(); -- } -- -- private SortedMap map(MetricName name, T metric) { -- final TreeMap map = new TreeMap<>(); -- map.put(name, metric); -- return map; -+final class CsvReporterTest { -+ @TempDir public File folder; -+ -+ private final MetricRegistry registry = mock(); -+ private final Clock clock = mock(); -+ -+ private File dataDirectory; -+ private CsvReporter reporter; -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ when(clock.getTime()).thenReturn(19910191000L); -+ -+ this.dataDirectory = newFolder(folder, "junit"); -+ -+ this.reporter = -+ CsvReporter.forRegistry(registry) -+ .formatFor(Locale.US) -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .withClock(clock) -+ .filter(MetricFilter.ALL) -+ .build(dataDirectory); -+ } -+ -+ @Test -+ void reportsGaugeValues() throws Exception { -+ final Gauge gauge = () -> 1; -+ -+ reporter.report(map(MetricName.build("gauge"), gauge), map(), map(), map(), map()); -+ -+ assertThat(fileContents("gauge.csv")).isEqualTo(csv("t,value", "19910191,1")); -+ } -+ -+ @Test -+ void reportsCounterValues() throws Exception { -+ final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(100L); -+ -+ reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); -+ -+ assertThat(fileContents("test.counter.csv")).isEqualTo(csv("t,count", "19910191,100")); -+ } -+ -+ @Test -+ void reportsHistogramValues() throws Exception { -+ final Histogram histogram = mock(); -+ when(histogram.getCount()).thenReturn(1L); -+ when(histogram.getSum()).thenReturn(12L); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(2L); -+ when(snapshot.getMean()).thenReturn(3.0); -+ when(snapshot.getMin()).thenReturn(4L); -+ when(snapshot.getStdDev()).thenReturn(5.0); -+ when(snapshot.getMedian()).thenReturn(6.0); -+ when(snapshot.get75thPercentile()).thenReturn(7.0); -+ when(snapshot.get95thPercentile()).thenReturn(8.0); -+ when(snapshot.get98thPercentile()).thenReturn(9.0); -+ when(snapshot.get99thPercentile()).thenReturn(10.0); -+ when(snapshot.get999thPercentile()).thenReturn(11.0); -+ -+ when(histogram.getSnapshot()).thenReturn(snapshot); -+ -+ reporter.report(map(), map(), map(MetricName.build("test.histogram"), histogram), map(), map()); -+ -+ assertThat(fileContents("test.histogram.csv")) -+ .isEqualTo( -+ csv( -+ "t,count,sum,max,mean,min,stddev,p50,p75,p95,p98,p99,p999", -+ "19910191,1,12,2,3.000000,4,5.000000,6.000000,7.000000,8.000000,9.000000,10.000000,11.000000")); -+ } -+ -+ @Test -+ void reportsMeterValues() throws Exception { -+ final Meter meter = mockMeter(); -+ -+ reporter.report(map(), map(), map(), map(MetricName.build("test.meter"), meter), map()); -+ -+ assertThat(fileContents("test.meter.csv")) -+ .isEqualTo( -+ csv( -+ "t,count,sum,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit", -+ "19910191,1,6,2.000000,3.000000,4.000000,5.000000,events/second")); -+ } -+ -+ @Test -+ void reportsTimerValues() throws Exception { -+ final Timer timer = mock(); -+ when(timer.getCount()).thenReturn(1L); -+ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); -+ when(timer.getMeanRate()).thenReturn(2.0); -+ when(timer.getOneMinuteRate()).thenReturn(3.0); -+ when(timer.getFiveMinuteRate()).thenReturn(4.0); -+ when(timer.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -+ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -+ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -+ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -+ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -+ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -+ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -+ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -+ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -+ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -+ -+ when(timer.getSnapshot()).thenReturn(snapshot); -+ -+ reporter.report(map(), map(), map(), map(), map(MetricName.build("test.another.timer"), timer)); -+ -+ assertThat(fileContents("test.another.timer.csv")) -+ .isEqualTo( -+ csv( -+ "t,count,sum,max,mean,min,stddev,p50,p75,p95,p98,p99,p999,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit,duration_unit", -+ "19910191,1,6.000000,100.000000,200.000000,300.000000,400.000000,500.000000,600.000000,700.000000,800.000000,900.000000,1000.000000,2.000000,3.000000,4.000000,5.000000,calls/second,milliseconds")); -+ } -+ -+ @Test -+ void csvFileProviderIsUsed() { -+ CsvFileProvider fileProvider = mock(); -+ when(fileProvider.getFile(dataDirectory, "gauge")) -+ .thenReturn(new File(dataDirectory, "guage.csv")); -+ -+ CsvReporter reporter = -+ CsvReporter.forRegistry(registry).withCsvFileProvider(fileProvider).build(dataDirectory); -+ -+ final Gauge gauge = () -> 1; -+ -+ reporter.report(map(MetricName.build("gauge"), gauge), map(), map(), map(), map()); -+ -+ verify(fileProvider).getFile(dataDirectory, "gauge"); -+ } -+ -+ @Test -+ void itFormatsWithCustomSeparator() throws Exception { -+ final Meter meter = mockMeter(); -+ -+ CsvReporter customSeparatorReporter = -+ CsvReporter.forRegistry(registry) -+ .formatFor(Locale.US) -+ .withSeparator("|") -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .withClock(clock) -+ .filter(MetricFilter.ALL) -+ .build(dataDirectory); -+ -+ customSeparatorReporter.report( -+ map(), map(), map(), map(MetricName.build("test.meter"), meter), map()); -+ -+ assertThat(fileContents("test.meter.csv")) -+ .isEqualTo( -+ csv( -+ "t|count|sum|mean_rate|m1_rate|m5_rate|m15_rate|rate_unit", -+ "19910191|1|6|2.000000|3.000000|4.000000|5.000000|events/second")); -+ } -+ -+ private Meter mockMeter() { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(6L); -+ when(meter.getMeanRate()).thenReturn(2.0); -+ when(meter.getOneMinuteRate()).thenReturn(3.0); -+ when(meter.getFiveMinuteRate()).thenReturn(4.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ return meter; -+ } -+ -+ private String csv(String... lines) { -+ final StringBuilder builder = new StringBuilder(); -+ for (String line : lines) { -+ builder.append(line).append(String.format("%n")); - } -- -- private static File newFolder(File root, String... subDirs) throws IOException { -- String subFolder = String.join("/", subDirs); -- File result = new File(root, subFolder); -- if (!result.mkdirs()) { -- throw new IOException("Couldn't create folders " + root); -- } -- return result; -+ return builder.toString(); -+ } -+ -+ @SuppressWarnings("FilesReadStringWithCharset") -+ private String fileContents(String filename) throws IOException { -+ return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), UTF_8); -+ } -+ -+ private SortedMap map() { -+ return new TreeMap<>(); -+ } -+ -+ private SortedMap map(MetricName name, T metric) { -+ final TreeMap map = new TreeMap<>(); -+ map.put(name, metric); -+ return map; -+ } -+ -+ private static File newFolder(File root, String... subDirs) throws IOException { -+ String subFolder = String.join("/", subDirs); -+ File result = new File(root, subFolder); -+ if (!result.mkdirs()) { -+ throw new IOException("Couldn't create folders " + root); - } -+ return result; -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java -@@ -1,26 +1,26 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; - --class DefaultSettableGaugeTest { -- @Test -- void newSettableGaugeWithoutDefaultReturnsNull() { -- DefaultSettableGauge gauge = new DefaultSettableGauge<>(); -- assertThat(gauge.getValue()).isNull(); -- } -+import org.junit.jupiter.api.Test; -+ -+final class DefaultSettableGaugeTest { -+ @Test -+ void newSettableGaugeWithoutDefaultReturnsNull() { -+ DefaultSettableGauge gauge = new DefaultSettableGauge<>(); -+ assertThat(gauge.getValue()).isNull(); -+ } - -- @Test -- void newSettableGaugeWithDefaultReturnsDefault() { -- DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); -- assertThat(gauge.getValue()).isEqualTo("default"); -- } -+ @Test -+ void newSettableGaugeWithDefaultReturnsDefault() { -+ DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); -+ assertThat(gauge.getValue()).isEqualTo("default"); -+ } - -- @Test -- void setValueOverwritesExistingValue() { -- DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); -- gauge.setValue("test"); -- assertThat(gauge.getValue()).isEqualTo("test"); -- } -+ @Test -+ void setValueOverwritesExistingValue() { -+ DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); -+ gauge.setValue("test"); -+ assertThat(gauge.getValue()).isEqualTo("test"); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java -@@ -1,21 +1,21 @@ - package io.dropwizard.metrics5; + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + }, + 10L, + TimeUnit.MILLISECONDS); --class DerivativeGaugeTest { -- private final Gauge gauge1 = () -> "woo"; -- private final Gauge gauge2 = new DerivativeGauge(gauge1) { -+import org.junit.jupiter.api.Test; -+ -+final class DerivativeGaugeTest { -+ private final Gauge gauge1 = () -> "woo"; -+ private final Gauge gauge2 = -+ new DerivativeGauge(gauge1) { - @Override - protected Integer transform(String value) { -- return value.length(); -+ return value.length(); - } -- }; -+ }; + theFuture.get(); -- @Test -- void returnsATransformedValue() { -- assertThat(gauge2.getValue()) -- .isEqualTo(3); -- } -+ @Test -+ void returnsATransformedValue() { -+ assertThat(gauge2.getValue()).isEqualTo(3); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java -@@ -1,224 +1,222 @@ - package io.dropwizard.metrics5; +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); --import org.junit.jupiter.api.Test; -- --import java.util.concurrent.TimeUnit; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.offset; +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } --class EWMATest { -- @Test -- void aOneMinuteEWMAWithAValueOfThree() { -- final EWMA ewma = EWMA.oneMinuteEWMA(); -- ewma.update(3); -- ewma.tick(); -+import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.Test; - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+final class EWMATest { -+ @Test -+ void aOneMinuteEWMAWithAValueOfThree() { -+ final EWMA ewma = EWMA.oneMinuteEWMA(); -+ ewma.update(3); -+ ewma.tick(); + @Test +- void testSubmitCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void submitCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + final Object obj = new Object(); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); -+ elapseMinute(ewma); +@@ -143,13 +143,13 @@ class InstrumentedScheduledExecutorServiceTest { + assertThat(submitted.getCount()).isEqualTo(1); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); + return obj; + }); +@@ -158,45 +158,45 @@ class InstrumentedScheduledExecutorServiceTest { -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.01098938, offset(0.000001)); -+ elapseMinute(ewma); + assertThat(submitted.getCount()).isEqualTo(1); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001)); +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00404277, offset(0.000001)); -+ elapseMinute(ewma); + @Test +- void testScheduleCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void scheduleCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001)); +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00148725, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001)); + final Object obj = new Object(); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00054713, offset(0.000001)); -+ elapseMinute(ewma); + ScheduledFuture theFuture = + instrumentedScheduledExecutor.schedule( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001)); + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00020128, offset(0.000001)); -+ elapseMinute(ewma); + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001)); + return obj; + }, +@@ -205,37 +205,37 @@ class InstrumentedScheduledExecutorServiceTest { -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00007405, offset(0.000001)); -+ elapseMinute(ewma); + assertThat(theFuture.get()).isEqualTo(obj); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001)); +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00002724, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001)); + @Test +- void testScheduleFixedRateCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void scheduleFixedRateCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00001002, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001)); +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000369, offset(0.000001)); -+ elapseMinute(ewma); + CountDownLatch countDownLatch = new CountDownLatch(1); + ScheduledFuture theFuture = + instrumentedScheduledExecutor.scheduleAtFixedRate( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001)); + assertThat(running.getCount()).isEqualTo(1); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000136, offset(0.000001)); -+ elapseMinute(ewma); +@@ -257,37 +257,37 @@ class InstrumentedScheduledExecutorServiceTest { + theFuture.cancel(true); + TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001)); +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000050, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isNotEqualTo(0); + assertThat(duration.getCount()).isNotEqualTo(0); + assertThat(duration.getSnapshot().size()).isNotEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001)); +- assertThat(scheduledOnce.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); + assertThat(scheduledRepetitively.getCount()).isEqualTo(1); + assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); + assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000018, offset(0.000001)); -- } -+ elapseMinute(ewma); + @Test +- void testScheduleFixedDelayCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void scheduleFixedDelayCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); -- @Test -- void aFiveMinuteEWMAWithAValueOfThree() { -- final EWMA ewma = EWMA.fiveMinuteEWMA(); -- ewma.update(3); -- ewma.tick(); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001)); -+ } +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ @Test -+ void aFiveMinuteEWMAWithAValueOfThree() { -+ final EWMA ewma = EWMA.fiveMinuteEWMA(); -+ ewma.update(3); -+ ewma.tick(); +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + CountDownLatch countDownLatch = new CountDownLatch(1); + ScheduledFuture theFuture = + instrumentedScheduledExecutor.scheduleWithFixedDelay( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); -+ elapseMinute(ewma); + assertThat(running.getCount()).isEqualTo(1); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); +@@ -310,9 +310,9 @@ class InstrumentedScheduledExecutorServiceTest { + theFuture.cancel(true); + TimeUnit.MILLISECONDS.sleep(200); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isNotEqualTo(0); + assertThat(duration.getCount()).isNotEqualTo(0); + assertThat(duration.getSnapshot().size()).isNotEqualTo(0); +@@ -322,7 +322,7 @@ class InstrumentedScheduledExecutorServiceTest { + void tearDown() throws Exception { + instrumentedScheduledExecutor.shutdown(); + if (!instrumentedScheduledExecutor.awaitTermination(2, TimeUnit.SECONDS)) { +- LOGGER.error("InstrumentedScheduledExecutorService did not terminate."); ++ LOG.error("InstrumentedScheduledExecutorService did not terminate."); + } + } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java +@@ -11,7 +11,7 @@ import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.Test; -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); -+ elapseMinute(ewma); +-class InstrumentedThreadFactoryTest { ++final class InstrumentedThreadFactoryTest { + private static final int THREAD_COUNT = 10; -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + private final ThreadFactory factory = Executors.defaultThreadFactory(); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java +@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.params.ParameterizedTest; + import org.junit.jupiter.params.provider.MethodSource; -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); -+ elapseMinute(ewma); +-public class MeterApproximationTest { ++final class MeterApproximationTest { -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + public static Collection ratesPerMinute() { + Object[][] data = new Object[][] {{15}, {60}, {600}, {6000}}; +@@ -32,7 +32,7 @@ public class MeterApproximationTest { + 3, TimeUnit.MINUTES); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ elapseMinute(ewma); + assertThat(meter.getOneMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + @MethodSource("ratesPerMinute") +@@ -45,7 +45,7 @@ public class MeterApproximationTest { + 13, TimeUnit.MINUTES); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.18071653, offset(0.000001)); -+ elapseMinute(ewma); + assertThat(meter.getFiveMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001)); + @MethodSource("ratesPerMinute") +@@ -58,7 +58,7 @@ public class MeterApproximationTest { + 38, TimeUnit.MINUTES); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.14795818, offset(0.000001)); -+ elapseMinute(ewma); + assertThat(meter.getFifteenMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001)); + private Meter simulateMetronome( +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java +@@ -9,8 +9,8 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.12113791, offset(0.000001)); -+ elapseMinute(ewma); +-class MeterTest { +- private final Clock clock = mock(Clock.class); ++final class MeterTest { ++ private final Clock clock = mock(); + private final Meter meter = new Meter(clock); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001)); + @BeforeEach +@@ -20,17 +20,17 @@ class MeterTest { -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.09917933, offset(0.000001)); -+ elapseMinute(ewma); + @Test + void startsOutWithNoRatesOrCount() { +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001)); +- assertThat(meter.getSum()).isZero(); ++ assertThat(meter.getSum()).isEqualTo(0); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(meter.getMeanRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001)); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.06648190, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001)); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.05443077, offset(0.000001)); -+ elapseMinute(ewma); + @Test +@@ -42,12 +42,12 @@ class MeterTest { -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001)); + assertThat(meter.getSum()).isEqualTo(10000000000L); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.04456415, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(meter.getMeanRate()).isEqualTo(0.3, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001)); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001)); +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.1840, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001)); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.03648604, offset(0.000001)); -+ elapseMinute(ewma); +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.1966, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001)); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001)); +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.1988, offset(0.001)); ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001)); + } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java +@@ -5,7 +5,7 @@ import static org.mockito.Mockito.mock; -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); -- } -+ elapseMinute(ewma); + import org.junit.jupiter.api.Test; -- @Test -- void aFifteenMinuteEWMAWithAValueOfThree() { -- final EWMA ewma = EWMA.fifteenMinuteEWMA(); -- ewma.update(3); -- ewma.tick(); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); -+ } +-class MetricFilterTest { ++final class MetricFilterTest { + @Test + void theAllFilterMatchesAllMetrics() { + assertThat(MetricFilter.ALL.matches(MetricName.build(""), mock(Metric.class))).isTrue(); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java +@@ -1,105 +1,106 @@ + package io.dropwizard.metrics5; -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ @Test -+ void aFifteenMinuteEWMAWithAValueOfThree() { -+ final EWMA ewma = EWMA.fifteenMinuteEWMA(); -+ ewma.update(3); -+ ewma.tick(); + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + import java.util.HashMap; + import java.util.Map; + import org.junit.jupiter.api.Test; -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.56130419, offset(0.000001)); -+ elapseMinute(ewma); +-class MetricNameTest { ++final class MetricNameTest { + @Test +- void testEmpty() { ++ void empty() { + assertThat(MetricName.EMPTY.getTags()).isEmpty(); +- assertThat(MetricName.EMPTY.getKey()).isEqualTo(""); ++ assertThat(MetricName.EMPTY.getKey()).isEmpty(); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001)); + assertThat(MetricName.build()).isEqualTo(MetricName.EMPTY); + assertThat(MetricName.EMPTY.resolve((String) null)).isEqualTo(MetricName.EMPTY); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.52510399, offset(0.000001)); -+ elapseMinute(ewma); + @Test +- void testEmptyResolve() { ++ void emptyResolve() { + final MetricName name = MetricName.build(); + assertThat(name.resolve("foo")).isEqualTo(MetricName.build("foo")); + } -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001)); + @Test +- void testResolveToEmpty() { ++ void resolveToEmpty() { + final MetricName name = MetricName.build("foo"); + assertThat(name.resolve((String) null)).isEqualTo(MetricName.build("foo")); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); -+ elapseMinute(ewma); + @Test +- void testResolve() { ++ void resolve() { + final MetricName name = MetricName.build("foo"); + assertThat(name.resolve("bar")).isEqualTo(MetricName.build("foo.bar")); + } -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); + @Test +- void testResolveBothEmpty() { ++ void resolveBothEmpty() { + final MetricName name = MetricName.build(); + assertThat(name.resolve((String) null)).isEqualTo(MetricName.EMPTY); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.45955700, offset(0.000001)); -+ elapseMinute(ewma); + @Test +- void testAddTagsVarious() { ++ void addTagsVarious() { + final Map refTags = new HashMap(); + refTags.put("foo", "bar"); + final MetricName test = MetricName.EMPTY.tagged("foo", "bar"); + final MetricName test2 = MetricName.EMPTY.tagged(refTags); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001)); + assertThat(test).isEqualTo(new MetricName("", refTags)); +- assertThat(test.getTags()).isEqualTo(refTags); ++ assertThat(test.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.42991879, offset(0.000001)); -+ elapseMinute(ewma); + assertThat(test2).isEqualTo(new MetricName("", refTags)); +- assertThat(test2.getTags()).isEqualTo(refTags); ++ assertThat(test2.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); + } -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001)); + @Test +- void testTaggedMoreArguments() { ++ void taggedMoreArguments() { + final Map refTags = new HashMap(); + refTags.put("foo", "bar"); + refTags.put("baz", "biz"); +- assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()).isEqualTo(refTags); ++ assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()) ++ .containsExactlyInAnyOrderEntriesOf(refTags); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); -+ elapseMinute(ewma); + @Test +- void testTaggedNotPairs() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- MetricName.EMPTY.tagged("foo"); +- }); ++ void taggedNotPairs() { ++ assertThatThrownBy( ++ () -> { ++ MetricName.EMPTY.tagged("foo"); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); + @Test +- void testTaggedNotPairs2() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- MetricName.EMPTY.tagged("foo", "bar", "baz"); +- }); ++ void taggedNotPairs2() { ++ assertThatThrownBy( ++ () -> { ++ MetricName.EMPTY.tagged("foo", "bar", "baz"); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.37625345, offset(0.000001)); -+ elapseMinute(ewma); + @Test +- void testCompareTo() { ++ void compareTo() { + final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); + final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001)); +- assertThat(a.compareTo(b)).isLessThan(0); +- assertThat(b.compareTo(a)).isGreaterThan(0); +- assertThat(b.resolve("key").compareTo(b)).isGreaterThan(0); +- assertThat(b.compareTo(b.resolve("key"))).isLessThan(0); ++ assertThat(a).isLessThan(b); ++ assertThat(b).isGreaterThan(a); ++ assertThat(b.resolve("key")).isGreaterThan(b); ++ assertThat(b).isLessThan(b.resolve("key")); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.35198773, offset(0.000001)); -+ elapseMinute(ewma); + @Test +- void testCompareTo2() { ++ void compareTo2() { + final MetricName a = MetricName.EMPTY.tagged("a", "x"); + final MetricName b = MetricName.EMPTY.tagged("b", "x"); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001)); +- assertThat(MetricName.EMPTY.compareTo(a)).isLessThan(0); +- assertThat(MetricName.EMPTY.compareTo(b)).isLessThan(0); +- assertThat(a.compareTo(b)).isLessThan(0); +- assertThat(b.compareTo(a)).isGreaterThan(0); ++ assertThat(MetricName.EMPTY).isLessThan(a); ++ assertThat(MetricName.EMPTY).isLessThan(b); ++ assertThat(a).isLessThan(b); ++ assertThat(b).isGreaterThan(a); + } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java +@@ -5,13 +5,13 @@ import static org.mockito.Mockito.verifyNoInteractions; -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); -+ elapseMinute(ewma); + import org.junit.jupiter.api.Test; -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); +-class MetricRegistryListenerTest { ++final class MetricRegistryListenerTest { + private static final MetricName BLAH = MetricName.build("blah"); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.30805027, offset(0.000001)); -+ elapseMinute(ewma); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + private final MetricRegistryListener listener = new MetricRegistryListener.Base() {}; -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001)); + @Test +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5; -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.28818318, offset(0.000001)); -+ elapseMinute(ewma); ++import static com.google.common.collect.ImmutableSet.toImmutableSet; + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatThrownBy; +@@ -11,11 +12,10 @@ import static org.mockito.Mockito.verify; + import java.util.HashMap; + import java.util.Map; + import java.util.Set; +-import java.util.stream.Collectors; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001)); +-class MetricRegistryTest { ++final class MetricRegistryTest { -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); -+ elapseMinute(ewma); + private static class CustomCounter extends Counter { -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); +@@ -37,14 +37,14 @@ class MetricRegistryTest { + private static final MetricName GAUGE2 = MetricName.build("gauge2"); + private static final MetricName SETTABLE_GAUGE = MetricName.build("settable-gauge"); + private static final MetricName THING = MetricName.build("thing"); +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); ++ private final MetricRegistryListener listener = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final Gauge gauge = () -> ""; + private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.25221023, offset(0.000001)); -+ elapseMinute(ewma); + @BeforeEach + void setUp() { +@@ -291,7 +291,7 @@ class MetricRegistryTest { + registry.register(METER2, meter); + registry.register(TIMER2, timer); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001)); +- final MetricRegistryListener other = mock(MetricRegistryListener.class); ++ final MetricRegistryListener other = mock(); + registry.addListener(other); + + verify(other).onGaugeAdded(GAUGE2, gauge); +@@ -425,7 +425,7 @@ class MetricRegistryTest { + MetricRegistry other = new MetricRegistry(); + other.register(GAUGE, gauge); + registry.register(MetricName.build("nested"), other); +- assertThat(registry.getNames()).containsOnly(MetricName.build("nested.gauge")); ++ assertThat(registry.getNames()).containsExactly(MetricName.build("nested.gauge")); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.23594443, offset(0.000001)); -+ elapseMinute(ewma); + @Test +@@ -501,10 +501,10 @@ class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); -- elapseMinute(ewma); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001)); + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + } -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -- } -+ elapseMinute(ewma); + @Test +@@ -522,10 +522,10 @@ class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); -+ } + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + } -- private void elapseMinute(EWMA ewma) { -- for (int i = 1; i <= 12; i++) { -- ewma.tick(); -- } -+ private void elapseMinute(EWMA ewma) { -+ for (int i = 1; i <= 12; i++) { -+ ewma.tick(); - } -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java -@@ -1,24 +1,23 @@ + @Test +@@ -548,19 +548,19 @@ class MetricRegistryTest { + Set deepChildMetrics = deepChild.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(childMetrics) + .containsAll( + deepChildMetrics.stream() + .map(m -> MetricName.build("deep-child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + +- assertThat(deepChildMetrics.size()).isEqualTo(3); +- assertThat(childMetrics.size()).isEqualTo(5); ++ assertThat(deepChildMetrics).hasSize(3); ++ assertThat(childMetrics).hasSize(5); + } + + @Test +@@ -578,10 +578,10 @@ class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(childMetrics).doesNotContain(MetricName.build("test-1")); + } +@@ -604,10 +604,10 @@ class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(childMetrics).doesNotContain(MetricName.build("test-1"), MetricName.build("test-3")); + } +@@ -633,21 +633,21 @@ class MetricRegistryTest { + Set deepChildMetrics = deepChild.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(childMetrics) + .containsAll( + deepChildMetrics.stream() + .map(m -> MetricName.build("deep-child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(deepChildMetrics).doesNotContain(MetricName.build("test-2")); + +- assertThat(deepChildMetrics.size()).isEqualTo(1); +- assertThat(childMetrics.size()).isEqualTo(3); ++ assertThat(deepChildMetrics).hasSize(1); ++ assertThat(childMetrics).hasSize(3); + } + + @Test +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java +@@ -1,7 +1,7 @@ package io.dropwizard.metrics5; --import org.junit.jupiter.api.Test; -- --import java.util.concurrent.TimeUnit; -- - import static org.junit.jupiter.api.Assertions.assertEquals; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatNullPointerException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; + import static org.mockito.Mockito.never; + import static org.mockito.Mockito.verify; +@@ -12,16 +12,16 @@ import java.util.Set; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; --public class ExponentialMovingAveragesTest { -- @Test -- public void testMaxTicks() { -- final Clock clock = mock(Clock.class); -- when(clock.getTick()).thenReturn(0L, Long.MAX_VALUE); -- final ExponentialMovingAverages ema = new ExponentialMovingAverages(clock); -- ema.update(Long.MAX_VALUE); -- ema.tickIfNecessary(); -- final long secondNanos = TimeUnit.SECONDS.toNanos(1); -- assertEquals(ema.getM1Rate(), Double.MIN_NORMAL * secondNanos, 0.0); -- assertEquals(ema.getM5Rate(), Double.MIN_NORMAL * secondNanos, 0.0); -- assertEquals(ema.getM15Rate(), Double.MIN_NORMAL * secondNanos, 0.0); -- } -+import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.Test; -+ -+final class ExponentialMovingAveragesTest { -+ @Test -+ void maxTicks() { -+ final Clock clock = mock(); -+ when(clock.getTick()).thenReturn(0L, Long.MAX_VALUE); -+ final ExponentialMovingAverages ema = new ExponentialMovingAverages(clock); -+ ema.update(Long.MAX_VALUE); -+ ema.tickIfNecessary(); -+ final long secondNanos = TimeUnit.SECONDS.toNanos(1); -+ assertEquals(ema.getM1Rate(), Double.MIN_NORMAL * secondNanos, 0.0); -+ assertEquals(ema.getM5Rate(), Double.MIN_NORMAL * secondNanos, 0.0); -+ assertEquals(ema.getM15Rate(), Double.MIN_NORMAL * secondNanos, 0.0); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java -@@ -1,437 +1,405 @@ - package io.dropwizard.metrics5; +-class NoopMetricRegistryTest { ++final class NoopMetricRegistryTest { + private static final MetricName METRIC_THING = MetricName.build("thing"); --import org.junit.jupiter.params.ParameterizedTest; --import org.junit.jupiter.params.provider.MethodSource; -+import static com.google.common.collect.ImmutableList.toImmutableList; -+import static org.assertj.core.api.Assertions.assertThat; +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); ++ private final MetricRegistryListener listener = mock(); + private final NoopMetricRegistry registry = new NoopMetricRegistry(); + private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); - import java.util.Arrays; - import java.util.Collection; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicBoolean; - import java.util.concurrent.atomic.AtomicInteger; --import java.util.stream.Collectors; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.params.ParameterizedTest; -+import org.junit.jupiter.params.provider.MethodSource; + @BeforeEach + void setUp() { +@@ -220,8 +220,8 @@ class NoopMetricRegistryTest { + verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); + } --public class ExponentiallyDecayingReservoirTest { -+final class ExponentiallyDecayingReservoirTest { +- @Test + @SuppressWarnings("rawtypes") ++ @Test + void accessingACustomGaugeRegistersAndReusesIt() { + final MetricRegistry.MetricSupplier> supplier = () -> gauge; + final Gauge gauge1 = registry.gauge(METRIC_THING, supplier); +@@ -242,7 +242,7 @@ class NoopMetricRegistryTest { + registry.register(MetricName.build("meter"), meter); + registry.register(MetricName.build("timer"), timer); -- public enum ReservoirFactory { -- EXPONENTIALLY_DECAYING() { -- @Override -- Reservoir create(int size, double alpha, Clock clock) { -- return new ExponentiallyDecayingReservoir(size, alpha, clock); -- } -+ public enum ReservoirFactory { -+ EXPONENTIALLY_DECAYING() { -+ @Override -+ Reservoir create(int size, double alpha, Clock clock) { -+ return new ExponentiallyDecayingReservoir(size, alpha, clock); -+ } - }, - -- LOCK_FREE_EXPONENTIALLY_DECAYING() { -- @Override -- Reservoir create(int size, double alpha, Clock clock) { -- return LockFreeExponentiallyDecayingReservoir.builder() -- .size(size) -- .alpha(alpha) -- .clock(clock) -- .build(); -- } -- }; -- -- abstract Reservoir create(int size, double alpha, Clock clock); -- -- Reservoir create(int size, double alpha) { -- return create(size, alpha, Clock.defaultClock()); -- } -+ LOCK_FREE_EXPONENTIALLY_DECAYING() { -+ @Override -+ Reservoir create(int size, double alpha, Clock clock) { -+ return LockFreeExponentiallyDecayingReservoir.builder() -+ .size(size) -+ .alpha(alpha) -+ .clock(clock) -+ .build(); -+ } -+ }; -+ -+ abstract Reservoir create(int size, double alpha, Clock clock); -+ -+ Reservoir create(int size, double alpha) { -+ return create(size, alpha, Clock.defaultClock()); - } -- -- public static Collection reservoirs() { -- return Arrays.stream(ReservoirFactory.values()) -- .map(value -> new Object[]{value}) -- .collect(Collectors.toList()); -+ } -+ -+ public static Collection reservoirs() { -+ return Arrays.stream(ReservoirFactory.values()) -+ .map(value -> new Object[] {value}) -+ .collect(toImmutableList()); -+ } -+ -+ private ReservoirFactory reservoirFactory; -+ -+ public void initExponentiallyDecayingReservoirTest(ReservoirFactory reservoirFactory) { -+ this.reservoirFactory = reservoirFactory; -+ } -+ -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void aReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final Reservoir reservoir = reservoirFactory.create(100, 0.99); -+ for (int i = 0; i < 1000; i++) { -+ reservoir.update(i); - } +- final MetricRegistryListener other = mock(MetricRegistryListener.class); ++ final MetricRegistryListener other = mock(); + registry.addListener(other); -- private ReservoirFactory reservoirFactory; -- -- public void initExponentiallyDecayingReservoirTest(ReservoirFactory reservoirFactory) { -- this.reservoirFactory = reservoirFactory; -- } -- -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void aReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final Reservoir reservoir = reservoirFactory.create(100, 0.99); -- for (int i = 0; i < 1000; i++) { -- reservoir.update(i); -- } -+ assertThat(reservoir.size()).isEqualTo(100); - -- assertThat(reservoir.size()) -- .isEqualTo(100); -+ final Snapshot snapshot = reservoir.getSnapshot(); - -- final Snapshot snapshot = reservoir.getSnapshot(); -+ assertThat(snapshot.size()).isEqualTo(100); - -- assertThat(snapshot.size()) -- .isEqualTo(100); -+ assertAllValuesBetween(reservoir, 0, 1000); -+ } - -- assertAllValuesBetween(reservoir, 0, 1000); -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void aReservoirOf100OutOf10Elements(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final Reservoir reservoir = reservoirFactory.create(100, 0.99); -+ for (int i = 0; i < 10; i++) { -+ reservoir.update(i); - } + verify(other, never()).onGaugeAdded(MetricName.build("gauge"), gauge); +@@ -491,8 +491,8 @@ class NoopMetricRegistryTest { + @Test + void registerNullMetric() { + MetricRegistry registry = new NoopMetricRegistry(); +- assertThatNullPointerException() +- .isThrownBy(() -> registry.register(MetricName.build("any_name"), null)) +- .withMessage("metric == null"); ++ assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)) ++ .isInstanceOf(NullPointerException.class) ++ .hasMessage("metric == null"); + } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java +@@ -4,12 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat; -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void aReservoirOf100OutOf10Elements(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final Reservoir reservoir = reservoirFactory.create(100, 0.99); -- for (int i = 0; i < 10; i++) { -- reservoir.update(i); -- } -+ final Snapshot snapshot = reservoir.getSnapshot(); - -- final Snapshot snapshot = reservoir.getSnapshot(); -+ assertThat(snapshot.size()).isEqualTo(10); - -- assertThat(snapshot.size()) -- .isEqualTo(10); -+ assertThat(snapshot.size()).isEqualTo(10); - -- assertThat(snapshot.size()) -- .isEqualTo(10); -+ assertAllValuesBetween(reservoir, 0, 10); -+ } - -- assertAllValuesBetween(reservoir, 0, 10); -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void aHeavilyBiasedReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final Reservoir reservoir = reservoirFactory.create(1000, 0.01); -+ for (int i = 0; i < 100; i++) { -+ reservoir.update(i); - } + import org.junit.jupiter.api.Test; -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void aHeavilyBiasedReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final Reservoir reservoir = reservoirFactory.create(1000, 0.01); -- for (int i = 0; i < 100; i++) { -- reservoir.update(i); -- } -+ assertThat(reservoir.size()).isEqualTo(100); - -+ final Snapshot snapshot = reservoir.getSnapshot(); - -- assertThat(reservoir.size()) -- .isEqualTo(100); -+ assertThat(snapshot.size()).isEqualTo(100); - -- final Snapshot snapshot = reservoir.getSnapshot(); -+ assertAllValuesBetween(reservoir, 0, 100); -+ } - -- assertThat(snapshot.size()) -- .isEqualTo(100); -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void longPeriodsOfInactivityShouldNotCorruptSamplingState(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final ManualClock clock = new ManualClock(); -+ final Reservoir reservoir = reservoirFactory.create(10, 0.15, clock); - -- assertAllValuesBetween(reservoir, 0, 100); -+ // add 1000 values at a rate of 10 values/second -+ for (int i = 0; i < 1000; i++) { -+ reservoir.update(1000 + i); -+ clock.addMillis(100); - } -- -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void longPeriodsOfInactivityShouldNotCorruptSamplingState(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final ManualClock clock = new ManualClock(); -- final Reservoir reservoir = reservoirFactory.create(10, 0.15, clock); -- -- // add 1000 values at a rate of 10 values/second -- for (int i = 0; i < 1000; i++) { -- reservoir.update(1000 + i); -- clock.addMillis(100); -- } -- assertThat(reservoir.getSnapshot().size()) -- .isEqualTo(10); -- assertAllValuesBetween(reservoir, 1000, 2000); -- -- // wait for 15 hours and add another value. -- // this should trigger a rescale. Note that the number of samples will be reduced to 1 -- // because scaling factor equal to zero will remove all existing entries after rescale. -- clock.addHours(15); -- reservoir.update(2000); -- assertThat(reservoir.getSnapshot().size()) -- .isEqualTo(1); -- assertAllValuesBetween(reservoir, 1000, 2001); -- -- -- // add 1000 values at a rate of 10 values/second -- for (int i = 0; i < 1000; i++) { -- reservoir.update(3000 + i); -- clock.addMillis(100); -- } -- assertThat(reservoir.getSnapshot().size()) -- .isEqualTo(10); -- assertAllValuesBetween(reservoir, 3000, 4000); -- } -- -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void longPeriodsOfInactivity_fetchShouldResample(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final ManualClock clock = new ManualClock(); -- final Reservoir reservoir = reservoirFactory.create(10, -- 0.015, -- clock); -- -- // add 1000 values at a rate of 10 values/second -- for (int i = 0; i < 1000; i++) { -- reservoir.update(1000 + i); -- clock.addMillis(100); -- } -- assertThat(reservoir.getSnapshot().size()) -- .isEqualTo(10); -- assertAllValuesBetween(reservoir, 1000, 2000); -- -- // wait for 20 hours and take snapshot. -- // this should trigger a rescale. Note that the number of samples will be reduced to 0 -- // because scaling factor equal to zero will remove all existing entries after rescale. -- clock.addHours(20); -- Snapshot snapshot = reservoir.getSnapshot(); -- assertThat(snapshot.getMax()).isEqualTo(0); -- assertThat(snapshot.getMean()).isEqualTo(0); -- assertThat(snapshot.getMedian()).isEqualTo(0); -- assertThat(snapshot.size()).isEqualTo(0); -+ assertThat(reservoir.getSnapshot().size()).isEqualTo(10); -+ assertAllValuesBetween(reservoir, 1000, 2000); -+ -+ // wait for 15 hours and add another value. -+ // this should trigger a rescale. Note that the number of samples will be reduced to 1 -+ // because scaling factor equal to zero will remove all existing entries after rescale. -+ clock.addHours(15); -+ reservoir.update(2000); -+ assertThat(reservoir.getSnapshot().size()).isEqualTo(1); -+ assertAllValuesBetween(reservoir, 1000, 2001); -+ -+ // add 1000 values at a rate of 10 values/second -+ for (int i = 0; i < 1000; i++) { -+ reservoir.update(3000 + i); -+ clock.addMillis(100); - } -- -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void emptyReservoirSnapshot_shouldReturnZeroForAllValues(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final Reservoir reservoir = reservoirFactory.create(100, 0.015, -- new ManualClock()); -- -- Snapshot snapshot = reservoir.getSnapshot(); -- assertThat(snapshot.getMax()).isEqualTo(0); -- assertThat(snapshot.getMean()).isEqualTo(0); -- assertThat(snapshot.getMedian()).isEqualTo(0); -- assertThat(snapshot.size()).isEqualTo(0); -+ assertThat(reservoir.getSnapshot().size()).isEqualTo(10); -+ assertAllValuesBetween(reservoir, 3000, 4000); -+ } -+ -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void longPeriodsOfInactivity_fetchShouldResample(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final ManualClock clock = new ManualClock(); -+ final Reservoir reservoir = reservoirFactory.create(10, 0.015, clock); -+ -+ // add 1000 values at a rate of 10 values/second -+ for (int i = 0; i < 1000; i++) { -+ reservoir.update(1000 + i); -+ clock.addMillis(100); - } -- -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void removeZeroWeightsInSamplesToPreventNaNInMeanValues(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final ManualClock clock = new ManualClock(); -- final Reservoir reservoir = reservoirFactory.create(1028, 0.015, clock); -- Timer timer = new Timer(reservoir, clock); -- -- Timer.Context context = timer.time(); -- clock.addMillis(100); -- context.stop(); -- -- for (int i = 1; i < 48; i++) { -- clock.addHours(1); -- assertThat(reservoir.getSnapshot().getMean()).isBetween(0.0, Double.MAX_VALUE); -- } -+ assertThat(reservoir.getSnapshot().size()).isEqualTo(10); -+ assertAllValuesBetween(reservoir, 1000, 2000); -+ -+ // wait for 20 hours and take snapshot. -+ // this should trigger a rescale. Note that the number of samples will be reduced to 0 -+ // because scaling factor equal to zero will remove all existing entries after rescale. -+ clock.addHours(20); -+ Snapshot snapshot = reservoir.getSnapshot(); -+ assertThat(snapshot.getMax()).isEqualTo(0); -+ assertThat(snapshot.getMean()).isEqualTo(0); -+ assertThat(snapshot.getMedian()).isEqualTo(0); -+ assertThat(snapshot.size()).isEqualTo(0); -+ } -+ -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void emptyReservoirSnapshot_shouldReturnZeroForAllValues(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final Reservoir reservoir = reservoirFactory.create(100, 0.015, new ManualClock()); -+ -+ Snapshot snapshot = reservoir.getSnapshot(); -+ assertThat(snapshot.getMax()).isEqualTo(0); -+ assertThat(snapshot.getMean()).isEqualTo(0); -+ assertThat(snapshot.getMedian()).isEqualTo(0); -+ assertThat(snapshot.size()).isEqualTo(0); -+ } -+ -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void removeZeroWeightsInSamplesToPreventNaNInMeanValues(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final ManualClock clock = new ManualClock(); -+ final Reservoir reservoir = reservoirFactory.create(1028, 0.015, clock); -+ Timer timer = new Timer(reservoir, clock); -+ -+ Timer.Context context = timer.time(); -+ clock.addMillis(100); -+ context.stop(); -+ -+ for (int i = 1; i < 48; i++) { -+ clock.addHours(1); -+ assertThat(reservoir.getSnapshot().getMean()).isBetween(0.0, Double.MAX_VALUE); - } -- -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void multipleUpdatesAfterlongPeriodsOfInactivityShouldNotCorruptSamplingState(ReservoirFactory reservoirFactory) throws Exception { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- // This test illustrates the potential race condition in rescale that -- // can lead to a corrupt state. Note that while this test uses updates -- // exclusively to trigger the race condition, two concurrent updates -- // may be made much more likely to trigger this behavior if executed -- // while another thread is constructing a snapshot of the reservoir; -- // that thread then holds the read lock when the two competing updates -- // are executed and the race condition's window is substantially -- // expanded. -- -- // Run the test several times. -- for (int attempt = 0; attempt < 10; attempt++) { -- final ManualClock clock = new ManualClock(); -- final Reservoir reservoir = reservoirFactory.create(10, -- 0.015, -- clock); -- -- // Various atomics used to communicate between this thread and the -- // thread created below. -- final AtomicBoolean running = new AtomicBoolean(true); -- final AtomicInteger threadUpdates = new AtomicInteger(0); -- final AtomicInteger testUpdates = new AtomicInteger(0); -- -- final Thread thread = new Thread(() -> { -+ } -+ -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void multipleUpdatesAfterlongPeriodsOfInactivityShouldNotCorruptSamplingState( -+ ReservoirFactory reservoirFactory) throws Exception { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ // This test illustrates the potential race condition in rescale that -+ // can lead to a corrupt state. Note that while this test uses updates -+ // exclusively to trigger the race condition, two concurrent updates -+ // may be made much more likely to trigger this behavior if executed -+ // while another thread is constructing a snapshot of the reservoir; -+ // that thread then holds the read lock when the two competing updates -+ // are executed and the race condition's window is substantially -+ // expanded. -+ -+ // Run the test several times. -+ for (int attempt = 0; attempt < 10; attempt++) { -+ final ManualClock clock = new ManualClock(); -+ final Reservoir reservoir = reservoirFactory.create(10, 0.015, clock); -+ -+ // Various atomics used to communicate between this thread and the -+ // thread created below. -+ final AtomicBoolean running = new AtomicBoolean(true); -+ final AtomicInteger threadUpdates = new AtomicInteger(0); -+ final AtomicInteger testUpdates = new AtomicInteger(0); -+ -+ final Thread thread = -+ new Thread( -+ () -> { - int previous = 0; - while (running.get()) { -- // Wait for the test thread to update it's counter -- // before updaing the reservoir. -- while (true) { -- int next = testUpdates.get(); -- if (previous < next) { -- previous = next; -- break; -- } -+ // Wait for the test thread to update it's counter -+ // before updaing the reservoir. -+ while (true) { -+ int next = testUpdates.get(); -+ if (previous < next) { -+ previous = next; -+ break; - } -+ } - -- // Update the reservoir. This needs to occur at the -- // same time as the test thread's update. -- reservoir.update(1000); -+ // Update the reservoir. This needs to occur at the -+ // same time as the test thread's update. -+ reservoir.update(1000); - -- // Signal the main thread; allows the next update -- // attempt to begin. -- threadUpdates.incrementAndGet(); -- } -- }); -- -- thread.start(); -- -- int sum = 0; -- int previous = -1; -- for (int i = 0; i < 100; i++) { -- // Wait for 15 hours before attempting the next concurrent -- // update. The delay here needs to be sufficiently long to -- // overflow if an update attempt is allowed to add a value to -- // the reservoir without rescaling. Note that: -- // e(alpha*(15*60*60)) =~ 10^351 >> Double.MAX_VALUE =~ 1.8*10^308. -- clock.addHours(15); -- -- // Signal the other thread; asynchronously updates the reservoir. -- testUpdates.incrementAndGet(); -- -- // Delay a variable length of time. Without a delay here this -- // thread is heavily favored and the race condition is almost -- // never observed. -- for (int j = 0; j < i; j++) -- sum += j; -- -- // Competing reservoir update. -- reservoir.update(1000); -- -- // Wait for the other thread to finish it's update. -- while (true) { -- int next = threadUpdates.get(); -- if (previous < next) { -- previous = next; -- break; -- } -+ // Signal the main thread; allows the next update -+ // attempt to begin. -+ threadUpdates.incrementAndGet(); - } -- } -+ }); -+ -+ thread.start(); -+ -+ int sum = 0; -+ int previous = -1; -+ for (int i = 0; i < 100; i++) { -+ // Wait for 15 hours before attempting the next concurrent -+ // update. The delay here needs to be sufficiently long to -+ // overflow if an update attempt is allowed to add a value to -+ // the reservoir without rescaling. Note that: -+ // e(alpha*(15*60*60)) =~ 10^351 >> Double.MAX_VALUE =~ 1.8*10^308. -+ clock.addHours(15); - -- // Terminate the thread. -- running.set(false); -- testUpdates.incrementAndGet(); -- thread.join(); -+ // Signal the other thread; asynchronously updates the reservoir. -+ testUpdates.incrementAndGet(); - -- // Test failures will result in normWeights that are not finite; -- // checking the mean value here is sufficient. -- assertThat(reservoir.getSnapshot().getMean()).isBetween(0.0, Double.MAX_VALUE); -+ // Delay a variable length of time. Without a delay here this -+ // thread is heavily favored and the race condition is almost -+ // never observed. -+ for (int j = 0; j < i; j++) sum += j; - -- // Check the value of sum; should prevent the JVM from optimizing -- // out the delay loop entirely. -- assertThat(sum).isEqualTo(161700); -- } -- } -+ // Competing reservoir update. -+ reservoir.update(1000); - -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void spotLift(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final ManualClock clock = new ManualClock(); -- final Reservoir reservoir = reservoirFactory.create(1000, -- 0.015, -- clock); -- -- final int valuesRatePerMinute = 10; -- final int valuesIntervalMillis = (int) (TimeUnit.MINUTES.toMillis(1) / valuesRatePerMinute); -- // mode 1: steady regime for 120 minutes -- for (int i = 0; i < 120 * valuesRatePerMinute; i++) { -- reservoir.update(177); -- clock.addMillis(valuesIntervalMillis); -+ // Wait for the other thread to finish it's update. -+ while (true) { -+ int next = threadUpdates.get(); -+ if (previous < next) { -+ previous = next; -+ break; -+ } - } -+ } +-class RatioGaugeTest { ++final class RatioGaugeTest { + @Test + void ratiosAreHumanReadable() { + final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); -- // switching to mode 2: 10 minutes more with the same rate, but larger value -- for (int i = 0; i < 10 * valuesRatePerMinute; i++) { -- reservoir.update(9999); -- clock.addMillis(valuesIntervalMillis); -- } -+ // Terminate the thread. -+ running.set(false); -+ testUpdates.incrementAndGet(); -+ thread.join(); - -- // expect that quantiles should be more about mode 2 after 10 minutes -- assertThat(reservoir.getSnapshot().getMedian()) -- .isEqualTo(9999); -- } -+ // Test failures will result in normWeights that are not finite; -+ // checking the mean value here is sufficient. -+ assertThat(reservoir.getSnapshot().getMean()).isBetween(0.0, Double.MAX_VALUE); - -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void spotFall(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final ManualClock clock = new ManualClock(); -- final Reservoir reservoir = reservoirFactory.create(1000, -- 0.015, -- clock); -- -- final int valuesRatePerMinute = 10; -- final int valuesIntervalMillis = (int) (TimeUnit.MINUTES.toMillis(1) / valuesRatePerMinute); -- // mode 1: steady regime for 120 minutes -- for (int i = 0; i < 120 * valuesRatePerMinute; i++) { -- reservoir.update(9998); -- clock.addMillis(valuesIntervalMillis); -- } -- -- // switching to mode 2: 10 minutes more with the same rate, but smaller value -- for (int i = 0; i < 10 * valuesRatePerMinute; i++) { -- reservoir.update(178); -- clock.addMillis(valuesIntervalMillis); -- } -- -- // expect that quantiles should be more about mode 2 after 10 minutes -- assertThat(reservoir.getSnapshot().get95thPercentile()) -- .isEqualTo(178); -+ // Check the value of sum; should prevent the JVM from optimizing -+ // out the delay loop entirely. -+ assertThat(sum).isEqualTo(161700); -+ } -+ } -+ -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void spotLift(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final ManualClock clock = new ManualClock(); -+ final Reservoir reservoir = reservoirFactory.create(1000, 0.015, clock); -+ -+ final int valuesRatePerMinute = 10; -+ final int valuesIntervalMillis = (int) (TimeUnit.MINUTES.toMillis(1) / valuesRatePerMinute); -+ // mode 1: steady regime for 120 minutes -+ for (int i = 0; i < 120 * valuesRatePerMinute; i++) { -+ reservoir.update(177); -+ clock.addMillis(valuesIntervalMillis); - } +- assertThat(ratio.toString()).isEqualTo("100.0:200.0"); ++ assertThat(ratio).hasToString("100.0:200.0"); + } -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void quantiliesShouldBeBasedOnWeights(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- final ManualClock clock = new ManualClock(); -- final Reservoir reservoir = reservoirFactory.create(1000, -- 0.015, -- clock); -- for (int i = 0; i < 40; i++) { -- reservoir.update(177); -- } -- -- clock.addSeconds(120); -- -- for (int i = 0; i < 10; i++) { -- reservoir.update(9999); -- } -+ // switching to mode 2: 10 minutes more with the same rate, but larger value -+ for (int i = 0; i < 10 * valuesRatePerMinute; i++) { -+ reservoir.update(9999); -+ clock.addMillis(valuesIntervalMillis); -+ } - -- assertThat(reservoir.getSnapshot().size()) -- .isEqualTo(50); -+ // expect that quantiles should be more about mode 2 after 10 minutes -+ assertThat(reservoir.getSnapshot().getMedian()).isEqualTo(9999); -+ } -+ -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void spotFall(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final ManualClock clock = new ManualClock(); -+ final Reservoir reservoir = reservoirFactory.create(1000, 0.015, clock); -+ -+ final int valuesRatePerMinute = 10; -+ final int valuesIntervalMillis = (int) (TimeUnit.MINUTES.toMillis(1) / valuesRatePerMinute); -+ // mode 1: steady regime for 120 minutes -+ for (int i = 0; i < 120 * valuesRatePerMinute; i++) { -+ reservoir.update(9998); -+ clock.addMillis(valuesIntervalMillis); -+ } - -- // the first added 40 items (177) have weights 1 -- // the next added 10 items (9999) have weights ~6 -- // so, it's 40 vs 60 distribution, not 40 vs 10 -- assertThat(reservoir.getSnapshot().getMedian()) -- .isEqualTo(9999); -- assertThat(reservoir.getSnapshot().get75thPercentile()) -- .isEqualTo(9999); -+ // switching to mode 2: 10 minutes more with the same rate, but smaller value -+ for (int i = 0; i < 10 * valuesRatePerMinute; i++) { -+ reservoir.update(178); -+ clock.addMillis(valuesIntervalMillis); - } + @Test +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java +@@ -1,10 +1,9 @@ + package io.dropwizard.metrics5; -- @MethodSource("reservoirs") -- @ParameterizedTest(name = "{index}: {0}") -- void clockWrapShouldNotRescale(ReservoirFactory reservoirFactory) { -- initExponentiallyDecayingReservoirTest(reservoirFactory); -- // First verify the test works as expected given low values -- testShortPeriodShouldNotRescale(0); -- // Now revalidate using an edge case nanoTime value just prior to wrapping -- testShortPeriodShouldNotRescale(Long.MAX_VALUE - TimeUnit.MINUTES.toNanos(30)); -+ // expect that quantiles should be more about mode 2 after 10 minutes -+ assertThat(reservoir.getSnapshot().get95thPercentile()).isEqualTo(178); -+ } -+ -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void quantiliesShouldBeBasedOnWeights(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ final ManualClock clock = new ManualClock(); -+ final Reservoir reservoir = reservoirFactory.create(1000, 0.015, clock); -+ for (int i = 0; i < 40; i++) { -+ reservoir.update(177); - } ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; ++import static org.assertj.core.api.Assertions.fail; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertFalse; +-import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.junit.jupiter.api.Assertions.assertTrue; +-import static org.junit.jupiter.api.Assertions.fail; + import static org.mockito.Mockito.any; + import static org.mockito.Mockito.eq; + import static org.mockito.Mockito.mock; +@@ -25,14 +24,14 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- private void testShortPeriodShouldNotRescale(long startTimeNanos) { -- final ManualClock clock = new ManualClock(startTimeNanos); -- final Reservoir reservoir = reservoirFactory.create(10, 1, clock); -+ clock.addSeconds(120); +-class ScheduledReporterTest { ++final class ScheduledReporterTest { + private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); -- reservoir.update(1000); -- assertThat(reservoir.getSnapshot().size()).isEqualTo(1); -- -- assertAllValuesBetween(reservoir, 1000, 1001); -- -- // wait for 10 millis and take snapshot. -- // this should not trigger a rescale. Note that the number of samples will be reduced to 0 -- // because scaling factor equal to zero will remove all existing entries after rescale. -- clock.addSeconds(20 * 60); -- Snapshot snapshot = reservoir.getSnapshot(); -- assertThat(snapshot.getMax()).isEqualTo(1000); -- assertThat(snapshot.getMean()).isEqualTo(1000); -- assertThat(snapshot.getMedian()).isEqualTo(1000); -- assertThat(snapshot.size()).isEqualTo(1); -+ for (int i = 0; i < 10; i++) { -+ reservoir.update(9999); - } +- private final ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); ++ private final ScheduledExecutorService mockExecutor = mock(); + private final ScheduledExecutorService customExecutor = + Executors.newSingleThreadScheduledExecutor(); + private final ScheduledExecutorService externalExecutor = +@@ -145,7 +144,7 @@ class ScheduledReporterTest { + void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { + reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); + +- verify(mockExecutor, times(1)) ++ verify(mockExecutor) + .scheduleWithFixedDelay(any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS)); + } -- private static void assertAllValuesBetween(Reservoir reservoir, -- double min, -- double max) { -- for (double i : reservoir.getSnapshot().getValues()) { -- assertThat(i) -- .isLessThan(max) -- .isGreaterThanOrEqualTo(min); -- } -+ assertThat(reservoir.getSnapshot().size()).isEqualTo(50); -+ -+ // the first added 40 items (177) have weights 1 -+ // the next added 10 items (9999) have weights ~6 -+ // so, it's 40 vs 60 distribution, not 40 vs 10 -+ assertThat(reservoir.getSnapshot().getMedian()).isEqualTo(9999); -+ assertThat(reservoir.getSnapshot().get75thPercentile()).isEqualTo(9999); -+ } -+ -+ @MethodSource("reservoirs") -+ @ParameterizedTest(name = "{index}: {0}") -+ void clockWrapShouldNotRescale(ReservoirFactory reservoirFactory) { -+ initExponentiallyDecayingReservoirTest(reservoirFactory); -+ // First verify the test works as expected given low values -+ testShortPeriodShouldNotRescale(0); -+ // Now revalidate using an edge case nanoTime value just prior to wrapping -+ testShortPeriodShouldNotRescale(Long.MAX_VALUE - TimeUnit.MINUTES.toNanos(30)); -+ } -+ -+ private void testShortPeriodShouldNotRescale(long startTimeNanos) { -+ final ManualClock clock = new ManualClock(startTimeNanos); -+ final Reservoir reservoir = reservoirFactory.create(10, 1, clock); -+ -+ reservoir.update(1000); -+ assertThat(reservoir.getSnapshot().size()).isEqualTo(1); -+ -+ assertAllValuesBetween(reservoir, 1000, 1001); -+ -+ // wait for 10 millis and take snapshot. -+ // this should not trigger a rescale. Note that the number of samples will be reduced to 0 -+ // because scaling factor equal to zero will remove all existing entries after rescale. -+ clock.addSeconds(20 * 60); -+ Snapshot snapshot = reservoir.getSnapshot(); -+ assertThat(snapshot.getMax()).isEqualTo(1000); -+ assertThat(snapshot.getMean()).isEqualTo(1000); -+ assertThat(snapshot.getMedian()).isEqualTo(1000); -+ assertThat(snapshot.size()).isEqualTo(1); -+ } -+ -+ private static void assertAllValuesBetween(Reservoir reservoir, double min, double max) { -+ for (double i : reservoir.getSnapshot().getValues()) { -+ assertThat(i).isLessThan(max).isGreaterThanOrEqualTo(min); - } -- -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java -@@ -1,47 +1,45 @@ - package io.dropwizard.metrics5; +@@ -182,32 +181,32 @@ class ScheduledReporterTest { --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; --import org.junit.jupiter.api.io.TempDir; -+import static org.assertj.core.api.Assertions.assertThat; + @Test + void shouldDisallowToStartReportingMultiple() throws Exception { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- reporter.start(200, TimeUnit.MILLISECONDS); +- reporter.start(200, TimeUnit.MILLISECONDS); +- }); ++ assertThatThrownBy( ++ () -> { ++ reporter.start(200, TimeUnit.MILLISECONDS); ++ reporter.start(200, TimeUnit.MILLISECONDS); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } - import java.io.File; - import java.io.IOException; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; -+import org.junit.jupiter.api.io.TempDir; + @Test + void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); +- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); +- }); ++ assertThatThrownBy( ++ () -> { ++ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); ++ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } --import static org.assertj.core.api.Assertions.assertThat; -- --public class FixedNameCsvFileProviderTest { -- @TempDir -- public File folder; -- -- private File dataDirectory; -- -- @BeforeEach -- void setUp() throws Exception { -- this.dataDirectory = newFolder(folder, "junit"); -- } -- -- @Test -- void testGetFile() { -- FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); -- File file = provider.getFile(dataDirectory, "test"); -- assertThat(file.getParentFile()).isEqualTo(dataDirectory); -- assertThat(file.getName()).isEqualTo("test.csv"); -- } -- -- @Test -- void testGetFileSanitize() { -- FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); -- File file = provider.getFile(dataDirectory, "/myfake/uri"); -- assertThat(file.getParentFile()).isEqualTo(dataDirectory); -- assertThat(file.getName()).isEqualTo("myfake.uri.csv"); -- } -- -- private static File newFolder(File root, String... subDirs) throws IOException { -- String subFolder = String.join("/", subDirs); -- File result = new File(root, subFolder); -- if (!result.mkdirs()) { -- throw new IOException("Couldn't create folders " + root); -- } -- return result; -+final class FixedNameCsvFileProviderTest { -+ @TempDir public File folder; -+ -+ private File dataDirectory; -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ this.dataDirectory = newFolder(folder, "junit"); -+ } -+ -+ @Test -+ void getFile() { -+ FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); -+ File file = provider.getFile(dataDirectory, "test"); -+ assertThat(file.getParentFile()).isEqualTo(dataDirectory); -+ assertThat(file.getName()).isEqualTo("test.csv"); -+ } -+ -+ @Test -+ void getFileSanitize() { -+ FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); -+ File file = provider.getFile(dataDirectory, "/myfake/uri"); -+ assertThat(file.getParentFile()).isEqualTo(dataDirectory); -+ assertThat(file.getName()).isEqualTo("myfake.uri.csv"); -+ } -+ -+ private static File newFolder(File root, String... subDirs) throws IOException { -+ String subFolder = String.join("/", subDirs); -+ File result = new File(root, subFolder); -+ if (!result.mkdirs()) { -+ throw new IOException("Couldn't create folders " + root); - } --} -\ No newline at end of file -+ return result; -+ } -+} ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java -@@ -1,45 +1,40 @@ - package io.dropwizard.metrics5; + @Test + void shouldDisallowToStartReportingMultipleTimesOnExternallyManagedExecutor() throws Exception { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); +- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); +- }); ++ assertThatThrownBy( ++ () -> { ++ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); ++ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test +@@ -231,15 +230,15 @@ class ScheduledReporterTest { + void shouldShutdownExecutorOnStopByDefault() { + reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); + reporterWithCustomExecutor.stop(); +- assertTrue(customExecutor.isTerminated()); ++ assertThat(customExecutor.isTerminated()).isTrue(); + } + + @Test + void shouldNotShutdownExternallyManagedExecutorOnStop() { + reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); + reporterWithExternallyManagedExecutor.stop(); +- assertFalse(mockExecutor.isTerminated()); +- assertFalse(mockExecutor.isShutdown()); ++ assertThat(mockExecutor.isTerminated()).isFalse(); ++ assertThat(mockExecutor.isShutdown()).isFalse(); + } + + @Test +@@ -306,7 +305,7 @@ class ScheduledReporterTest { + + Thread.sleep(1_000); + +- verify(reporter, times(1)) ++ verify(reporter) + .report( + map(MetricName.build("gauge"), gauge), + map(MetricName.build("counter"), counter), +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java +@@ -2,13 +2,12 @@ package io.dropwizard.metrics5; --import org.junit.jupiter.api.Test; -- import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; + import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.junit.jupiter.api.Assertions.assertTrue; --class HistogramTest { -- private final Reservoir reservoir = mock(Reservoir.class); -- private final Histogram histogram = new Histogram(reservoir); -- -- @Test -- void updatesTheCountAndSumOnUpdates() { -- assertThat(histogram.getCount()) -- .isZero(); -- assertThat(histogram.getSum()) -- .isZero(); -- -- histogram.update(1); -- histogram.update(5); -- -- assertThat(histogram.getCount()) -- .isEqualTo(2); -- assertThat(histogram.getSum()) -- .isEqualTo(6); -- } -- -- @Test -- void returnsTheSnapshotFromTheReservoir() { -- final Snapshot snapshot = mock(Snapshot.class); -- when(reservoir.getSnapshot()).thenReturn(snapshot); -- -- assertThat(histogram.getSnapshot()) -- .isEqualTo(snapshot); -- } -- -- @Test -- void updatesTheReservoir() throws Exception { -- histogram.update(1); -- -- verify(reservoir).update(1); -- } -+import org.junit.jupiter.api.Test; -+ -+final class HistogramTest { -+ private final Reservoir reservoir = mock(); -+ private final Histogram histogram = new Histogram(reservoir); -+ -+ @Test -+ void updatesTheCountAndSumOnUpdates() { -+ assertThat(histogram.getCount()).isEqualTo(0); -+ assertThat(histogram.getSum()).isEqualTo(0); -+ -+ histogram.update(1); -+ histogram.update(5); -+ -+ assertThat(histogram.getCount()).isEqualTo(2); -+ assertThat(histogram.getSum()).isEqualTo(6); -+ } -+ -+ @Test -+ void returnsTheSnapshotFromTheReservoir() { -+ final Snapshot snapshot = mock(); -+ when(reservoir.getSnapshot()).thenReturn(snapshot); -+ -+ assertThat(histogram.getSnapshot()).isEqualTo(snapshot); -+ } -+ -+ @Test -+ void updatesTheReservoir() throws Exception { -+ histogram.update(1); -+ -+ verify(reservoir).update(1); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java -@@ -1,10 +1,7 @@ - package io.dropwizard.metrics5; + import java.util.concurrent.atomic.AtomicReference; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; +-class SharedMetricRegistriesTest { ++final class SharedMetricRegistriesTest { - import java.time.Duration; - import java.util.concurrent.Callable; -@@ -16,283 +13,301 @@ import java.util.concurrent.LinkedBlockingQueue; - import java.util.concurrent.RejectedExecutionException; - import java.util.concurrent.ThreadPoolExecutor; - import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatThrownBy; -- --class InstrumentedExecutorServiceTest { -- -- private static final Logger LOGGER = LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); -- private ExecutorService executor; -- private MetricRegistry registry; -- private InstrumentedExecutorService instrumentedExecutorService; -- private Meter submitted; -- private Counter running; -- private Meter completed; -- private Timer duration; -- private Timer idle; -- -- @BeforeEach -- void setup() { -- executor = Executors.newCachedThreadPool(); -- registry = new MetricRegistry(); -- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "xs"); -- submitted = registry.meter("xs.submitted"); -- running = registry.counter("xs.running"); -- completed = registry.meter("xs.completed"); -- duration = registry.timer("xs.duration"); -- idle = registry.timer("xs.idle"); -- } -- -- @AfterEach -- void tearDown() throws Exception { -- instrumentedExecutorService.shutdown(); -- if (!instrumentedExecutorService.awaitTermination(2, TimeUnit.SECONDS)) { -- LOGGER.error("InstrumentedExecutorService did not terminate."); -- } -+final class InstrumentedExecutorServiceTest { -+ -+ private static final Logger LOG = LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); -+ private ExecutorService executor; -+ private MetricRegistry registry; -+ private InstrumentedExecutorService instrumentedExecutorService; -+ private Meter submitted; -+ private Counter running; -+ private Meter completed; -+ private Timer duration; -+ private Timer idle; -+ -+ @BeforeEach -+ void setup() { -+ executor = Executors.newCachedThreadPool(); -+ registry = new MetricRegistry(); -+ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "xs"); -+ submitted = registry.meter("xs.submitted"); -+ running = registry.counter("xs.running"); -+ completed = registry.meter("xs.completed"); -+ duration = registry.timer("xs.duration"); -+ idle = registry.timer("xs.idle"); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ instrumentedExecutorService.shutdown(); -+ if (!instrumentedExecutorService.awaitTermination(2, TimeUnit.SECONDS)) { -+ LOG.error("InstrumentedExecutorService did not terminate."); - } -- -- @Test -- void reportsTasksInformationForRunnable() throws Exception { -- -- assertThat(submitted.getCount()).isEqualTo(0); -- assertThat(running.getCount()).isEqualTo(0); -- assertThat(completed.getCount()).isEqualTo(0); -- assertThat(duration.getCount()).isEqualTo(0); -- assertThat(idle.getCount()).isEqualTo(0); -- -- Runnable runnable = () -> { -- assertThat(submitted.getCount()).isEqualTo(1); -- assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isEqualTo(0); -- assertThat(duration.getCount()).isEqualTo(0); -- assertThat(idle.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void reportsTasksInformationForRunnable() throws Exception { -+ -+ assertThat(submitted.getCount()).isEqualTo(0); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ assertThat(idle.getCount()).isEqualTo(0); -+ -+ Runnable runnable = -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(1); -+ assertThat(running.getCount()).isEqualTo(1); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ assertThat(idle.getCount()).isEqualTo(1); - }; + @BeforeEach + void setUp() { +@@ -28,7 +27,7 @@ class SharedMetricRegistriesTest { + void hasASetOfNames() { + SharedMetricRegistries.getOrCreate("one"); -- Future theFuture = instrumentedExecutorService.submit(runnable); -- -- theFuture.get(); -- -- assertThat(submitted.getCount()).isEqualTo(1); -- assertThat(running.getCount()).isEqualTo(0); -- assertThat(completed.getCount()).isEqualTo(1); -- assertThat(duration.getCount()).isEqualTo(1); -- assertThat(duration.getSnapshot().size()).isEqualTo(1); -- assertThat(idle.getCount()).isEqualTo(1); -- assertThat(idle.getSnapshot().size()).isEqualTo(1); -- } -- -- @Test -- void reportsTasksInformationForCallable() throws Exception { -- -- assertThat(submitted.getCount()).isEqualTo(0); -- assertThat(running.getCount()).isEqualTo(0); -- assertThat(completed.getCount()).isEqualTo(0); -- assertThat(duration.getCount()).isEqualTo(0); -- assertThat(idle.getCount()).isEqualTo(0); -- -- Callable callable = () -> { -- assertThat(submitted.getCount()).isEqualTo(1); -- assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isEqualTo(0); -- assertThat(duration.getCount()).isEqualTo(0); -- assertThat(idle.getCount()).isEqualTo(1); -- return null; -+ Future theFuture = instrumentedExecutorService.submit(runnable); -+ -+ theFuture.get(); -+ -+ assertThat(submitted.getCount()).isEqualTo(1); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(1); -+ assertThat(duration.getCount()).isEqualTo(1); -+ assertThat(duration.getSnapshot().size()).isEqualTo(1); -+ assertThat(idle.getCount()).isEqualTo(1); -+ assertThat(idle.getSnapshot().size()).isEqualTo(1); -+ } -+ -+ @Test -+ void reportsTasksInformationForCallable() throws Exception { -+ -+ assertThat(submitted.getCount()).isEqualTo(0); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ assertThat(idle.getCount()).isEqualTo(0); -+ -+ Callable callable = -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(1); -+ assertThat(running.getCount()).isEqualTo(1); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ assertThat(idle.getCount()).isEqualTo(1); -+ return null; - }; - -- Future theFuture = instrumentedExecutorService.submit(callable); -- -- theFuture.get(); -- -- assertThat(submitted.getCount()).isEqualTo(1); -- assertThat(running.getCount()).isEqualTo(0); -- assertThat(completed.getCount()).isEqualTo(1); -- assertThat(duration.getCount()).isEqualTo(1); -- assertThat(duration.getSnapshot().size()).isEqualTo(1); -- assertThat(idle.getCount()).isEqualTo(1); -- assertThat(idle.getSnapshot().size()).isEqualTo(1); -- } -- -- @Test -- @SuppressWarnings("unchecked") -- void reportsTasksInformationForThreadPoolExecutor() throws Exception { -- executor = new ThreadPoolExecutor(4, 16, -- 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); -- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); -- submitted = registry.meter("tp.submitted"); -- running = registry.counter("tp.running"); -- completed = registry.meter("tp.completed"); -- duration = registry.timer("tp.duration"); -- idle = registry.timer("tp.idle"); -- final Gauge poolSize = (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "size")); -- final Gauge poolCoreSize = (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "core")); -- final Gauge poolMaxSize = (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "max")); -- final Gauge tasksActive = (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "active")); -- final Gauge tasksCompleted = (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "completed")); -- final Gauge tasksQueued = (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "queued")); -- final Gauge tasksCapacityRemaining = (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "capacity")); -- -- assertThat(submitted.getCount()).isEqualTo(0); -- assertThat(running.getCount()).isEqualTo(0); -- assertThat(completed.getCount()).isEqualTo(0); -- assertThat(duration.getCount()).isEqualTo(0); -- assertThat(idle.getCount()).isEqualTo(0); -- assertThat(poolSize.getValue()).isEqualTo(0); -- assertThat(poolCoreSize.getValue()).isEqualTo(4); -- assertThat(poolMaxSize.getValue()).isEqualTo(16); -- assertThat(tasksActive.getValue()).isEqualTo(0); -- assertThat(tasksCompleted.getValue()).isEqualTo(0L); -- assertThat(tasksQueued.getValue()).isEqualTo(0); -- assertThat(tasksCapacityRemaining.getValue()).isEqualTo(32); -- -- Runnable runnable = () -> { -- assertThat(submitted.getCount()).isEqualTo(1); -- assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isEqualTo(0); -- assertThat(duration.getCount()).isEqualTo(0); -- assertThat(idle.getCount()).isEqualTo(1); -- assertThat(tasksActive.getValue()).isEqualTo(1); -- assertThat(tasksQueued.getValue()).isEqualTo(0); -+ Future theFuture = instrumentedExecutorService.submit(callable); -+ -+ theFuture.get(); -+ -+ assertThat(submitted.getCount()).isEqualTo(1); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(1); -+ assertThat(duration.getCount()).isEqualTo(1); -+ assertThat(duration.getSnapshot().size()).isEqualTo(1); -+ assertThat(idle.getCount()).isEqualTo(1); -+ assertThat(idle.getSnapshot().size()).isEqualTo(1); -+ } -+ -+ @SuppressWarnings("unchecked") -+ @Test -+ void reportsTasksInformationForThreadPoolExecutor() throws Exception { -+ executor = -+ new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); -+ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); -+ submitted = registry.meter("tp.submitted"); -+ running = registry.counter("tp.running"); -+ completed = registry.meter("tp.completed"); -+ duration = registry.timer("tp.duration"); -+ idle = registry.timer("tp.idle"); -+ final Gauge poolSize = -+ (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "size")); -+ final Gauge poolCoreSize = -+ (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "core")); -+ final Gauge poolMaxSize = -+ (Gauge) registry.getGauges().get(MetricName.build("tp", "pool", "max")); -+ final Gauge tasksActive = -+ (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "active")); -+ final Gauge tasksCompleted = -+ (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "completed")); -+ final Gauge tasksQueued = -+ (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "queued")); -+ final Gauge tasksCapacityRemaining = -+ (Gauge) registry.getGauges().get(MetricName.build("tp", "tasks", "capacity")); -+ -+ assertThat(submitted.getCount()).isEqualTo(0); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ assertThat(idle.getCount()).isEqualTo(0); -+ assertThat(poolSize.getValue()).isEqualTo(0); -+ assertThat(poolCoreSize.getValue()).isEqualTo(4); -+ assertThat(poolMaxSize.getValue()).isEqualTo(16); -+ assertThat(tasksActive.getValue()).isEqualTo(0); -+ assertThat(tasksCompleted.getValue()).isEqualTo(0L); -+ assertThat(tasksQueued.getValue()).isEqualTo(0); -+ assertThat(tasksCapacityRemaining.getValue()).isEqualTo(32); -+ -+ Runnable runnable = -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(1); -+ assertThat(running.getCount()).isEqualTo(1); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ assertThat(idle.getCount()).isEqualTo(1); -+ assertThat(tasksActive.getValue()).isEqualTo(1); -+ assertThat(tasksQueued.getValue()).isEqualTo(0); - }; - -- Future theFuture = instrumentedExecutorService.submit(runnable); -- -- assertThat(theFuture).succeedsWithin(Duration.ofSeconds(5L)); -- -- assertThat(submitted.getCount()).isEqualTo(1); -- assertThat(running.getCount()).isEqualTo(0); -- assertThat(completed.getCount()).isEqualTo(1); -- assertThat(duration.getCount()).isEqualTo(1); -- assertThat(duration.getSnapshot().size()).isEqualTo(1); -- assertThat(idle.getCount()).isEqualTo(1); -- assertThat(idle.getSnapshot().size()).isEqualTo(1); -- assertThat(poolSize.getValue()).isEqualTo(1); -- } -- -- @Test -- public void reportsRejectedTasksForThreadPoolExecutor() throws Exception { -- executor = new ThreadPoolExecutor(1, 1, -- 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1)); -- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); -- final Counter rejected = registry.counter("tp.rejected"); -- assertThat(rejected.getCount()).isEqualTo(0); -- -- final CountDownLatch latch = new CountDownLatch(1); -- -- Runnable runnable = () -> { -- try { -- latch.await(); -- } catch (InterruptedException e) { -- throw new RuntimeException(e); -- } -+ Future theFuture = instrumentedExecutorService.submit(runnable); -+ -+ assertThat(theFuture).succeedsWithin(Duration.ofSeconds(5L)); -+ -+ assertThat(submitted.getCount()).isEqualTo(1); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(1); -+ assertThat(duration.getCount()).isEqualTo(1); -+ assertThat(duration.getSnapshot().size()).isEqualTo(1); -+ assertThat(idle.getCount()).isEqualTo(1); -+ assertThat(idle.getSnapshot().size()).isEqualTo(1); -+ assertThat(poolSize.getValue()).isEqualTo(1); -+ } -+ -+ @Test -+ void reportsRejectedTasksForThreadPoolExecutor() throws Exception { -+ executor = -+ new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1)); -+ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); -+ final Counter rejected = registry.counter("tp.rejected"); -+ assertThat(rejected.getCount()).isEqualTo(0); -+ -+ final CountDownLatch latch = new CountDownLatch(1); -+ -+ Runnable runnable = -+ () -> { -+ try { -+ latch.await(); -+ } catch (InterruptedException e) { -+ throw new RuntimeException(e); -+ } - }; - -- Future executingFuture = instrumentedExecutorService.submit(runnable); -- Future queuedFuture = instrumentedExecutorService.submit(runnable); -- assertThatThrownBy(() -> instrumentedExecutorService.submit(runnable)) -- .isInstanceOf(RejectedExecutionException.class); -- latch.countDown(); -- assertThat(rejected.getCount()).isEqualTo(1); -- } -- -- @Test -- public void removesMetricsAfterShutdownForThreadPoolExecutor() { -- executor = new ThreadPoolExecutor(4, 16, -- 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); -- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "stp"); -- -- MetricName prefix = MetricName.build("stp"); -- assertThat(registry.getMetrics()).containsKeys( -- MetricRegistry.name("stp", "pool.size"), -- MetricRegistry.name("stp", "pool.core"), -- MetricRegistry.name("stp", "pool.max"), -- MetricRegistry.name("stp", "tasks.active"), -- MetricRegistry.name("stp", "tasks.completed"), -- MetricRegistry.name("stp", "tasks.queued"), -- MetricRegistry.name("stp", "tasks.capacity") -- ); -- -- instrumentedExecutorService.shutdown(); -- -- assertThat(registry.getMetrics()).doesNotContainKeys( -- MetricRegistry.name("stp", "pool.size"), -- MetricRegistry.name("stp", "pool.core"), -- MetricRegistry.name("stp", "pool.max"), -- MetricRegistry.name("stp", "tasks.active"), -- MetricRegistry.name("stp", "tasks.completed"), -- MetricRegistry.name("stp", "tasks.queued"), -- MetricRegistry.name("stp", "tasks.capacity") -- ); -- } -- -- @Test -- @SuppressWarnings("unchecked") -- void reportsTasksInformationForForkJoinPool() throws Exception { -- executor = Executors.newWorkStealingPool(4); -- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); -- submitted = registry.meter("fjp.submitted"); -- running = registry.counter("fjp.running"); -- completed = registry.meter("fjp.completed"); -- duration = registry.timer("fjp.duration"); -- idle = registry.timer("fjp.idle"); -- final Gauge tasksStolen = (Gauge) registry.getGauges().get(MetricName.build("fjp", "tasks", "stolen")); -- final Gauge tasksQueued = (Gauge) registry.getGauges().get(MetricName.build("fjp", "tasks", "queued")); -- final Gauge threadsActive = (Gauge) registry.getGauges().get(MetricName.build("fjp", "threads", "active")); -- final Gauge threadsRunning = (Gauge) registry.getGauges().get(MetricName.build("fjp", "threads", "running")); -- -- assertThat(submitted.getCount()).isEqualTo(0); -- assertThat(running.getCount()).isEqualTo(0); -- assertThat(completed.getCount()).isEqualTo(0); -- assertThat(duration.getCount()).isEqualTo(0); -- assertThat(idle.getCount()).isEqualTo(0); -- assertThat(tasksStolen.getValue()).isEqualTo(0L); -- assertThat(tasksQueued.getValue()).isEqualTo(0L); -- assertThat(threadsActive.getValue()).isEqualTo(0); -- assertThat(threadsRunning.getValue()).isEqualTo(0); -- -- Runnable runnable = () -> { -- assertThat(submitted.getCount()).isEqualTo(1); -- assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isEqualTo(0); -- assertThat(duration.getCount()).isEqualTo(0); -- assertThat(idle.getCount()).isEqualTo(1); -- assertThat(tasksQueued.getValue()).isEqualTo(0L); -- assertThat(threadsActive.getValue()).isEqualTo(1); -- assertThat(threadsRunning.getValue()).isEqualTo(1); -+ Future executingFuture = instrumentedExecutorService.submit(runnable); -+ Future queuedFuture = instrumentedExecutorService.submit(runnable); -+ assertThatThrownBy(() -> instrumentedExecutorService.submit(runnable)) -+ .isInstanceOf(RejectedExecutionException.class); -+ latch.countDown(); -+ assertThat(rejected.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void removesMetricsAfterShutdownForThreadPoolExecutor() { -+ executor = -+ new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); -+ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "stp"); -+ -+ MetricName prefix = MetricName.build("stp"); -+ assertThat(registry.getMetrics()) -+ .containsKeys( -+ MetricRegistry.name("stp", "pool.size"), -+ MetricRegistry.name("stp", "pool.core"), -+ MetricRegistry.name("stp", "pool.max"), -+ MetricRegistry.name("stp", "tasks.active"), -+ MetricRegistry.name("stp", "tasks.completed"), -+ MetricRegistry.name("stp", "tasks.queued"), -+ MetricRegistry.name("stp", "tasks.capacity")); -+ -+ instrumentedExecutorService.shutdown(); -+ -+ assertThat(registry.getMetrics()) -+ .doesNotContainKeys( -+ MetricRegistry.name("stp", "pool.size"), -+ MetricRegistry.name("stp", "pool.core"), -+ MetricRegistry.name("stp", "pool.max"), -+ MetricRegistry.name("stp", "tasks.active"), -+ MetricRegistry.name("stp", "tasks.completed"), -+ MetricRegistry.name("stp", "tasks.queued"), -+ MetricRegistry.name("stp", "tasks.capacity")); -+ } -+ -+ @SuppressWarnings("unchecked") -+ @Test -+ void reportsTasksInformationForForkJoinPool() throws Exception { -+ executor = Executors.newWorkStealingPool(4); -+ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); -+ submitted = registry.meter("fjp.submitted"); -+ running = registry.counter("fjp.running"); -+ completed = registry.meter("fjp.completed"); -+ duration = registry.timer("fjp.duration"); -+ idle = registry.timer("fjp.idle"); -+ final Gauge tasksStolen = -+ (Gauge) registry.getGauges().get(MetricName.build("fjp", "tasks", "stolen")); -+ final Gauge tasksQueued = -+ (Gauge) registry.getGauges().get(MetricName.build("fjp", "tasks", "queued")); -+ final Gauge threadsActive = -+ (Gauge) registry.getGauges().get(MetricName.build("fjp", "threads", "active")); -+ final Gauge threadsRunning = -+ (Gauge) registry.getGauges().get(MetricName.build("fjp", "threads", "running")); -+ -+ assertThat(submitted.getCount()).isEqualTo(0); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ assertThat(idle.getCount()).isEqualTo(0); -+ assertThat(tasksStolen.getValue()).isEqualTo(0L); -+ assertThat(tasksQueued.getValue()).isEqualTo(0L); -+ assertThat(threadsActive.getValue()).isEqualTo(0); -+ assertThat(threadsRunning.getValue()).isEqualTo(0); -+ -+ Runnable runnable = -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(1); -+ assertThat(running.getCount()).isEqualTo(1); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ assertThat(idle.getCount()).isEqualTo(1); -+ assertThat(tasksQueued.getValue()).isEqualTo(0L); -+ assertThat(threadsActive.getValue()).isEqualTo(1); -+ assertThat(threadsRunning.getValue()).isEqualTo(1); - }; - -- Future theFuture = instrumentedExecutorService.submit(runnable); -- -- assertThat(theFuture).succeedsWithin(Duration.ofSeconds(5L)); -- -- assertThat(submitted.getCount()).isEqualTo(1); -- assertThat(running.getCount()).isEqualTo(0); -- assertThat(completed.getCount()).isEqualTo(1); -- assertThat(duration.getCount()).isEqualTo(1); -- assertThat(duration.getSnapshot().size()).isEqualTo(1); -- assertThat(idle.getCount()).isEqualTo(1); -- assertThat(idle.getSnapshot().size()).isEqualTo(1); -- } -- -- @Test -- public void removesMetricsAfterShutdownForForkJoinPool() { -- executor = Executors.newWorkStealingPool(4); -- instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "sfjp"); -- -- assertThat(registry.getMetrics()).containsKeys( -- MetricRegistry.name("sfjp", "tasks.stolen"), -- MetricRegistry.name("sfjp", "tasks.queued"), -- MetricRegistry.name("sfjp", "threads.active"), -- MetricRegistry.name("sfjp", "threads.running") -- ); -- -- instrumentedExecutorService.shutdown(); -- -- assertThat(registry.getMetrics()).doesNotContainKeys( -- MetricRegistry.name("sfjp", "tasks.stolen"), -- MetricRegistry.name("sfjp", "tasks.queued"), -- MetricRegistry.name("sfjp", "threads.active"), -- MetricRegistry.name("sfjp", "threads.running") -- ); -- } -+ Future theFuture = instrumentedExecutorService.submit(runnable); -+ -+ assertThat(theFuture).succeedsWithin(Duration.ofSeconds(5L)); -+ -+ assertThat(submitted.getCount()).isEqualTo(1); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(1); -+ assertThat(duration.getCount()).isEqualTo(1); -+ assertThat(duration.getSnapshot().size()).isEqualTo(1); -+ assertThat(idle.getCount()).isEqualTo(1); -+ assertThat(idle.getSnapshot().size()).isEqualTo(1); -+ } -+ -+ @Test -+ void removesMetricsAfterShutdownForForkJoinPool() { -+ executor = Executors.newWorkStealingPool(4); -+ instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "sfjp"); -+ -+ assertThat(registry.getMetrics()) -+ .containsKeys( -+ MetricRegistry.name("sfjp", "tasks.stolen"), -+ MetricRegistry.name("sfjp", "tasks.queued"), -+ MetricRegistry.name("sfjp", "threads.active"), -+ MetricRegistry.name("sfjp", "threads.running")); -+ -+ instrumentedExecutorService.shutdown(); -+ -+ assertThat(registry.getMetrics()) -+ .doesNotContainKeys( -+ MetricRegistry.name("sfjp", "tasks.stolen"), -+ MetricRegistry.name("sfjp", "tasks.queued"), -+ MetricRegistry.name("sfjp", "threads.active"), -+ MetricRegistry.name("sfjp", "threads.running")); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java -@@ -1,9 +1,6 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.Test; --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -+import static org.assertj.core.api.Assertions.assertThat; - - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.Executors; -@@ -11,295 +8,321 @@ import java.util.concurrent.Future; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.ScheduledFuture; - import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.Test; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; - --import static org.assertj.core.api.Assertions.assertThat; -- --class InstrumentedScheduledExecutorServiceTest { -- private static final Logger LOGGER = LoggerFactory.getLogger(InstrumentedScheduledExecutorServiceTest.class); -- -- private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); -- private final MetricRegistry registry = new MetricRegistry(); -- private final InstrumentedScheduledExecutorService instrumentedScheduledExecutor = new InstrumentedScheduledExecutorService(scheduledExecutor, registry, "xs"); -- -- private final Meter submitted = registry.meter("xs.submitted"); -- -- private final Counter running = registry.counter("xs.running"); -- private final Meter completed = registry.meter("xs.completed"); -- private final Timer duration = registry.timer("xs.duration"); -- -- private final Meter scheduledOnce = registry.meter("xs.scheduled.once"); -- private final Meter scheduledRepetitively = registry.meter("xs.scheduled.repetitively"); -- private final Counter scheduledOverrun = registry.counter("xs.scheduled.overrun"); -- private final Histogram percentOfPeriod = registry.histogram("xs.scheduled.percent-of-period"); -- -- @Test -- void testSubmitRunnable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- -- Future theFuture = instrumentedScheduledExecutor.submit(() -> { -- assertThat(submitted.getCount()).isEqualTo(1); -- -- assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- }); -- -- theFuture.get(); -- -- assertThat(submitted.getCount()).isEqualTo(1); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isEqualTo(1); -- assertThat(duration.getCount()).isEqualTo(1); -- assertThat(duration.getSnapshot().size()).isEqualTo(1); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- } -- -- @Test -- void testScheduleRunnable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- -- ScheduledFuture theFuture = instrumentedScheduledExecutor.schedule(() -> { -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -- -- assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- }, 10L, TimeUnit.MILLISECONDS); -- -- theFuture.get(); -- -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isEqualTo(1); -- assertThat(duration.getCount()).isEqualTo(1); -- assertThat(duration.getSnapshot().size()).isEqualTo(1); -- -- assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- } -- -- @Test -- void testSubmitCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- -- final Object obj = new Object(); -- -- Future theFuture = instrumentedScheduledExecutor.submit(() -> { -- assertThat(submitted.getCount()).isEqualTo(1); -- -- assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- -- return obj; -- }); -- -- assertThat(theFuture.get()).isEqualTo(obj); -- -- assertThat(submitted.getCount()).isEqualTo(1); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isEqualTo(1); -- assertThat(duration.getCount()).isEqualTo(1); -- assertThat(duration.getSnapshot().size()).isEqualTo(1); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- } -- -- @Test -- void testScheduleCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- -- final Object obj = new Object(); -+final class InstrumentedScheduledExecutorServiceTest { -+ private static final Logger LOG = -+ LoggerFactory.getLogger(InstrumentedScheduledExecutorServiceTest.class); -+ -+ private final ScheduledExecutorService scheduledExecutor = -+ Executors.newSingleThreadScheduledExecutor(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final InstrumentedScheduledExecutorService instrumentedScheduledExecutor = -+ new InstrumentedScheduledExecutorService(scheduledExecutor, registry, "xs"); -+ -+ private final Meter submitted = registry.meter("xs.submitted"); -+ -+ private final Counter running = registry.counter("xs.running"); -+ private final Meter completed = registry.meter("xs.completed"); -+ private final Timer duration = registry.timer("xs.duration"); -+ -+ private final Meter scheduledOnce = registry.meter("xs.scheduled.once"); -+ private final Meter scheduledRepetitively = registry.meter("xs.scheduled.repetitively"); -+ private final Counter scheduledOverrun = registry.counter("xs.scheduled.overrun"); -+ private final Histogram percentOfPeriod = registry.histogram("xs.scheduled.percent-of-period"); -+ -+ @Test -+ void submitRunnable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ -+ Future theFuture = -+ instrumentedScheduledExecutor.submit( -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(1); -+ -+ assertThat(running.getCount()).isEqualTo(1); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ }); -+ -+ theFuture.get(); -+ -+ assertThat(submitted.getCount()).isEqualTo(1); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(1); -+ assertThat(duration.getCount()).isEqualTo(1); -+ assertThat(duration.getSnapshot().size()).isEqualTo(1); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void scheduleRunnable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ -+ ScheduledFuture theFuture = -+ instrumentedScheduledExecutor.schedule( -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(1); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(1); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ }, -+ 10L, -+ TimeUnit.MILLISECONDS); - -- ScheduledFuture theFuture = instrumentedScheduledExecutor.schedule(() -> { -- assertThat(submitted.getCount()).isZero(); -+ theFuture.get(); -+ -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(1); -+ assertThat(duration.getCount()).isEqualTo(1); -+ assertThat(duration.getSnapshot().size()).isEqualTo(1); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(1); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void submitCallable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ -+ final Object obj = new Object(); -+ -+ Future theFuture = -+ instrumentedScheduledExecutor.submit( -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(1); -+ -+ assertThat(running.getCount()).isEqualTo(1); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ -+ return obj; -+ }); -+ -+ assertThat(theFuture.get()).isEqualTo(obj); -+ -+ assertThat(submitted.getCount()).isEqualTo(1); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(1); -+ assertThat(duration.getCount()).isEqualTo(1); -+ assertThat(duration.getSnapshot().size()).isEqualTo(1); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void scheduleCallable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ -+ final Object obj = new Object(); -+ -+ ScheduledFuture theFuture = -+ instrumentedScheduledExecutor.schedule( -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(1); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- return obj; -- }, 10L, TimeUnit.MILLISECONDS); -+ assertThat(scheduledOnce.getCount()).isEqualTo(1); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - -- assertThat(theFuture.get()).isEqualTo(obj); -+ return obj; -+ }, -+ 10L, -+ TimeUnit.MILLISECONDS); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(theFuture.get()).isEqualTo(obj); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isEqualTo(1); -- assertThat(duration.getCount()).isEqualTo(1); -- assertThat(duration.getSnapshot().size()).isEqualTo(1); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- } -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(1); -+ assertThat(duration.getCount()).isEqualTo(1); -+ assertThat(duration.getSnapshot().size()).isEqualTo(1); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(1); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ } - -- @Test -- void testScheduleFixedRateCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ @Test -+ void scheduleFixedRateCallable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - -- CountDownLatch countDownLatch = new CountDownLatch(1); -- ScheduledFuture theFuture = instrumentedScheduledExecutor.scheduleAtFixedRate(() -> { -- assertThat(submitted.getCount()).isZero(); -+ CountDownLatch countDownLatch = new CountDownLatch(1); -+ ScheduledFuture theFuture = -+ instrumentedScheduledExecutor.scheduleAtFixedRate( -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isEqualTo(1); -+ assertThat(running.getCount()).isEqualTo(1); - -- assertThat(scheduledOnce.getCount()).isEqualTo(0); -- assertThat(scheduledRepetitively.getCount()).isEqualTo(1); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(1); - -- try { -+ try { - TimeUnit.MILLISECONDS.sleep(50); -- } catch (InterruptedException ex) { -+ } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); -- } -- countDownLatch.countDown(); -- }, 10L, 10L, TimeUnit.MILLISECONDS); -- TimeUnit.MILLISECONDS.sleep(100); // Give some time for the task to be run -- countDownLatch.await(5, TimeUnit.SECONDS); // Don't cancel until it didn't complete once -- theFuture.cancel(true); -- TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled -- -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isNotEqualTo(0); -- assertThat(duration.getCount()).isNotEqualTo(0); -- assertThat(duration.getSnapshot().size()).isNotEqualTo(0); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isEqualTo(1); -- assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); -- assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); -- } -- -- @Test -- void testScheduleFixedDelayCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -- -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -- -- CountDownLatch countDownLatch = new CountDownLatch(1); -- ScheduledFuture theFuture = instrumentedScheduledExecutor.scheduleWithFixedDelay(() -> { -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isEqualTo(1); -- -- assertThat(scheduledOnce.getCount()).isEqualTo(0); -- assertThat(scheduledRepetitively.getCount()).isEqualTo(1); -- -- try { -+ } -+ countDownLatch.countDown(); -+ }, -+ 10L, -+ 10L, -+ TimeUnit.MILLISECONDS); -+ TimeUnit.MILLISECONDS.sleep(100); // Give some time for the task to be run -+ countDownLatch.await(5, TimeUnit.SECONDS); // Don't cancel until it didn't complete once -+ theFuture.cancel(true); -+ TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled -+ -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isNotEqualTo(0); -+ assertThat(duration.getCount()).isNotEqualTo(0); -+ assertThat(duration.getSnapshot().size()).isNotEqualTo(0); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(1); -+ assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); -+ } -+ -+ @Test -+ void scheduleFixedDelayCallable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); -+ -+ CountDownLatch countDownLatch = new CountDownLatch(1); -+ ScheduledFuture theFuture = -+ instrumentedScheduledExecutor.scheduleWithFixedDelay( -+ () -> { -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(1); -+ -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(1); -+ -+ try { - TimeUnit.MILLISECONDS.sleep(50); -- } catch (InterruptedException ex) { -+ } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); -- } -- countDownLatch.countDown(); -- }, 10L, 10L, TimeUnit.MILLISECONDS); -- -- TimeUnit.MILLISECONDS.sleep(100); -- countDownLatch.await(5, TimeUnit.SECONDS); -- theFuture.cancel(true); -- TimeUnit.MILLISECONDS.sleep(200); -- -- assertThat(submitted.getCount()).isZero(); -- -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isNotEqualTo(0); -- assertThat(duration.getCount()).isNotEqualTo(0); -- assertThat(duration.getSnapshot().size()).isNotEqualTo(0); -- } -- -- @AfterEach -- void tearDown() throws Exception { -- instrumentedScheduledExecutor.shutdown(); -- if (!instrumentedScheduledExecutor.awaitTermination(2, TimeUnit.SECONDS)) { -- LOGGER.error("InstrumentedScheduledExecutorService did not terminate."); -- } -+ } -+ countDownLatch.countDown(); -+ }, -+ 10L, -+ 10L, -+ TimeUnit.MILLISECONDS); -+ -+ TimeUnit.MILLISECONDS.sleep(100); -+ countDownLatch.await(5, TimeUnit.SECONDS); -+ theFuture.cancel(true); -+ TimeUnit.MILLISECONDS.sleep(200); -+ -+ assertThat(submitted.getCount()).isEqualTo(0); -+ -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isNotEqualTo(0); -+ assertThat(duration.getCount()).isNotEqualTo(0); -+ assertThat(duration.getSnapshot().size()).isNotEqualTo(0); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ instrumentedScheduledExecutor.shutdown(); -+ if (!instrumentedScheduledExecutor.awaitTermination(2, TimeUnit.SECONDS)) { -+ LOG.error("InstrumentedScheduledExecutorService did not terminate."); - } -- -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java -@@ -9,69 +9,71 @@ import java.util.concurrent.Future; - import java.util.concurrent.ThreadFactory; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicInteger; -- - import org.junit.jupiter.api.Test; - --class InstrumentedThreadFactoryTest { -- private static final int THREAD_COUNT = 10; -+final class InstrumentedThreadFactoryTest { -+ private static final int THREAD_COUNT = 10; - -- private final ThreadFactory factory = Executors.defaultThreadFactory(); -- private final MetricRegistry registry = new MetricRegistry(); -- private final InstrumentedThreadFactory instrumentedFactory = new InstrumentedThreadFactory(factory, registry, "factory"); -- private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT, instrumentedFactory); -+ private final ThreadFactory factory = Executors.defaultThreadFactory(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final InstrumentedThreadFactory instrumentedFactory = -+ new InstrumentedThreadFactory(factory, registry, "factory"); -+ private final ExecutorService executor = -+ Executors.newFixedThreadPool(THREAD_COUNT, instrumentedFactory); - -- /** -- * Tests all parts of the InstrumentedThreadFactory except for termination since that -- * is currently difficult to do without race conditions. -- * TODO: Try not using real threads in a unit test? -- */ -- @Test -- void reportsThreadInformation() throws Exception { -- final CountDownLatch allTasksAreCreated = new CountDownLatch(THREAD_COUNT); -- final CountDownLatch allTasksAreCounted = new CountDownLatch(1); -- final AtomicInteger interrupted = new AtomicInteger(); -+ /** -+ * Tests all parts of the InstrumentedThreadFactory except for termination since that is currently -+ * difficult to do without race conditions. TODO: Try not using real threads in a unit test? -+ */ -+ @Test -+ void reportsThreadInformation() throws Exception { -+ final CountDownLatch allTasksAreCreated = new CountDownLatch(THREAD_COUNT); -+ final CountDownLatch allTasksAreCounted = new CountDownLatch(1); -+ final AtomicInteger interrupted = new AtomicInteger(); - -- Meter created = registry.meter("factory.created"); -- Meter terminated = registry.meter("factory.terminated"); -+ Meter created = registry.meter("factory.created"); -+ Meter terminated = registry.meter("factory.terminated"); - -- assertThat(created.getCount()).isEqualTo(0); -- assertThat(terminated.getCount()).isEqualTo(0); -+ assertThat(created.getCount()).isEqualTo(0); -+ assertThat(terminated.getCount()).isEqualTo(0); - -- // generate demand so the executor service creates the threads through our factory. -- for (int i = 0; i < THREAD_COUNT + 1; i++) { -- Future t = executor.submit(() -> { -+ // generate demand so the executor service creates the threads through our factory. -+ for (int i = 0; i < THREAD_COUNT + 1; i++) { -+ Future t = -+ executor.submit( -+ () -> { - allTasksAreCreated.countDown(); - - // This asserts that all threads have wait wail the testing thread notifies all. - // We have to do this to guarantee that the thread pool has 10 LIVE threads - // before we check the 'created' Meter. - try { -- allTasksAreCounted.await(); -+ allTasksAreCounted.await(); - } catch (InterruptedException e) { -- interrupted.incrementAndGet(); -- Thread.currentThread().interrupt(); -+ interrupted.incrementAndGet(); -+ Thread.currentThread().interrupt(); - } -- }); -- assertThat(t).isNotNull(); -- } -+ }); -+ assertThat(t).isNotNull(); -+ } - -- allTasksAreCreated.await(1, TimeUnit.SECONDS); -- allTasksAreCounted.countDown(); -+ allTasksAreCreated.await(1, TimeUnit.SECONDS); -+ allTasksAreCounted.countDown(); - -- assertThat(created.getCount()).isEqualTo(10); -- assertThat(terminated.getCount()).isEqualTo(0); -+ assertThat(created.getCount()).isEqualTo(10); -+ assertThat(terminated.getCount()).isEqualTo(0); - -- // terminate all threads in the executor service. -- executor.shutdown(); -- executor.awaitTermination(1, TimeUnit.SECONDS); -+ // terminate all threads in the executor service. -+ executor.shutdown(); -+ executor.awaitTermination(1, TimeUnit.SECONDS); - -- // assert that all threads from the factory have been terminated. -- // TODO: Remove this? -- // There is no guarantee that all threads have entered the block where they are -- // counted as terminated by this time. -- // assertThat(terminated.getCount()).isEqualTo(10); -+ // assert that all threads from the factory have been terminated. -+ // TODO: Remove this? -+ // There is no guarantee that all threads have entered the block where they are -+ // counted as terminated by this time. -+ // assertThat(terminated.getCount()).isEqualTo(10); - -- // Check that none of the threads were interrupted. -- assertThat(interrupted.get()).isEqualTo(0); -- } -+ // Check that none of the threads were interrupted. -+ assertThat(interrupted.get()).isEqualTo(0); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ManualClock.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ManualClock.java -@@ -3,42 +3,41 @@ package io.dropwizard.metrics5; - import java.util.concurrent.TimeUnit; - - public class ManualClock extends Clock { -- private final long initialTicksInNanos; -- long ticksInNanos; -- -- public ManualClock(long initialTicksInNanos) { -- this.initialTicksInNanos = initialTicksInNanos; -- this.ticksInNanos = initialTicksInNanos; -- } -- -- public ManualClock() { -- this(0L); -- } -- -- public synchronized void addNanos(long nanos) { -- ticksInNanos += nanos; -- } -- -- public synchronized void addSeconds(long seconds) { -- ticksInNanos += TimeUnit.SECONDS.toNanos(seconds); -- } -- -- public synchronized void addMillis(long millis) { -- ticksInNanos += TimeUnit.MILLISECONDS.toNanos(millis); -- } -- -- public synchronized void addHours(long hours) { -- ticksInNanos += TimeUnit.HOURS.toNanos(hours); -- } -- -- @Override -- public synchronized long getTick() { -- return ticksInNanos; -- } -- -- @Override -- public synchronized long getTime() { -- return TimeUnit.NANOSECONDS.toMillis(ticksInNanos - initialTicksInNanos); -- } -- -+ private final long initialTicksInNanos; -+ long ticksInNanos; -+ -+ public ManualClock(long initialTicksInNanos) { -+ this.initialTicksInNanos = initialTicksInNanos; -+ this.ticksInNanos = initialTicksInNanos; -+ } -+ -+ public ManualClock() { -+ this(0L); -+ } -+ -+ public synchronized void addNanos(long nanos) { -+ ticksInNanos += nanos; -+ } -+ -+ public synchronized void addSeconds(long seconds) { -+ ticksInNanos += TimeUnit.SECONDS.toNanos(seconds); -+ } -+ -+ public synchronized void addMillis(long millis) { -+ ticksInNanos += TimeUnit.MILLISECONDS.toNanos(millis); -+ } -+ -+ public synchronized void addHours(long hours) { -+ ticksInNanos += TimeUnit.HOURS.toNanos(hours); -+ } -+ -+ @Override -+ public synchronized long getTick() { -+ return ticksInNanos; -+ } -+ -+ @Override -+ public synchronized long getTime() { -+ return TimeUnit.NANOSECONDS.toMillis(ticksInNanos - initialTicksInNanos); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java -@@ -1,84 +1,82 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.params.ParameterizedTest; --import org.junit.jupiter.params.provider.MethodSource; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.offset; - - import java.util.Arrays; - import java.util.Collection; - import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.params.ParameterizedTest; -+import org.junit.jupiter.params.provider.MethodSource; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.offset; -- --public class MeterApproximationTest { -- -- public static Collection ratesPerMinute() { -- Object[][] data = new Object[][]{ -- {15}, {60}, {600}, {6000} -- }; -- return Arrays.asList(data); -- } -- -- private long ratePerMinute; -- -- public void initMeterApproximationTest(long ratePerMinute) { -- this.ratePerMinute = ratePerMinute; -- } -- -- @MethodSource("ratesPerMinute") -- @ParameterizedTest -- void controlMeter1MinuteMeanApproximation(long ratePerMinute) { -- initMeterApproximationTest(ratePerMinute); -- final Meter meter = simulateMetronome( -- 62934, TimeUnit.MILLISECONDS, -- 3, TimeUnit.MINUTES); -- -- assertThat(meter.getOneMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -- } -- -- @MethodSource("ratesPerMinute") -- @ParameterizedTest -- void controlMeter5MinuteMeanApproximation(long ratePerMinute) { -- initMeterApproximationTest(ratePerMinute); -- final Meter meter = simulateMetronome( -- 62934, TimeUnit.MILLISECONDS, -- 13, TimeUnit.MINUTES); -- -- assertThat(meter.getFiveMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -- } -- -- @MethodSource("ratesPerMinute") -- @ParameterizedTest -- void controlMeter15MinuteMeanApproximation(long ratePerMinute) { -- initMeterApproximationTest(ratePerMinute); -- final Meter meter = simulateMetronome( -- 62934, TimeUnit.MILLISECONDS, -- 38, TimeUnit.MINUTES); -- -- assertThat(meter.getFifteenMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -- } -- -- private Meter simulateMetronome( -- long introDelay, TimeUnit introDelayUnit, -- long duration, TimeUnit durationUnit) { -- -- final ManualClock clock = new ManualClock(); -- final Meter meter = new Meter(clock); -- -- clock.addNanos(introDelayUnit.toNanos(introDelay)); -- -- final long endTick = clock.getTick() + durationUnit.toNanos(duration); -- final long marksIntervalInNanos = TimeUnit.MINUTES.toNanos(1) / ratePerMinute; -- -- while (clock.getTick() <= endTick) { -- clock.addNanos(marksIntervalInNanos); -- meter.mark(); -- } -- -- return meter; -+final class MeterApproximationTest { -+ -+ public static Collection ratesPerMinute() { -+ Object[][] data = new Object[][] {{15}, {60}, {600}, {6000}}; -+ return Arrays.asList(data); -+ } -+ -+ private long ratePerMinute; -+ -+ public void initMeterApproximationTest(long ratePerMinute) { -+ this.ratePerMinute = ratePerMinute; -+ } -+ -+ @MethodSource("ratesPerMinute") -+ @ParameterizedTest -+ void controlMeter1MinuteMeanApproximation(long ratePerMinute) { -+ initMeterApproximationTest(ratePerMinute); -+ final Meter meter = -+ simulateMetronome( -+ 62934, TimeUnit.MILLISECONDS, -+ 3, TimeUnit.MINUTES); -+ -+ assertThat(meter.getOneMinuteRate() * 60.0) -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ } -+ -+ @MethodSource("ratesPerMinute") -+ @ParameterizedTest -+ void controlMeter5MinuteMeanApproximation(long ratePerMinute) { -+ initMeterApproximationTest(ratePerMinute); -+ final Meter meter = -+ simulateMetronome( -+ 62934, TimeUnit.MILLISECONDS, -+ 13, TimeUnit.MINUTES); -+ -+ assertThat(meter.getFiveMinuteRate() * 60.0) -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ } -+ -+ @MethodSource("ratesPerMinute") -+ @ParameterizedTest -+ void controlMeter15MinuteMeanApproximation(long ratePerMinute) { -+ initMeterApproximationTest(ratePerMinute); -+ final Meter meter = -+ simulateMetronome( -+ 62934, TimeUnit.MILLISECONDS, -+ 38, TimeUnit.MINUTES); -+ -+ assertThat(meter.getFifteenMinuteRate() * 60.0) -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ } -+ -+ private Meter simulateMetronome( -+ long introDelay, TimeUnit introDelayUnit, long duration, TimeUnit durationUnit) { -+ -+ final ManualClock clock = new ManualClock(); -+ final Meter meter = new Meter(clock); -+ -+ clock.addNanos(introDelayUnit.toNanos(introDelay)); -+ -+ final long endTick = clock.getTick() + durationUnit.toNanos(duration); -+ final long marksIntervalInNanos = TimeUnit.MINUTES.toNanos(1) / ratePerMinute; -+ -+ while (clock.getTick() <= endTick) { -+ clock.addNanos(marksIntervalInNanos); -+ meter.mark(); - } - -+ return meter; -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java -@@ -1,67 +1,53 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import java.util.concurrent.TimeUnit; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.offset; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; - --class MeterTest { -- private final Clock clock = mock(Clock.class); -- private final Meter meter = new Meter(clock); -+import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - -- @BeforeEach -- void setUp() throws Exception { -- when(clock.getTick()).thenReturn(0L, TimeUnit.SECONDS.toNanos(10)); -+final class MeterTest { -+ private final Clock clock = mock(); -+ private final Meter meter = new Meter(clock); - -- } -+ @BeforeEach -+ void setUp() throws Exception { -+ when(clock.getTick()).thenReturn(0L, TimeUnit.SECONDS.toNanos(10)); -+ } - -- @Test -- void startsOutWithNoRatesOrCount() { -- assertThat(meter.getCount()) -- .isZero(); -+ @Test -+ void startsOutWithNoRatesOrCount() { -+ assertThat(meter.getCount()).isEqualTo(0); - -- assertThat(meter.getSum()) -- .isZero(); -+ assertThat(meter.getSum()).isEqualTo(0); - -- assertThat(meter.getMeanRate()) -- .isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getOneMinuteRate()) -- .isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getFiveMinuteRate()) -- .isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getFifteenMinuteRate()) -- .isEqualTo(0.0, offset(0.001)); -- } -+ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); -+ } - -- @Test -- void marksEventsAndUpdatesRatesAndCount() { -- meter.mark(); -- meter.mark(2); -+ @Test -+ void marksEventsAndUpdatesRatesAndCount() { -+ meter.mark(); -+ meter.mark(2); - -- assertThat(meter.getCount()) -- .isEqualTo(3); -+ assertThat(meter.getCount()).isEqualTo(3); - -- assertThat(meter.getSum()) -- .isEqualTo(10000000000L); -+ assertThat(meter.getSum()).isEqualTo(10000000000L); - -- assertThat(meter.getMeanRate()) -- .isEqualTo(0.3, offset(0.001)); -+ assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001)); - -- assertThat(meter.getOneMinuteRate()) -- .isEqualTo(0.1840, offset(0.001)); -+ assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001)); - -- assertThat(meter.getFiveMinuteRate()) -- .isEqualTo(0.1966, offset(0.001)); -+ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001)); - -- assertThat(meter.getFifteenMinuteRate()) -- .isEqualTo(0.1988, offset(0.001)); -- } -+ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001)); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java -@@ -1,38 +1,44 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - --class MetricFilterTest { -- @Test -- void theAllFilterMatchesAllMetrics() { -- assertThat(MetricFilter.ALL.matches(MetricName.build(""), mock(Metric.class))) -- .isTrue(); -- } -+import org.junit.jupiter.api.Test; -+ -+final class MetricFilterTest { -+ @Test -+ void theAllFilterMatchesAllMetrics() { -+ assertThat(MetricFilter.ALL.matches(MetricName.build(""), mock(Metric.class))).isTrue(); -+ } - -- @Test -- void theStartsWithFilterMatches() { -- assertThat(MetricFilter.startsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) -- .isTrue(); -- assertThat(MetricFilter.startsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) -- .isFalse(); -- } -+ @Test -+ void theStartsWithFilterMatches() { -+ assertThat( -+ MetricFilter.startsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) -+ .isTrue(); -+ assertThat( -+ MetricFilter.startsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) -+ .isFalse(); -+ } - -- @Test -- void theEndsWithFilterMatches() { -- assertThat(MetricFilter.endsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) -- .isFalse(); -- assertThat(MetricFilter.endsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) -- .isTrue(); -- } -+ @Test -+ void theEndsWithFilterMatches() { -+ assertThat( -+ MetricFilter.endsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) -+ .isFalse(); -+ assertThat( -+ MetricFilter.endsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) -+ .isTrue(); -+ } - -- @Test -- void theContainsFilterMatches() { -- assertThat(MetricFilter.contains("foo").matches(MetricName.build("bar.foo.bar"), mock(Metric.class))) -- .isTrue(); -- assertThat(MetricFilter.contains("foo").matches(MetricName.build("bar.bar"), mock(Metric.class))) -- .isFalse(); -- } -+ @Test -+ void theContainsFilterMatches() { -+ assertThat( -+ MetricFilter.contains("foo") -+ .matches(MetricName.build("bar.foo.bar"), mock(Metric.class))) -+ .isTrue(); -+ assertThat( -+ MetricFilter.contains("foo").matches(MetricName.build("bar.bar"), mock(Metric.class))) -+ .isFalse(); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java -@@ -1,102 +1,106 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - - import java.util.HashMap; - import java.util.Map; -+import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; -- --class MetricNameTest { -- @Test -- void testEmpty() { -- assertThat(MetricName.EMPTY.getTags()).isEmpty(); -- assertThat(MetricName.EMPTY.getKey()).isEqualTo(""); -- -- assertThat(MetricName.build()).isEqualTo(MetricName.EMPTY); -- assertThat(MetricName.EMPTY.resolve((String) null)).isEqualTo(MetricName.EMPTY); -- } -- -- @Test -- void testEmptyResolve() { -- final MetricName name = MetricName.build(); -- assertThat(name.resolve("foo")).isEqualTo(MetricName.build("foo")); -- } -- -- @Test -- void testResolveToEmpty() { -- final MetricName name = MetricName.build("foo"); -- assertThat(name.resolve((String) null)).isEqualTo(MetricName.build("foo")); -- } -- -- @Test -- void testResolve() { -- final MetricName name = MetricName.build("foo"); -- assertThat(name.resolve("bar")).isEqualTo(MetricName.build("foo.bar")); -- } -- -- @Test -- void testResolveBothEmpty() { -- final MetricName name = MetricName.build(); -- assertThat(name.resolve((String) null)).isEqualTo(MetricName.EMPTY); -- } -- -- @Test -- void testAddTagsVarious() { -- final Map refTags = new HashMap(); -- refTags.put("foo", "bar"); -- final MetricName test = MetricName.EMPTY.tagged("foo", "bar"); -- final MetricName test2 = MetricName.EMPTY.tagged(refTags); -- -- assertThat(test).isEqualTo(new MetricName("", refTags)); -- assertThat(test.getTags()).isEqualTo(refTags); -- -- assertThat(test2).isEqualTo(new MetricName("", refTags)); -- assertThat(test2.getTags()).isEqualTo(refTags); -- } -- -- @Test -- void testTaggedMoreArguments() { -- final Map refTags = new HashMap(); -- refTags.put("foo", "bar"); -- refTags.put("baz", "biz"); -- assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()).isEqualTo(refTags); -- } -- -- @Test -- void testTaggedNotPairs() { -- assertThrows(IllegalArgumentException.class, () -> { -- MetricName.EMPTY.tagged("foo"); -- }); -- } -- -- @Test -- void testTaggedNotPairs2() { -- assertThrows(IllegalArgumentException.class, () -> { -- MetricName.EMPTY.tagged("foo", "bar", "baz"); -- }); -- } -- -- @Test -- void testCompareTo() { -- final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); -- final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); -- -- assertThat(a.compareTo(b)).isLessThan(0); -- assertThat(b.compareTo(a)).isGreaterThan(0); -- assertThat(b.resolve("key").compareTo(b)).isGreaterThan(0); -- assertThat(b.compareTo(b.resolve("key"))).isLessThan(0); -- } -- -- @Test -- void testCompareTo2() { -- final MetricName a = MetricName.EMPTY.tagged("a", "x"); -- final MetricName b = MetricName.EMPTY.tagged("b", "x"); -- -- assertThat(MetricName.EMPTY.compareTo(a)).isLessThan(0); -- assertThat(MetricName.EMPTY.compareTo(b)).isLessThan(0); -- assertThat(a.compareTo(b)).isLessThan(0); -- assertThat(b.compareTo(a)).isGreaterThan(0); -- } -+final class MetricNameTest { -+ @Test -+ void empty() { -+ assertThat(MetricName.EMPTY.getTags()).isEmpty(); -+ assertThat(MetricName.EMPTY.getKey()).isEmpty(); -+ -+ assertThat(MetricName.build()).isEqualTo(MetricName.EMPTY); -+ assertThat(MetricName.EMPTY.resolve((String) null)).isEqualTo(MetricName.EMPTY); -+ } -+ -+ @Test -+ void emptyResolve() { -+ final MetricName name = MetricName.build(); -+ assertThat(name.resolve("foo")).isEqualTo(MetricName.build("foo")); -+ } -+ -+ @Test -+ void resolveToEmpty() { -+ final MetricName name = MetricName.build("foo"); -+ assertThat(name.resolve((String) null)).isEqualTo(MetricName.build("foo")); -+ } -+ -+ @Test -+ void resolve() { -+ final MetricName name = MetricName.build("foo"); -+ assertThat(name.resolve("bar")).isEqualTo(MetricName.build("foo.bar")); -+ } -+ -+ @Test -+ void resolveBothEmpty() { -+ final MetricName name = MetricName.build(); -+ assertThat(name.resolve((String) null)).isEqualTo(MetricName.EMPTY); -+ } -+ -+ @Test -+ void addTagsVarious() { -+ final Map refTags = new HashMap(); -+ refTags.put("foo", "bar"); -+ final MetricName test = MetricName.EMPTY.tagged("foo", "bar"); -+ final MetricName test2 = MetricName.EMPTY.tagged(refTags); -+ -+ assertThat(test).isEqualTo(new MetricName("", refTags)); -+ assertThat(test.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); -+ -+ assertThat(test2).isEqualTo(new MetricName("", refTags)); -+ assertThat(test2.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); -+ } -+ -+ @Test -+ void taggedMoreArguments() { -+ final Map refTags = new HashMap(); -+ refTags.put("foo", "bar"); -+ refTags.put("baz", "biz"); -+ assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()) -+ .containsExactlyInAnyOrderEntriesOf(refTags); -+ } -+ -+ @Test -+ void taggedNotPairs() { -+ assertThatThrownBy( -+ () -> { -+ MetricName.EMPTY.tagged("foo"); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void taggedNotPairs2() { -+ assertThatThrownBy( -+ () -> { -+ MetricName.EMPTY.tagged("foo", "bar", "baz"); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void compareTo() { -+ final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); -+ final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); -+ -+ assertThat(a).isLessThan(b); -+ assertThat(b).isGreaterThan(a); -+ assertThat(b.resolve("key")).isGreaterThan(b); -+ assertThat(b).isLessThan(b.resolve("key")); -+ } -+ -+ @Test -+ void compareTo2() { -+ final MetricName a = MetricName.EMPTY.tagged("a", "x"); -+ final MetricName b = MetricName.EMPTY.tagged("b", "x"); -+ -+ assertThat(MetricName.EMPTY).isLessThan(a); -+ assertThat(MetricName.EMPTY).isLessThan(b); -+ assertThat(a).isLessThan(b); -+ assertThat(b).isGreaterThan(a); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java -@@ -1,62 +1,62 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -- - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verifyNoInteractions; - --class MetricRegistryListenerTest { -- private static final MetricName BLAH = MetricName.build("blah"); -- -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -- private final MetricRegistryListener listener = new MetricRegistryListener.Base() { -- -- }; -+import org.junit.jupiter.api.Test; - -- @Test -- void noOpsOnGaugeAdded() { -- listener.onGaugeAdded(BLAH, () -> { -- throw new RuntimeException("Should not be called"); -+final class MetricRegistryListenerTest { -+ private static final MetricName BLAH = MetricName.build("blah"); -+ -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); -+ private final MetricRegistryListener listener = new MetricRegistryListener.Base() {}; -+ -+ @Test -+ void noOpsOnGaugeAdded() { -+ listener.onGaugeAdded( -+ BLAH, -+ () -> { -+ throw new RuntimeException("Should not be called"); - }); -- } -+ } - -- @Test -- void noOpsOnCounterAdded() { -- listener.onCounterAdded(BLAH, counter); -+ @Test -+ void noOpsOnCounterAdded() { -+ listener.onCounterAdded(BLAH, counter); - -- verifyNoInteractions(counter); -- } -+ verifyNoInteractions(counter); -+ } - -- @Test -- void noOpsOnHistogramAdded() { -- listener.onHistogramAdded(BLAH, histogram); -+ @Test -+ void noOpsOnHistogramAdded() { -+ listener.onHistogramAdded(BLAH, histogram); - -- verifyNoInteractions(histogram); -- } -+ verifyNoInteractions(histogram); -+ } - -- @Test -- void noOpsOnMeterAdded() { -- listener.onMeterAdded(BLAH, meter); -+ @Test -+ void noOpsOnMeterAdded() { -+ listener.onMeterAdded(BLAH, meter); - -- verifyNoInteractions(meter); -- } -+ verifyNoInteractions(meter); -+ } - -- @Test -- void noOpsOnTimerAdded() { -- listener.onTimerAdded(BLAH, timer); -+ @Test -+ void noOpsOnTimerAdded() { -+ listener.onTimerAdded(BLAH, timer); - -- verifyNoInteractions(timer); -- } -+ verifyNoInteractions(timer); -+ } - -- @Test -- void doesNotExplodeWhenMetricsAreRemoved() { -- listener.onGaugeRemoved(BLAH); -- listener.onCounterRemoved(BLAH); -- listener.onHistogramRemoved(BLAH); -- listener.onMeterRemoved(BLAH); -- listener.onTimerRemoved(BLAH); -- } -+ @Test -+ void doesNotExplodeWhenMetricsAreRemoved() { -+ listener.onGaugeRemoved(BLAH); -+ listener.onCounterRemoved(BLAH); -+ listener.onHistogramRemoved(BLAH); -+ listener.onMeterRemoved(BLAH); -+ listener.onTimerRemoved(BLAH); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java -@@ -1,13 +1,6 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import java.util.HashMap; --import java.util.Map; --import java.util.Set; --import java.util.stream.Collectors; -- -+import static com.google.common.collect.ImmutableSet.toImmutableSet; - import static io.dropwizard.metrics5.MetricRegistry.name; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatThrownBy; -@@ -16,665 +9,665 @@ import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; - import static org.mockito.Mockito.verify; - --class MetricRegistryTest { -- -- private static class CustomCounter extends Counter { -- -- CustomCounter() { -- super(); -- } -- -- public void incTheAnswer() { -- inc(42); -- } -- } -- -- private static final MetricName TIMER2 = MetricName.build("timer"); -- private static final MetricName METER2 = MetricName.build("meter"); -- private static final MetricName HISTOGRAM2 = MetricName.build("histogram"); -- private static final MetricName COUNTER = MetricName.build("counter"); -- private static final MetricName COUNTER2 = MetricName.build("counter2"); -- private static final MetricName GAUGE = MetricName.build("gauge"); -- private static final MetricName GAUGE2 = MetricName.build("gauge2"); -- private static final MetricName SETTABLE_GAUGE = MetricName.build("settable-gauge"); -- private static final MetricName THING = MetricName.build("thing"); -- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); -- private final MetricRegistry registry = new MetricRegistry(); -- private final Gauge gauge = () -> ""; -- private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -- -- @BeforeEach -- void setUp() { -- registry.addListener(listener); -- } -- -- @Test -- void registeringAGaugeTriggersANotification() { -- assertThat(registry.register(THING, gauge)) -- .isEqualTo(gauge); -- -- verify(listener).onGaugeAdded(THING, gauge); -- } -- -- @Test -- void removingAGaugeTriggersANotification() { -- registry.register(THING, gauge); -- -- assertThat(registry.remove(THING)) -- .isTrue(); -- -- verify(listener).onGaugeRemoved(THING); -- } -- -- @Test -- void registeringACounterTriggersANotification() { -- assertThat(registry.register(THING, counter)) -- .isEqualTo(counter); -- -- verify(listener).onCounterAdded(THING, counter); -- } -- -- @Test -- void accessingACounterRegistersAndReusesTheCounter() { -- final Counter counter1 = registry.counter(THING); -- final Counter counter2 = registry.counter(THING); -- -- assertThat(counter1) -- .isSameAs(counter2); -- -- verify(listener).onCounterAdded(THING, counter1); -- } -- -- @Test -- void accessingACustomCounterRegistersAndReusesTheCounter() { -- final MetricRegistry.MetricSupplier supplier = () -> counter; -- final Counter counter1 = registry.counter(THING, supplier); -- final Counter counter2 = registry.counter(THING, supplier); -- -- assertThat(counter1) -- .isSameAs(counter2); -+import java.util.HashMap; -+import java.util.Map; -+import java.util.Set; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - -- verify(listener).onCounterAdded(THING, counter1); -- } -+final class MetricRegistryTest { - -- @Test -- void createsTypesafeCustomCounter() { -- MetricName name = MetricName.build("custom-counter"); -- final CustomCounter customCounter = registry.counter(name, CustomCounter::new); -- customCounter.incTheAnswer(); -+ private static class CustomCounter extends Counter { - -- assertThat(registry.counter(name).getCount()).isEqualTo(42); -+ CustomCounter() { -+ super(); - } - -- @Test -- void removingACounterTriggersANotification() { -- registry.register(THING, counter); -- -- assertThat(registry.remove(THING)) -- .isTrue(); -- -- verify(listener).onCounterRemoved(THING); -+ public void incTheAnswer() { -+ inc(42); - } -+ } - -- @Test -- void registeringAHistogramTriggersANotification() { -- assertThat(registry.register(THING, histogram)) -- .isEqualTo(histogram); -+ private static final MetricName TIMER2 = MetricName.build("timer"); -+ private static final MetricName METER2 = MetricName.build("meter"); -+ private static final MetricName HISTOGRAM2 = MetricName.build("histogram"); -+ private static final MetricName COUNTER = MetricName.build("counter"); -+ private static final MetricName COUNTER2 = MetricName.build("counter2"); -+ private static final MetricName GAUGE = MetricName.build("gauge"); -+ private static final MetricName GAUGE2 = MetricName.build("gauge2"); -+ private static final MetricName SETTABLE_GAUGE = MetricName.build("settable-gauge"); -+ private static final MetricName THING = MetricName.build("thing"); -+ private final MetricRegistryListener listener = mock(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final Gauge gauge = () -> ""; -+ private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - -- verify(listener).onHistogramAdded(THING, histogram); -- } -+ @BeforeEach -+ void setUp() { -+ registry.addListener(listener); -+ } - -- @Test -- void accessingAHistogramRegistersAndReusesIt() { -- final Histogram histogram1 = registry.histogram(THING); -- final Histogram histogram2 = registry.histogram(THING); -+ @Test -+ void registeringAGaugeTriggersANotification() { -+ assertThat(registry.register(THING, gauge)).isEqualTo(gauge); - -- assertThat(histogram1) -- .isSameAs(histogram2); -+ verify(listener).onGaugeAdded(THING, gauge); -+ } - -- verify(listener).onHistogramAdded(THING, histogram1); -- } -+ @Test -+ void removingAGaugeTriggersANotification() { -+ registry.register(THING, gauge); - -- @Test -- void accessingACustomHistogramRegistersAndReusesIt() { -- final MetricRegistry.MetricSupplier supplier = () -> histogram; -- final Histogram histogram1 = registry.histogram(THING, supplier); -- final Histogram histogram2 = registry.histogram(THING, supplier); -+ assertThat(registry.remove(THING)).isTrue(); - -- assertThat(histogram1) -- .isSameAs(histogram2); -+ verify(listener).onGaugeRemoved(THING); -+ } - -- verify(listener).onHistogramAdded(THING, histogram1); -- } -+ @Test -+ void registeringACounterTriggersANotification() { -+ assertThat(registry.register(THING, counter)).isEqualTo(counter); - -- @Test -- void removingAHistogramTriggersANotification() { -- registry.register(THING, histogram); -+ verify(listener).onCounterAdded(THING, counter); -+ } - -- assertThat(registry.remove(THING)) -- .isTrue(); -+ @Test -+ void accessingACounterRegistersAndReusesTheCounter() { -+ final Counter counter1 = registry.counter(THING); -+ final Counter counter2 = registry.counter(THING); - -- verify(listener).onHistogramRemoved(THING); -- } -+ assertThat(counter1).isSameAs(counter2); - -- @Test -- void registeringAMeterTriggersANotification() { -- assertThat(registry.register(THING, meter)) -- .isEqualTo(meter); -+ verify(listener).onCounterAdded(THING, counter1); -+ } - -- verify(listener).onMeterAdded(THING, meter); -- } -+ @Test -+ void accessingACustomCounterRegistersAndReusesTheCounter() { -+ final MetricRegistry.MetricSupplier supplier = () -> counter; -+ final Counter counter1 = registry.counter(THING, supplier); -+ final Counter counter2 = registry.counter(THING, supplier); - -- @Test -- void accessingAMeterRegistersAndReusesIt() { -- final Meter meter1 = registry.meter(THING); -- final Meter meter2 = registry.meter(THING); -+ assertThat(counter1).isSameAs(counter2); - -- assertThat(meter1) -- .isSameAs(meter2); -+ verify(listener).onCounterAdded(THING, counter1); -+ } - -- verify(listener).onMeterAdded(THING, meter1); -- } -+ @Test -+ void createsTypesafeCustomCounter() { -+ MetricName name = MetricName.build("custom-counter"); -+ final CustomCounter customCounter = registry.counter(name, CustomCounter::new); -+ customCounter.incTheAnswer(); - -- @Test -- void accessingACustomMeterRegistersAndReusesIt() { -- final MetricRegistry.MetricSupplier supplier = () -> meter; -- final Meter meter1 = registry.meter(THING, supplier); -- final Meter meter2 = registry.meter(THING, supplier); -+ assertThat(registry.counter(name).getCount()).isEqualTo(42); -+ } - -- assertThat(meter1) -- .isSameAs(meter2); -+ @Test -+ void removingACounterTriggersANotification() { -+ registry.register(THING, counter); - -- verify(listener).onMeterAdded(THING, meter1); -- } -+ assertThat(registry.remove(THING)).isTrue(); - -- @Test -- void removingAMeterTriggersANotification() { -- registry.register(THING, meter); -+ verify(listener).onCounterRemoved(THING); -+ } - -- assertThat(registry.remove(THING)) -- .isTrue(); -+ @Test -+ void registeringAHistogramTriggersANotification() { -+ assertThat(registry.register(THING, histogram)).isEqualTo(histogram); - -- verify(listener).onMeterRemoved(THING); -- } -+ verify(listener).onHistogramAdded(THING, histogram); -+ } - -- @Test -- void registeringATimerTriggersANotification() { -- assertThat(registry.register(THING, timer)) -- .isEqualTo(timer); -+ @Test -+ void accessingAHistogramRegistersAndReusesIt() { -+ final Histogram histogram1 = registry.histogram(THING); -+ final Histogram histogram2 = registry.histogram(THING); - -- verify(listener).onTimerAdded(THING, timer); -- } -+ assertThat(histogram1).isSameAs(histogram2); - -- @Test -- void accessingATimerRegistersAndReusesIt() { -- final Timer timer1 = registry.timer(THING); -- final Timer timer2 = registry.timer(THING); -+ verify(listener).onHistogramAdded(THING, histogram1); -+ } - -- assertThat(timer1) -- .isSameAs(timer2); -+ @Test -+ void accessingACustomHistogramRegistersAndReusesIt() { -+ final MetricRegistry.MetricSupplier supplier = () -> histogram; -+ final Histogram histogram1 = registry.histogram(THING, supplier); -+ final Histogram histogram2 = registry.histogram(THING, supplier); - -- verify(listener).onTimerAdded(THING, timer1); -- } -+ assertThat(histogram1).isSameAs(histogram2); - -- @Test -- void accessingACustomTimerRegistersAndReusesIt() { -- final MetricRegistry.MetricSupplier supplier = () -> timer; -- final Timer timer1 = registry.timer(THING, supplier); -- final Timer timer2 = registry.timer(THING, supplier); -+ verify(listener).onHistogramAdded(THING, histogram1); -+ } - -- assertThat(timer1) -- .isSameAs(timer2); -+ @Test -+ void removingAHistogramTriggersANotification() { -+ registry.register(THING, histogram); - -- verify(listener).onTimerAdded(THING, timer1); -- } -+ assertThat(registry.remove(THING)).isTrue(); - -+ verify(listener).onHistogramRemoved(THING); -+ } - -- @Test -- void removingATimerTriggersANotification() { -- registry.register(THING, timer); -+ @Test -+ void registeringAMeterTriggersANotification() { -+ assertThat(registry.register(THING, meter)).isEqualTo(meter); - -- assertThat(registry.remove(THING)) -- .isTrue(); -+ verify(listener).onMeterAdded(THING, meter); -+ } - -- verify(listener).onTimerRemoved(THING); -- } -+ @Test -+ void accessingAMeterRegistersAndReusesIt() { -+ final Meter meter1 = registry.meter(THING); -+ final Meter meter2 = registry.meter(THING); - -- @Test -- void accessingACustomGaugeRegistersAndReusesIt() { -- final MetricRegistry.MetricSupplier> supplier = () -> gauge; -- final Gauge gauge1 = registry.gauge(THING, supplier); -- final Gauge gauge2 = registry.gauge(THING, supplier); -+ assertThat(meter1).isSameAs(meter2); - -- assertThat(gauge1) -- .isSameAs(gauge2); -+ verify(listener).onMeterAdded(THING, meter1); -+ } - -- verify(listener).onGaugeAdded(THING, gauge1); -- } -+ @Test -+ void accessingACustomMeterRegistersAndReusesIt() { -+ final MetricRegistry.MetricSupplier supplier = () -> meter; -+ final Meter meter1 = registry.meter(THING, supplier); -+ final Meter meter2 = registry.meter(THING, supplier); - -- @Test -- void accessingASettableGaugeRegistersAndReusesIt() { -- final SettableGauge gauge1 = registry.gauge(THING); -- gauge1.setValue("Test"); -- final Gauge gauge2 = registry.gauge(THING); -+ assertThat(meter1).isSameAs(meter2); - -- assertThat(gauge1).isSameAs(gauge2); -- assertThat(gauge2.getValue()).isEqualTo("Test"); -+ verify(listener).onMeterAdded(THING, meter1); -+ } - -- verify(listener).onGaugeAdded(THING, gauge1); -- } -+ @Test -+ void removingAMeterTriggersANotification() { -+ registry.register(THING, meter); - -- @Test -- void accessingAnExistingGaugeReusesIt() { -- final Gauge gauge1 = registry.gauge(THING, () -> () -> "string-gauge"); -- final Gauge gauge2 = registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); -+ assertThat(registry.remove(THING)).isTrue(); - -- assertThat(gauge1).isSameAs(gauge2); -- assertThat(gauge2.getValue()).isEqualTo("string-gauge"); -+ verify(listener).onMeterRemoved(THING); -+ } - -- verify(listener).onGaugeAdded(THING, gauge1); -- } -+ @Test -+ void registeringATimerTriggersANotification() { -+ assertThat(registry.register(THING, timer)).isEqualTo(timer); - -- @Test -- void accessingAnExistingSettableGaugeReusesIt() { -- final Gauge gauge1 = registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); -- final Gauge gauge2 = registry.gauge(THING); -+ verify(listener).onTimerAdded(THING, timer); -+ } - -- assertThat(gauge1).isSameAs(gauge2); -- assertThat(gauge2.getValue()).isEqualTo("settable-gauge"); -+ @Test -+ void accessingATimerRegistersAndReusesIt() { -+ final Timer timer1 = registry.timer(THING); -+ final Timer timer2 = registry.timer(THING); - -- verify(listener).onGaugeAdded(THING, gauge1); -- } -+ assertThat(timer1).isSameAs(timer2); - -- @Test -- void settableGaugeIsTreatedLikeAGauge() { -- final MetricRegistry.MetricSupplier> supplier = () -> settableGauge; -- final SettableGauge gauge1 = registry.gauge(THING, supplier); -- final SettableGauge gauge2 = registry.gauge(THING, supplier); -+ verify(listener).onTimerAdded(THING, timer1); -+ } - -- assertThat(gauge1) -- .isSameAs(gauge2); -+ @Test -+ void accessingACustomTimerRegistersAndReusesIt() { -+ final MetricRegistry.MetricSupplier supplier = () -> timer; -+ final Timer timer1 = registry.timer(THING, supplier); -+ final Timer timer2 = registry.timer(THING, supplier); - -- verify(listener).onGaugeAdded(THING, gauge1); -- } -+ assertThat(timer1).isSameAs(timer2); - -- @Test -- void addingAListenerWithExistingMetricsCatchesItUp() { -- registry.register(GAUGE2, gauge); -- registry.register(SETTABLE_GAUGE, settableGauge); -- registry.register(COUNTER2, counter); -- registry.register(HISTOGRAM2, histogram); -- registry.register(METER2, meter); -- registry.register(TIMER2, timer); -- -- final MetricRegistryListener other = mock(MetricRegistryListener.class); -- registry.addListener(other); -- -- verify(other).onGaugeAdded(GAUGE2, gauge); -- verify(other).onGaugeAdded(SETTABLE_GAUGE, settableGauge); -- verify(other).onCounterAdded(COUNTER2, counter); -- verify(other).onHistogramAdded(HISTOGRAM2, histogram); -- verify(other).onMeterAdded(METER2, meter); -- verify(other).onTimerAdded(TIMER2, timer); -- } -+ verify(listener).onTimerAdded(THING, timer1); -+ } - -- @Test -- void aRemovedListenerDoesNotReceiveUpdates() { -- registry.register(GAUGE, gauge); -- registry.removeListener(listener); -- registry.register(GAUGE2, gauge); -+ @Test -+ void removingATimerTriggersANotification() { -+ registry.register(THING, timer); - -- verify(listener, never()).onGaugeAdded(GAUGE2, gauge); -- } -+ assertThat(registry.remove(THING)).isTrue(); - -- @Test -- void hasAMapOfRegisteredGauges() { -- registry.register(GAUGE2, gauge); -- registry.register(SETTABLE_GAUGE, settableGauge); -+ verify(listener).onTimerRemoved(THING); -+ } - -- assertThat(registry.getGauges()) -- .containsEntry(GAUGE2, gauge) -- .containsEntry(SETTABLE_GAUGE, settableGauge); -- } -+ @Test -+ void accessingACustomGaugeRegistersAndReusesIt() { -+ final MetricRegistry.MetricSupplier> supplier = () -> gauge; -+ final Gauge gauge1 = registry.gauge(THING, supplier); -+ final Gauge gauge2 = registry.gauge(THING, supplier); - -- @Test -- void hasAMapOfRegisteredCounters() { -- registry.register(COUNTER2, counter); -+ assertThat(gauge1).isSameAs(gauge2); - -- assertThat(registry.getCounters()) -- .contains(entry(COUNTER2, counter)); -- } -+ verify(listener).onGaugeAdded(THING, gauge1); -+ } - -- @Test -- void hasAMapOfRegisteredHistograms() { -- registry.register(HISTOGRAM2, histogram); -+ @Test -+ void accessingASettableGaugeRegistersAndReusesIt() { -+ final SettableGauge gauge1 = registry.gauge(THING); -+ gauge1.setValue("Test"); -+ final Gauge gauge2 = registry.gauge(THING); - -- assertThat(registry.getHistograms()) -- .contains(entry(HISTOGRAM2, histogram)); -- } -+ assertThat(gauge1).isSameAs(gauge2); -+ assertThat(gauge2.getValue()).isEqualTo("Test"); - -- @Test -- void hasAMapOfRegisteredMeters() { -- registry.register(METER2, meter); -+ verify(listener).onGaugeAdded(THING, gauge1); -+ } - -- assertThat(registry.getMeters()) -- .contains(entry(METER2, meter)); -- } -+ @Test -+ void accessingAnExistingGaugeReusesIt() { -+ final Gauge gauge1 = registry.gauge(THING, () -> () -> "string-gauge"); -+ final Gauge gauge2 = -+ registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); - -- @Test -- void hasAMapOfRegisteredTimers() { -- registry.register(TIMER2, timer); -+ assertThat(gauge1).isSameAs(gauge2); -+ assertThat(gauge2.getValue()).isEqualTo("string-gauge"); - -- assertThat(registry.getTimers()) -- .contains(entry(TIMER2, timer)); -- } -+ verify(listener).onGaugeAdded(THING, gauge1); -+ } - -- @Test -- void hasASetOfRegisteredMetricNames() { -- registry.register(GAUGE2, gauge); -- registry.register(SETTABLE_GAUGE, settableGauge); -- registry.register(COUNTER2, counter); -- registry.register(HISTOGRAM2, histogram); -- registry.register(METER2, meter); -- registry.register(TIMER2, timer); -- -- assertThat(registry.getNames()) -- .containsOnly(GAUGE2, SETTABLE_GAUGE, COUNTER2, HISTOGRAM2, METER2, TIMER2); -- } -+ @Test -+ void accessingAnExistingSettableGaugeReusesIt() { -+ final Gauge gauge1 = -+ registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); -+ final Gauge gauge2 = registry.gauge(THING); - -- @Test -- void registersMultipleMetrics() { -- final MetricSet metrics = () -> { -- final Map m = new HashMap<>(); -- m.put(GAUGE2, gauge); -- m.put(COUNTER2, counter); -- return m; -+ assertThat(gauge1).isSameAs(gauge2); -+ assertThat(gauge2.getValue()).isEqualTo("settable-gauge"); -+ -+ verify(listener).onGaugeAdded(THING, gauge1); -+ } -+ -+ @Test -+ void settableGaugeIsTreatedLikeAGauge() { -+ final MetricRegistry.MetricSupplier> supplier = () -> settableGauge; -+ final SettableGauge gauge1 = registry.gauge(THING, supplier); -+ final SettableGauge gauge2 = registry.gauge(THING, supplier); -+ -+ assertThat(gauge1).isSameAs(gauge2); -+ -+ verify(listener).onGaugeAdded(THING, gauge1); -+ } -+ -+ @Test -+ void addingAListenerWithExistingMetricsCatchesItUp() { -+ registry.register(GAUGE2, gauge); -+ registry.register(SETTABLE_GAUGE, settableGauge); -+ registry.register(COUNTER2, counter); -+ registry.register(HISTOGRAM2, histogram); -+ registry.register(METER2, meter); -+ registry.register(TIMER2, timer); -+ -+ final MetricRegistryListener other = mock(); -+ registry.addListener(other); -+ -+ verify(other).onGaugeAdded(GAUGE2, gauge); -+ verify(other).onGaugeAdded(SETTABLE_GAUGE, settableGauge); -+ verify(other).onCounterAdded(COUNTER2, counter); -+ verify(other).onHistogramAdded(HISTOGRAM2, histogram); -+ verify(other).onMeterAdded(METER2, meter); -+ verify(other).onTimerAdded(TIMER2, timer); -+ } -+ -+ @Test -+ void aRemovedListenerDoesNotReceiveUpdates() { -+ registry.register(GAUGE, gauge); -+ registry.removeListener(listener); -+ registry.register(GAUGE2, gauge); -+ -+ verify(listener, never()).onGaugeAdded(GAUGE2, gauge); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredGauges() { -+ registry.register(GAUGE2, gauge); -+ registry.register(SETTABLE_GAUGE, settableGauge); -+ -+ assertThat(registry.getGauges()) -+ .containsEntry(GAUGE2, gauge) -+ .containsEntry(SETTABLE_GAUGE, settableGauge); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredCounters() { -+ registry.register(COUNTER2, counter); -+ -+ assertThat(registry.getCounters()).contains(entry(COUNTER2, counter)); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredHistograms() { -+ registry.register(HISTOGRAM2, histogram); -+ -+ assertThat(registry.getHistograms()).contains(entry(HISTOGRAM2, histogram)); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredMeters() { -+ registry.register(METER2, meter); -+ -+ assertThat(registry.getMeters()).contains(entry(METER2, meter)); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredTimers() { -+ registry.register(TIMER2, timer); -+ -+ assertThat(registry.getTimers()).contains(entry(TIMER2, timer)); -+ } -+ -+ @Test -+ void hasASetOfRegisteredMetricNames() { -+ registry.register(GAUGE2, gauge); -+ registry.register(SETTABLE_GAUGE, settableGauge); -+ registry.register(COUNTER2, counter); -+ registry.register(HISTOGRAM2, histogram); -+ registry.register(METER2, meter); -+ registry.register(TIMER2, timer); -+ -+ assertThat(registry.getNames()) -+ .containsOnly(GAUGE2, SETTABLE_GAUGE, COUNTER2, HISTOGRAM2, METER2, TIMER2); -+ } -+ -+ @Test -+ void registersMultipleMetrics() { -+ final MetricSet metrics = -+ () -> { -+ final Map m = new HashMap<>(); -+ m.put(GAUGE2, gauge); -+ m.put(COUNTER2, counter); -+ return m; - }; - -- registry.registerAll(metrics); -+ registry.registerAll(metrics); - -- assertThat(registry.getNames()) -- .containsOnly(GAUGE2, COUNTER2); -- } -+ assertThat(registry.getNames()).containsOnly(GAUGE2, COUNTER2); -+ } - -- @Test -- void registersMultipleMetricsWithAPrefix() { -- final MetricName myCounter = MetricName.build("my.counter"); -- final MetricName myGauge = MetricName.build("my.gauge"); -+ @Test -+ void registersMultipleMetricsWithAPrefix() { -+ final MetricName myCounter = MetricName.build("my.counter"); -+ final MetricName myGauge = MetricName.build("my.gauge"); - -- final MetricSet metrics = () -> { -- final Map m = new HashMap<>(); -- m.put(GAUGE, gauge); -- m.put(COUNTER, counter); -- return m; -+ final MetricSet metrics = -+ () -> { -+ final Map m = new HashMap<>(); -+ m.put(GAUGE, gauge); -+ m.put(COUNTER, counter); -+ return m; - }; - -- registry.register(MetricName.build("my"), metrics); -+ registry.register(MetricName.build("my"), metrics); - -- assertThat(registry.getNames()) -- .containsOnly(myGauge, myCounter); -- } -+ assertThat(registry.getNames()).containsOnly(myGauge, myCounter); -+ } - -- @Test -- void registersRecursiveMetricSets() { -- final MetricSet inner = () -> { -- final Map m = new HashMap<>(); -- m.put(GAUGE, gauge); -- return m; -+ @Test -+ void registersRecursiveMetricSets() { -+ final MetricSet inner = -+ () -> { -+ final Map m = new HashMap<>(); -+ m.put(GAUGE, gauge); -+ return m; - }; - -- final MetricSet outer = () -> { -- final Map m = new HashMap<>(); -- m.put(MetricName.build("inner"), inner); -- m.put(COUNTER, counter); -- return m; -+ final MetricSet outer = -+ () -> { -+ final Map m = new HashMap<>(); -+ m.put(MetricName.build("inner"), inner); -+ m.put(COUNTER, counter); -+ return m; - }; - -- registry.register(MetricName.build("my"), outer); -- -- final MetricName myCounter = MetricName.build("my.counter"); -- final MetricName myInnerGauge = MetricName.build("my.inner.gauge"); -- -- assertThat(registry.getNames()) -- .containsOnly(myInnerGauge, myCounter); -- } -- -- @Test -- void registersMetricsFromAnotherRegistry() { -- MetricRegistry other = new MetricRegistry(); -- other.register(GAUGE, gauge); -- registry.register(MetricName.build("nested"), other); -- assertThat(registry.getNames()).containsOnly(MetricName.build("nested.gauge")); -- } -- -- @Test -- void concatenatesStringsToFormADottedName() { -- assertThat(name("one", "two", "three")) -- .isEqualTo(MetricName.build("one.two.three")); -- } -- -- @Test -- void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { -- assertThat(name("one", (String) null)) -- .isEqualTo(MetricName.build("one")); -- } -- -- @Test -- void elidesNullValuesFromNamesWhenManyNullsPassedIn() { -- assertThat(name("one", null, null)) -- .isEqualTo(MetricName.build("one")); -- } -- -- @Test -- void elidesNullValuesFromNamesWhenNullAndNotNullPassedIn() { -- assertThat(name("one", null, "three")) -- .isEqualTo(MetricName.build("one.three")); -- } -- -- @Test -- void elidesEmptyStringsFromNames() { -- assertThat(name("one", "", "three")) -- .isEqualTo(MetricName.build("one.three")); -- } -- -- @Test -- void concatenatesClassNamesWithStringsToFormADottedName() { -- assertThat(name(MetricRegistryTest.class, "one", "two")) -- .isEqualTo(MetricName.build("io.dropwizard.metrics5.MetricRegistryTest.one.two")); -- } -- -- @Test -- void concatenatesClassesWithoutCanonicalNamesWithStrings() { -- final Gauge g = () -> null; -- -- assertThat(name(g.getClass(), "one", "two")) -- .isEqualTo(MetricName.build(g.getClass().getName() + ".one.two")); -- } -- -- @Test -- void removesMetricsMatchingAFilter() { -- final MetricName timer1 = MetricName.build("timer-1"); -- final MetricName timer2 = MetricName.build("timer-2"); -- final MetricName histogram1 = MetricName.build("histogram-1"); -- -- registry.timer(timer1); -- registry.timer(timer2); -- registry.histogram(histogram1); -- -- assertThat(registry.getNames()) -- .contains(timer1, timer2, histogram1); -- -- registry.removeMatching((name, metric) -> name.getKey().endsWith("1")); -- -- assertThat(registry.getNames()) -- .doesNotContain(timer1, histogram1); -- assertThat(registry.getNames()) -- .contains(timer2); -- -- verify(listener).onTimerRemoved(timer1); -- verify(listener).onHistogramRemoved(histogram1); -- } -- -- @Test -- void addingChildMetricAfterRegister() { -- MetricRegistry parent = new MetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- -- child.counter("test-1"); -- parent.register(MetricName.build("child"), child); -- child.counter("test-2"); -- -- Set parentMetrics = parent.getMetrics().keySet(); -- Set childMetrics = child.getMetrics().keySet(); -- -- assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); -- } -- -- @Test -- void addingMultipleChildMetricsAfterRegister() { -- MetricRegistry parent = new MetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- -- child.counter("test-1"); -- child.counter("test-2"); -- parent.register(MetricName.build("child"), child); -- child.counter("test-3"); -- child.counter("test-4"); -- -- Set parentMetrics = parent.getMetrics().keySet(); -- Set childMetrics = child.getMetrics().keySet(); -- -- assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); -- } -- -- @Test -- void addingDeepChildMetricsAfterRegister() { -- MetricRegistry parent = new MetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- MetricRegistry deepChild = new MetricRegistry(); -- -- deepChild.counter("test-1"); -- child.register(MetricName.build("deep-child"), deepChild); -- deepChild.counter("test-2"); -- -- child.counter("test-3"); -- parent.register(MetricName.build("child"), child); -- child.counter("test-4"); -- -- deepChild.counter("test-5"); -- Set parentMetrics = parent.getMetrics().keySet(); -- Set childMetrics = child.getMetrics().keySet(); -- Set deepChildMetrics = deepChild.getMetrics().keySet(); -+ registry.register(MetricName.build("my"), outer); -+ -+ final MetricName myCounter = MetricName.build("my.counter"); -+ final MetricName myInnerGauge = MetricName.build("my.inner.gauge"); -+ -+ assertThat(registry.getNames()).containsOnly(myInnerGauge, myCounter); -+ } -+ -+ @Test -+ void registersMetricsFromAnotherRegistry() { -+ MetricRegistry other = new MetricRegistry(); -+ other.register(GAUGE, gauge); -+ registry.register(MetricName.build("nested"), other); -+ assertThat(registry.getNames()).containsExactly(MetricName.build("nested.gauge")); -+ } -+ -+ @Test -+ void concatenatesStringsToFormADottedName() { -+ assertThat(name("one", "two", "three")).isEqualTo(MetricName.build("one.two.three")); -+ } -+ -+ @Test -+ void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { -+ assertThat(name("one", (String) null)).isEqualTo(MetricName.build("one")); -+ } -+ -+ @Test -+ void elidesNullValuesFromNamesWhenManyNullsPassedIn() { -+ assertThat(name("one", null, null)).isEqualTo(MetricName.build("one")); -+ } -+ -+ @Test -+ void elidesNullValuesFromNamesWhenNullAndNotNullPassedIn() { -+ assertThat(name("one", null, "three")).isEqualTo(MetricName.build("one.three")); -+ } -+ -+ @Test -+ void elidesEmptyStringsFromNames() { -+ assertThat(name("one", "", "three")).isEqualTo(MetricName.build("one.three")); -+ } -+ -+ @Test -+ void concatenatesClassNamesWithStringsToFormADottedName() { -+ assertThat(name(MetricRegistryTest.class, "one", "two")) -+ .isEqualTo(MetricName.build("io.dropwizard.metrics5.MetricRegistryTest.one.two")); -+ } -+ -+ @Test -+ void concatenatesClassesWithoutCanonicalNamesWithStrings() { -+ final Gauge g = () -> null; -+ -+ assertThat(name(g.getClass(), "one", "two")) -+ .isEqualTo(MetricName.build(g.getClass().getName() + ".one.two")); -+ } -+ -+ @Test -+ void removesMetricsMatchingAFilter() { -+ final MetricName timer1 = MetricName.build("timer-1"); -+ final MetricName timer2 = MetricName.build("timer-2"); -+ final MetricName histogram1 = MetricName.build("histogram-1"); -+ -+ registry.timer(timer1); -+ registry.timer(timer2); -+ registry.histogram(histogram1); -+ -+ assertThat(registry.getNames()).contains(timer1, timer2, histogram1); -+ -+ registry.removeMatching((name, metric) -> name.getKey().endsWith("1")); -+ -+ assertThat(registry.getNames()).doesNotContain(timer1, histogram1); -+ assertThat(registry.getNames()).contains(timer2); -+ -+ verify(listener).onTimerRemoved(timer1); -+ verify(listener).onHistogramRemoved(histogram1); -+ } -+ -+ @Test -+ void addingChildMetricAfterRegister() { -+ MetricRegistry parent = new MetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ -+ child.counter("test-1"); -+ parent.register(MetricName.build("child"), child); -+ child.counter("test-2"); -+ -+ Set parentMetrics = parent.getMetrics().keySet(); -+ Set childMetrics = child.getMetrics().keySet(); -+ -+ assertThat(parentMetrics) -+ .hasSameElementsAs( -+ childMetrics.stream() -+ .map(m -> MetricName.build("child", m.getKey())) -+ .collect(toImmutableSet())); -+ } -+ -+ @Test -+ void addingMultipleChildMetricsAfterRegister() { -+ MetricRegistry parent = new MetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ -+ child.counter("test-1"); -+ child.counter("test-2"); -+ parent.register(MetricName.build("child"), child); -+ child.counter("test-3"); -+ child.counter("test-4"); -+ -+ Set parentMetrics = parent.getMetrics().keySet(); -+ Set childMetrics = child.getMetrics().keySet(); -+ -+ assertThat(parentMetrics) -+ .hasSameElementsAs( -+ childMetrics.stream() -+ .map(m -> MetricName.build("child", m.getKey())) -+ .collect(toImmutableSet())); -+ } -+ -+ @Test -+ void addingDeepChildMetricsAfterRegister() { -+ MetricRegistry parent = new MetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ MetricRegistry deepChild = new MetricRegistry(); -+ -+ deepChild.counter("test-1"); -+ child.register(MetricName.build("deep-child"), deepChild); -+ deepChild.counter("test-2"); -+ -+ child.counter("test-3"); -+ parent.register(MetricName.build("child"), child); -+ child.counter("test-4"); -+ -+ deepChild.counter("test-5"); -+ Set parentMetrics = parent.getMetrics().keySet(); -+ Set childMetrics = child.getMetrics().keySet(); -+ Set deepChildMetrics = deepChild.getMetrics().keySet(); -+ -+ assertThat(parentMetrics) -+ .hasSameElementsAs( -+ childMetrics.stream() -+ .map(m -> MetricName.build("child", m.getKey())) -+ .collect(toImmutableSet())); -+ -+ assertThat(childMetrics) -+ .containsAll( -+ deepChildMetrics.stream() -+ .map(m -> MetricName.build("deep-child", m.getKey())) -+ .collect(toImmutableSet())); -+ -+ assertThat(deepChildMetrics).hasSize(3); -+ assertThat(childMetrics).hasSize(5); -+ } -+ -+ @Test -+ void removingChildMetricAfterRegister() { -+ MetricRegistry parent = new MetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ -+ child.counter("test-1"); -+ parent.register(MetricName.build("child"), child); -+ child.counter("test-2"); -+ -+ child.remove(MetricName.build("test-1")); -+ -+ Set parentMetrics = parent.getMetrics().keySet(); -+ Set childMetrics = child.getMetrics().keySet(); -+ -+ assertThat(parentMetrics) -+ .hasSameElementsAs( -+ childMetrics.stream() -+ .map(m -> MetricName.build("child", m.getKey())) -+ .collect(toImmutableSet())); -+ -+ assertThat(childMetrics).doesNotContain(MetricName.build("test-1")); -+ } -+ -+ @Test -+ void removingMultipleChildMetricsAfterRegister() { -+ MetricRegistry parent = new MetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ -+ child.counter("test-1"); -+ child.counter("test-2"); -+ parent.register(MetricName.build("child"), child); -+ child.counter("test-3"); -+ child.counter("test-4"); -+ -+ child.remove(MetricName.build("test-1")); -+ child.remove(MetricName.build("test-3")); -+ -+ Set parentMetrics = parent.getMetrics().keySet(); -+ Set childMetrics = child.getMetrics().keySet(); -+ -+ assertThat(parentMetrics) -+ .hasSameElementsAs( -+ childMetrics.stream() -+ .map(m -> MetricName.build("child", m.getKey())) -+ .collect(toImmutableSet())); -+ -+ assertThat(childMetrics).doesNotContain(MetricName.build("test-1"), MetricName.build("test-3")); -+ } -+ -+ @Test -+ void removingDeepChildMetricsAfterRegister() { -+ MetricRegistry parent = new MetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ MetricRegistry deepChild = new MetricRegistry(); -+ -+ deepChild.counter("test-1"); -+ child.register(MetricName.build("deep-child"), deepChild); -+ deepChild.counter("test-2"); -+ -+ child.counter("test-3"); -+ parent.register(MetricName.build("child"), child); -+ child.counter("test-4"); -+ -+ deepChild.remove(MetricName.build("test-2")); -+ -+ Set parentMetrics = parent.getMetrics().keySet(); -+ Set childMetrics = child.getMetrics().keySet(); -+ Set deepChildMetrics = deepChild.getMetrics().keySet(); -+ -+ assertThat(parentMetrics) -+ .hasSameElementsAs( -+ childMetrics.stream() -+ .map(m -> MetricName.build("child", m.getKey())) -+ .collect(toImmutableSet())); -+ -+ assertThat(childMetrics) -+ .containsAll( -+ deepChildMetrics.stream() -+ .map(m -> MetricName.build("deep-child", m.getKey())) -+ .collect(toImmutableSet())); -+ -+ assertThat(deepChildMetrics).doesNotContain(MetricName.build("test-2")); -+ -+ assertThat(deepChildMetrics).hasSize(1); -+ assertThat(childMetrics).hasSize(3); -+ } -+ -+ @Test -+ void registerNullMetric() { -+ MetricRegistry registry = new MetricRegistry(); -+ assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)) -+ .hasMessage("metric == null"); -+ } -+ -+ @Test -+ void infersGaugeType() { -+ Gauge gauge = registry.registerGauge(GAUGE, () -> 10_000_000_000L); -+ -+ assertThat(gauge.getValue()).isEqualTo(10_000_000_000L); -+ } -+ -+ @Test -+ void registersGaugeAsLambda() { -+ registry.registerGauge(GAUGE, () -> 3.14); - -- assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); -- -- assertThat(childMetrics) -- .containsAll(deepChildMetrics.stream().map(m -> MetricName.build("deep-child", m.getKey())).collect(Collectors.toSet())); -- -- assertThat(deepChildMetrics.size()).isEqualTo(3); -- assertThat(childMetrics.size()).isEqualTo(5); -- } -- -- @Test -- void removingChildMetricAfterRegister() { -- MetricRegistry parent = new MetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- -- child.counter("test-1"); -- parent.register(MetricName.build("child"), child); -- child.counter("test-2"); -- -- child.remove(MetricName.build("test-1")); -- -- Set parentMetrics = parent.getMetrics().keySet(); -- Set childMetrics = child.getMetrics().keySet(); -- -- assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); -- -- assertThat(childMetrics).doesNotContain(MetricName.build("test-1")); -- } -- -- @Test -- void removingMultipleChildMetricsAfterRegister() { -- MetricRegistry parent = new MetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- -- child.counter("test-1"); -- child.counter("test-2"); -- parent.register(MetricName.build("child"), child); -- child.counter("test-3"); -- child.counter("test-4"); -- -- child.remove(MetricName.build("test-1")); -- child.remove(MetricName.build("test-3")); -- -- Set parentMetrics = parent.getMetrics().keySet(); -- Set childMetrics = child.getMetrics().keySet(); -- -- assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); -- -- assertThat(childMetrics).doesNotContain(MetricName.build("test-1"), MetricName.build("test-3")); -- } -- -- @Test -- void removingDeepChildMetricsAfterRegister() { -- MetricRegistry parent = new MetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- MetricRegistry deepChild = new MetricRegistry(); -- -- deepChild.counter("test-1"); -- child.register(MetricName.build("deep-child"), deepChild); -- deepChild.counter("test-2"); -- -- child.counter("test-3"); -- parent.register(MetricName.build("child"), child); -- child.counter("test-4"); -- -- deepChild.remove(MetricName.build("test-2")); -- -- Set parentMetrics = parent.getMetrics().keySet(); -- Set childMetrics = child.getMetrics().keySet(); -- Set deepChildMetrics = deepChild.getMetrics().keySet(); -- -- assertThat(parentMetrics) -- .isEqualTo(childMetrics.stream().map(m -> MetricName.build("child", m.getKey())).collect(Collectors.toSet())); -- -- assertThat(childMetrics) -- .containsAll(deepChildMetrics.stream().map(m -> MetricName.build("deep-child", m.getKey())).collect(Collectors.toSet())); -- -- assertThat(deepChildMetrics).doesNotContain(MetricName.build("test-2")); -- -- assertThat(deepChildMetrics.size()).isEqualTo(1); -- assertThat(childMetrics.size()).isEqualTo(3); -- } -- -- @Test -- void registerNullMetric() { -- MetricRegistry registry = new MetricRegistry(); -- assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)) -- .hasMessage("metric == null"); -- } -- -- @Test -- void infersGaugeType() { -- Gauge gauge = registry.registerGauge(GAUGE, () -> 10_000_000_000L); -- -- assertThat(gauge.getValue()).isEqualTo(10_000_000_000L); -- } -- -- @Test -- void registersGaugeAsLambda() { -- registry.registerGauge(GAUGE, () -> 3.14); -- -- assertThat(registry.gauge(GAUGE).getValue()).isEqualTo(3.14); -- } -+ assertThat(registry.gauge(GAUGE).getValue()).isEqualTo(3.14); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java -@@ -1,497 +1,498 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import java.util.HashMap; --import java.util.Map; --import java.util.Set; -- - import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatNullPointerException; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; - import static org.mockito.Mockito.verify; - --class NoopMetricRegistryTest { -- private static final MetricName METRIC_THING = MetricName.build("thing"); -- -- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); -- private final NoopMetricRegistry registry = new NoopMetricRegistry(); -- private final Gauge gauge = () -> ""; -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -- -- @BeforeEach -- void setUp() { -- registry.addListener(listener); -- } -- -- @Test -- void registeringAGaugeTriggersNoNotification() { -- assertThat(registry.register(METRIC_THING, gauge)).isEqualTo(gauge); -- -- verify(listener, never()).onGaugeAdded(METRIC_THING, gauge); -- } -- -- @Test -- void removingAGaugeTriggersNoNotification() { -- registry.register(METRIC_THING, gauge); -- -- assertThat(registry.remove(METRIC_THING)).isFalse(); -- -- verify(listener, never()).onGaugeRemoved(METRIC_THING); -- } -- -- @Test -- void registeringACounterTriggersNoNotification() { -- assertThat(registry.register(METRIC_THING, counter)).isEqualTo(counter); -- -- verify(listener, never()).onCounterAdded(METRIC_THING, counter); -- } -- -- @Test -- void accessingACounterRegistersAndReusesTheCounter() { -- final Counter counter1 = registry.counter(METRIC_THING); -- final Counter counter2 = registry.counter(METRIC_THING); -- -- assertThat(counter1).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); -- assertThat(counter2).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); -- assertThat(counter1).isSameAs(counter2); -- -- verify(listener, never()).onCounterAdded(METRIC_THING, counter1); -- } -- -- @Test -- void accessingACustomCounterRegistersAndReusesTheCounter() { -- final MetricRegistry.MetricSupplier supplier = () -> counter; -- final Counter counter1 = registry.counter(METRIC_THING, supplier); -- final Counter counter2 = registry.counter(METRIC_THING, supplier); -- -- assertThat(counter1).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); -- assertThat(counter2).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); -- assertThat(counter1).isSameAs(counter2); -- -- verify(listener, never()).onCounterAdded(METRIC_THING, counter1); -- } -- -- -- @Test -- void removingACounterTriggersNoNotification() { -- registry.register(METRIC_THING, counter); -+import java.util.HashMap; -+import java.util.Map; -+import java.util.Set; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - -- assertThat(registry.remove(METRIC_THING)).isFalse(); -+final class NoopMetricRegistryTest { -+ private static final MetricName METRIC_THING = MetricName.build("thing"); - -- verify(listener, never()).onCounterRemoved(METRIC_THING); -- } -+ private final MetricRegistryListener listener = mock(); -+ private final NoopMetricRegistry registry = new NoopMetricRegistry(); -+ private final Gauge gauge = () -> ""; -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - -- @Test -- void registeringAHistogramTriggersNoNotification() { -- assertThat(registry.register(METRIC_THING, histogram)).isEqualTo(histogram); -+ @BeforeEach -+ void setUp() { -+ registry.addListener(listener); -+ } - -- verify(listener, never()).onHistogramAdded(METRIC_THING, histogram); -- } -+ @Test -+ void registeringAGaugeTriggersNoNotification() { -+ assertThat(registry.register(METRIC_THING, gauge)).isEqualTo(gauge); - -- @Test -- void accessingAHistogramRegistersAndReusesIt() { -- final Histogram histogram1 = registry.histogram(METRIC_THING); -- final Histogram histogram2 = registry.histogram(METRIC_THING); -+ verify(listener, never()).onGaugeAdded(METRIC_THING, gauge); -+ } - -- assertThat(histogram1).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); -- assertThat(histogram2).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); -- assertThat(histogram1).isSameAs(histogram2); -+ @Test -+ void removingAGaugeTriggersNoNotification() { -+ registry.register(METRIC_THING, gauge); - -- verify(listener, never()).onHistogramAdded(METRIC_THING, histogram1); -- } -+ assertThat(registry.remove(METRIC_THING)).isFalse(); - -- @Test -- void accessingACustomHistogramRegistersAndReusesIt() { -- final MetricRegistry.MetricSupplier supplier = () -> histogram; -- final Histogram histogram1 = registry.histogram(METRIC_THING, supplier); -- final Histogram histogram2 = registry.histogram(METRIC_THING, supplier); -+ verify(listener, never()).onGaugeRemoved(METRIC_THING); -+ } - -- assertThat(histogram1).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); -- assertThat(histogram2).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); -- assertThat(histogram1).isSameAs(histogram2); -+ @Test -+ void registeringACounterTriggersNoNotification() { -+ assertThat(registry.register(METRIC_THING, counter)).isEqualTo(counter); - -- verify(listener, never()).onHistogramAdded(METRIC_THING, histogram1); -- } -+ verify(listener, never()).onCounterAdded(METRIC_THING, counter); -+ } - -- @Test -- void removingAHistogramTriggersNoNotification() { -- registry.register(METRIC_THING, histogram); -+ @Test -+ void accessingACounterRegistersAndReusesTheCounter() { -+ final Counter counter1 = registry.counter(METRIC_THING); -+ final Counter counter2 = registry.counter(METRIC_THING); - -- assertThat(registry.remove(METRIC_THING)).isFalse(); -+ assertThat(counter1).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); -+ assertThat(counter2).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); -+ assertThat(counter1).isSameAs(counter2); - -- verify(listener, never()).onHistogramRemoved(METRIC_THING); -- } -+ verify(listener, never()).onCounterAdded(METRIC_THING, counter1); -+ } - -- @Test -- void registeringAMeterTriggersNoNotification() { -- assertThat(registry.register(METRIC_THING, meter)).isEqualTo(meter); -+ @Test -+ void accessingACustomCounterRegistersAndReusesTheCounter() { -+ final MetricRegistry.MetricSupplier supplier = () -> counter; -+ final Counter counter1 = registry.counter(METRIC_THING, supplier); -+ final Counter counter2 = registry.counter(METRIC_THING, supplier); - -- verify(listener, never()).onMeterAdded(METRIC_THING, meter); -- } -+ assertThat(counter1).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); -+ assertThat(counter2).isExactlyInstanceOf(NoopMetricRegistry.NoopCounter.class); -+ assertThat(counter1).isSameAs(counter2); - -- @Test -- void accessingAMeterRegistersAndReusesIt() { -- final Meter meter1 = registry.meter(METRIC_THING); -- final Meter meter2 = registry.meter(METRIC_THING); -+ verify(listener, never()).onCounterAdded(METRIC_THING, counter1); -+ } - -- assertThat(meter1).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); -- assertThat(meter2).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); -- assertThat(meter1).isSameAs(meter2); -+ @Test -+ void removingACounterTriggersNoNotification() { -+ registry.register(METRIC_THING, counter); - -- verify(listener, never()).onMeterAdded(METRIC_THING, meter1); -- } -+ assertThat(registry.remove(METRIC_THING)).isFalse(); - -- @Test -- void accessingACustomMeterRegistersAndReusesIt() { -- final MetricRegistry.MetricSupplier supplier = () -> meter; -- final Meter meter1 = registry.meter(METRIC_THING, supplier); -- final Meter meter2 = registry.meter(METRIC_THING, supplier); -+ verify(listener, never()).onCounterRemoved(METRIC_THING); -+ } - -- assertThat(meter1).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); -- assertThat(meter2).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); -- assertThat(meter1).isSameAs(meter2); -+ @Test -+ void registeringAHistogramTriggersNoNotification() { -+ assertThat(registry.register(METRIC_THING, histogram)).isEqualTo(histogram); - -- verify(listener, never()).onMeterAdded(METRIC_THING, meter1); -- } -+ verify(listener, never()).onHistogramAdded(METRIC_THING, histogram); -+ } - -- @Test -- void removingAMeterTriggersNoNotification() { -- registry.register(METRIC_THING, meter); -+ @Test -+ void accessingAHistogramRegistersAndReusesIt() { -+ final Histogram histogram1 = registry.histogram(METRIC_THING); -+ final Histogram histogram2 = registry.histogram(METRIC_THING); - -- assertThat(registry.remove(METRIC_THING)).isFalse(); -+ assertThat(histogram1).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); -+ assertThat(histogram2).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); -+ assertThat(histogram1).isSameAs(histogram2); - -- verify(listener, never()).onMeterRemoved(METRIC_THING); -- } -+ verify(listener, never()).onHistogramAdded(METRIC_THING, histogram1); -+ } - -- @Test -- void registeringATimerTriggersNoNotification() { -- assertThat(registry.register(METRIC_THING, timer)).isEqualTo(timer); -+ @Test -+ void accessingACustomHistogramRegistersAndReusesIt() { -+ final MetricRegistry.MetricSupplier supplier = () -> histogram; -+ final Histogram histogram1 = registry.histogram(METRIC_THING, supplier); -+ final Histogram histogram2 = registry.histogram(METRIC_THING, supplier); - -- verify(listener, never()).onTimerAdded(METRIC_THING, timer); -- } -+ assertThat(histogram1).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); -+ assertThat(histogram2).isExactlyInstanceOf(NoopMetricRegistry.NoopHistogram.class); -+ assertThat(histogram1).isSameAs(histogram2); - -- @Test -- void accessingATimerRegistersAndReusesIt() { -- final Timer timer1 = registry.timer(METRIC_THING); -- final Timer timer2 = registry.timer(METRIC_THING); -+ verify(listener, never()).onHistogramAdded(METRIC_THING, histogram1); -+ } - -- assertThat(timer1).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); -- assertThat(timer2).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); -- assertThat(timer1).isSameAs(timer2); -+ @Test -+ void removingAHistogramTriggersNoNotification() { -+ registry.register(METRIC_THING, histogram); - -- verify(listener, never()).onTimerAdded(METRIC_THING, timer1); -- } -+ assertThat(registry.remove(METRIC_THING)).isFalse(); - -- @Test -- void accessingACustomTimerRegistersAndReusesIt() { -- final MetricRegistry.MetricSupplier supplier = () -> timer; -- final Timer timer1 = registry.timer(METRIC_THING, supplier); -- final Timer timer2 = registry.timer(METRIC_THING, supplier); -+ verify(listener, never()).onHistogramRemoved(METRIC_THING); -+ } - -- assertThat(timer1).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); -- assertThat(timer2).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); -- assertThat(timer1).isSameAs(timer2); -+ @Test -+ void registeringAMeterTriggersNoNotification() { -+ assertThat(registry.register(METRIC_THING, meter)).isEqualTo(meter); - -- verify(listener, never()).onTimerAdded(METRIC_THING, timer1); -- } -+ verify(listener, never()).onMeterAdded(METRIC_THING, meter); -+ } - -+ @Test -+ void accessingAMeterRegistersAndReusesIt() { -+ final Meter meter1 = registry.meter(METRIC_THING); -+ final Meter meter2 = registry.meter(METRIC_THING); - -- @Test -- void removingATimerTriggersNoNotification() { -- registry.register(METRIC_THING, timer); -+ assertThat(meter1).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); -+ assertThat(meter2).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); -+ assertThat(meter1).isSameAs(meter2); - -- assertThat(registry.remove(METRIC_THING)).isFalse(); -+ verify(listener, never()).onMeterAdded(METRIC_THING, meter1); -+ } - -- verify(listener, never()).onTimerRemoved(METRIC_THING); -- } -+ @Test -+ void accessingACustomMeterRegistersAndReusesIt() { -+ final MetricRegistry.MetricSupplier supplier = () -> meter; -+ final Meter meter1 = registry.meter(METRIC_THING, supplier); -+ final Meter meter2 = registry.meter(METRIC_THING, supplier); - -- @Test -- void accessingAGaugeRegistersAndReusesIt() { -- final Gauge gauge1 = registry.gauge(METRIC_THING); -- final Gauge gauge2 = registry.gauge(METRIC_THING); -+ assertThat(meter1).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); -+ assertThat(meter2).isExactlyInstanceOf(NoopMetricRegistry.NoopMeter.class); -+ assertThat(meter1).isSameAs(meter2); - -- assertThat(gauge1).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); -- assertThat(gauge2).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); -- assertThat(gauge1).isSameAs(gauge2); -+ verify(listener, never()).onMeterAdded(METRIC_THING, meter1); -+ } - -- verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); -- } -+ @Test -+ void removingAMeterTriggersNoNotification() { -+ registry.register(METRIC_THING, meter); - -- @Test -- @SuppressWarnings("rawtypes") -- void accessingACustomGaugeRegistersAndReusesIt() { -- final MetricRegistry.MetricSupplier> supplier = () -> gauge; -- final Gauge gauge1 = registry.gauge(METRIC_THING, supplier); -- final Gauge gauge2 = registry.gauge(METRIC_THING, supplier); -+ assertThat(registry.remove(METRIC_THING)).isFalse(); - -- assertThat(gauge1).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); -- assertThat(gauge2).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); -- assertThat(gauge1).isSameAs(gauge2); -+ verify(listener, never()).onMeterRemoved(METRIC_THING); -+ } - -- verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); -- } -+ @Test -+ void registeringATimerTriggersNoNotification() { -+ assertThat(registry.register(METRIC_THING, timer)).isEqualTo(timer); - -+ verify(listener, never()).onTimerAdded(METRIC_THING, timer); -+ } - -- @Test -- void addingAListenerWithExistingMetricsDoesNotNotify() { -- registry.register(MetricName.build("gauge"), gauge); -- registry.register(MetricName.build("counter"), counter); -- registry.register(MetricName.build("histogram"), histogram); -- registry.register(MetricName.build("meter"), meter); -- registry.register(MetricName.build("timer"), timer); -+ @Test -+ void accessingATimerRegistersAndReusesIt() { -+ final Timer timer1 = registry.timer(METRIC_THING); -+ final Timer timer2 = registry.timer(METRIC_THING); - -- final MetricRegistryListener other = mock(MetricRegistryListener.class); -- registry.addListener(other); -+ assertThat(timer1).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); -+ assertThat(timer2).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); -+ assertThat(timer1).isSameAs(timer2); - -- verify(other, never()).onGaugeAdded(MetricName.build("gauge"), gauge); -- verify(other, never()).onCounterAdded(MetricName.build("counter"), counter); -- verify(other, never()).onHistogramAdded(MetricName.build("histogram"), histogram); -- verify(other, never()).onMeterAdded(MetricName.build("meter"), meter); -- verify(other, never()).onTimerAdded(MetricName.build("timer"), timer); -- } -+ verify(listener, never()).onTimerAdded(METRIC_THING, timer1); -+ } - -- @Test -- void aRemovedListenerDoesNotReceiveUpdates() { -- registry.register(MetricName.build("gauge"), gauge); -- registry.removeListener(listener); -- registry.register(MetricName.build("gauge2"), gauge); -+ @Test -+ void accessingACustomTimerRegistersAndReusesIt() { -+ final MetricRegistry.MetricSupplier supplier = () -> timer; -+ final Timer timer1 = registry.timer(METRIC_THING, supplier); -+ final Timer timer2 = registry.timer(METRIC_THING, supplier); - -- verify(listener, never()).onGaugeAdded(MetricName.build("gauge2"), gauge); -- } -+ assertThat(timer1).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); -+ assertThat(timer2).isExactlyInstanceOf(NoopMetricRegistry.NoopTimer.class); -+ assertThat(timer1).isSameAs(timer2); - -- @Test -- void hasAMapOfRegisteredGauges() { -- registry.register(MetricName.build("gauge"), gauge); -+ verify(listener, never()).onTimerAdded(METRIC_THING, timer1); -+ } - -- assertThat(registry.getGauges()).isEmpty(); -- } -+ @Test -+ void removingATimerTriggersNoNotification() { -+ registry.register(METRIC_THING, timer); - -- @Test -- void hasAMapOfRegisteredCounters() { -- registry.register(MetricName.build("counter"), counter); -+ assertThat(registry.remove(METRIC_THING)).isFalse(); - -- assertThat(registry.getCounters()).isEmpty(); -- } -- -- @Test -- void hasAMapOfRegisteredHistograms() { -- registry.register(MetricName.build("histogram"), histogram); -- -- assertThat(registry.getHistograms()).isEmpty(); -- } -- -- @Test -- void hasAMapOfRegisteredMeters() { -- registry.register(MetricName.build("meter"), meter); -- -- assertThat(registry.getMeters()).isEmpty(); -- } -+ verify(listener, never()).onTimerRemoved(METRIC_THING); -+ } - -- @Test -- void hasAMapOfRegisteredTimers() { -- registry.register(MetricName.build("timer"), timer); -+ @Test -+ void accessingAGaugeRegistersAndReusesIt() { -+ final Gauge gauge1 = registry.gauge(METRIC_THING); -+ final Gauge gauge2 = registry.gauge(METRIC_THING); - -- assertThat(registry.getTimers()).isEmpty(); -- } -+ assertThat(gauge1).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); -+ assertThat(gauge2).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); -+ assertThat(gauge1).isSameAs(gauge2); - -- @Test -- void hasASetOfRegisteredMetricNames() { -- registry.register(MetricName.build("gauge"), gauge); -- registry.register(MetricName.build("counter"), counter); -- registry.register(MetricName.build("histogram"), histogram); -- registry.register(MetricName.build("meter"), meter); -- registry.register(MetricName.build("timer"), timer); -- -- assertThat(registry.getNames()).isEmpty(); -- } -- -- @Test -- void doesNotRegisterMultipleMetrics() { -- final MetricSet metrics = () -> { -- final Map m = new HashMap<>(); -- m.put(MetricName.build("gauge"), gauge); -- m.put(MetricName.build("counter"), counter); -- return m; -+ verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); -+ } -+ -+ @SuppressWarnings("rawtypes") -+ @Test -+ void accessingACustomGaugeRegistersAndReusesIt() { -+ final MetricRegistry.MetricSupplier> supplier = () -> gauge; -+ final Gauge gauge1 = registry.gauge(METRIC_THING, supplier); -+ final Gauge gauge2 = registry.gauge(METRIC_THING, supplier); -+ -+ assertThat(gauge1).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); -+ assertThat(gauge2).isExactlyInstanceOf(NoopMetricRegistry.NoopGauge.class); -+ assertThat(gauge1).isSameAs(gauge2); -+ -+ verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); -+ } -+ -+ @Test -+ void addingAListenerWithExistingMetricsDoesNotNotify() { -+ registry.register(MetricName.build("gauge"), gauge); -+ registry.register(MetricName.build("counter"), counter); -+ registry.register(MetricName.build("histogram"), histogram); -+ registry.register(MetricName.build("meter"), meter); -+ registry.register(MetricName.build("timer"), timer); -+ -+ final MetricRegistryListener other = mock(); -+ registry.addListener(other); -+ -+ verify(other, never()).onGaugeAdded(MetricName.build("gauge"), gauge); -+ verify(other, never()).onCounterAdded(MetricName.build("counter"), counter); -+ verify(other, never()).onHistogramAdded(MetricName.build("histogram"), histogram); -+ verify(other, never()).onMeterAdded(MetricName.build("meter"), meter); -+ verify(other, never()).onTimerAdded(MetricName.build("timer"), timer); -+ } -+ -+ @Test -+ void aRemovedListenerDoesNotReceiveUpdates() { -+ registry.register(MetricName.build("gauge"), gauge); -+ registry.removeListener(listener); -+ registry.register(MetricName.build("gauge2"), gauge); -+ -+ verify(listener, never()).onGaugeAdded(MetricName.build("gauge2"), gauge); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredGauges() { -+ registry.register(MetricName.build("gauge"), gauge); -+ -+ assertThat(registry.getGauges()).isEmpty(); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredCounters() { -+ registry.register(MetricName.build("counter"), counter); -+ -+ assertThat(registry.getCounters()).isEmpty(); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredHistograms() { -+ registry.register(MetricName.build("histogram"), histogram); -+ -+ assertThat(registry.getHistograms()).isEmpty(); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredMeters() { -+ registry.register(MetricName.build("meter"), meter); -+ -+ assertThat(registry.getMeters()).isEmpty(); -+ } -+ -+ @Test -+ void hasAMapOfRegisteredTimers() { -+ registry.register(MetricName.build("timer"), timer); -+ -+ assertThat(registry.getTimers()).isEmpty(); -+ } -+ -+ @Test -+ void hasASetOfRegisteredMetricNames() { -+ registry.register(MetricName.build("gauge"), gauge); -+ registry.register(MetricName.build("counter"), counter); -+ registry.register(MetricName.build("histogram"), histogram); -+ registry.register(MetricName.build("meter"), meter); -+ registry.register(MetricName.build("timer"), timer); -+ -+ assertThat(registry.getNames()).isEmpty(); -+ } -+ -+ @Test -+ void doesNotRegisterMultipleMetrics() { -+ final MetricSet metrics = -+ () -> { -+ final Map m = new HashMap<>(); -+ m.put(MetricName.build("gauge"), gauge); -+ m.put(MetricName.build("counter"), counter); -+ return m; - }; - -- registry.registerAll(metrics); -+ registry.registerAll(metrics); - -- assertThat(registry.getNames()).isEmpty(); -- } -+ assertThat(registry.getNames()).isEmpty(); -+ } - -- @Test -- void doesNotRegisterMultipleMetricsWithAPrefix() { -- final MetricSet metrics = () -> { -- final Map m = new HashMap<>(); -- m.put(MetricName.build("gauge"), gauge); -- m.put(MetricName.build("counter"), counter); -- return m; -+ @Test -+ void doesNotRegisterMultipleMetricsWithAPrefix() { -+ final MetricSet metrics = -+ () -> { -+ final Map m = new HashMap<>(); -+ m.put(MetricName.build("gauge"), gauge); -+ m.put(MetricName.build("counter"), counter); -+ return m; - }; - -- registry.register(MetricName.build("my"), metrics); -+ registry.register(MetricName.build("my"), metrics); - -- assertThat(registry.getNames()).isEmpty(); -- } -+ assertThat(registry.getNames()).isEmpty(); -+ } - -- @Test -- void doesNotRegisterRecursiveMetricSets() { -- final MetricSet inner = () -> { -- final Map m = new HashMap<>(); -- m.put(MetricName.build("gauge"), gauge); -- return m; -+ @Test -+ void doesNotRegisterRecursiveMetricSets() { -+ final MetricSet inner = -+ () -> { -+ final Map m = new HashMap<>(); -+ m.put(MetricName.build("gauge"), gauge); -+ return m; - }; - -- final MetricSet outer = () -> { -- final Map m = new HashMap<>(); -- m.put(MetricName.build("inner"), inner); -- m.put(MetricName.build("counter"), counter); -- return m; -+ final MetricSet outer = -+ () -> { -+ final Map m = new HashMap<>(); -+ m.put(MetricName.build("inner"), inner); -+ m.put(MetricName.build("counter"), counter); -+ return m; - }; - -- registry.register(MetricName.build("my"), outer); -- -- assertThat(registry.getNames()).isEmpty(); -- } -- -- @Test -- void doesNotRegisterMetricsFromAnotherRegistry() { -- MetricRegistry other = new MetricRegistry(); -- other.register(MetricName.build("gauge"), gauge); -- registry.register(MetricName.build("nested"), other); -- assertThat(registry.getNames()).isEmpty(); -- } -- -- @Test -- void removesMetricsMatchingAFilter() { -- registry.timer("timer-1"); -- registry.timer("timer-2"); -- registry.histogram("histogram-1"); -+ registry.register(MetricName.build("my"), outer); - -- assertThat(registry.getNames()).isEmpty(); -+ assertThat(registry.getNames()).isEmpty(); -+ } - -- registry.removeMatching((name, metric) -> name.getKey().endsWith("1")); -+ @Test -+ void doesNotRegisterMetricsFromAnotherRegistry() { -+ MetricRegistry other = new MetricRegistry(); -+ other.register(MetricName.build("gauge"), gauge); -+ registry.register(MetricName.build("nested"), other); -+ assertThat(registry.getNames()).isEmpty(); -+ } - -- assertThat(registry.getNames()).isEmpty(); -+ @Test -+ void removesMetricsMatchingAFilter() { -+ registry.timer("timer-1"); -+ registry.timer("timer-2"); -+ registry.histogram("histogram-1"); -+ -+ assertThat(registry.getNames()).isEmpty(); - -- verify(listener, never()).onTimerRemoved(MetricName.build("timer-1")); -- verify(listener, never()).onHistogramRemoved(MetricName.build("histogram-1")); -- } -+ registry.removeMatching((name, metric) -> name.getKey().endsWith("1")); -+ -+ assertThat(registry.getNames()).isEmpty(); - -- @Test -- void addingChildMetricAfterRegister() { -- MetricRegistry parent = new NoopMetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -+ verify(listener, never()).onTimerRemoved(MetricName.build("timer-1")); -+ verify(listener, never()).onHistogramRemoved(MetricName.build("histogram-1")); -+ } - -- child.counter(MetricName.build("test-1")); -- parent.register(MetricName.build("child"), child); -- child.counter(MetricName.build("test-2")); -+ @Test -+ void addingChildMetricAfterRegister() { -+ MetricRegistry parent = new NoopMetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); - -- assertThat(parent.getMetrics()).isEmpty(); -- } -- -- @Test -- void addingMultipleChildMetricsAfterRegister() { -- MetricRegistry parent = new NoopMetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- -- child.counter(MetricName.build("test-1")); -- child.counter(MetricName.build("test-2")); -- parent.register(MetricName.build("child"), child); -- child.counter(MetricName.build("test-3")); -- child.counter(MetricName.build("test-4")); -- -- assertThat(parent.getMetrics()).isEmpty(); -- } -- -- @Test -- void addingDeepChildMetricsAfterRegister() { -- MetricRegistry parent = new NoopMetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- MetricRegistry deepChild = new MetricRegistry(); -- -- deepChild.counter(MetricName.build("test-1")); -- child.register(MetricName.build("deep-child"), deepChild); -- deepChild.counter(MetricName.build("test-2")); -- -- child.counter(MetricName.build("test-3")); -- parent.register(MetricName.build("child"), child); -- child.counter(MetricName.build("test-4")); -- -- deepChild.counter("test-5"); -- -- assertThat(parent.getMetrics()).isEmpty(); -- assertThat(deepChild.getMetrics()).hasSize(3); -- assertThat(child.getMetrics()).hasSize(5); -- } -- -- @Test -- void removingChildMetricAfterRegister() { -- MetricRegistry parent = new NoopMetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- -- child.counter(MetricName.build("test-1")); -- parent.register(MetricName.build("child"), child); -- child.counter(MetricName.build("test-2")); -- -- child.remove(MetricName.build("test-1")); -- -- assertThat(parent.getMetrics()).isEmpty(); -- assertThat(child.getMetrics()).doesNotContainKey(MetricName.build("test-1")); -- } -- -- @Test -- void removingMultipleChildMetricsAfterRegister() { -- MetricRegistry parent = new NoopMetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- -- child.counter(MetricName.build("test-1")); -- child.counter(MetricName.build("test-2")); -- parent.register(MetricName.build("child"), child); -- child.counter(MetricName.build("test-3")); -- child.counter(MetricName.build("test-4")); -- -- child.remove(MetricName.build("test-1")); -- child.remove(MetricName.build("test-3")); -- -- assertThat(parent.getMetrics()).isEmpty(); -- assertThat(child.getMetrics()).doesNotContainKeys(MetricName.build("test-1"), MetricName.build("test-3")); -- } -- -- @Test -- void removingDeepChildMetricsAfterRegister() { -- MetricRegistry parent = new NoopMetricRegistry(); -- MetricRegistry child = new MetricRegistry(); -- MetricRegistry deepChild = new MetricRegistry(); -- -- deepChild.counter(MetricName.build("test-1")); -- child.register(MetricName.build("deep-child"), deepChild); -- deepChild.counter(MetricName.build("test-2")); -+ child.counter(MetricName.build("test-1")); -+ parent.register(MetricName.build("child"), child); -+ child.counter(MetricName.build("test-2")); - -- child.counter(MetricName.build("test-3")); -- parent.register(MetricName.build("child"), child); -- child.counter(MetricName.build("test-4")); -- -- deepChild.remove(MetricName.build("test-2")); -- -- Set childMetrics = child.getMetrics().keySet(); -- Set deepChildMetrics = deepChild.getMetrics().keySet(); -- -- assertThat(parent.getMetrics()).isEmpty(); -- assertThat(deepChildMetrics).hasSize(1); -- assertThat(childMetrics).hasSize(3); -- } -- -- @Test -- void registerNullMetric() { -- MetricRegistry registry = new NoopMetricRegistry(); -- assertThatNullPointerException() -- .isThrownBy(() -> registry.register(MetricName.build("any_name"), null)) -- .withMessage("metric == null"); -- } -+ assertThat(parent.getMetrics()).isEmpty(); -+ } -+ -+ @Test -+ void addingMultipleChildMetricsAfterRegister() { -+ MetricRegistry parent = new NoopMetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ -+ child.counter(MetricName.build("test-1")); -+ child.counter(MetricName.build("test-2")); -+ parent.register(MetricName.build("child"), child); -+ child.counter(MetricName.build("test-3")); -+ child.counter(MetricName.build("test-4")); -+ -+ assertThat(parent.getMetrics()).isEmpty(); -+ } -+ -+ @Test -+ void addingDeepChildMetricsAfterRegister() { -+ MetricRegistry parent = new NoopMetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ MetricRegistry deepChild = new MetricRegistry(); -+ -+ deepChild.counter(MetricName.build("test-1")); -+ child.register(MetricName.build("deep-child"), deepChild); -+ deepChild.counter(MetricName.build("test-2")); -+ -+ child.counter(MetricName.build("test-3")); -+ parent.register(MetricName.build("child"), child); -+ child.counter(MetricName.build("test-4")); -+ -+ deepChild.counter("test-5"); -+ -+ assertThat(parent.getMetrics()).isEmpty(); -+ assertThat(deepChild.getMetrics()).hasSize(3); -+ assertThat(child.getMetrics()).hasSize(5); -+ } -+ -+ @Test -+ void removingChildMetricAfterRegister() { -+ MetricRegistry parent = new NoopMetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ -+ child.counter(MetricName.build("test-1")); -+ parent.register(MetricName.build("child"), child); -+ child.counter(MetricName.build("test-2")); -+ -+ child.remove(MetricName.build("test-1")); -+ -+ assertThat(parent.getMetrics()).isEmpty(); -+ assertThat(child.getMetrics()).doesNotContainKey(MetricName.build("test-1")); -+ } -+ -+ @Test -+ void removingMultipleChildMetricsAfterRegister() { -+ MetricRegistry parent = new NoopMetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ -+ child.counter(MetricName.build("test-1")); -+ child.counter(MetricName.build("test-2")); -+ parent.register(MetricName.build("child"), child); -+ child.counter(MetricName.build("test-3")); -+ child.counter(MetricName.build("test-4")); -+ -+ child.remove(MetricName.build("test-1")); -+ child.remove(MetricName.build("test-3")); -+ -+ assertThat(parent.getMetrics()).isEmpty(); -+ assertThat(child.getMetrics()) -+ .doesNotContainKeys(MetricName.build("test-1"), MetricName.build("test-3")); -+ } -+ -+ @Test -+ void removingDeepChildMetricsAfterRegister() { -+ MetricRegistry parent = new NoopMetricRegistry(); -+ MetricRegistry child = new MetricRegistry(); -+ MetricRegistry deepChild = new MetricRegistry(); -+ -+ deepChild.counter(MetricName.build("test-1")); -+ child.register(MetricName.build("deep-child"), deepChild); -+ deepChild.counter(MetricName.build("test-2")); -+ -+ child.counter(MetricName.build("test-3")); -+ parent.register(MetricName.build("child"), child); -+ child.counter(MetricName.build("test-4")); -+ -+ deepChild.remove(MetricName.build("test-2")); -+ -+ Set childMetrics = child.getMetrics().keySet(); -+ Set deepChildMetrics = deepChild.getMetrics().keySet(); -+ -+ assertThat(parent.getMetrics()).isEmpty(); -+ assertThat(deepChildMetrics).hasSize(1); -+ assertThat(childMetrics).hasSize(3); -+ } -+ -+ @Test -+ void registerNullMetric() { -+ MetricRegistry registry = new NoopMetricRegistry(); -+ assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)) -+ .isInstanceOf(NullPointerException.class) -+ .hasMessage("metric == null"); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java -@@ -1,67 +1,66 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; - --class RatioGaugeTest { -- @Test -- void ratiosAreHumanReadable() { -- final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); -+import org.junit.jupiter.api.Test; -+ -+final class RatioGaugeTest { -+ @Test -+ void ratiosAreHumanReadable() { -+ final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); - -- assertThat(ratio.toString()) -- .isEqualTo("100.0:200.0"); -- } -+ assertThat(ratio).hasToString("100.0:200.0"); -+ } - -- @Test -- void calculatesTheRatioOfTheNumeratorToTheDenominator() { -- final RatioGauge regular = new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return RatioGauge.Ratio.of(2, 4); -- } -+ @Test -+ void calculatesTheRatioOfTheNumeratorToTheDenominator() { -+ final RatioGauge regular = -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return RatioGauge.Ratio.of(2, 4); -+ } - }; - -- assertThat(regular.getValue()) -- .isEqualTo(0.5); -- } -+ assertThat(regular.getValue()).isEqualTo(0.5); -+ } - -- @Test -- void handlesDivideByZeroIssues() { -- final RatioGauge divByZero = new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(100, 0); -- } -+ @Test -+ void handlesDivideByZeroIssues() { -+ final RatioGauge divByZero = -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(100, 0); -+ } - }; - -- assertThat(divByZero.getValue()) -- .isNaN(); -- } -+ assertThat(divByZero.getValue()).isNaN(); -+ } - -- @Test -- void handlesInfiniteDenominators() { -- final RatioGauge infinite = new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(10, Double.POSITIVE_INFINITY); -- } -+ @Test -+ void handlesInfiniteDenominators() { -+ final RatioGauge infinite = -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(10, Double.POSITIVE_INFINITY); -+ } - }; - -- assertThat(infinite.getValue()) -- .isNaN(); -- } -+ assertThat(infinite.getValue()).isNaN(); -+ } - -- @Test -- void handlesNaNDenominators() { -- final RatioGauge nan = new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(10, Double.NaN); -- } -+ @Test -+ void handlesNaNDenominators() { -+ final RatioGauge nan = -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(10, Double.NaN); -+ } - }; - -- assertThat(nan.getValue()) -- .isNaN(); -- } -+ assertThat(nan.getValue()).isNaN(); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java -@@ -1,8 +1,15 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; -+import static org.assertj.core.api.Assertions.fail; -+import static org.junit.jupiter.api.Assertions.assertEquals; -+import static org.mockito.Mockito.any; -+import static org.mockito.Mockito.eq; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.spy; -+import static org.mockito.Mockito.times; -+import static org.mockito.Mockito.verify; - - import java.util.SortedMap; - import java.util.TreeMap; -@@ -13,279 +20,350 @@ import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.TimeoutException; - import java.util.concurrent.atomic.AtomicInteger; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - --import static org.junit.jupiter.api.Assertions.assertEquals; --import static org.junit.jupiter.api.Assertions.assertFalse; --import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.junit.jupiter.api.Assertions.assertTrue; --import static org.junit.jupiter.api.Assertions.fail; --import static org.mockito.Mockito.any; --import static org.mockito.Mockito.eq; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.spy; --import static org.mockito.Mockito.times; --import static org.mockito.Mockito.verify; -- --class ScheduledReporterTest { -- private final Gauge gauge = () -> ""; -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -- -- private final ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); -- private final ScheduledExecutorService customExecutor = Executors.newSingleThreadScheduledExecutor(); -- private final ScheduledExecutorService externalExecutor = Executors.newSingleThreadScheduledExecutor(); -- -- private final MetricRegistry registry = new MetricRegistry(); -- private final ScheduledReporter reporter = spy( -- new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS) -- ); -- private final ScheduledReporter reporterWithNullExecutor = spy( -- new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, null) -- ); -- private final ScheduledReporter reporterWithCustomMockExecutor = new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, mockExecutor); -- private final ScheduledReporter reporterWithCustomExecutor = new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, customExecutor); -- private final DummyReporter reporterWithExternallyManagedExecutor = new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, externalExecutor, false); -- private final ScheduledReporter[] reporters = new ScheduledReporter[]{reporter, reporterWithCustomExecutor, reporterWithExternallyManagedExecutor}; -- -- @BeforeEach -- void setUp() throws Exception { -- registry.register(MetricRegistry.name("gauge"), gauge); -- registry.register(MetricRegistry.name("counter"), counter); -- registry.register(MetricRegistry.name("histogram"), histogram); -- registry.register(MetricRegistry.name("meter"), meter); -- registry.register(MetricRegistry.name("timer"), timer); -- } -- -- @AfterEach -- void tearDown() throws Exception { -- customExecutor.shutdown(); -- externalExecutor.shutdown(); -- reporter.stop(); -- reporterWithNullExecutor.stop(); -- } -- -- @Test -- void createWithNullMetricRegistry() { -- ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); -- DummyReporter r = null; -- try { -- r = new DummyReporter(null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); -- fail("NullPointerException must be thrown !!!"); -- } catch (NullPointerException e) { -- assertEquals("registry == null", e.getMessage()); -- } finally { -- if (r != null) { -- r.close(); -- } -- } -+final class ScheduledReporterTest { -+ private final Gauge gauge = () -> ""; -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); -+ -+ private final ScheduledExecutorService mockExecutor = mock(); -+ private final ScheduledExecutorService customExecutor = -+ Executors.newSingleThreadScheduledExecutor(); -+ private final ScheduledExecutorService externalExecutor = -+ Executors.newSingleThreadScheduledExecutor(); -+ -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final ScheduledReporter reporter = -+ spy( -+ new DummyReporter( -+ registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS)); -+ private final ScheduledReporter reporterWithNullExecutor = -+ spy( -+ new DummyReporter( -+ registry, -+ "example", -+ MetricFilter.ALL, -+ TimeUnit.SECONDS, -+ TimeUnit.MILLISECONDS, -+ null)); -+ private final ScheduledReporter reporterWithCustomMockExecutor = -+ new DummyReporter( -+ registry, -+ "example", -+ MetricFilter.ALL, -+ TimeUnit.SECONDS, -+ TimeUnit.MILLISECONDS, -+ mockExecutor); -+ private final ScheduledReporter reporterWithCustomExecutor = -+ new DummyReporter( -+ registry, -+ "example", -+ MetricFilter.ALL, -+ TimeUnit.SECONDS, -+ TimeUnit.MILLISECONDS, -+ customExecutor); -+ private final DummyReporter reporterWithExternallyManagedExecutor = -+ new DummyReporter( -+ registry, -+ "example", -+ MetricFilter.ALL, -+ TimeUnit.SECONDS, -+ TimeUnit.MILLISECONDS, -+ externalExecutor, -+ false); -+ private final ScheduledReporter[] reporters = -+ new ScheduledReporter[] { -+ reporter, reporterWithCustomExecutor, reporterWithExternallyManagedExecutor -+ }; -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ registry.register(MetricRegistry.name("gauge"), gauge); -+ registry.register(MetricRegistry.name("counter"), counter); -+ registry.register(MetricRegistry.name("histogram"), histogram); -+ registry.register(MetricRegistry.name("meter"), meter); -+ registry.register(MetricRegistry.name("timer"), timer); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ customExecutor.shutdown(); -+ externalExecutor.shutdown(); -+ reporter.stop(); -+ reporterWithNullExecutor.stop(); -+ } -+ -+ @Test -+ void createWithNullMetricRegistry() { -+ ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); -+ DummyReporter r = null; -+ try { -+ r = -+ new DummyReporter( -+ null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); -+ fail("NullPointerException must be thrown !!!"); -+ } catch (NullPointerException e) { -+ assertEquals("registry == null", e.getMessage()); -+ } finally { -+ if (r != null) { -+ r.close(); -+ } - } -- -- @Test -- void pollsPeriodically() throws Exception { -- CountDownLatch latch = new CountDownLatch(2); -- reporter.start(100, 100, TimeUnit.MILLISECONDS, () -> { -- if (latch.getCount() > 0) { -- reporter.report(); -- latch.countDown(); -- } -+ } -+ -+ @Test -+ void pollsPeriodically() throws Exception { -+ CountDownLatch latch = new CountDownLatch(2); -+ reporter.start( -+ 100, -+ 100, -+ TimeUnit.MILLISECONDS, -+ () -> { -+ if (latch.getCount() > 0) { -+ reporter.report(); -+ latch.countDown(); -+ } - }); -- latch.await(5, TimeUnit.SECONDS); -- -- verify(reporter, times(2)).report( -- map(MetricName.build("gauge"), gauge), -- map(MetricName.build("counter"), counter), -- map(MetricName.build("histogram"), histogram), -- map(MetricName.build("meter"), meter), -- map(MetricName.build("timer"), timer) -- ); -- } -- -- @Test -- void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { -- reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); -- -- verify(mockExecutor, times(1)).scheduleWithFixedDelay( -- any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS) -- ); -- } -- -- @Test -- void shouldStartWithSpecifiedInitialDelay() throws Exception { -- reporterWithCustomMockExecutor.start(350, 100, TimeUnit.MILLISECONDS); -- -- verify(mockExecutor).scheduleWithFixedDelay( -- any(Runnable.class), eq(350L), eq(100L), eq(TimeUnit.MILLISECONDS) -- ); -- } -- -- @Test -- void shouldAutoCreateExecutorWhenItNull() throws Exception { -- CountDownLatch latch = new CountDownLatch(2); -- reporterWithNullExecutor.start(100, 100, TimeUnit.MILLISECONDS, () -> { -- if (latch.getCount() > 0) { -- reporterWithNullExecutor.report(); -- latch.countDown(); -- } -+ latch.await(5, TimeUnit.SECONDS); -+ -+ verify(reporter, times(2)) -+ .report( -+ map(MetricName.build("gauge"), gauge), -+ map(MetricName.build("counter"), counter), -+ map(MetricName.build("histogram"), histogram), -+ map(MetricName.build("meter"), meter), -+ map(MetricName.build("timer"), timer)); -+ } -+ -+ @Test -+ void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { -+ reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); -+ -+ verify(mockExecutor) -+ .scheduleWithFixedDelay(any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS)); -+ } -+ -+ @Test -+ void shouldStartWithSpecifiedInitialDelay() throws Exception { -+ reporterWithCustomMockExecutor.start(350, 100, TimeUnit.MILLISECONDS); -+ -+ verify(mockExecutor) -+ .scheduleWithFixedDelay(any(Runnable.class), eq(350L), eq(100L), eq(TimeUnit.MILLISECONDS)); -+ } -+ -+ @Test -+ void shouldAutoCreateExecutorWhenItNull() throws Exception { -+ CountDownLatch latch = new CountDownLatch(2); -+ reporterWithNullExecutor.start( -+ 100, -+ 100, -+ TimeUnit.MILLISECONDS, -+ () -> { -+ if (latch.getCount() > 0) { -+ reporterWithNullExecutor.report(); -+ latch.countDown(); -+ } - }); -- latch.await(5, TimeUnit.SECONDS); -- verify(reporterWithNullExecutor, times(2)).report( -- map(MetricName.build("gauge"), gauge), -- map(MetricName.build("counter"), counter), -- map(MetricName.build("histogram"), histogram), -- map(MetricName.build("meter"), meter), -- map(MetricName.build("timer"), timer) -- ); -+ latch.await(5, TimeUnit.SECONDS); -+ verify(reporterWithNullExecutor, times(2)) -+ .report( -+ map(MetricName.build("gauge"), gauge), -+ map(MetricName.build("counter"), counter), -+ map(MetricName.build("histogram"), histogram), -+ map(MetricName.build("meter"), meter), -+ map(MetricName.build("timer"), timer)); -+ } -+ -+ @Test -+ void shouldDisallowToStartReportingMultiple() throws Exception { -+ assertThatThrownBy( -+ () -> { -+ reporter.start(200, TimeUnit.MILLISECONDS); -+ reporter.start(200, TimeUnit.MILLISECONDS); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception { -+ assertThatThrownBy( -+ () -> { -+ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -+ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void shouldDisallowToStartReportingMultipleTimesOnExternallyManagedExecutor() throws Exception { -+ assertThatThrownBy( -+ () -> { -+ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -+ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void shouldNotFailOnStopIfReporterWasNotStared() { -+ for (ScheduledReporter reporter : reporters) { -+ reporter.stop(); - } -- -- @Test -- void shouldDisallowToStartReportingMultiple() throws Exception { -- assertThrows(IllegalArgumentException.class, () -> { -- reporter.start(200, TimeUnit.MILLISECONDS); -- reporter.start(200, TimeUnit.MILLISECONDS); -- }); -+ } -+ -+ @Test -+ void shouldNotFailWhenStoppingMultipleTimes() { -+ for (ScheduledReporter reporter : reporters) { -+ reporter.start(200, TimeUnit.MILLISECONDS); -+ reporter.stop(); -+ reporter.stop(); -+ reporter.stop(); - } -- -- @Test -- void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception { -- assertThrows(IllegalArgumentException.class, () -> { -- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -+ } -+ -+ @Test -+ void shouldShutdownExecutorOnStopByDefault() { -+ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -+ reporterWithCustomExecutor.stop(); -+ assertThat(customExecutor.isTerminated()).isTrue(); -+ } -+ -+ @Test -+ void shouldNotShutdownExternallyManagedExecutorOnStop() { -+ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -+ reporterWithExternallyManagedExecutor.stop(); -+ assertThat(mockExecutor.isTerminated()).isFalse(); -+ assertThat(mockExecutor.isShutdown()).isFalse(); -+ } -+ -+ @Test -+ void shouldCancelScheduledFutureWhenStoppingWithExternallyManagedExecutor() -+ throws InterruptedException, ExecutionException, TimeoutException { -+ // configure very frequency rate of execution -+ reporterWithExternallyManagedExecutor.start(1, TimeUnit.MILLISECONDS); -+ reporterWithExternallyManagedExecutor.stop(); -+ Thread.sleep(100); -+ -+ // executionCount should not increase when scheduled future is canceled properly -+ int executionCount = reporterWithExternallyManagedExecutor.executionCount.get(); -+ Thread.sleep(500); -+ assertEquals(executionCount, reporterWithExternallyManagedExecutor.executionCount.get()); -+ } -+ -+ @Test -+ void shouldConvertDurationToMillisecondsPrecisely() { -+ assertEquals(2.0E-5, reporter.convertDuration(20), 0.0); -+ } -+ -+ @Test -+ void shouldReportMetricsOnShutdown() throws Exception { -+ CountDownLatch latch = new CountDownLatch(1); -+ reporterWithNullExecutor.start( -+ 0, -+ 10, -+ TimeUnit.SECONDS, -+ () -> { -+ if (latch.getCount() > 0) { -+ reporterWithNullExecutor.report(); -+ latch.countDown(); -+ } - }); -- } -- -- @Test -- void shouldDisallowToStartReportingMultipleTimesOnExternallyManagedExecutor() throws Exception { -- assertThrows(IllegalArgumentException.class, () -> { -- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -+ latch.await(5, TimeUnit.SECONDS); -+ reporterWithNullExecutor.stop(); -+ -+ verify(reporterWithNullExecutor, times(2)) -+ .report( -+ map(MetricName.build("gauge"), gauge), -+ map(MetricName.build("counter"), counter), -+ map(MetricName.build("histogram"), histogram), -+ map(MetricName.build("meter"), meter), -+ map(MetricName.build("timer"), timer)); -+ } -+ -+ @Test -+ void shouldRescheduleAfterReportFinish() throws Exception { -+ // the first report is triggered at T + 0.1 seconds and takes 0.8 seconds -+ // after the first report finishes at T + 0.9 seconds the next report is scheduled to run at T + -+ // 1.4 seconds -+ reporter.start( -+ 100, -+ 500, -+ TimeUnit.MILLISECONDS, -+ () -> { -+ reporter.report(); -+ try { -+ Thread.sleep(800); -+ } catch (InterruptedException e) { -+ Thread.currentThread().interrupt(); -+ } - }); -- } -- -- @Test -- void shouldNotFailOnStopIfReporterWasNotStared() { -- for (ScheduledReporter reporter : reporters) { -- reporter.stop(); -- } -- } -- -- @Test -- void shouldNotFailWhenStoppingMultipleTimes() { -- for (ScheduledReporter reporter : reporters) { -- reporter.start(200, TimeUnit.MILLISECONDS); -- reporter.stop(); -- reporter.stop(); -- reporter.stop(); -- } -- } -- -- @Test -- void shouldShutdownExecutorOnStopByDefault() { -- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -- reporterWithCustomExecutor.stop(); -- assertTrue(customExecutor.isTerminated()); -- } -- -- @Test -- void shouldNotShutdownExternallyManagedExecutorOnStop() { -- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -- reporterWithExternallyManagedExecutor.stop(); -- assertFalse(mockExecutor.isTerminated()); -- assertFalse(mockExecutor.isShutdown()); -- } -- -- @Test -- void shouldCancelScheduledFutureWhenStoppingWithExternallyManagedExecutor() throws InterruptedException, ExecutionException, TimeoutException { -- // configure very frequency rate of execution -- reporterWithExternallyManagedExecutor.start(1, TimeUnit.MILLISECONDS); -- reporterWithExternallyManagedExecutor.stop(); -- Thread.sleep(100); -- -- // executionCount should not increase when scheduled future is canceled properly -- int executionCount = reporterWithExternallyManagedExecutor.executionCount.get(); -- Thread.sleep(500); -- assertEquals(executionCount, reporterWithExternallyManagedExecutor.executionCount.get()); -- } -- -- @Test -- void shouldConvertDurationToMillisecondsPrecisely() { -- assertEquals(2.0E-5, reporter.convertDuration(20), 0.0); -- } - -- @Test -- void shouldReportMetricsOnShutdown() throws Exception { -- CountDownLatch latch = new CountDownLatch(1); -- reporterWithNullExecutor.start(0, 10, TimeUnit.SECONDS, () -> { -- if (latch.getCount() > 0) { -- reporterWithNullExecutor.report(); -- latch.countDown(); -- } -- }); -- latch.await(5, TimeUnit.SECONDS); -- reporterWithNullExecutor.stop(); -- -- verify(reporterWithNullExecutor, times(2)).report( -- map(MetricName.build("gauge"), gauge), -- map(MetricName.build("counter"), counter), -- map(MetricName.build("histogram"), histogram), -- map(MetricName.build("meter"), meter), -- map(MetricName.build("timer"), timer) -- ); -+ Thread.sleep(1_000); -+ -+ verify(reporter) -+ .report( -+ map(MetricName.build("gauge"), gauge), -+ map(MetricName.build("counter"), counter), -+ map(MetricName.build("histogram"), histogram), -+ map(MetricName.build("meter"), meter), -+ map(MetricName.build("timer"), timer)); -+ } -+ -+ private SortedMap map(MetricName name, T value) { -+ final SortedMap map = new TreeMap<>(); -+ map.put(name, value); -+ return map; -+ } -+ -+ private static class DummyReporter extends ScheduledReporter { -+ -+ private AtomicInteger executionCount = new AtomicInteger(); -+ -+ DummyReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit) { -+ super(registry, name, filter, rateUnit, durationUnit); - } - -- @Test -- void shouldRescheduleAfterReportFinish() throws Exception { -- // the first report is triggered at T + 0.1 seconds and takes 0.8 seconds -- // after the first report finishes at T + 0.9 seconds the next report is scheduled to run at T + 1.4 seconds -- reporter.start(100, 500, TimeUnit.MILLISECONDS, () -> { -- reporter.report(); -- try { -- Thread.sleep(800); -- } catch (InterruptedException e) { -- Thread.currentThread().interrupt(); -- } -- }); -- -- Thread.sleep(1_000); -- -- verify(reporter, times(1)).report( -- map(MetricName.build("gauge"), gauge), -- map(MetricName.build("counter"), counter), -- map(MetricName.build("histogram"), histogram), -- map(MetricName.build("meter"), meter), -- map(MetricName.build("timer"), timer) -- ); -+ DummyReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor) { -+ super(registry, name, filter, rateUnit, durationUnit, executor); - } - -- private SortedMap map(MetricName name, T value) { -- final SortedMap map = new TreeMap<>(); -- map.put(name, value); -- return map; -+ DummyReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop) { -+ super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop); - } - -- private static class DummyReporter extends ScheduledReporter { -- -- private AtomicInteger executionCount = new AtomicInteger(); -- -- DummyReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit) { -- super(registry, name, filter, rateUnit, durationUnit); -- } -- -- DummyReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor) { -- super(registry, name, filter, rateUnit, durationUnit, executor); -- } -- -- DummyReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop) { -- super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop); -- } -- -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap> gauges, SortedMap counters, SortedMap histograms, SortedMap meters, SortedMap timers) { -- executionCount.incrementAndGet(); -- // nothing doing! -- } -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap> gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ executionCount.incrementAndGet(); -+ // nothing doing! - } -- -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java -@@ -1,95 +1,95 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.junit.jupiter.api.Assertions.assertTrue; - - import java.util.concurrent.atomic.AtomicReference; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - --class SharedMetricRegistriesTest { -- -- @BeforeEach -- void setUp() { -- SharedMetricRegistries.setDefaultRegistryName(new AtomicReference<>()); -- SharedMetricRegistries.clear(); -- } -- -- @Test -- void memorizesRegistriesByName() { -- final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); -- final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); -- -- assertThat(one) -- .isSameAs(two); -- } -- -- @Test -- void hasASetOfNames() { -- SharedMetricRegistries.getOrCreate("one"); -- -- assertThat(SharedMetricRegistries.names()) -- .containsOnly("one"); -- } -- -- @Test -- void removesRegistries() { -- final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); -- SharedMetricRegistries.remove("one"); -- -- assertThat(SharedMetricRegistries.names()) -- .isEmpty(); -- -- final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); -- assertThat(two) -- .isNotSameAs(one); -- } -- -- @Test -- void clearsRegistries() { -- SharedMetricRegistries.getOrCreate("one"); -- SharedMetricRegistries.getOrCreate("two"); -- -- SharedMetricRegistries.clear(); -- -- assertThat(SharedMetricRegistries.names()) -- .isEmpty(); -- } -- -- @Test -- void errorsWhenDefaultUnset() { -- Throwable exception = assertThrows(IllegalStateException.class, () -> { -- SharedMetricRegistries.getDefault(); -- }); -- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); -- } -- -- @Test -- void createsDefaultRegistries() { -- final String defaultName = "default"; -- final MetricRegistry registry = SharedMetricRegistries.setDefault(defaultName); -- assertThat(registry).isNotNull(); -- assertThat(SharedMetricRegistries.getDefault()).isEqualTo(registry); -- assertThat(SharedMetricRegistries.getOrCreate(defaultName)).isEqualTo(registry); -- } -- -- @Test -- void errorsWhenDefaultAlreadySet() { -- Throwable exception = assertThrows(IllegalStateException.class, () -> { -- SharedMetricRegistries.setDefault("foobah"); -- SharedMetricRegistries.setDefault("borg"); -- }); -- assertTrue(exception.getMessage().contains("Default metric registry name is already set.")); -- } -- -- @Test -- void setsDefaultExistingRegistries() { -- final String defaultName = "default"; -- final MetricRegistry registry = new MetricRegistry(); -- assertThat(SharedMetricRegistries.setDefault(defaultName, registry)).isEqualTo(registry); -- assertThat(SharedMetricRegistries.getDefault()).isEqualTo(registry); -- assertThat(SharedMetricRegistries.getOrCreate(defaultName)).isEqualTo(registry); -- } -+final class SharedMetricRegistriesTest { -+ -+ @BeforeEach -+ void setUp() { -+ SharedMetricRegistries.setDefaultRegistryName(new AtomicReference<>()); -+ SharedMetricRegistries.clear(); -+ } -+ -+ @Test -+ void memorizesRegistriesByName() { -+ final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); -+ final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); -+ -+ assertThat(one).isSameAs(two); -+ } -+ -+ @Test -+ void hasASetOfNames() { -+ SharedMetricRegistries.getOrCreate("one"); -+ -+ assertThat(SharedMetricRegistries.names()).containsExactly("one"); -+ } -+ -+ @Test -+ void removesRegistries() { -+ final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); -+ SharedMetricRegistries.remove("one"); -+ -+ assertThat(SharedMetricRegistries.names()).isEmpty(); -+ -+ final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); -+ assertThat(two).isNotSameAs(one); -+ } -+ -+ @Test -+ void clearsRegistries() { -+ SharedMetricRegistries.getOrCreate("one"); -+ SharedMetricRegistries.getOrCreate("two"); -+ -+ SharedMetricRegistries.clear(); -+ -+ assertThat(SharedMetricRegistries.names()).isEmpty(); -+ } -+ -+ @Test -+ void errorsWhenDefaultUnset() { -+ Throwable exception = -+ assertThrows( -+ IllegalStateException.class, -+ () -> { -+ SharedMetricRegistries.getDefault(); -+ }); -+ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); -+ } -+ -+ @Test -+ void createsDefaultRegistries() { -+ final String defaultName = "default"; -+ final MetricRegistry registry = SharedMetricRegistries.setDefault(defaultName); -+ assertThat(registry).isNotNull(); -+ assertThat(SharedMetricRegistries.getDefault()).isEqualTo(registry); -+ assertThat(SharedMetricRegistries.getOrCreate(defaultName)).isEqualTo(registry); -+ } -+ -+ @Test -+ void errorsWhenDefaultAlreadySet() { -+ Throwable exception = -+ assertThrows( -+ IllegalStateException.class, -+ () -> { -+ SharedMetricRegistries.setDefault("foobah"); -+ SharedMetricRegistries.setDefault("borg"); -+ }); -+ assertThat(exception.getMessage().contains("Default metric registry name is already set.")) -+ .isTrue(); -+ } -+ -+ @Test -+ void setsDefaultExistingRegistries() { -+ final String defaultName = "default"; -+ final MetricRegistry registry = new MetricRegistry(); -+ assertThat(SharedMetricRegistries.setDefault(defaultName, registry)).isEqualTo(registry); -+ assertThat(SharedMetricRegistries.getDefault()).isEqualTo(registry); -+ assertThat(SharedMetricRegistries.getOrCreate(defaultName)).isEqualTo(registry); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java -@@ -1,29 +1,26 @@ - package io.dropwizard.metrics5; - --import io.dropwizard.metrics5.DefaultSettableGauge; --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; - --class SimpleSettableGaugeTest { -+import org.junit.jupiter.api.Test; -+ -+final class SimpleSettableGaugeTest { - -- @Test -- void defaultValue() { -- DefaultSettableGauge settable = new DefaultSettableGauge<>(1); -+ @Test -+ void defaultValue() { -+ DefaultSettableGauge settable = new DefaultSettableGauge<>(1); - -- assertThat(settable.getValue()).isEqualTo(1); -- } -+ assertThat(settable.getValue()).isEqualTo(1); -+ } - -- @Test -- void setValueAndThenGetValue() { -- DefaultSettableGauge settable = new DefaultSettableGauge<>("default"); -+ @Test -+ void setValueAndThenGetValue() { -+ DefaultSettableGauge settable = new DefaultSettableGauge<>("default"); - -- settable.setValue("first"); -- assertThat(settable.getValue()) -- .isEqualTo("first"); -+ settable.setValue("first"); -+ assertThat(settable.getValue()).isEqualTo("first"); - -- settable.setValue("second"); -- assertThat(settable.getValue()) -- .isEqualTo("second"); -- } -+ settable.setValue("second"); -+ assertThat(settable.getValue()).isEqualTo("second"); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java -@@ -1,19 +1,8 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; --import org.slf4j.Logger; --import org.slf4j.Marker; -- --import java.util.EnumSet; --import java.util.Set; --import java.util.SortedMap; --import java.util.TreeMap; --import java.util.concurrent.TimeUnit; -- - import static io.dropwizard.metrics5.MetricAttribute.COUNT; - import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; - import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MIN; - import static io.dropwizard.metrics5.MetricAttribute.P50; - import static io.dropwizard.metrics5.MetricAttribute.P999; - import static io.dropwizard.metrics5.MetricAttribute.STDDEV; -@@ -21,342 +10,330 @@ import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - --class Slf4jReporterTest { -- -- private final Logger logger = mock(Logger.class); -- private final Marker marker = mock(Marker.class); -- private final MetricRegistry registry = mock(MetricRegistry.class); -- -- /** -- * The set of disabled metric attributes to pass to the Slf4jReporter builder -- * in the default factory methods of {@link #infoReporter} -- * and {@link #errorReporter}. -- * -- * This value can be overridden by tests before calling the {@link #infoReporter} -- * and {@link #errorReporter} factory methods. -- */ -- private Set disabledMetricAttributes = null; -- -- private Slf4jReporter infoReporter() { -- return Slf4jReporter.forRegistry(registry) -- .outputTo(logger) -- .markWith(marker) -- .prefixedWith("prefix") -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(disabledMetricAttributes) -- .build(); -- } -- -- private Slf4jReporter errorReporter() { -- return Slf4jReporter.forRegistry(registry) -- .outputTo(logger) -- .markWith(marker) -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .withLoggingLevel(Slf4jReporter.LoggingLevel.ERROR) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(disabledMetricAttributes) -- .build(); -- } -- -- @Test -- void reportsGaugeValuesAtErrorDefault() { -- reportsGaugeValuesAtError(); -- } -- -- @Test -- void reportsGaugeValuesAtErrorAllDisabled() { -- disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect -- reportsGaugeValuesAtError(); -- } -- -- private void reportsGaugeValuesAtError() { -- when(logger.isErrorEnabled(marker)).thenReturn(true); -- errorReporter().report(map("gauge", () -> "value"), -- map(), -- map(), -- map(), -- map()); -- -- verify(logger).error(marker, "type=GAUGE, name=gauge, value=value"); -- } -- -- -- private Timer timer() { -- final Timer timer = mock(Timer.class); -- when(timer.getCount()).thenReturn(1L); -- -- when(timer.getMeanRate()).thenReturn(2.0); -- when(timer.getOneMinuteRate()).thenReturn(3.0); -- when(timer.getFiveMinuteRate()).thenReturn(4.0); -- when(timer.getFifteenMinuteRate()).thenReturn(5.0); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS -- .toNanos(1000)); -- -- when(timer.getSnapshot()).thenReturn(snapshot); -- return timer; -- } -- -- private Histogram histogram() { -- final Histogram histogram = mock(Histogram.class); -- when(histogram.getCount()).thenReturn(1L); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(2L); -- when(snapshot.getMean()).thenReturn(3.0); -- when(snapshot.getMin()).thenReturn(4L); -- when(snapshot.getStdDev()).thenReturn(5.0); -- when(snapshot.getMedian()).thenReturn(6.0); -- when(snapshot.get75thPercentile()).thenReturn(7.0); -- when(snapshot.get95thPercentile()).thenReturn(8.0); -- when(snapshot.get98thPercentile()).thenReturn(9.0); -- when(snapshot.get99thPercentile()).thenReturn(10.0); -- when(snapshot.get999thPercentile()).thenReturn(11.0); -- -- when(histogram.getSnapshot()).thenReturn(snapshot); -- return histogram; -- } -- -- private Meter meter() { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getMeanRate()).thenReturn(2.0); -- when(meter.getOneMinuteRate()).thenReturn(3.0); -- when(meter.getFiveMinuteRate()).thenReturn(4.0); -- when(meter.getFifteenMinuteRate()).thenReturn(5.0); -- return meter; -- } -- -- private Counter counter() { -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(100L); -- return counter; -- } -- -- @Test -- void reportsCounterValuesAtErrorDefault() { -- reportsCounterValuesAtError(); -- } -- -- @Test -- void reportsCounterValuesAtErrorAllDisabled() { -- disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect -- reportsCounterValuesAtError(); -- } -- -- private void reportsCounterValuesAtError() { -- final Counter counter = counter(); -- when(logger.isErrorEnabled(marker)).thenReturn(true); -- -- errorReporter().report(map(), -- map("test.counter", counter), -- map(), -- map(), -- map()); -- -- verify(logger).error(marker, "type=COUNTER, name=test.counter, count=100"); -- } -- -- @Test -- void reportsHistogramValuesAtErrorDefault() { -- reportsHistogramValuesAtError("type=HISTOGRAM, name=test.histogram, count=1, min=4, " + -- "max=2, mean=3.0, stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -- } -- -- @Test -- void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); -- reportsHistogramValuesAtError("type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " + -- "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -- } -- -- private void reportsHistogramValuesAtError(final String expectedLog) { -- final Histogram histogram = histogram(); -- when(logger.isErrorEnabled(marker)).thenReturn(true); -- -- errorReporter().report(map(), -- map(), -- map("test.histogram", histogram), -- map(), -- map()); -- -- verify(logger).error(marker, expectedLog); -- } -- -- @Test -- void reportsMeterValuesAtErrorDefault() { -- reportsMeterValuesAtError("type=METER, name=test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " + -- "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); -- } -- -- @Test -- void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); -- reportsMeterValuesAtError("type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " + -- "mean_rate=2.0, rate_unit=events/second"); -- } -- -- private void reportsMeterValuesAtError(final String expectedLog) { -- final Meter meter = meter(); -- when(logger.isErrorEnabled(marker)).thenReturn(true); -- -- errorReporter().report(map(), -- map(), -- map(), -- map("test.meter", meter), -- map()); -- -- verify(logger).error(marker, expectedLog); -- } -- -- -- @Test -- void reportsTimerValuesAtErrorDefault() { -- reportsTimerValuesAtError("type=TIMER, name=test.another.timer, count=1, min=300.0, max=100.0, " + -- "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0, " + -- "m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, " + -- "duration_unit=milliseconds"); -- } -- -- @Test -- void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); -- reportsTimerValuesAtError("type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " + -- "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " + -- "rate_unit=events/second, duration_unit=milliseconds"); -- } -- -- private void reportsTimerValuesAtError(final String expectedLog) { -- final Timer timer = timer(); -- -- when(logger.isErrorEnabled(marker)).thenReturn(true); -- -- errorReporter().report(map(), -- map(), -- map(), -- map(), -- map("test.another.timer", timer)); -- -- verify(logger).error(marker, expectedLog); -- } -- -- @Test -- void reportsGaugeValuesDefault() { -- when(logger.isInfoEnabled(marker)).thenReturn(true); -- infoReporter().report(map("gauge", () -> "value"), -- map(), -- map(), -- map(), -- map()); -- -- verify(logger).info(marker, "type=GAUGE, name=prefix.gauge, value=value"); -- } -- -- -- @Test -- void reportsCounterValuesDefault() { -- final Counter counter = counter(); -- when(logger.isInfoEnabled(marker)).thenReturn(true); -- -- infoReporter().report(map(), -- map("test.counter", counter), -- map(), -- map(), -- map()); -- -- verify(logger).info(marker, "type=COUNTER, name=prefix.test.counter, count=100"); -- } -- -- @Test -- void reportsHistogramValuesDefault() { -- final Histogram histogram = histogram(); -- when(logger.isInfoEnabled(marker)).thenReturn(true); -- -- infoReporter().report(map(), -- map(), -- map("test.histogram", histogram), -- map(), -- map()); -- -- verify(logger).info(marker, "type=HISTOGRAM, name=prefix.test.histogram, count=1, min=4, max=2, mean=3.0, " + -- "stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -- } -- -- @Test -- void reportsMeterValuesDefault() { -- final Meter meter = meter(); -- when(logger.isInfoEnabled(marker)).thenReturn(true); -- -- infoReporter().report(map(), -- map(), -- map(), -- map("test.meter", meter), -- map()); -- -- verify(logger).info(marker, "type=METER, name=prefix.test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " + -- "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); -- } -- -- @Test -- void reportsTimerValuesDefault() { -- final Timer timer = timer(); -- when(logger.isInfoEnabled(marker)).thenReturn(true); -- -- infoReporter().report(map(), -- map(), -- map(), -- map(), -- map("test.another.timer", timer)); -- -- verify(logger).info(marker, "type=TIMER, name=prefix.test.another.timer, count=1, min=300.0, max=100.0, " + -- "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0," + -- " m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, duration_unit=milliseconds"); -- } -- -- -- @Test -- void reportsAllMetricsDefault() { -- when(logger.isInfoEnabled(marker)).thenReturn(true); -- -- infoReporter().report(map("test.gauge", () -> "value"), -- map("test.counter", counter()), -- map("test.histogram", histogram()), -- map("test.meter", meter()), -- map("test.timer", timer())); -- -- verify(logger).info(marker, "type=GAUGE, name=prefix.test.gauge, value=value"); -- verify(logger).info(marker, "type=COUNTER, name=prefix.test.counter, count=100"); -- verify(logger).info(marker, "type=HISTOGRAM, name=prefix.test.histogram, count=1, min=4, max=2, mean=3.0, " + -- "stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -- verify(logger).info(marker, "type=METER, name=prefix.test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " + -- "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); -- verify(logger).info(marker, "type=TIMER, name=prefix.test.timer, count=1, min=300.0, max=100.0, " + -- "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0," + -- " m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, duration_unit=milliseconds"); -- } -- -- private SortedMap map() { -- return new TreeMap<>(); -- } -- -- private SortedMap map(String name, T metric) { -- final SortedMap map = new TreeMap<>(); -- map.put(MetricName.build(name), metric); -- return map; -- } -+import java.util.EnumSet; -+import java.util.Set; -+import java.util.SortedMap; -+import java.util.TreeMap; -+import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.Test; -+import org.slf4j.Logger; -+import org.slf4j.Marker; - -+final class Slf4jReporterTest { -+ -+ private final Logger logger = mock(); -+ private final Marker marker = mock(); -+ private final MetricRegistry registry = mock(); -+ -+ /** -+ * The set of disabled metric attributes to pass to the Slf4jReporter builder in the default -+ * factory methods of {@link #infoReporter} and {@link #errorReporter}. -+ * -+ *

    This value can be overridden by tests before calling the {@link #infoReporter} and {@link -+ * #errorReporter} factory methods. -+ */ -+ private Set disabledMetricAttributes = null; -+ -+ private Slf4jReporter infoReporter() { -+ return Slf4jReporter.forRegistry(registry) -+ .outputTo(logger) -+ .markWith(marker) -+ .prefixedWith("prefix") -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(disabledMetricAttributes) -+ .build(); -+ } -+ -+ private Slf4jReporter errorReporter() { -+ return Slf4jReporter.forRegistry(registry) -+ .outputTo(logger) -+ .markWith(marker) -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .withLoggingLevel(Slf4jReporter.LoggingLevel.ERROR) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(disabledMetricAttributes) -+ .build(); -+ } -+ -+ @Test -+ void reportsGaugeValuesAtErrorDefault() { -+ reportsGaugeValuesAtError(); -+ } -+ -+ @Test -+ void reportsGaugeValuesAtErrorAllDisabled() { -+ disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect -+ reportsGaugeValuesAtError(); -+ } -+ -+ private void reportsGaugeValuesAtError() { -+ when(logger.isErrorEnabled(marker)).thenReturn(true); -+ errorReporter().report(map("gauge", () -> "value"), map(), map(), map(), map()); -+ -+ verify(logger).error(marker, "type=GAUGE, name=gauge, value=value"); -+ } -+ -+ private Timer timer() { -+ final Timer timer = mock(); -+ when(timer.getCount()).thenReturn(1L); -+ -+ when(timer.getMeanRate()).thenReturn(2.0); -+ when(timer.getOneMinuteRate()).thenReturn(3.0); -+ when(timer.getFiveMinuteRate()).thenReturn(4.0); -+ when(timer.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -+ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -+ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -+ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -+ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -+ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -+ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -+ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -+ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -+ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -+ -+ when(timer.getSnapshot()).thenReturn(snapshot); -+ return timer; -+ } -+ -+ private Histogram histogram() { -+ final Histogram histogram = mock(); -+ when(histogram.getCount()).thenReturn(1L); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(2L); -+ when(snapshot.getMean()).thenReturn(3.0); -+ when(snapshot.getMin()).thenReturn(4L); -+ when(snapshot.getStdDev()).thenReturn(5.0); -+ when(snapshot.getMedian()).thenReturn(6.0); -+ when(snapshot.get75thPercentile()).thenReturn(7.0); -+ when(snapshot.get95thPercentile()).thenReturn(8.0); -+ when(snapshot.get98thPercentile()).thenReturn(9.0); -+ when(snapshot.get99thPercentile()).thenReturn(10.0); -+ when(snapshot.get999thPercentile()).thenReturn(11.0); -+ -+ when(histogram.getSnapshot()).thenReturn(snapshot); -+ return histogram; -+ } -+ -+ private Meter meter() { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getMeanRate()).thenReturn(2.0); -+ when(meter.getOneMinuteRate()).thenReturn(3.0); -+ when(meter.getFiveMinuteRate()).thenReturn(4.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(5.0); -+ return meter; -+ } -+ -+ private Counter counter() { -+ final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(100L); -+ return counter; -+ } -+ -+ @Test -+ void reportsCounterValuesAtErrorDefault() { -+ reportsCounterValuesAtError(); -+ } -+ -+ @Test -+ void reportsCounterValuesAtErrorAllDisabled() { -+ disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect -+ reportsCounterValuesAtError(); -+ } -+ -+ private void reportsCounterValuesAtError() { -+ final Counter counter = counter(); -+ when(logger.isErrorEnabled(marker)).thenReturn(true); -+ -+ errorReporter().report(map(), map("test.counter", counter), map(), map(), map()); -+ -+ verify(logger).error(marker, "type=COUNTER, name=test.counter, count=100"); -+ } -+ -+ @Test -+ void reportsHistogramValuesAtErrorDefault() { -+ reportsHistogramValuesAtError( -+ "type=HISTOGRAM, name=test.histogram, count=1, min=4, " -+ + "max=2, mean=3.0, stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -+ } -+ -+ @Test -+ void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { -+ disabledMetricAttributes = EnumSet.of(COUNT, MetricAttribute.MIN, P50); -+ reportsHistogramValuesAtError( -+ "type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " -+ + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -+ } -+ -+ private void reportsHistogramValuesAtError(final String expectedLog) { -+ final Histogram histogram = histogram(); -+ when(logger.isErrorEnabled(marker)).thenReturn(true); -+ -+ errorReporter().report(map(), map(), map("test.histogram", histogram), map(), map()); -+ -+ verify(logger).error(marker, expectedLog); -+ } -+ -+ @Test -+ void reportsMeterValuesAtErrorDefault() { -+ reportsMeterValuesAtError( -+ "type=METER, name=test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " -+ + "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); -+ } -+ -+ @Test -+ void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { -+ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, P50, M1_RATE); -+ reportsMeterValuesAtError( -+ "type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " -+ + "mean_rate=2.0, rate_unit=events/second"); -+ } -+ -+ private void reportsMeterValuesAtError(final String expectedLog) { -+ final Meter meter = meter(); -+ when(logger.isErrorEnabled(marker)).thenReturn(true); -+ -+ errorReporter().report(map(), map(), map(), map("test.meter", meter), map()); -+ -+ verify(logger).error(marker, expectedLog); -+ } -+ -+ @Test -+ void reportsTimerValuesAtErrorDefault() { -+ reportsTimerValuesAtError( -+ "type=TIMER, name=test.another.timer, count=1, min=300.0, max=100.0, " -+ + "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0, " -+ + "m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, " -+ + "duration_unit=milliseconds"); -+ } -+ -+ @Test -+ void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { -+ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, STDDEV, P999, MEAN_RATE); -+ reportsTimerValuesAtError( -+ "type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " -+ + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " -+ + "rate_unit=events/second, duration_unit=milliseconds"); -+ } -+ -+ private void reportsTimerValuesAtError(final String expectedLog) { -+ final Timer timer = timer(); -+ -+ when(logger.isErrorEnabled(marker)).thenReturn(true); -+ -+ errorReporter().report(map(), map(), map(), map(), map("test.another.timer", timer)); -+ -+ verify(logger).error(marker, expectedLog); -+ } -+ -+ @Test -+ void reportsGaugeValuesDefault() { -+ when(logger.isInfoEnabled(marker)).thenReturn(true); -+ infoReporter().report(map("gauge", () -> "value"), map(), map(), map(), map()); -+ -+ verify(logger).info(marker, "type=GAUGE, name=prefix.gauge, value=value"); -+ } -+ -+ @Test -+ void reportsCounterValuesDefault() { -+ final Counter counter = counter(); -+ when(logger.isInfoEnabled(marker)).thenReturn(true); -+ -+ infoReporter().report(map(), map("test.counter", counter), map(), map(), map()); -+ -+ verify(logger).info(marker, "type=COUNTER, name=prefix.test.counter, count=100"); -+ } -+ -+ @Test -+ void reportsHistogramValuesDefault() { -+ final Histogram histogram = histogram(); -+ when(logger.isInfoEnabled(marker)).thenReturn(true); -+ -+ infoReporter().report(map(), map(), map("test.histogram", histogram), map(), map()); -+ -+ verify(logger) -+ .info( -+ marker, -+ "type=HISTOGRAM, name=prefix.test.histogram, count=1, min=4, max=2, mean=3.0, " -+ + "stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -+ } -+ -+ @Test -+ void reportsMeterValuesDefault() { -+ final Meter meter = meter(); -+ when(logger.isInfoEnabled(marker)).thenReturn(true); -+ -+ infoReporter().report(map(), map(), map(), map("test.meter", meter), map()); -+ -+ verify(logger) -+ .info( -+ marker, -+ "type=METER, name=prefix.test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " -+ + "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); -+ } -+ -+ @Test -+ void reportsTimerValuesDefault() { -+ final Timer timer = timer(); -+ when(logger.isInfoEnabled(marker)).thenReturn(true); -+ -+ infoReporter().report(map(), map(), map(), map(), map("test.another.timer", timer)); -+ -+ verify(logger) -+ .info( -+ marker, -+ "type=TIMER, name=prefix.test.another.timer, count=1, min=300.0, max=100.0, " -+ + "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0," -+ + " m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, duration_unit=milliseconds"); -+ } -+ -+ @Test -+ void reportsAllMetricsDefault() { -+ when(logger.isInfoEnabled(marker)).thenReturn(true); -+ -+ infoReporter() -+ .report( -+ map("test.gauge", () -> "value"), -+ map("test.counter", counter()), -+ map("test.histogram", histogram()), -+ map("test.meter", meter()), -+ map("test.timer", timer())); -+ -+ verify(logger).info(marker, "type=GAUGE, name=prefix.test.gauge, value=value"); -+ verify(logger).info(marker, "type=COUNTER, name=prefix.test.counter, count=100"); -+ verify(logger) -+ .info( -+ marker, -+ "type=HISTOGRAM, name=prefix.test.histogram, count=1, min=4, max=2, mean=3.0, " -+ + "stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -+ verify(logger) -+ .info( -+ marker, -+ "type=METER, name=prefix.test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " -+ + "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); -+ verify(logger) -+ .info( -+ marker, -+ "type=TIMER, name=prefix.test.timer, count=1, min=300.0, max=100.0, " -+ + "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0," -+ + " m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, duration_unit=milliseconds"); -+ } -+ -+ private SortedMap map() { -+ return new TreeMap<>(); -+ } -+ -+ private SortedMap map(String name, T metric) { -+ final SortedMap map = new TreeMap<>(); -+ map.put(MetricName.build(name), metric); -+ return map; -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java -@@ -1,150 +1,166 @@ - package io.dropwizard.metrics5; - -+import static java.util.concurrent.TimeUnit.NANOSECONDS; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; --import static java.util.concurrent.TimeUnit.NANOSECONDS; -- --import org.junit.jupiter.api.Test; - - import java.util.Arrays; - import java.util.Random; - import java.util.concurrent.ThreadLocalRandom; - import java.util.concurrent.atomic.AtomicLong; -+import org.junit.jupiter.api.Test; - - @SuppressWarnings("Duplicates") --class SlidingTimeWindowArrayReservoirTest { -- -- @Test -- void storesMeasurementsWithDuplicateTicks() { -- final Clock clock = mock(Clock.class); -- final SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); -- -- when(clock.getTick()).thenReturn(20L); -- -- reservoir.update(1); -- reservoir.update(2); -- -- assertThat(reservoir.getSnapshot().getValues()) -- .containsOnly(1, 2); -- } -- -- @Test -- void boundsMeasurementsToATimeWindow() { -- final Clock clock = mock(Clock.class); -- final SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); -- -- when(clock.getTick()).thenReturn(0L); -- reservoir.update(1); -- -- when(clock.getTick()).thenReturn(5L); -- reservoir.update(2); -- -- when(clock.getTick()).thenReturn(10L); -- reservoir.update(3); -- -- when(clock.getTick()).thenReturn(15L); -- reservoir.update(4); -- -- when(clock.getTick()).thenReturn(20L); -- reservoir.update(5); -- -- assertThat(reservoir.getSnapshot().getValues()) -- .containsOnly(4, 5); -+final class SlidingTimeWindowArrayReservoirTest { -+ -+ @Test -+ void storesMeasurementsWithDuplicateTicks() { -+ final Clock clock = mock(); -+ final SlidingTimeWindowArrayReservoir reservoir = -+ new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); -+ -+ when(clock.getTick()).thenReturn(20L); -+ -+ reservoir.update(1); -+ reservoir.update(2); -+ -+ assertThat(reservoir.getSnapshot().getValues()).containsOnly(1, 2); -+ } -+ -+ @Test -+ void boundsMeasurementsToATimeWindow() { -+ final Clock clock = mock(); -+ final SlidingTimeWindowArrayReservoir reservoir = -+ new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); -+ -+ when(clock.getTick()).thenReturn(0L); -+ reservoir.update(1); -+ -+ when(clock.getTick()).thenReturn(5L); -+ reservoir.update(2); -+ -+ when(clock.getTick()).thenReturn(10L); -+ reservoir.update(3); -+ -+ when(clock.getTick()).thenReturn(15L); -+ reservoir.update(4); -+ -+ when(clock.getTick()).thenReturn(20L); -+ reservoir.update(5); -+ -+ assertThat(reservoir.getSnapshot().getValues()).containsOnly(4, 5); -+ } -+ -+ @Test -+ void comparisonResultsTest() { -+ int cycles = 1000000; -+ long time = (Long.MAX_VALUE / 256) - (long) (cycles * 0.5); -+ ManualClock manualClock = new ManualClock(); -+ manualClock.addNanos(time); -+ int window = 300; -+ Random random = new Random(ThreadLocalRandom.current().nextInt()); -+ -+ SlidingTimeWindowReservoir treeReservoir = -+ new SlidingTimeWindowReservoir(window, NANOSECONDS, manualClock); -+ SlidingTimeWindowArrayReservoir arrayReservoir = -+ new SlidingTimeWindowArrayReservoir(window, NANOSECONDS, manualClock); -+ -+ for (int i = 0; i < cycles; i++) { -+ manualClock.addNanos(1); -+ treeReservoir.update(i); -+ arrayReservoir.update(i); -+ if (random.nextDouble() < 0.01) { -+ long[] treeValues = treeReservoir.getSnapshot().getValues(); -+ long[] arrValues = arrayReservoir.getSnapshot().getValues(); -+ assertThat(arrValues).isEqualTo(treeValues); -+ } -+ if (random.nextDouble() < 0.05) { -+ assertThat(arrayReservoir.size()).isEqualTo(treeReservoir.size()); -+ } - } -- -- @Test -- void comparisonResultsTest() { -- int cycles = 1000000; -- long time = (Long.MAX_VALUE / 256) - (long) (cycles * 0.5); -- ManualClock manualClock = new ManualClock(); -- manualClock.addNanos(time); -- int window = 300; -- Random random = new Random(ThreadLocalRandom.current().nextInt()); -- -- SlidingTimeWindowReservoir treeReservoir = new SlidingTimeWindowReservoir(window, NANOSECONDS, manualClock); -- SlidingTimeWindowArrayReservoir arrayReservoir = new SlidingTimeWindowArrayReservoir(window, NANOSECONDS, manualClock); -- -- for (int i = 0; i < cycles; i++) { -- manualClock.addNanos(1); -- treeReservoir.update(i); -- arrayReservoir.update(i); -- if (random.nextDouble() < 0.01) { -- long[] treeValues = treeReservoir.getSnapshot().getValues(); -- long[] arrValues = arrayReservoir.getSnapshot().getValues(); -- assertThat(arrValues).isEqualTo(treeValues); -- } -- if (random.nextDouble() < 0.05) { -- assertThat(arrayReservoir.size()).isEqualTo(treeReservoir.size()); -+ } -+ -+ @Test -+ void getTickOverflow() { -+ final Random random = new Random(0); -+ final int window = 128; -+ AtomicLong counter = new AtomicLong(0L); -+ -+ // Note: 'threshold' defines the number of updates submitted to the reservoir after overflowing -+ for (int threshold : Arrays.asList(0, 1, 2, 127, 128, 129, 255, 256, 257)) { -+ -+ // Note: 'updatePerTick' defines the number of updates submitted to the reservoir between each -+ // tick -+ for (int updatesPerTick : Arrays.asList(1, 2, 127, 128, 129, 255, 256, 257)) { -+ // logger.info("Executing test: threshold={}, updatesPerTick={}", threshold, -+ // updatesPerTick); -+ -+ // Set the clock to overflow in (2*window+1)ns -+ final ManualClock clock = new ManualClock(); -+ clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -+ assertThat(clock.getTick() * 256).isPositive(); -+ -+ // Create the reservoir -+ final SlidingTimeWindowArrayReservoir reservoir = -+ new SlidingTimeWindowArrayReservoir(window, NANOSECONDS, clock); -+ int updatesAfterThreshold = 0; -+ while (true) { -+ // Update the reservoir -+ for (int i = 0; i < updatesPerTick; i++) { -+ long l = counter.incrementAndGet(); -+ reservoir.update(l); -+ } -+ -+ // Randomly check the reservoir size -+ if (random.nextDouble() < 0.1) { -+ assertThat(reservoir.size()) -+ .as( -+ "Bad reservoir size with: threshold=%d, updatesPerTick=%d", -+ threshold, updatesPerTick) -+ .isLessThanOrEqualTo(window * 256); -+ } -+ -+ // Update the clock -+ clock.addNanos(1); -+ -+ // If the clock has overflowed start counting updates -+ if ((clock.getTick() * 256) < 0) { -+ if (updatesAfterThreshold++ >= threshold) { -+ break; - } -+ } - } -- } - -- @Test -- void testGetTickOverflow() { -- final Random random = new Random(0); -- final int window = 128; -- AtomicLong counter = new AtomicLong(0L); -- -- // Note: 'threshold' defines the number of updates submitted to the reservoir after overflowing -- for (int threshold : Arrays.asList(0, 1, 2, 127, 128, 129, 255, 256, 257)) { -- -- // Note: 'updatePerTick' defines the number of updates submitted to the reservoir between each tick -- for (int updatesPerTick : Arrays.asList(1, 2, 127, 128, 129, 255, 256, 257)) { -- //logger.info("Executing test: threshold={}, updatesPerTick={}", threshold, updatesPerTick); -- -- // Set the clock to overflow in (2*window+1)ns -- final ManualClock clock = new ManualClock(); -- clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -- assertThat(clock.getTick() * 256).isGreaterThan(0); -- -- // Create the reservoir -- final SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(window, NANOSECONDS, clock); -- int updatesAfterThreshold = 0; -- while (true) { -- // Update the reservoir -- for (int i = 0; i < updatesPerTick; i++) { -- long l = counter.incrementAndGet(); -- reservoir.update(l); -- } -- -- // Randomly check the reservoir size -- if (random.nextDouble() < 0.1) { -- assertThat(reservoir.size()) -- .as("Bad reservoir size with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) -- .isLessThanOrEqualTo(window * 256); -- } -- -- // Update the clock -- clock.addNanos(1); -- -- // If the clock has overflowed start counting updates -- if ((clock.getTick() * 256) < 0) { -- if (updatesAfterThreshold++ >= threshold) { -- break; -- } -- } -- } -- -- // Check the final reservoir size -- assertThat(reservoir.size()) -- .as("Bad final reservoir size with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) -- .isLessThanOrEqualTo(window * 256); -- -- // Advance the clock far enough to clear the reservoir. Note that here the window only loosely defines -- // the reservoir window; when updatesPerTick is greater than 128 the sliding window will always be well -- // ahead of the current clock time, and advances in getTick while in trim (called randomly above from -- // size and every 256 updates). Until the clock "catches up" advancing the clock will have no effect on -- // the reservoir, and reservoir.size() will merely move the window forward 1/256th of a ns - as such, an -- // arbitrary increment of 1s here was used instead to advance the clock well beyond any updates recorded -- // above. -- clock.addSeconds(1); -- -- // The reservoir should now be empty -- assertThat(reservoir.size()) -- .as("Bad reservoir size after delay with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) -- .isEqualTo(0); -- } -- } -+ // Check the final reservoir size -+ assertThat(reservoir.size()) -+ .as( -+ "Bad final reservoir size with: threshold=%d, updatesPerTick=%d", -+ threshold, updatesPerTick) -+ .isLessThanOrEqualTo(window * 256); -+ -+ // Advance the clock far enough to clear the reservoir. Note that here the window only -+ // loosely defines -+ // the reservoir window; when updatesPerTick is greater than 128 the sliding window will -+ // always be well -+ // ahead of the current clock time, and advances in getTick while in trim (called randomly -+ // above from -+ // size and every 256 updates). Until the clock "catches up" advancing the clock will have -+ // no effect on -+ // the reservoir, and reservoir.size() will merely move the window forward 1/256th of a ns - -+ // as such, an -+ // arbitrary increment of 1s here was used instead to advance the clock well beyond any -+ // updates recorded -+ // above. -+ clock.addSeconds(1); -+ -+ // The reservoir should now be empty -+ assertThat(reservoir.size()) -+ .as( -+ "Bad reservoir size after delay with: threshold=%d, updatesPerTick=%d", -+ threshold, updatesPerTick) -+ .isEqualTo(0); -+ } - } --} -\ No newline at end of file -+ } -+} ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java -@@ -1,166 +1,165 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import java.time.Instant; -- - import static io.dropwizard.metrics5.SlidingTimeWindowMovingAverages.NUMBER_OF_BUCKETS; - import static org.assertj.core.api.Assertions.assertThat; - --class SlidingTimeWindowMovingAveragesTest { -- -- private ManualClock clock; -- private SlidingTimeWindowMovingAverages movingAverages; -- private Meter meter; -+import java.time.Instant; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - -- @BeforeEach -- void init() { -- clock = new ManualClock(); -- movingAverages = new SlidingTimeWindowMovingAverages(clock); -- meter = new Meter(movingAverages, clock); -- } -+final class SlidingTimeWindowMovingAveragesTest { - -- @Test -- void normalizeIndex() { -+ private ManualClock clock; -+ private SlidingTimeWindowMovingAverages movingAverages; -+ private Meter meter; - -- SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(); -+ @BeforeEach -+ void init() { -+ clock = new ManualClock(); -+ movingAverages = new SlidingTimeWindowMovingAverages(clock); -+ meter = new Meter(movingAverages, clock); -+ } - -- assertThat(stwm.normalizeIndex(0)).isEqualTo(0); -- assertThat(stwm.normalizeIndex(900)).isEqualTo(0); -- assertThat(stwm.normalizeIndex(9000)).isEqualTo(0); -- assertThat(stwm.normalizeIndex(-900)).isEqualTo(0); -+ @Test -+ void normalizeIndex() { - -- assertThat(stwm.normalizeIndex(1)).isEqualTo(1); -+ SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(); - -- assertThat(stwm.normalizeIndex(899)).isEqualTo(899); -- assertThat(stwm.normalizeIndex(-1)).isEqualTo(899); -- assertThat(stwm.normalizeIndex(-901)).isEqualTo(899); -- } -+ assertThat(stwm.normalizeIndex(0)).isEqualTo(0); -+ assertThat(stwm.normalizeIndex(900)).isEqualTo(0); -+ assertThat(stwm.normalizeIndex(9000)).isEqualTo(0); -+ assertThat(stwm.normalizeIndex(-900)).isEqualTo(0); - -- @Test -- void calculateIndexOfTick() { -+ assertThat(stwm.normalizeIndex(1)).isEqualTo(1); - -- SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); -+ assertThat(stwm.normalizeIndex(899)).isEqualTo(899); -+ assertThat(stwm.normalizeIndex(-1)).isEqualTo(899); -+ assertThat(stwm.normalizeIndex(-901)).isEqualTo(899); -+ } - -- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(0L))).isEqualTo(0); -- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L))).isEqualTo(1); -- } -+ @Test -+ void calculateIndexOfTick() { - -- @Test -- void mark_max_without_cleanup() { -+ SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); - -- int markCount = NUMBER_OF_BUCKETS; -+ assertThat(stwm.calculateIndexOfTick(Instant.EPOCH)).isEqualTo(0); -+ assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L))).isEqualTo(1); -+ } - -- // compensate the first addSeconds in the loop; first tick should be at zero -- clock.addSeconds(-1); -+ @Test -+ void mark_max_without_cleanup() { - -- for (int i = 0; i < markCount; i++) { -- clock.addSeconds(1); -- meter.mark(); -- } -+ int markCount = NUMBER_OF_BUCKETS; - -- // verify that no cleanup happened yet -- assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.ofEpochSecond(0L)); -+ // compensate the first addSeconds in the loop; first tick should be at zero -+ clock.addSeconds(-1); - -- assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); -- assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); -+ for (int i = 0; i < markCount; i++) { -+ clock.addSeconds(1); -+ meter.mark(); - } - -- @Test -- void mark_first_cleanup() { -+ // verify that no cleanup happened yet -+ assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.EPOCH); - -- int markCount = NUMBER_OF_BUCKETS + 1; -+ assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); -+ assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); -+ assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); -+ } - -- // compensate the first addSeconds in the loop; first tick should be at zero -- clock.addSeconds(-1); -+ @Test -+ void mark_first_cleanup() { - -- for (int i = 0; i < markCount; i++) { -- clock.addSeconds(1); -- meter.mark(); -- } -+ int markCount = NUMBER_OF_BUCKETS + 1; - -- // verify that at least one cleanup happened -- assertThat(movingAverages.oldestBucketTime).isNotEqualTo(Instant.EPOCH); -+ // compensate the first addSeconds in the loop; first tick should be at zero -+ clock.addSeconds(-1); - -- assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); -- assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); -+ for (int i = 0; i < markCount; i++) { -+ clock.addSeconds(1); -+ meter.mark(); - } - -- @Test -- void mark_10_values() { -+ // verify that at least one cleanup happened -+ assertThat(movingAverages.oldestBucketTime).isNotEqualTo(Instant.EPOCH); - -- // compensate the first addSeconds in the loop; first tick should be at zero -- clock.addSeconds(-1); -+ assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); -+ assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); -+ assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); -+ } - -- for (int i = 0; i < 10; i++) { -- clock.addSeconds(1); -- meter.mark(); -- } -+ @Test -+ void mark_10_values() { - -- assertThat(meter.getCount()).isEqualTo(10L); -- assertThat(meter.getOneMinuteRate()).isEqualTo(10.0); -- assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); -- } -- -- @Test -- void mark_1000_values() { -- -- for (int i = 0; i < 1000; i++) { -- clock.addSeconds(1); -- meter.mark(); -- } -+ // compensate the first addSeconds in the loop; first tick should be at zero -+ clock.addSeconds(-1); - -- // only 60/300/900 of the 1000 events took place in the last 1/5/15 minute(s) -- assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); -- assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); -+ for (int i = 0; i < 10; i++) { -+ clock.addSeconds(1); -+ meter.mark(); - } - -- @Test -- void cleanup_pause_shorter_than_window() { -+ assertThat(meter.getCount()).isEqualTo(10L); -+ assertThat(meter.getOneMinuteRate()).isEqualTo(10.0); -+ assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); -+ assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); -+ } - -- meter.mark(10); -+ @Test -+ void mark_1000_values() { - -- // no mark for three minutes -- clock.addSeconds(180); -- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); -- assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); -+ for (int i = 0; i < 1000; i++) { -+ clock.addSeconds(1); -+ meter.mark(); - } - -- @Test -- void cleanup_window_wrap_around() { -- -- // mark at 14:40 minutes of the 15 minute window... -- clock.addSeconds(880); -- meter.mark(10); -- -- // and query at 15:30 minutes (the bucket index must have wrapped around) -- clock.addSeconds(50); -- assertThat(meter.getOneMinuteRate()).isEqualTo(10.0); -- assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); -- -- // and query at 30:10 minutes (the bucket index must have wrapped around for the second time) -- clock.addSeconds(880); -- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); -- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0); -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0); -- } -- -- @Test -- void cleanup_pause_longer_than_two_windows() { -- -- meter.mark(10); -- -- // after forty minutes all rates should be zero -- clock.addSeconds(2400); -- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); -- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0); -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0); -- } --} -\ No newline at end of file -+ // only 60/300/900 of the 1000 events took place in the last 1/5/15 minute(s) -+ assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); -+ assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); -+ assertThat(meter.getFifteenMinuteRate()).isEqualTo(900.0); -+ } -+ -+ @Test -+ void cleanup_pause_shorter_than_window() { -+ -+ meter.mark(10); -+ -+ // no mark for three minutes -+ clock.addSeconds(180); -+ assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); -+ assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); -+ assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); -+ } -+ -+ @Test -+ void cleanup_window_wrap_around() { -+ -+ // mark at 14:40 minutes of the 15 minute window... -+ clock.addSeconds(880); -+ meter.mark(10); -+ -+ // and query at 15:30 minutes (the bucket index must have wrapped around) -+ clock.addSeconds(50); -+ assertThat(meter.getOneMinuteRate()).isEqualTo(10.0); -+ assertThat(meter.getFiveMinuteRate()).isEqualTo(10.0); -+ assertThat(meter.getFifteenMinuteRate()).isEqualTo(10.0); -+ -+ // and query at 30:10 minutes (the bucket index must have wrapped around for the second time) -+ clock.addSeconds(880); -+ assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); -+ assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0); -+ assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0); -+ } -+ -+ @Test -+ void cleanup_pause_longer_than_two_windows() { -+ -+ meter.mark(10); -+ -+ // after forty minutes all rates should be zero -+ clock.addSeconds(2400); -+ assertThat(meter.getOneMinuteRate()).isEqualTo(0.0); -+ assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0); -+ assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0); -+ } -+} ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java -@@ -1,119 +1,131 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -- --import java.util.Arrays; --import java.util.Random; -- - import static java.util.concurrent.TimeUnit.NANOSECONDS; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; - --class SlidingTimeWindowReservoirTest { -- @Test -- void storesMeasurementsWithDuplicateTicks() { -- final Clock clock = mock(Clock.class); -- final SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); -+import java.util.Arrays; -+import java.util.Random; -+import org.junit.jupiter.api.Test; - -- when(clock.getTick()).thenReturn(20L); -+final class SlidingTimeWindowReservoirTest { -+ @Test -+ void storesMeasurementsWithDuplicateTicks() { -+ final Clock clock = mock(); -+ final SlidingTimeWindowReservoir reservoir = -+ new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); - -- reservoir.update(1); -- reservoir.update(2); -+ when(clock.getTick()).thenReturn(20L); - -- assertThat(reservoir.getSnapshot().getValues()) -- .containsOnly(1, 2); -- } -+ reservoir.update(1); -+ reservoir.update(2); - -- @Test -- void boundsMeasurementsToATimeWindow() { -- final Clock clock = mock(Clock.class); -- when(clock.getTick()).thenReturn(0L); -+ assertThat(reservoir.getSnapshot().getValues()).containsOnly(1, 2); -+ } - -- final SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); -+ @Test -+ void boundsMeasurementsToATimeWindow() { -+ final Clock clock = mock(); -+ when(clock.getTick()).thenReturn(0L); - -- when(clock.getTick()).thenReturn(0L); -- reservoir.update(1); -+ final SlidingTimeWindowReservoir reservoir = -+ new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); - -- when(clock.getTick()).thenReturn(5L); -- reservoir.update(2); -+ when(clock.getTick()).thenReturn(0L); -+ reservoir.update(1); - -- when(clock.getTick()).thenReturn(10L); -- reservoir.update(3); -+ when(clock.getTick()).thenReturn(5L); -+ reservoir.update(2); - -- when(clock.getTick()).thenReturn(15L); -- reservoir.update(4); -+ when(clock.getTick()).thenReturn(10L); -+ reservoir.update(3); - -- when(clock.getTick()).thenReturn(20L); -- reservoir.update(5); -+ when(clock.getTick()).thenReturn(15L); -+ reservoir.update(4); - -- assertThat(reservoir.getSnapshot().getValues()) -- .containsOnly(4, 5); -- } -+ when(clock.getTick()).thenReturn(20L); -+ reservoir.update(5); -+ -+ assertThat(reservoir.getSnapshot().getValues()).containsOnly(4, 5); -+ } - -- @Test -- void testGetTickOverflow() { -- final Random random = new Random(0); -- final int window = 128; -- -- // Note: 'threshold' defines the number of updates submitted to the reservoir after overflowing -- for (int threshold : Arrays.asList(0, 1, 2, 127, 128, 129, 255, 256, 257)) { -- -- // Note: 'updatePerTick' defines the number of updates submitted to the reservoir between each tick -- for (int updatesPerTick : Arrays.asList(1, 2, 127, 128, 129, 255, 256, 257)) { -- //logger.info("Executing test: threshold={}, updatesPerTick={}", threshold, updatesPerTick); -- -- final ManualClock clock = new ManualClock(); -- -- // Create the reservoir -- final SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(window, NANOSECONDS, clock); -- -- // Set the clock to overflow in (2*window+1)ns -- clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -- assertThat(clock.getTick() * 256).isGreaterThan(0); -- -- int updatesAfterThreshold = 0; -- while (true) { -- // Update the reservoir -- for (int i = 0; i < updatesPerTick; i++) -- reservoir.update(0); -- -- // Randomly check the reservoir size -- if (random.nextDouble() < 0.1) { -- assertThat(reservoir.size()) -- .as("Bad reservoir size with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) -- .isLessThanOrEqualTo(window * 256); -- } -- -- // Update the clock -- clock.addNanos(1); -- -- // If the clock has overflowed start counting updates -- if ((clock.getTick() * 256) < 0) { -- if (updatesAfterThreshold++ >= threshold) -- break; -- } -- } -- -- // Check the final reservoir size -- assertThat(reservoir.size()) -- .as("Bad final reservoir size with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) -- .isLessThanOrEqualTo(window * 256); -- -- // Advance the clock far enough to clear the reservoir. Note that here the window only loosely defines -- // the reservoir window; when updatesPerTick is greater than 128 the sliding window will always be well -- // ahead of the current clock time, and advances in getTick while in trim (called randomly above from -- // size and every 256 updates). Until the clock "catches up" advancing the clock will have no effect on -- // the reservoir, and reservoir.size() will merely move the window forward 1/256th of a ns - as such, an -- // arbitrary increment of 1s here was used instead to advance the clock well beyond any updates recorded -- // above. -- clock.addSeconds(1); -- -- // The reservoir should now be empty -- assertThat(reservoir.size()) -- .as("Bad reservoir size after delay with: threshold=%d, updatesPerTick=%d", threshold, updatesPerTick) -- .isEqualTo(0); -- } -+ @Test -+ void getTickOverflow() { -+ final Random random = new Random(0); -+ final int window = 128; -+ -+ // Note: 'threshold' defines the number of updates submitted to the reservoir after overflowing -+ for (int threshold : Arrays.asList(0, 1, 2, 127, 128, 129, 255, 256, 257)) { -+ -+ // Note: 'updatePerTick' defines the number of updates submitted to the reservoir between each -+ // tick -+ for (int updatesPerTick : Arrays.asList(1, 2, 127, 128, 129, 255, 256, 257)) { -+ // logger.info("Executing test: threshold={}, updatesPerTick={}", threshold, -+ // updatesPerTick); -+ -+ final ManualClock clock = new ManualClock(); -+ -+ // Create the reservoir -+ final SlidingTimeWindowReservoir reservoir = -+ new SlidingTimeWindowReservoir(window, NANOSECONDS, clock); -+ -+ // Set the clock to overflow in (2*window+1)ns -+ clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -+ assertThat(clock.getTick() * 256).isPositive(); -+ -+ int updatesAfterThreshold = 0; -+ while (true) { -+ // Update the reservoir -+ for (int i = 0; i < updatesPerTick; i++) reservoir.update(0); -+ -+ // Randomly check the reservoir size -+ if (random.nextDouble() < 0.1) { -+ assertThat(reservoir.size()) -+ .as( -+ "Bad reservoir size with: threshold=%d, updatesPerTick=%d", -+ threshold, updatesPerTick) -+ .isLessThanOrEqualTo(window * 256); -+ } -+ -+ // Update the clock -+ clock.addNanos(1); -+ -+ // If the clock has overflowed start counting updates -+ if ((clock.getTick() * 256) < 0) { -+ if (updatesAfterThreshold++ >= threshold) break; -+ } - } -+ -+ // Check the final reservoir size -+ assertThat(reservoir.size()) -+ .as( -+ "Bad final reservoir size with: threshold=%d, updatesPerTick=%d", -+ threshold, updatesPerTick) -+ .isLessThanOrEqualTo(window * 256); -+ -+ // Advance the clock far enough to clear the reservoir. Note that here the window only -+ // loosely defines -+ // the reservoir window; when updatesPerTick is greater than 128 the sliding window will -+ // always be well -+ // ahead of the current clock time, and advances in getTick while in trim (called randomly -+ // above from -+ // size and every 256 updates). Until the clock "catches up" advancing the clock will have -+ // no effect on -+ // the reservoir, and reservoir.size() will merely move the window forward 1/256th of a ns - -+ // as such, an -+ // arbitrary increment of 1s here was used instead to advance the clock well beyond any -+ // updates recorded -+ // above. -+ clock.addSeconds(1); -+ -+ // The reservoir should now be empty -+ assertThat(reservoir.size()) -+ .as( -+ "Bad reservoir size after delay with: threshold=%d, updatesPerTick=%d", -+ threshold, updatesPerTick) -+ .isEqualTo(0); -+ } - } --} -\ No newline at end of file -+ } -+} ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java -@@ -1,29 +1,27 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; - --class SlidingWindowReservoirTest { -- private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); -+import org.junit.jupiter.api.Test; -+ -+final class SlidingWindowReservoirTest { -+ private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); - -- @Test -- void handlesSmallDataStreams() { -- reservoir.update(1); -- reservoir.update(2); -+ @Test -+ void handlesSmallDataStreams() { -+ reservoir.update(1); -+ reservoir.update(2); - -- assertThat(reservoir.getSnapshot().getValues()) -- .containsOnly(1, 2); -- } -+ assertThat(reservoir.getSnapshot().getValues()).containsOnly(1, 2); -+ } - -- @Test -- void onlyKeepsTheMostRecentFromBigDataStreams() { -- reservoir.update(1); -- reservoir.update(2); -- reservoir.update(3); -- reservoir.update(4); -+ @Test -+ void onlyKeepsTheMostRecentFromBigDataStreams() { -+ reservoir.update(1); -+ reservoir.update(2); -+ reservoir.update(3); -+ reservoir.update(4); - -- assertThat(reservoir.getSnapshot().getValues()) -- .containsOnly(2, 3, 4); -- } -+ assertThat(reservoir.getSnapshot().getValues()).containsOnly(2, 3, 4); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java -@@ -1,11 +1,5 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -- --import java.time.Duration; --import java.util.concurrent.TimeUnit; --import java.util.concurrent.atomic.AtomicBoolean; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.offset; - import static org.mockito.Mockito.mock; -@@ -13,168 +7,148 @@ import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.verifyNoInteractions; - import static org.mockito.Mockito.when; - --class TimerTest { -- private final Reservoir reservoir = mock(Reservoir.class); -- private final Clock clock = new Clock() { -+import java.time.Duration; -+import java.util.concurrent.TimeUnit; -+import java.util.concurrent.atomic.AtomicBoolean; -+import org.junit.jupiter.api.Test; -+ -+final class TimerTest { -+ private final Reservoir reservoir = mock(); -+ private final Clock clock = -+ new Clock() { - // a mock clock that increments its ticker by 50msec per call - private long val = 0; - - @Override - public long getTick() { -- return val += 50000000; -+ return val += 50000000; - } -- }; -- private final Timer timer = new Timer(reservoir, clock); -+ }; -+ private final Timer timer = new Timer(reservoir, clock); - -- @Test -- void hasRates() { -- assertThat(timer.getCount()) -- .isZero(); -+ @Test -+ void hasRates() { -+ assertThat(timer.getCount()).isEqualTo(0); - -- assertThat(timer.getSum()) -- .isZero(); -+ assertThat(timer.getSum()).isEqualTo(0); - -- assertThat(timer.getMeanRate()) -- .isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getOneMinuteRate()) -- .isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getFiveMinuteRate()) -- .isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getFifteenMinuteRate()) -- .isEqualTo(0.0, offset(0.001)); -- } -+ assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); -+ } - -- @Test -- void updatesTheCountAndSumOnUpdates() { -- assertThat(timer.getCount()) -- .isZero(); -- assertThat(timer.getSum()) -- .isZero(); -+ @Test -+ void updatesTheCountAndSumOnUpdates() { -+ assertThat(timer.getCount()).isEqualTo(0); -+ assertThat(timer.getSum()).isEqualTo(0); - -- timer.update(1, TimeUnit.SECONDS); -- timer.update(5, TimeUnit.SECONDS); -+ timer.update(1, TimeUnit.SECONDS); -+ timer.update(5, TimeUnit.SECONDS); - -- assertThat(timer.getCount()) -- .isEqualTo(2); -- assertThat(timer.getSum()) -- .isEqualTo(6000000000L); -- } -+ assertThat(timer.getCount()).isEqualTo(2); -+ assertThat(timer.getSum()).isEqualTo(6000000000L); -+ } - -- @Test -- void timesCallableInstances() throws Exception { -- final String value = timer.time(() -> "one"); -+ @Test -+ void timesCallableInstances() throws Exception { -+ final String value = timer.time(() -> "one"); - -- assertThat(timer.getCount()) -- .isEqualTo(1); -- assertThat(timer.getSum()) -- .isEqualTo(50000000); -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSum()).isEqualTo(50000000); - -- assertThat(value) -- .isEqualTo("one"); -+ assertThat(value).isEqualTo("one"); - -- verify(reservoir).update(50000000); -- } -+ verify(reservoir).update(50000000); -+ } - -- @Test -- void timesSuppliedInstances() { -- final String value = timer.timeSupplier(() -> "one"); -+ @Test -+ void timesSuppliedInstances() { -+ final String value = timer.timeSupplier(() -> "one"); - -- assertThat(timer.getCount()) -- .isEqualTo(1); -+ assertThat(timer.getCount()).isEqualTo(1); - -- assertThat(value) -- .isEqualTo("one"); -+ assertThat(value).isEqualTo("one"); - -- verify(reservoir).update(50000000); -- } -+ verify(reservoir).update(50000000); -+ } - -- @Test -- void timesRunnableInstances() { -- final AtomicBoolean called = new AtomicBoolean(); -- timer.time(() -> called.set(true)); -+ @Test -+ void timesRunnableInstances() { -+ final AtomicBoolean called = new AtomicBoolean(); -+ timer.time(() -> called.set(true)); - -- assertThat(timer.getCount()) -- .isEqualTo(1); -- assertThat(timer.getSum()) -- .isEqualTo(50000000); -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSum()).isEqualTo(50000000); - -- assertThat(called.get()) -- .isTrue(); -+ assertThat(called.get()).isTrue(); - -- verify(reservoir).update(50000000); -- } -+ verify(reservoir).update(50000000); -+ } - -- @Test -- void timesContexts() { -- timer.time().stop(); -+ @Test -+ void timesContexts() { -+ timer.time().stop(); - -- assertThat(timer.getCount()) -- .isEqualTo(1); -- assertThat(timer.getSum()) -- .isEqualTo(50000000); -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSum()).isEqualTo(50000000); - -- verify(reservoir).update(50000000); -- } -+ verify(reservoir).update(50000000); -+ } - -- @Test -- void returnsTheSnapshotFromTheReservoir() { -- final Snapshot snapshot = mock(Snapshot.class); -- when(reservoir.getSnapshot()).thenReturn(snapshot); -+ @Test -+ void returnsTheSnapshotFromTheReservoir() { -+ final Snapshot snapshot = mock(); -+ when(reservoir.getSnapshot()).thenReturn(snapshot); - -- assertThat(timer.getSnapshot()) -- .isEqualTo(snapshot); -- } -+ assertThat(timer.getSnapshot()).isEqualTo(snapshot); -+ } - -- @Test -- void ignoresNegativeValues() { -- timer.update(-1, TimeUnit.SECONDS); -+ @Test -+ void ignoresNegativeValues() { -+ timer.update(-1, TimeUnit.SECONDS); - -- assertThat(timer.getCount()) -- .isZero(); -- assertThat(timer.getSum()) -- .isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); -+ assertThat(timer.getSum()).isEqualTo(0); - -- verifyNoInteractions(reservoir); -- } -+ verifyNoInteractions(reservoir); -+ } - -- @Test -- void java8Duration() { -- timer.update(Duration.ofSeconds(1234)); -+ @Test -+ void java8Duration() { -+ timer.update(Duration.ofSeconds(1234)); - -- assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getCount()).isEqualTo(1); - -- verify(reservoir).update((long) 1234e9); -- } -+ verify(reservoir).update((long) 1234e9); -+ } - -- @Test -- void java8NegativeDuration() { -- timer.update(Duration.ofMillis(-5678)); -+ @Test -+ void java8NegativeDuration() { -+ timer.update(Duration.ofMillis(-5678)); - -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - -- verifyNoInteractions(reservoir); -- } -+ verifyNoInteractions(reservoir); -+ } - -- @Test -- void tryWithResourcesWork() { -- assertThat(timer.getCount()).isZero(); -- assertThat(timer.getSum()).isZero(); -- -- int dummy = 0; -- try (Timer.Context context = timer.time()) { -- assertThat(context).isNotNull(); -- dummy += 1; -- } -- assertThat(dummy).isEqualTo(1); -- assertThat(timer.getCount()) -- .isEqualTo(1); -- assertThat(timer.getSum()) -- .isEqualTo(50000000); -+ @Test -+ void tryWithResourcesWork() { -+ assertThat(timer.getCount()).isEqualTo(0); -+ assertThat(timer.getSum()).isEqualTo(0); - -- verify(reservoir).update(50000000); -+ int dummy = 0; -+ try (Timer.Context context = timer.time()) { -+ assertThat(context).isNotNull(); -+ dummy += 1; - } -+ assertThat(dummy).isEqualTo(1); -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSum()).isEqualTo(50000000); - -+ verify(reservoir).update(50000000); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java -@@ -1,31 +1,26 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; - --class UniformReservoirTest { -- @Test -- @SuppressWarnings("unchecked") -- void aReservoirOf100OutOf1000Elements() { -- final UniformReservoir reservoir = new UniformReservoir(100); -- for (int i = 0; i < 1000; i++) { -- reservoir.update(i); -- } -+import org.junit.jupiter.api.Test; -+ -+final class UniformReservoirTest { -+ @SuppressWarnings("unchecked") -+ @Test -+ void aReservoirOf100OutOf1000Elements() { -+ final UniformReservoir reservoir = new UniformReservoir(100); -+ for (int i = 0; i < 1000; i++) { -+ reservoir.update(i); -+ } - -- final Snapshot snapshot = reservoir.getSnapshot(); -+ final Snapshot snapshot = reservoir.getSnapshot(); - -- assertThat(reservoir.size()) -- .isEqualTo(100); -+ assertThat(reservoir.size()).isEqualTo(100); - -- assertThat(snapshot.size()) -- .isEqualTo(100); -+ assertThat(snapshot.size()).isEqualTo(100); - -- for (double i : snapshot.getValues()) { -- assertThat(i) -- .isLessThan(1000) -- .isGreaterThanOrEqualTo(0); -- } -+ for (double i : snapshot.getValues()) { -+ assertThat(i).isLessThan(1000).isNotNegative(); - } -- -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java -@@ -1,205 +1,198 @@ - package io.dropwizard.metrics5; - --import org.junit.jupiter.api.Test; -+import static java.util.Arrays.asList; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; -+import static org.assertj.core.api.Assertions.offset; - - import java.io.ByteArrayOutputStream; - import java.util.Random; - import java.util.concurrent.ConcurrentSkipListSet; - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.Test; - --import static java.util.Arrays.asList; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.offset; --import static org.junit.jupiter.api.Assertions.assertThrows; -- --class UniformSnapshotTest { -- private final Snapshot snapshot = new UniformSnapshot(new long[]{5, 1, 2, 3, 4}); -- -- @Test -- void smallQuantilesAreTheFirstValue() { -- assertThat(snapshot.getValue(0.0)) -- .isEqualTo(1, offset(0.1)); -- } -- -- @Test -- void bigQuantilesAreTheLastValue() { -- assertThat(snapshot.getValue(1.0)) -- .isEqualTo(5, offset(0.1)); -- } -- -- @Test -- void disallowsNotANumberQuantile() { -- assertThrows(IllegalArgumentException.class, () -> { -- snapshot.getValue(Double.NaN); -- }); -- } -- -- @Test -- void disallowsNegativeQuantile() { -- assertThrows(IllegalArgumentException.class, () -> { -- snapshot.getValue(-0.5); -- }); -- } -- -- @Test -- void disallowsQuantileOverOne() { -- assertThrows(IllegalArgumentException.class, () -> { -- snapshot.getValue(1.5); -- }); -- } -- -- @Test -- void hasAMedian() { -- assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); -- } -- -- @Test -- void hasAp75() { -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); -- } -- -- @Test -- void hasAp95() { -- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); -- } -- -- @Test -- void hasAp98() { -- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); -- } -- -- @Test -- void hasAp99() { -- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); -- } -- -- @Test -- void hasAp999() { -- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); -- } -- -- @Test -- void hasValues() { -- assertThat(snapshot.getValues()) -- .containsOnly(1, 2, 3, 4, 5); -- } -- -- @Test -- void hasASize() { -- assertThat(snapshot.size()) -- .isEqualTo(5); -- } -- -- @Test -- void canAlsoBeCreatedFromACollectionOfLongs() { -- final Snapshot other = new UniformSnapshot(asList(5L, 1L, 2L, 3L, 4L)); -- -- assertThat(other.getValues()) -- .containsOnly(1, 2, 3, 4, 5); -- } -- -- @Test -- void correctlyCreatedFromCollectionWithWeakIterator() throws Exception { -- final ConcurrentSkipListSet values = new ConcurrentSkipListSet<>(); -- -- // Create a latch to make sure that the background thread has started and -- // pushed some data to the collection. -- final CountDownLatch latch = new CountDownLatch(10); -- final Thread backgroundThread = new Thread(() -> { -- final Random random = new Random(); -- // Update the collection in the loop to trigger a potential `ArrayOutOfBoundException` -- // and verify that the snapshot doesn't make assumptions about the size of the iterator. -- while (!Thread.currentThread().isInterrupted()) { -+final class UniformSnapshotTest { -+ private final Snapshot snapshot = new UniformSnapshot(new long[] {5, 1, 2, 3, 4}); -+ -+ @Test -+ void smallQuantilesAreTheFirstValue() { -+ assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1)); -+ } -+ -+ @Test -+ void bigQuantilesAreTheLastValue() { -+ assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1)); -+ } -+ -+ @Test -+ void disallowsNotANumberQuantile() { -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(Double.NaN); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void disallowsNegativeQuantile() { -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(-0.5); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void disallowsQuantileOverOne() { -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(1.5); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void hasAMedian() { -+ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp75() { -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp95() { -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp98() { -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp99() { -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp999() { -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasValues() { -+ assertThat(snapshot.getValues()).containsOnly(1, 2, 3, 4, 5); -+ } -+ -+ @Test -+ void hasASize() { -+ assertThat(snapshot.size()).isEqualTo(5); -+ } -+ -+ @Test -+ void canAlsoBeCreatedFromACollectionOfLongs() { -+ final Snapshot other = new UniformSnapshot(asList(5L, 1L, 2L, 3L, 4L)); -+ -+ assertThat(other.getValues()).containsOnly(1, 2, 3, 4, 5); -+ } -+ -+ @Test -+ void correctlyCreatedFromCollectionWithWeakIterator() throws Exception { -+ final ConcurrentSkipListSet values = new ConcurrentSkipListSet<>(); -+ -+ // Create a latch to make sure that the background thread has started and -+ // pushed some data to the collection. -+ final CountDownLatch latch = new CountDownLatch(10); -+ final Thread backgroundThread = -+ new Thread( -+ () -> { -+ final Random random = new Random(); -+ // Update the collection in the loop to trigger a potential `ArrayOutOfBoundException` -+ // and verify that the snapshot doesn't make assumptions about the size of the -+ // iterator. -+ while (!Thread.currentThread().isInterrupted()) { - values.add(random.nextLong()); - latch.countDown(); -- } -- }); -- backgroundThread.start(); -- -- try { -- latch.await(5, TimeUnit.SECONDS); -- assertThat(latch.getCount()).isEqualTo(0); -- -- // Create a snapshot while the collection is being updated. -- final Snapshot snapshot = new UniformSnapshot(values); -- assertThat(snapshot.getValues().length).isGreaterThanOrEqualTo(10); -- } finally { -- backgroundThread.interrupt(); -- } -+ } -+ }); -+ backgroundThread.start(); -+ -+ try { -+ latch.await(5, TimeUnit.SECONDS); -+ assertThat(latch.getCount()).isEqualTo(0); -+ -+ // Create a snapshot while the collection is being updated. -+ final Snapshot snapshot = new UniformSnapshot(values); -+ assertThat(snapshot.getValues().length).isGreaterThanOrEqualTo(10); -+ } finally { -+ backgroundThread.interrupt(); - } -+ } - -- @Test -- void dumpsToAStream() { -- final ByteArrayOutputStream output = new ByteArrayOutputStream(); -+ @Test -+ void dumpsToAStream() { -+ final ByteArrayOutputStream output = new ByteArrayOutputStream(); - -- snapshot.dump(output); -+ snapshot.dump(output); - -- assertThat(output.toString()) -- .isEqualTo(String.format("1%n2%n3%n4%n5%n")); -- } -+ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); -+ } - -- @Test -- void calculatesTheMinimumValue() { -- assertThat(snapshot.getMin()) -- .isEqualTo(1); -- } -+ @Test -+ void calculatesTheMinimumValue() { -+ assertThat(snapshot.getMin()).isEqualTo(1); -+ } - -- @Test -- void calculatesTheMaximumValue() { -- assertThat(snapshot.getMax()) -- .isEqualTo(5); -- } -+ @Test -+ void calculatesTheMaximumValue() { -+ assertThat(snapshot.getMax()).isEqualTo(5); -+ } - -- @Test -- void calculatesTheMeanValue() { -- assertThat(snapshot.getMean()) -- .isEqualTo(3.0); -- } -+ @Test -+ void calculatesTheMeanValue() { -+ assertThat(snapshot.getMean()).isEqualTo(3.0); -+ } - -- @Test -- void calculatesTheStdDev() { -- assertThat(snapshot.getStdDev()) -- .isEqualTo(1.5811, offset(0.0001)); -- } -+ @Test -+ void calculatesTheStdDev() { -+ assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001)); -+ } - -- @Test -- void calculatesAMinOfZeroForAnEmptySnapshot() { -- final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); -+ @Test -+ void calculatesAMinOfZeroForAnEmptySnapshot() { -+ final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMin()) -- .isZero(); -- } -+ assertThat(emptySnapshot.getMin()).isEqualTo(0); -+ } - -- @Test -- void calculatesAMaxOfZeroForAnEmptySnapshot() { -- final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); -+ @Test -+ void calculatesAMaxOfZeroForAnEmptySnapshot() { -+ final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMax()) -- .isZero(); -- } -+ assertThat(emptySnapshot.getMax()).isEqualTo(0); -+ } - -- @Test -- void calculatesAMeanOfZeroForAnEmptySnapshot() { -- final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); -+ @Test -+ void calculatesAMeanOfZeroForAnEmptySnapshot() { -+ final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMean()) -- .isZero(); -- } -+ assertThat(emptySnapshot.getMean()).isEqualTo(0); -+ } - -- @Test -- void calculatesAStdDevOfZeroForAnEmptySnapshot() { -- final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); -+ @Test -+ void calculatesAStdDevOfZeroForAnEmptySnapshot() { -+ final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getStdDev()) -- .isZero(); -- } -+ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); -+ } - -- @Test -- void calculatesAStdDevOfZeroForASingletonSnapshot() { -- final Snapshot singleItemSnapshot = new UniformSnapshot(new long[]{1}); -+ @Test -+ void calculatesAStdDevOfZeroForASingletonSnapshot() { -+ final Snapshot singleItemSnapshot = new UniformSnapshot(new long[] {1}); - -- assertThat(singleItemSnapshot.getStdDev()) -- .isZero(); -- } -+ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); -+ } - } ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java -@@ -1,235 +1,232 @@ - package io.dropwizard.metrics5; - --import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; --import org.junit.jupiter.api.Test; --import org.mockito.ArgumentMatchers; -- --import java.io.ByteArrayOutputStream; --import java.util.ArrayList; --import java.util.List; -- -+import static com.google.common.base.Preconditions.checkArgument; - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.assertj.core.api.Assertions.offset; --import static org.junit.jupiter.api.Assertions.assertThrows; -+import static org.mockito.ArgumentMatchers.any; - import static org.mockito.Mockito.doReturn; - import static org.mockito.Mockito.spy; - import static org.mockito.Mockito.when; - --class WeightedSnapshotTest { -- -- private static List weightedArray(long[] values, double[] weights) { -- if (values.length != weights.length) { -- throw new IllegalArgumentException("Mismatched lengths: " + values.length + " vs " + weights.length); -- } -- -- final List samples = new ArrayList<>(); -- for (int i = 0; i < values.length; i++) { -- samples.add(new WeightedSnapshot.WeightedSample(values[i], weights[i])); -- } -- -- return samples; -- } -- -- private final Snapshot snapshot = new WeightedSnapshot( -- weightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2})); -- -- @Test -- void smallQuantilesAreTheFirstValue() { -- assertThat(snapshot.getValue(0.0)) -- .isEqualTo(1.0, offset(0.1)); -- } -- -- @Test -- void bigQuantilesAreTheLastValue() { -- assertThat(snapshot.getValue(1.0)) -- .isEqualTo(5.0, offset(0.1)); -- } -- -- @Test -- void disallowsNotANumberQuantile() { -- assertThrows(IllegalArgumentException.class, () -> { -- snapshot.getValue(Double.NaN); -- }); -- } -- -- @Test -- void disallowsNegativeQuantile() { -- assertThrows(IllegalArgumentException.class, () -> { -- snapshot.getValue(-0.5); -- }); -- } -- -- @Test -- void disallowsQuantileOverOne() { -- assertThrows(IllegalArgumentException.class, () -> { -- snapshot.getValue(1.5); -- }); -- } -- -- @Test -- void hasAMedian() { -- assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); -- } -- -- @Test -- void hasAp75() { -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); -- } -- -- @Test -- void hasAp95() { -- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); -- } -- -- @Test -- void hasAp98() { -- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); -- } -- -- @Test -- void hasAp99() { -- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); -- } -- -- @Test -- void hasAp999() { -- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); -- } -- -- @Test -- void hasValues() { -- assertThat(snapshot.getValues()) -- .containsOnly(1, 2, 3, 4, 5); -- } -- -- @Test -- void hasASize() { -- assertThat(snapshot.size()) -- .isEqualTo(5); -- } -- -- @Test -- void worksWithUnderestimatedCollections() { -- final List originalItems = weightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2}); -- final List spyItems = spy(originalItems); -- doReturn(originalItems.toArray(new WeightedSample[]{})).when(spyItems).toArray(ArgumentMatchers.any(WeightedSample[].class)); -- when(spyItems.size()).thenReturn(4, 5); -- -- final Snapshot other = new WeightedSnapshot(spyItems); -- -- assertThat(other.getValues()) -- .containsOnly(1, 2, 3, 4, 5); -- } -- -- @Test -- void worksWithOverestimatedCollections() { -- final List originalItems = weightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2}); -- final List spyItems = spy(originalItems); -- doReturn(originalItems.toArray(new WeightedSample[]{})).when(spyItems).toArray(ArgumentMatchers.any(WeightedSample[].class)); -- when(spyItems.size()).thenReturn(6, 5); -- -- final Snapshot other = new WeightedSnapshot(spyItems); -- -- assertThat(other.getValues()) -- .containsOnly(1, 2, 3, 4, 5); -- } -- -- @Test -- void dumpsToAStream() { -- final ByteArrayOutputStream output = new ByteArrayOutputStream(); -- -- snapshot.dump(output); -- -- assertThat(output.toString()) -- .isEqualTo(String.format("1%n2%n3%n4%n5%n")); -- } -- -- @Test -- void calculatesTheMinimumValue() { -- assertThat(snapshot.getMin()) -- .isEqualTo(1); -- } -- -- @Test -- void calculatesTheMaximumValue() { -- assertThat(snapshot.getMax()) -- .isEqualTo(5); -- } -- -- @Test -- void calculatesTheMeanValue() { -- assertThat(snapshot.getMean()) -- .isEqualTo(2.7); -- } -- -- @Test -- void calculatesTheStdDev() { -- assertThat(snapshot.getStdDev()) -- .isEqualTo(1.2688, offset(0.0001)); -- } -- -- @Test -- void calculatesAMinOfZeroForAnEmptySnapshot() { -- final Snapshot emptySnapshot = new WeightedSnapshot( -- weightedArray(new long[]{}, new double[]{})); -- -- assertThat(emptySnapshot.getMin()) -- .isZero(); -- } -- -- @Test -- void calculatesAMaxOfZeroForAnEmptySnapshot() { -- final Snapshot emptySnapshot = new WeightedSnapshot( -- weightedArray(new long[]{}, new double[]{})); -- -- assertThat(emptySnapshot.getMax()) -- .isZero(); -- } -- -- @Test -- void calculatesAMeanOfZeroForAnEmptySnapshot() { -- final Snapshot emptySnapshot = new WeightedSnapshot( -- weightedArray(new long[]{}, new double[]{})); -- -- assertThat(emptySnapshot.getMean()) -- .isZero(); -- } -- -- @Test -- void calculatesAStdDevOfZeroForAnEmptySnapshot() { -- final Snapshot emptySnapshot = new WeightedSnapshot( -- weightedArray(new long[]{}, new double[]{})); -- -- assertThat(emptySnapshot.getStdDev()) -- .isZero(); -- } -- -- @Test -- void calculatesAStdDevOfZeroForASingletonSnapshot() { -- final Snapshot singleItemSnapshot = new WeightedSnapshot( -- weightedArray(new long[]{1}, new double[]{1.0})); -- -- assertThat(singleItemSnapshot.getStdDev()) -- .isZero(); -- } -- -- @Test -- void expectNoOverflowForLowWeights() { -- final Snapshot scatteredSnapshot = new WeightedSnapshot( -- weightedArray( -- new long[]{1, 2, 3}, -- new double[]{Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE} -- ) -- ); -- -- assertThat(scatteredSnapshot.getMean()) -- .isEqualTo(2); -- } -+import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; -+import java.io.ByteArrayOutputStream; -+import java.util.ArrayList; -+import java.util.List; -+import org.junit.jupiter.api.Test; - -- @Test -- void doesNotProduceNaNValues() { -- WeightedSnapshot weightedSnapshot = new WeightedSnapshot( -- weightedArray(new long[]{1, 2, 3}, new double[]{0, 0, 0})); -- assertThat(weightedSnapshot.getMean()).isEqualTo(0); -- } -+final class WeightedSnapshotTest { -+ -+ private static List weightedArray( -+ long[] values, double[] weights) { -+ checkArgument( -+ values.length == weights.length, -+ "Mismatched lengths: %s vs %s", -+ values.length, -+ weights.length); -+ -+ final List samples = new ArrayList<>(); -+ for (int i = 0; i < values.length; i++) { -+ samples.add(new WeightedSnapshot.WeightedSample(values[i], weights[i])); -+ } -+ -+ return samples; -+ } -+ -+ private final Snapshot snapshot = -+ new WeightedSnapshot(weightedArray(new long[] {5, 1, 2, 3, 4}, new double[] {1, 2, 3, 2, 2})); -+ -+ @Test -+ void smallQuantilesAreTheFirstValue() { -+ assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1)); -+ } -+ -+ @Test -+ void bigQuantilesAreTheLastValue() { -+ assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1)); -+ } -+ -+ @Test -+ void disallowsNotANumberQuantile() { -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(Double.NaN); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void disallowsNegativeQuantile() { -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(-0.5); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void disallowsQuantileOverOne() { -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(1.5); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void hasAMedian() { -+ assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp75() { -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp95() { -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp98() { -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp99() { -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasAp999() { -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); -+ } -+ -+ @Test -+ void hasValues() { -+ assertThat(snapshot.getValues()).containsOnly(1, 2, 3, 4, 5); -+ } -+ -+ @Test -+ void hasASize() { -+ assertThat(snapshot.size()).isEqualTo(5); -+ } -+ -+ @Test -+ void worksWithUnderestimatedCollections() { -+ final List originalItems = -+ weightedArray(new long[] {5, 1, 2, 3, 4}, new double[] {1, 2, 3, 2, 2}); -+ final List spyItems = spy(originalItems); -+ doReturn(originalItems.toArray(new WeightedSample[] {})) -+ .when(spyItems) -+ .toArray(any(WeightedSample[].class)); -+ when(spyItems.size()).thenReturn(4, 5); -+ -+ final Snapshot other = new WeightedSnapshot(spyItems); -+ -+ assertThat(other.getValues()).containsOnly(1, 2, 3, 4, 5); -+ } -+ -+ @Test -+ void worksWithOverestimatedCollections() { -+ final List originalItems = -+ weightedArray(new long[] {5, 1, 2, 3, 4}, new double[] {1, 2, 3, 2, 2}); -+ final List spyItems = spy(originalItems); -+ doReturn(originalItems.toArray(new WeightedSample[] {})) -+ .when(spyItems) -+ .toArray(any(WeightedSample[].class)); -+ when(spyItems.size()).thenReturn(6, 5); -+ -+ final Snapshot other = new WeightedSnapshot(spyItems); -+ -+ assertThat(other.getValues()).containsOnly(1, 2, 3, 4, 5); -+ } -+ -+ @Test -+ void dumpsToAStream() { -+ final ByteArrayOutputStream output = new ByteArrayOutputStream(); -+ -+ snapshot.dump(output); -+ -+ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); -+ } -+ -+ @Test -+ void calculatesTheMinimumValue() { -+ assertThat(snapshot.getMin()).isEqualTo(1); -+ } -+ -+ @Test -+ void calculatesTheMaximumValue() { -+ assertThat(snapshot.getMax()).isEqualTo(5); -+ } -+ -+ @Test -+ void calculatesTheMeanValue() { -+ assertThat(snapshot.getMean()).isEqualTo(2.7); -+ } -+ -+ @Test -+ void calculatesTheStdDev() { -+ assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001)); -+ } -+ -+ @Test -+ void calculatesAMinOfZeroForAnEmptySnapshot() { -+ final Snapshot emptySnapshot = -+ new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); -+ -+ assertThat(emptySnapshot.getMin()).isEqualTo(0); -+ } -+ -+ @Test -+ void calculatesAMaxOfZeroForAnEmptySnapshot() { -+ final Snapshot emptySnapshot = -+ new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); -+ -+ assertThat(emptySnapshot.getMax()).isEqualTo(0); -+ } -+ -+ @Test -+ void calculatesAMeanOfZeroForAnEmptySnapshot() { -+ final Snapshot emptySnapshot = -+ new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); -+ -+ assertThat(emptySnapshot.getMean()).isEqualTo(0); -+ } -+ -+ @Test -+ void calculatesAStdDevOfZeroForAnEmptySnapshot() { -+ final Snapshot emptySnapshot = -+ new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); -+ -+ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); -+ } -+ -+ @Test -+ void calculatesAStdDevOfZeroForASingletonSnapshot() { -+ final Snapshot singleItemSnapshot = -+ new WeightedSnapshot(weightedArray(new long[] {1}, new double[] {1.0})); -+ -+ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); -+ } -+ -+ @Test -+ void expectNoOverflowForLowWeights() { -+ final Snapshot scatteredSnapshot = -+ new WeightedSnapshot( -+ weightedArray( -+ new long[] {1, 2, 3}, -+ new double[] {Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE})); -+ -+ assertThat(scatteredSnapshot.getMean()).isEqualTo(2); -+ } -+ -+ @Test -+ void doesNotProduceNaNValues() { -+ WeightedSnapshot weightedSnapshot = -+ new WeightedSnapshot(weightedArray(new long[] {1, 2, 3}, new double[] {0, 0, 0})); -+ assertThat(weightedSnapshot.getMean()).isEqualTo(0); -+ } - } ---- a/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactory.java -+++ b/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactory.java -@@ -2,23 +2,22 @@ package io.dropwizard.metrics5.ehcache; - - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.SharedMetricRegistries; -+import java.util.Properties; - import net.sf.ehcache.Ehcache; - import net.sf.ehcache.constructs.CacheDecoratorFactory; - --import java.util.Properties; -- - public class InstrumentedCacheDecoratorFactory extends CacheDecoratorFactory { -- @Override -- public Ehcache createDecoratedEhcache(Ehcache cache, Properties properties) { -- final String name = properties.getProperty("metric-registry-name"); -- final MetricRegistry registry = SharedMetricRegistries.getOrCreate(name); -- return InstrumentedEhcache.instrument(registry, cache); -- } -+ @Override -+ public Ehcache createDecoratedEhcache(Ehcache cache, Properties properties) { -+ final String name = properties.getProperty("metric-registry-name"); -+ final MetricRegistry registry = SharedMetricRegistries.getOrCreate(name); -+ return InstrumentedEhcache.instrument(registry, cache); -+ } - -- @Override -- public Ehcache createDefaultDecoratedEhcache(Ehcache cache, Properties properties) { -- final String name = properties.getProperty("metric-registry-name"); -- final MetricRegistry registry = SharedMetricRegistries.getOrCreate(name); -- return InstrumentedEhcache.instrument(registry, cache); -- } -+ @Override -+ public Ehcache createDefaultDecoratedEhcache(Ehcache cache, Properties properties) { -+ final String name = properties.getProperty("metric-registry-name"); -+ final MetricRegistry registry = SharedMetricRegistries.getOrCreate(name); -+ return InstrumentedEhcache.instrument(registry, cache); -+ } - } ---- a/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcache.java -+++ b/metrics-ehcache/src/main/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcache.java -@@ -1,232 +1,233 @@ - package io.dropwizard.metrics5.ehcache; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -+import java.io.Serializable; - import net.sf.ehcache.CacheException; - import net.sf.ehcache.Ehcache; - import net.sf.ehcache.Element; - import net.sf.ehcache.constructs.EhcacheDecoratorAdapter; - import net.sf.ehcache.statistics.StatisticsGateway; - --import java.io.Serializable; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -- --/** -- * An instrumented {@link Ehcache} instance. -- */ -+/** An instrumented {@link Ehcache} instance. */ - public class InstrumentedEhcache extends EhcacheDecoratorAdapter { -- /** -- * Instruments the given {@link Ehcache} instance with get and put timers -- * and a set of gauges for Ehcache's built-in statistics: -- *

    -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- *
    Ehcache timered metrics
    {@code hits}The number of times a requested item was found in the -- * cache.
    {@code in-memory-hits}Number of times a requested item was found in the memory -- * store.
    {@code off-heap-hits}Number of times a requested item was found in the off-heap -- * store.
    {@code on-disk-hits}Number of times a requested item was found in the disk -- * store.
    {@code misses}Number of times a requested item was not found in the -- * cache.
    {@code in-memory-misses}Number of times a requested item was not found in the memory -- * store.
    {@code off-heap-misses}Number of times a requested item was not found in the -- * off-heap store.
    {@code on-disk-misses}Number of times a requested item was not found in the disk -- * store.
    {@code objects}Number of elements stored in the cache.
    {@code in-memory-objects}Number of objects in the memory store.
    {@code off-heap-objects}Number of objects in the off-heap store.
    {@code on-disk-objects}Number of objects in the disk store.
    {@code mean-get-time}The average get time. Because ehcache support JDK1.4.2, each -- * get time uses {@link System#currentTimeMillis()}, rather than -- * nanoseconds. The accuracy is thus limited.
    {@code mean-search-time}The average execution time (in milliseconds) within the last -- * sample period.
    {@code eviction-count}The number of cache evictions, since the cache was created, -- * or statistics were cleared.
    {@code searches-per-second}The number of search executions that have completed in the -- * last second.
    {@code accuracy}A human readable description of the accuracy setting. One of -- * "None", "Best Effort" or "Guaranteed".
    -- *

    -- * N.B.: This enables Ehcache's sampling statistics with an accuracy -- * level of "none." -- * -- * @param cache an {@link Ehcache} instance -- * @param registry a {@link MetricRegistry} -- * @return an instrumented decorator for {@code cache} -- * @see StatisticsGateway -- */ -- public static Ehcache instrument(MetricRegistry registry, final Ehcache cache) { -- -- final MetricName prefix = name(cache.getClass(), cache.getName()); -- registry.registerGauge(prefix.resolve("hits"), -- () -> cache.getStatistics().cacheHitCount()); -- -- registry.registerGauge(prefix.resolve("in-memory-hits"), -- () -> cache.getStatistics().localHeapHitCount()); -- -- registry.registerGauge(prefix.resolve("off-heap-hits"), -- () -> cache.getStatistics().localOffHeapHitCount()); -- -- registry.registerGauge(prefix.resolve("on-disk-hits"), -- () -> cache.getStatistics().localDiskHitCount()); -- -- registry.registerGauge(prefix.resolve("misses"), -- () -> cache.getStatistics().cacheMissCount()); -- -- registry.registerGauge(prefix.resolve("in-memory-misses"), -- () -> cache.getStatistics().localHeapMissCount()); -- -- registry.registerGauge(prefix.resolve("off-heap-misses"), -- () -> cache.getStatistics().localOffHeapMissCount()); -- -- registry.registerGauge(prefix.resolve("on-disk-misses"), -- () -> cache.getStatistics().localDiskMissCount()); -- -- registry.registerGauge(prefix.resolve("objects"), -- () -> cache.getStatistics().getSize()); -- -- registry.registerGauge(prefix.resolve("in-memory-objects"), -- () -> cache.getStatistics().getLocalHeapSize()); -- -- registry.registerGauge(prefix.resolve("off-heap-objects"), -- () -> cache.getStatistics().getLocalOffHeapSize()); -- -- registry.registerGauge(prefix.resolve("on-disk-objects"), -- () -> cache.getStatistics().getLocalDiskSize()); -- -- registry.registerGauge(prefix.resolve("mean-get-time"), -- () -> cache.getStatistics().cacheGetOperation().latency().average().value()); -- -- registry.registerGauge(prefix.resolve("mean-search-time"), -- () -> cache.getStatistics().cacheSearchOperation().latency().average().value()); -- -- registry.registerGauge(prefix.resolve("eviction-count"), -- () -> cache.getStatistics().cacheEvictionOperation().count().value()); -- -- registry.registerGauge(prefix.resolve("searches-per-second"), -- () -> cache.getStatistics().cacheSearchOperation().rate().value()); -- -- registry.registerGauge(prefix.resolve("writer-queue-size"), -- () -> cache.getStatistics().getWriterQueueLength()); -- -- return new InstrumentedEhcache(registry, cache); -- } -- -- private final Timer getTimer, putTimer; -- -- private InstrumentedEhcache(MetricRegistry registry, Ehcache cache) { -- super(cache); -- this.getTimer = registry.timer(MetricRegistry.name(cache.getClass(), cache.getName(), "gets")); -- this.putTimer = registry.timer(MetricRegistry.name(cache.getClass(), cache.getName(), "puts")); -- } -- -- @Override -- public Element get(Object key) throws IllegalStateException, CacheException { -- final Timer.Context ctx = getTimer.time(); -- try { -- return underlyingCache.get(key); -- } finally { -- ctx.stop(); -- } -+ /** -+ * Instruments the given {@link Ehcache} instance with get and put timers and a set of gauges for -+ * Ehcache's built-in statistics: -+ * -+ *

    -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ * -+ *
    Ehcache timered metrics
    {@code hits}The number of times a requested item was found in the -+ * cache.
    {@code in-memory-hits}Number of times a requested item was found in the memory -+ * store.
    {@code off-heap-hits}Number of times a requested item was found in the off-heap -+ * store.
    {@code on-disk-hits}Number of times a requested item was found in the disk -+ * store.
    {@code misses}Number of times a requested item was not found in the -+ * cache.
    {@code in-memory-misses}Number of times a requested item was not found in the memory -+ * store.
    {@code off-heap-misses}Number of times a requested item was not found in the -+ * off-heap store.
    {@code on-disk-misses}Number of times a requested item was not found in the disk -+ * store.
    {@code objects}Number of elements stored in the cache.
    {@code in-memory-objects}Number of objects in the memory store.
    {@code off-heap-objects}Number of objects in the off-heap store.
    {@code on-disk-objects}Number of objects in the disk store.
    {@code mean-get-time}The average get time. Because ehcache support JDK1.4.2, each -+ * get time uses {@link System#currentTimeMillis()}, rather than -+ * nanoseconds. The accuracy is thus limited.
    {@code mean-search-time}The average execution time (in milliseconds) within the last -+ * sample period.
    {@code eviction-count}The number of cache evictions, since the cache was created, -+ * or statistics were cleared.
    {@code searches-per-second}The number of search executions that have completed in the -+ * last second.
    {@code accuracy}A human readable description of the accuracy setting. One of -+ * "None", "Best Effort" or "Guaranteed".
    -+ * -+ *

    N.B.: This enables Ehcache's sampling statistics with an accuracy level of "none." -+ * -+ * @param cache an {@link Ehcache} instance -+ * @param registry a {@link MetricRegistry} -+ * @return an instrumented decorator for {@code cache} -+ * @see StatisticsGateway -+ */ -+ public static Ehcache instrument(MetricRegistry registry, final Ehcache cache) { -+ -+ final MetricName prefix = name(cache.getClass(), cache.getName()); -+ registry.registerGauge(prefix.resolve("hits"), () -> cache.getStatistics().cacheHitCount()); -+ -+ registry.registerGauge( -+ prefix.resolve("in-memory-hits"), () -> cache.getStatistics().localHeapHitCount()); -+ -+ registry.registerGauge( -+ prefix.resolve("off-heap-hits"), () -> cache.getStatistics().localOffHeapHitCount()); -+ -+ registry.registerGauge( -+ prefix.resolve("on-disk-hits"), () -> cache.getStatistics().localDiskHitCount()); -+ -+ registry.registerGauge(prefix.resolve("misses"), () -> cache.getStatistics().cacheMissCount()); -+ -+ registry.registerGauge( -+ prefix.resolve("in-memory-misses"), () -> cache.getStatistics().localHeapMissCount()); -+ -+ registry.registerGauge( -+ prefix.resolve("off-heap-misses"), () -> cache.getStatistics().localOffHeapMissCount()); -+ -+ registry.registerGauge( -+ prefix.resolve("on-disk-misses"), () -> cache.getStatistics().localDiskMissCount()); -+ -+ registry.registerGauge(prefix.resolve("objects"), () -> cache.getStatistics().getSize()); -+ -+ registry.registerGauge( -+ prefix.resolve("in-memory-objects"), () -> cache.getStatistics().getLocalHeapSize()); -+ -+ registry.registerGauge( -+ prefix.resolve("off-heap-objects"), () -> cache.getStatistics().getLocalOffHeapSize()); -+ -+ registry.registerGauge( -+ prefix.resolve("on-disk-objects"), () -> cache.getStatistics().getLocalDiskSize()); -+ -+ registry.registerGauge( -+ prefix.resolve("mean-get-time"), -+ () -> cache.getStatistics().cacheGetOperation().latency().average().value()); -+ -+ registry.registerGauge( -+ prefix.resolve("mean-search-time"), -+ () -> cache.getStatistics().cacheSearchOperation().latency().average().value()); -+ -+ registry.registerGauge( -+ prefix.resolve("eviction-count"), -+ () -> cache.getStatistics().cacheEvictionOperation().count().value()); -+ -+ registry.registerGauge( -+ prefix.resolve("searches-per-second"), -+ () -> cache.getStatistics().cacheSearchOperation().rate().value()); -+ -+ registry.registerGauge( -+ prefix.resolve("writer-queue-size"), () -> cache.getStatistics().getWriterQueueLength()); -+ -+ return new InstrumentedEhcache(registry, cache); -+ } -+ -+ private final Timer getTimer, putTimer; -+ -+ private InstrumentedEhcache(MetricRegistry registry, Ehcache cache) { -+ super(cache); -+ this.getTimer = registry.timer(MetricRegistry.name(cache.getClass(), cache.getName(), "gets")); -+ this.putTimer = registry.timer(MetricRegistry.name(cache.getClass(), cache.getName(), "puts")); -+ } -+ -+ @Override -+ public Element get(Object key) throws IllegalStateException, CacheException { -+ final Timer.Context ctx = getTimer.time(); -+ try { -+ return underlyingCache.get(key); -+ } finally { -+ ctx.stop(); - } -- -- @Override -- public Element get(Serializable key) throws IllegalStateException, CacheException { -- final Timer.Context ctx = getTimer.time(); -- try { -- return underlyingCache.get(key); -- } finally { -- ctx.stop(); -- } -+ } -+ -+ @Override -+ public Element get(Serializable key) throws IllegalStateException, CacheException { -+ final Timer.Context ctx = getTimer.time(); -+ try { -+ return underlyingCache.get(key); -+ } finally { -+ ctx.stop(); - } -- -- @Override -- public void put(Element element) throws IllegalArgumentException, IllegalStateException, CacheException { -- final Timer.Context ctx = putTimer.time(); -- try { -- underlyingCache.put(element); -- } finally { -- ctx.stop(); -- } -+ } -+ -+ @Override -+ public void put(Element element) -+ throws IllegalArgumentException, IllegalStateException, CacheException { -+ final Timer.Context ctx = putTimer.time(); -+ try { -+ underlyingCache.put(element); -+ } finally { -+ ctx.stop(); - } -- -- @Override -- public void put(Element element, boolean doNotNotifyCacheReplicators) throws IllegalArgumentException, IllegalStateException, CacheException { -- final Timer.Context ctx = putTimer.time(); -- try { -- underlyingCache.put(element, doNotNotifyCacheReplicators); -- } finally { -- ctx.stop(); -- } -+ } -+ -+ @Override -+ public void put(Element element, boolean doNotNotifyCacheReplicators) -+ throws IllegalArgumentException, IllegalStateException, CacheException { -+ final Timer.Context ctx = putTimer.time(); -+ try { -+ underlyingCache.put(element, doNotNotifyCacheReplicators); -+ } finally { -+ ctx.stop(); - } -- -- @Override -- public Element putIfAbsent(Element element) throws NullPointerException { -- final Timer.Context ctx = putTimer.time(); -- try { -- return underlyingCache.putIfAbsent(element); -- } finally { -- ctx.stop(); -- } -+ } -+ -+ @Override -+ public Element putIfAbsent(Element element) throws NullPointerException { -+ final Timer.Context ctx = putTimer.time(); -+ try { -+ return underlyingCache.putIfAbsent(element); -+ } finally { -+ ctx.stop(); - } -+ } - } ---- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java -+++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java -@@ -1,5 +1,8 @@ - package io.dropwizard.metrics5.ehcache; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assumptions.assumeThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.SharedMetricRegistries; - import net.sf.ehcache.Cache; -@@ -9,37 +12,33 @@ import net.sf.ehcache.Element; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assumptions.assumeThat; -- --class InstrumentedCacheDecoratorFactoryTest { -- private static final CacheManager MANAGER = CacheManager.create(); -- -- private MetricRegistry registry; -- private Ehcache cache; -+final class InstrumentedCacheDecoratorFactoryTest { -+ private static final CacheManager MANAGER = CacheManager.create(); - -- @BeforeEach -- void setUp() { -- this.cache = MANAGER.getEhcache("test-config"); -- assumeThat(cache).isNotNull(); -+ private MetricRegistry registry; -+ private Ehcache cache; - -- this.registry = SharedMetricRegistries.getOrCreate("cache-metrics"); -- } -+ @BeforeEach -+ void setUp() { -+ this.cache = MANAGER.getEhcache("test-config"); -+ assumeThat(cache).isNotNull(); - -- @Test -- void measuresGets() { -- cache.get("woo"); -+ this.registry = SharedMetricRegistries.getOrCreate("cache-metrics"); -+ } - -- assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "gets")).getCount()) -- .isEqualTo(1); -+ @Test -+ void measuresGets() { -+ cache.get("woo"); - -- } -+ assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "gets")).getCount()) -+ .isEqualTo(1); -+ } - -- @Test -- void measuresPuts() { -- cache.put(new Element("woo", "whee")); -+ @Test -+ void measuresPuts() { -+ cache.put(new Element("woo", "whee")); - -- assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "puts")).getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "puts")).getCount()) -+ .isEqualTo(1); -+ } - } ---- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java -+++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java -@@ -1,5 +1,8 @@ - package io.dropwizard.metrics5.ehcache; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.entry; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import net.sf.ehcache.Cache; -@@ -10,57 +13,52 @@ import net.sf.ehcache.config.CacheConfiguration; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.entry; -- --class InstrumentedEhcacheTest { -- private static final CacheManager MANAGER = CacheManager.create(); -+final class InstrumentedEhcacheTest { -+ private static final CacheManager MANAGER = CacheManager.create(); - -- private final MetricRegistry registry = new MetricRegistry(); -- private Ehcache cache; -+ private final MetricRegistry registry = new MetricRegistry(); -+ private Ehcache cache; - -- @BeforeEach -- void setUp() { -- final Cache c = new Cache(new CacheConfiguration("test", 100)); -- MANAGER.addCache(c); -- this.cache = InstrumentedEhcache.instrument(registry, c); -- assertThat(registry.getGauges().entrySet().stream() -+ @BeforeEach -+ void setUp() { -+ final Cache c = new Cache(new CacheConfiguration("test", 100)); -+ MANAGER.addCache(c); -+ this.cache = InstrumentedEhcache.instrument(registry, c); -+ assertThat( -+ registry.getGauges().entrySet().stream() - .map(e -> entry(e.getKey().getKey(), (Number) e.getValue().getValue()))) -- .containsOnly( -- entry("net.sf.ehcache.Cache.test.eviction-count", 0L), -- entry("net.sf.ehcache.Cache.test.hits", 0L), -- entry("net.sf.ehcache.Cache.test.in-memory-hits", 0L), -- entry("net.sf.ehcache.Cache.test.in-memory-misses", 0L), -- entry("net.sf.ehcache.Cache.test.in-memory-objects", 0L), -- entry("net.sf.ehcache.Cache.test.mean-get-time", Double.NaN), -- entry("net.sf.ehcache.Cache.test.mean-search-time", Double.NaN), -- entry("net.sf.ehcache.Cache.test.misses", 0L), -- entry("net.sf.ehcache.Cache.test.objects", 0L), -- entry("net.sf.ehcache.Cache.test.off-heap-hits", 0L), -- entry("net.sf.ehcache.Cache.test.off-heap-misses", 0L), -- entry("net.sf.ehcache.Cache.test.off-heap-objects", 0L), -- entry("net.sf.ehcache.Cache.test.on-disk-hits", 0L), -- entry("net.sf.ehcache.Cache.test.on-disk-misses", 0L), -- entry("net.sf.ehcache.Cache.test.on-disk-objects", 0L), -- entry("net.sf.ehcache.Cache.test.searches-per-second", 0.0), -- entry("net.sf.ehcache.Cache.test.writer-queue-size", 0L) -- ); -- } -+ .containsOnly( -+ entry("net.sf.ehcache.Cache.test.eviction-count", 0L), -+ entry("net.sf.ehcache.Cache.test.hits", 0L), -+ entry("net.sf.ehcache.Cache.test.in-memory-hits", 0L), -+ entry("net.sf.ehcache.Cache.test.in-memory-misses", 0L), -+ entry("net.sf.ehcache.Cache.test.in-memory-objects", 0L), -+ entry("net.sf.ehcache.Cache.test.mean-get-time", Double.NaN), -+ entry("net.sf.ehcache.Cache.test.mean-search-time", Double.NaN), -+ entry("net.sf.ehcache.Cache.test.misses", 0L), -+ entry("net.sf.ehcache.Cache.test.objects", 0L), -+ entry("net.sf.ehcache.Cache.test.off-heap-hits", 0L), -+ entry("net.sf.ehcache.Cache.test.off-heap-misses", 0L), -+ entry("net.sf.ehcache.Cache.test.off-heap-objects", 0L), -+ entry("net.sf.ehcache.Cache.test.on-disk-hits", 0L), -+ entry("net.sf.ehcache.Cache.test.on-disk-misses", 0L), -+ entry("net.sf.ehcache.Cache.test.on-disk-objects", 0L), -+ entry("net.sf.ehcache.Cache.test.searches-per-second", 0.0), -+ entry("net.sf.ehcache.Cache.test.writer-queue-size", 0L)); -+ } - -- @Test -- void measuresGetsAndPuts() { -- cache.get("woo"); -+ @Test -+ void measuresGetsAndPuts() { -+ cache.get("woo"); - -- cache.put(new Element("woo", "whee")); -+ cache.put(new Element("woo", "whee")); - -- final Timer gets = registry.timer(MetricRegistry.name(Cache.class, "test", "gets")); -+ final Timer gets = registry.timer(MetricRegistry.name(Cache.class, "test", "gets")); - -- assertThat(gets.getCount()) -- .isEqualTo(1); -+ assertThat(gets.getCount()).isEqualTo(1); - -- final Timer puts = registry.timer(MetricRegistry.name(Cache.class, "test", "puts")); -+ final Timer puts = registry.timer(MetricRegistry.name(Cache.class, "test", "puts")); - -- assertThat(puts.getCount()) -- .isEqualTo(1); -- } -+ assertThat(puts.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java -@@ -1,9 +1,11 @@ - package io.dropwizard.metrics5.graphite; - --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -+import static com.google.common.base.Preconditions.checkArgument; -+import static com.google.common.base.Preconditions.checkState; -+import static java.nio.charset.StandardCharsets.UTF_8; -+import static java.util.Objects.requireNonNull; - --import javax.net.SocketFactory; -+import com.google.common.base.Strings; - import java.io.BufferedWriter; - import java.io.IOException; - import java.io.OutputStreamWriter; -@@ -12,190 +14,184 @@ import java.net.InetSocketAddress; - import java.net.Socket; - import java.net.UnknownHostException; - import java.nio.charset.Charset; -+import javax.net.SocketFactory; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; - --import static java.nio.charset.StandardCharsets.UTF_8; --import static java.util.Objects.requireNonNull; -- --/** -- * A client to a Carbon server via TCP. -- */ -+/** A client to a Carbon server via TCP. */ - public class Graphite implements GraphiteSender { -- // this may be optimistic about Carbon/Graphite -- -- private final String hostname; -- private final int port; -- private final InetSocketAddress address; -- private final SocketFactory socketFactory; -- private final Charset charset; -- -- private Socket socket; -- private Writer writer; -- private int failures; -- -- private static final Logger LOGGER = LoggerFactory.getLogger(Graphite.class); -- -- /** -- * Creates a new client which connects to the given address using the default -- * {@link SocketFactory}. -- * -- * @param hostname The hostname of the Carbon server -- * @param port The port of the Carbon server -- */ -- public Graphite(String hostname, int port) { -- this(hostname, port, SocketFactory.getDefault()); -- } -- -- /** -- * Creates a new client which connects to the given address and socket factory. -- * -- * @param hostname The hostname of the Carbon server -- * @param port The port of the Carbon server -- * @param socketFactory the socket factory -- */ -- public Graphite(String hostname, int port, SocketFactory socketFactory) { -- this(hostname, port, socketFactory, UTF_8); -- } -- -- /** -- * Creates a new client which connects to the given address and socket factory using the given -- * character set. -- * -- * @param hostname The hostname of the Carbon server -- * @param port The port of the Carbon server -- * @param socketFactory the socket factory -- * @param charset the character set used by the server -- */ -- public Graphite(String hostname, int port, SocketFactory socketFactory, Charset charset) { -- if (hostname == null || hostname.isEmpty()) { -- throw new IllegalArgumentException("hostname must not be null or empty"); -- } -- -- if (port < 0 || port > 65535) { -- throw new IllegalArgumentException("port must be a valid IP port (0-65535)"); -- } -- -- this.hostname = hostname; -- this.port = port; -- this.address = null; -- this.socketFactory = requireNonNull(socketFactory, "socketFactory must not be null"); -- this.charset = requireNonNull(charset, "charset must not be null"); -- } -- -- /** -- * Creates a new client which connects to the given address using the default -- * {@link SocketFactory}. -- * -- * @param address the address of the Carbon server -- */ -- public Graphite(InetSocketAddress address) { -- this(address, SocketFactory.getDefault()); -- } -- -- /** -- * Creates a new client which connects to the given address and socket factory. -- * -- * @param address the address of the Carbon server -- * @param socketFactory the socket factory -- */ -- public Graphite(InetSocketAddress address, SocketFactory socketFactory) { -- this(address, socketFactory, UTF_8); -- } -- -- /** -- * Creates a new client which connects to the given address and socket factory using the given -- * character set. -- * -- * @param address the address of the Carbon server -- * @param socketFactory the socket factory -- * @param charset the character set used by the server -- */ -- public Graphite(InetSocketAddress address, SocketFactory socketFactory, Charset charset) { -- this.hostname = null; -- this.port = -1; -- this.address = requireNonNull(address, "address must not be null"); -- this.socketFactory = requireNonNull(socketFactory, "socketFactory must not be null"); -- this.charset = requireNonNull(charset, "charset must not be null"); -+ // this may be optimistic about Carbon/Graphite -+ -+ private final String hostname; -+ private final int port; -+ private final InetSocketAddress address; -+ private final SocketFactory socketFactory; -+ private final Charset charset; -+ -+ private Socket socket; -+ private Writer writer; -+ private int failures; -+ -+ private static final Logger LOG = LoggerFactory.getLogger(Graphite.class); -+ -+ /** -+ * Creates a new client which connects to the given address using the default {@link -+ * SocketFactory}. -+ * -+ * @param hostname The hostname of the Carbon server -+ * @param port The port of the Carbon server -+ */ -+ public Graphite(String hostname, int port) { -+ this(hostname, port, SocketFactory.getDefault()); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address and socket factory. -+ * -+ * @param hostname The hostname of the Carbon server -+ * @param port The port of the Carbon server -+ * @param socketFactory the socket factory -+ */ -+ public Graphite(String hostname, int port, SocketFactory socketFactory) { -+ this(hostname, port, socketFactory, UTF_8); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address and socket factory using the given -+ * character set. -+ * -+ * @param hostname The hostname of the Carbon server -+ * @param port The port of the Carbon server -+ * @param socketFactory the socket factory -+ * @param charset the character set used by the server -+ */ -+ public Graphite(String hostname, int port, SocketFactory socketFactory, Charset charset) { -+ checkArgument(!Strings.isNullOrEmpty(hostname), "hostname must not be null or empty"); -+ -+ checkArgument(port >= 0 && port <= 65535, "port must be a valid IP port (0-65535)"); -+ -+ this.hostname = hostname; -+ this.port = port; -+ this.address = null; -+ this.socketFactory = requireNonNull(socketFactory, "socketFactory must not be null"); -+ this.charset = requireNonNull(charset, "charset must not be null"); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address using the default {@link -+ * SocketFactory}. -+ * -+ * @param address the address of the Carbon server -+ */ -+ public Graphite(InetSocketAddress address) { -+ this(address, SocketFactory.getDefault()); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address and socket factory. -+ * -+ * @param address the address of the Carbon server -+ * @param socketFactory the socket factory -+ */ -+ public Graphite(InetSocketAddress address, SocketFactory socketFactory) { -+ this(address, socketFactory, UTF_8); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address and socket factory using the given -+ * character set. -+ * -+ * @param address the address of the Carbon server -+ * @param socketFactory the socket factory -+ * @param charset the character set used by the server -+ */ -+ public Graphite(InetSocketAddress address, SocketFactory socketFactory, Charset charset) { -+ this.hostname = null; -+ this.port = -1; -+ this.address = requireNonNull(address, "address must not be null"); -+ this.socketFactory = requireNonNull(socketFactory, "socketFactory must not be null"); -+ this.charset = requireNonNull(charset, "charset must not be null"); -+ } -+ -+ @Override -+ public void connect() throws IllegalStateException, IOException { -+ checkState(!isConnected(), "Already connected"); -+ InetSocketAddress address = this.address; -+ // the previous dns retry logic did not work, as address.getAddress would always return the -+ // cached value -+ // this version of the simplified logic will always cause a dns request if hostname has been -+ // supplied. -+ // InetAddress.getByName forces the dns lookup -+ // if an InetSocketAddress was supplied at create time that will take precedence. -+ if (address == null || address.getHostName() == null && hostname != null) { -+ address = new InetSocketAddress(hostname, port); - } - -- @Override -- public void connect() throws IllegalStateException, IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -- InetSocketAddress address = this.address; -- // the previous dns retry logic did not work, as address.getAddress would always return the cached value -- // this version of the simplified logic will always cause a dns request if hostname has been supplied. -- // InetAddress.getByName forces the dns lookup -- // if an InetSocketAddress was supplied at create time that will take precedence. -- if (address == null || address.getHostName() == null && hostname != null) { -- address = new InetSocketAddress(hostname, port); -- } -- -- if (address.getAddress() == null) { -- throw new UnknownHostException(address.getHostName()); -- } -- -- this.socket = socketFactory.createSocket(address.getAddress(), address.getPort()); -- this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); -+ if (address.getAddress() == null) { -+ throw new UnknownHostException(address.getHostName()); - } - -- @Override -- public boolean isConnected() { -- return socket != null && socket.isConnected() && !socket.isClosed(); -+ this.socket = socketFactory.createSocket(address.getAddress(), address.getPort()); -+ this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); -+ } -+ -+ @Override -+ public boolean isConnected() { -+ return socket != null && socket.isConnected() && !socket.isClosed(); -+ } -+ -+ @Override -+ public void send(String name, String value, long timestamp) throws IOException { -+ try { -+ writer.write(sanitize(name)); -+ writer.write(' '); -+ writer.write(sanitize(value)); -+ writer.write(' '); -+ writer.write(Long.toString(timestamp)); -+ writer.write('\n'); -+ this.failures = 0; -+ } catch (IOException e) { -+ failures++; -+ throw e; - } -+ } - -- @Override -- public void send(String name, String value, long timestamp) throws IOException { -- try { -- writer.write(sanitize(name)); -- writer.write(' '); -- writer.write(sanitize(value)); -- writer.write(' '); -- writer.write(Long.toString(timestamp)); -- writer.write('\n'); -- this.failures = 0; -- } catch (IOException e) { -- failures++; -- throw e; -- } -- } -+ @Override -+ public int getFailures() { -+ return failures; -+ } - -- @Override -- public int getFailures() { -- return failures; -+ @Override -+ public void flush() throws IOException { -+ if (writer != null) { -+ writer.flush(); - } -- -- @Override -- public void flush() throws IOException { -- if (writer != null) { -- writer.flush(); -- } -+ } -+ -+ @Override -+ public void close() throws IOException { -+ try { -+ if (writer != null) { -+ writer.close(); -+ } -+ } catch (IOException ex) { -+ LOG.debug("Error closing writer", ex); -+ } finally { -+ this.writer = null; - } - -- @Override -- public void close() throws IOException { -- try { -- if (writer != null) { -- writer.close(); -- } -- } catch (IOException ex) { -- LOGGER.debug("Error closing writer", ex); -- } finally { -- this.writer = null; -- } -- -- try { -- if (socket != null) { -- socket.close(); -- } -- } catch (IOException ex) { -- LOGGER.debug("Error closing socket", ex); -- } finally { -- this.socket = null; -- } -+ try { -+ if (socket != null) { -+ socket.close(); -+ } -+ } catch (IOException ex) { -+ LOG.debug("Error closing socket", ex); -+ } finally { -+ this.socket = null; - } -+ } - -- protected String sanitize(String s) { -- return GraphiteSanitize.sanitize(s); -- } -+ protected String sanitize(String s) { -+ return GraphiteSanitize.sanitize(s); -+ } - } ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java -@@ -1,163 +1,162 @@ - package io.dropwizard.metrics5.graphite; - -+import static com.google.common.base.Preconditions.checkState; -+import static java.nio.charset.StandardCharsets.UTF_8; -+ - import com.rabbitmq.client.Channel; - import com.rabbitmq.client.Connection; - import com.rabbitmq.client.ConnectionFactory; - import com.rabbitmq.client.DefaultSocketConfigurator; -- - import java.io.IOException; - import java.net.Socket; - import java.util.concurrent.TimeoutException; - --import static java.nio.charset.StandardCharsets.UTF_8; -- --/** -- * A rabbit-mq client to a Carbon server. -- */ -+/** A rabbit-mq client to a Carbon server. */ - public class GraphiteRabbitMQ implements GraphiteSender { - -- private static final Integer DEFAULT_RABBIT_CONNECTION_TIMEOUT_MS = 500; -- private static final Integer DEFAULT_RABBIT_SOCKET_TIMEOUT_MS = 5000; -- private static final Integer DEFAULT_RABBIT_REQUESTED_HEARTBEAT_SEC = 10; -- -- private ConnectionFactory connectionFactory; -- private Connection connection; -- private Channel channel; -- private String exchange; -- -- private int failures; -- -- /** -- * Creates a new client with a given a {@link com.rabbitmq.client.ConnectionFactory} and an amqp exchange -- * -- * @param connectionFactory the {@link com.rabbitmq.client.ConnectionFactory} used to establish connection and publish to graphite server -- * @param exchange the amqp exchange -- */ -- public GraphiteRabbitMQ(final ConnectionFactory connectionFactory, final String exchange) { -- this.connectionFactory = connectionFactory; -- this.exchange = exchange; -- } -- -- /** -- * Creates a new client given connection details -- * -- * @param rabbitHost the rabbitmq server host -- * @param rabbitPort the rabbitmq server port -- * @param rabbitUsername the rabbitmq server username -- * @param rabbitPassword the rabbitmq server password -- * @param exchange the amqp exchange -- */ -- public GraphiteRabbitMQ( -- final String rabbitHost, -- final Integer rabbitPort, -- final String rabbitUsername, -- final String rabbitPassword, -- final String exchange) { -- -- this(rabbitHost, -- rabbitPort, -- rabbitUsername, -- rabbitPassword, -- exchange, -- DEFAULT_RABBIT_CONNECTION_TIMEOUT_MS, -- DEFAULT_RABBIT_SOCKET_TIMEOUT_MS, -- DEFAULT_RABBIT_REQUESTED_HEARTBEAT_SEC); -- } -- -- /** -- * Creates a new client given connection details -- * -- * @param rabbitHost the rabbitmq server host -- * @param rabbitPort the rabbitmq server port -- * @param rabbitUsername the rabbitmq server username -- * @param rabbitPassword the rabbitmq server password -- * @param exchange the amqp exchange -- * @param rabbitConnectionTimeoutMS the connection timeout in milliseconds -- * @param rabbitSocketTimeoutMS the socket timeout in milliseconds -- * @param rabbitRequestedHeartbeatInSeconds the hearthbeat in seconds -- */ -- public GraphiteRabbitMQ( -- final String rabbitHost, -- final Integer rabbitPort, -- final String rabbitUsername, -- final String rabbitPassword, -- final String exchange, -- final Integer rabbitConnectionTimeoutMS, -- final Integer rabbitSocketTimeoutMS, -- final Integer rabbitRequestedHeartbeatInSeconds) { -- -- this.exchange = exchange; -- -- this.connectionFactory = new ConnectionFactory(); -- -- connectionFactory.setSocketConfigurator(new DefaultSocketConfigurator() { -- @Override -- public void configure(Socket socket) throws IOException { -- super.configure(socket); -- socket.setSoTimeout(rabbitSocketTimeoutMS); -- } -+ private static final Integer DEFAULT_RABBIT_CONNECTION_TIMEOUT_MS = 500; -+ private static final Integer DEFAULT_RABBIT_SOCKET_TIMEOUT_MS = 5000; -+ private static final Integer DEFAULT_RABBIT_REQUESTED_HEARTBEAT_SEC = 10; -+ -+ private ConnectionFactory connectionFactory; -+ private Connection connection; -+ private Channel channel; -+ private String exchange; -+ -+ private int failures; -+ -+ /** -+ * Creates a new client with a given a {@link com.rabbitmq.client.ConnectionFactory} and an amqp -+ * exchange -+ * -+ * @param connectionFactory the {@link com.rabbitmq.client.ConnectionFactory} used to establish -+ * connection and publish to graphite server -+ * @param exchange the amqp exchange -+ */ -+ public GraphiteRabbitMQ(final ConnectionFactory connectionFactory, final String exchange) { -+ this.connectionFactory = connectionFactory; -+ this.exchange = exchange; -+ } -+ -+ /** -+ * Creates a new client given connection details -+ * -+ * @param rabbitHost the rabbitmq server host -+ * @param rabbitPort the rabbitmq server port -+ * @param rabbitUsername the rabbitmq server username -+ * @param rabbitPassword the rabbitmq server password -+ * @param exchange the amqp exchange -+ */ -+ public GraphiteRabbitMQ( -+ final String rabbitHost, -+ final Integer rabbitPort, -+ final String rabbitUsername, -+ final String rabbitPassword, -+ final String exchange) { -+ -+ this( -+ rabbitHost, -+ rabbitPort, -+ rabbitUsername, -+ rabbitPassword, -+ exchange, -+ DEFAULT_RABBIT_CONNECTION_TIMEOUT_MS, -+ DEFAULT_RABBIT_SOCKET_TIMEOUT_MS, -+ DEFAULT_RABBIT_REQUESTED_HEARTBEAT_SEC); -+ } -+ -+ /** -+ * Creates a new client given connection details -+ * -+ * @param rabbitHost the rabbitmq server host -+ * @param rabbitPort the rabbitmq server port -+ * @param rabbitUsername the rabbitmq server username -+ * @param rabbitPassword the rabbitmq server password -+ * @param exchange the amqp exchange -+ * @param rabbitConnectionTimeoutMS the connection timeout in milliseconds -+ * @param rabbitSocketTimeoutMS the socket timeout in milliseconds -+ * @param rabbitRequestedHeartbeatInSeconds the hearthbeat in seconds -+ */ -+ public GraphiteRabbitMQ( -+ final String rabbitHost, -+ final Integer rabbitPort, -+ final String rabbitUsername, -+ final String rabbitPassword, -+ final String exchange, -+ final Integer rabbitConnectionTimeoutMS, -+ final Integer rabbitSocketTimeoutMS, -+ final Integer rabbitRequestedHeartbeatInSeconds) { -+ -+ this.exchange = exchange; -+ -+ this.connectionFactory = new ConnectionFactory(); -+ -+ connectionFactory.setSocketConfigurator( -+ new DefaultSocketConfigurator() { -+ @Override -+ public void configure(Socket socket) throws IOException { -+ super.configure(socket); -+ socket.setSoTimeout(rabbitSocketTimeoutMS); -+ } - }); - -- connectionFactory.setConnectionTimeout(rabbitConnectionTimeoutMS); -- connectionFactory.setRequestedHeartbeat(rabbitRequestedHeartbeatInSeconds); -- connectionFactory.setHost(rabbitHost); -- connectionFactory.setPort(rabbitPort); -- connectionFactory.setUsername(rabbitUsername); -- connectionFactory.setPassword(rabbitPassword); -+ connectionFactory.setConnectionTimeout(rabbitConnectionTimeoutMS); -+ connectionFactory.setRequestedHeartbeat(rabbitRequestedHeartbeatInSeconds); -+ connectionFactory.setHost(rabbitHost); -+ connectionFactory.setPort(rabbitPort); -+ connectionFactory.setUsername(rabbitUsername); -+ connectionFactory.setPassword(rabbitPassword); -+ } -+ -+ @Override -+ public void connect() throws IllegalStateException, IOException { -+ checkState(!isConnected(), "Already connected"); -+ -+ try { -+ connection = connectionFactory.newConnection(); -+ } catch (TimeoutException e) { -+ throw new IllegalStateException(e); - } -- -- @Override -- public void connect() throws IllegalStateException, IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -- -- try { -- connection = connectionFactory.newConnection(); -- } catch (TimeoutException e) { -- throw new IllegalStateException(e); -- } -- channel = connection.createChannel(); -+ channel = connection.createChannel(); -+ } -+ -+ @Override -+ public boolean isConnected() { -+ return connection != null && connection.isOpen(); -+ } -+ -+ @Override -+ public void send(String name, String value, long timestamp) throws IOException { -+ try { -+ final String sanitizedName = sanitize(name); -+ final String sanitizedValue = sanitize(value); -+ -+ final String message = sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n'; -+ channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); -+ } catch (IOException e) { -+ failures++; -+ throw e; - } -+ } - -- @Override -- public boolean isConnected() { -- return connection != null && connection.isOpen(); -- } -+ @Override -+ public void flush() throws IOException { -+ // Nothing to do -+ } - -- @Override -- public void send(String name, String value, long timestamp) throws IOException { -- try { -- final String sanitizedName = sanitize(name); -- final String sanitizedValue = sanitize(value); -- -- final String message = sanitizedName + ' ' + sanitizedValue + ' ' + Long.toString(timestamp) + '\n'; -- channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); -- } catch (IOException e) { -- failures++; -- throw e; -- } -+ @Override -+ public void close() throws IOException { -+ if (connection != null) { -+ connection.close(); - } -+ } - -- @Override -- public void flush() throws IOException { -- // Nothing to do -- } -- -- @Override -- public void close() throws IOException { -- if (connection != null) { -- connection.close(); -- } -- } -- -- @Override -- public int getFailures() { -- return failures; -- } -- -- public String sanitize(String s) { -- return GraphiteSanitize.sanitize(s); -- } -+ @Override -+ public int getFailures() { -+ return failures; -+ } - -+ public String sanitize(String s) { -+ return GraphiteSanitize.sanitize(s); -+ } - } ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java -@@ -1,5 +1,21 @@ - package io.dropwizard.metrics5.graphite; - -+import static io.dropwizard.metrics5.MetricAttribute.COUNT; -+import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; -+import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; -+import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; -+import static io.dropwizard.metrics5.MetricAttribute.MEAN; -+import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; -+import static io.dropwizard.metrics5.MetricAttribute.P50; -+import static io.dropwizard.metrics5.MetricAttribute.P75; -+import static io.dropwizard.metrics5.MetricAttribute.P95; -+import static io.dropwizard.metrics5.MetricAttribute.P98; -+import static io.dropwizard.metrics5.MetricAttribute.P99; -+import static io.dropwizard.metrics5.MetricAttribute.P999; -+import static io.dropwizard.metrics5.MetricAttribute.STDDEV; -+import static io.dropwizard.metrics5.MetricAttribute.SUM; -+ -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -13,11 +29,7 @@ import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.ScheduledReporter; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -- - import java.io.IOException; --import java.util.Collections; - import java.util.Locale; - import java.util.Map; - import java.util.Set; -@@ -25,23 +37,8 @@ import java.util.SortedMap; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; - import java.util.function.DoubleFunction; -- --import static io.dropwizard.metrics5.MetricAttribute.COUNT; --import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; --import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; --import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MAX; --import static io.dropwizard.metrics5.MetricAttribute.MEAN; --import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MIN; --import static io.dropwizard.metrics5.MetricAttribute.P50; --import static io.dropwizard.metrics5.MetricAttribute.P75; --import static io.dropwizard.metrics5.MetricAttribute.P95; --import static io.dropwizard.metrics5.MetricAttribute.P98; --import static io.dropwizard.metrics5.MetricAttribute.P99; --import static io.dropwizard.metrics5.MetricAttribute.P999; --import static io.dropwizard.metrics5.MetricAttribute.STDDEV; --import static io.dropwizard.metrics5.MetricAttribute.SUM; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; - - /** - * A reporter which publishes metric values to a Graphite server. -@@ -49,477 +46,521 @@ import static io.dropwizard.metrics5.MetricAttribute.SUM; - * @see Graphite - Scalable Realtime Graphing - */ - public class GraphiteReporter extends ScheduledReporter { -+ /** -+ * Returns a new {@link Builder} for {@link GraphiteReporter}. -+ * -+ * @param registry the registry to report -+ * @return a {@link Builder} instance for a {@link GraphiteReporter} -+ */ -+ public static Builder forRegistry(MetricRegistry registry) { -+ return new Builder(registry); -+ } -+ -+ /** -+ * A builder for {@link GraphiteReporter} instances. Defaults to not using a prefix, using the -+ * default clock, converting rates to events/second, converting durations to milliseconds, and not -+ * filtering metrics. -+ */ -+ public static class Builder { -+ private final MetricRegistry registry; -+ private Clock clock; -+ private String prefix; -+ private TimeUnit rateUnit; -+ private TimeUnit durationUnit; -+ private MetricFilter filter; -+ private ScheduledExecutorService executor; -+ private boolean shutdownExecutorOnStop; -+ private Set disabledMetricAttributes; -+ private boolean addMetricAttributesAsTags; -+ private DoubleFunction floatingPointFormatter; -+ -+ private Builder(MetricRegistry registry) { -+ this.registry = registry; -+ this.clock = Clock.defaultClock(); -+ this.prefix = null; -+ this.rateUnit = TimeUnit.SECONDS; -+ this.durationUnit = TimeUnit.MILLISECONDS; -+ this.filter = MetricFilter.ALL; -+ this.executor = null; -+ this.shutdownExecutorOnStop = true; -+ this.disabledMetricAttributes = ImmutableSet.of(); -+ this.addMetricAttributesAsTags = false; -+ this.floatingPointFormatter = DEFAULT_FP_FORMATTER; -+ } -+ - /** -- * Returns a new {@link Builder} for {@link GraphiteReporter}. -+ * Specifies whether or not, the executor (used for reporting) will be stopped with same time -+ * with reporter. Default value is true. Setting this parameter to false, has the sense in -+ * combining with providing external managed executor via {@link -+ * #scheduleOn(ScheduledExecutorService)}. - * -- * @param registry the registry to report -- * @return a {@link Builder} instance for a {@link GraphiteReporter} -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ * @return {@code this} - */ -- public static Builder forRegistry(MetricRegistry registry) { -- return new Builder(registry); -+ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -+ this.shutdownExecutorOnStop = shutdownExecutorOnStop; -+ return this; - } - - /** -- * A builder for {@link GraphiteReporter} instances. Defaults to not using a prefix, using the -- * default clock, converting rates to events/second, converting durations to milliseconds, and -- * not filtering metrics. -+ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. -+ * Null value leads to executor will be auto created on start. -+ * -+ * @param executor the executor to use while scheduling reporting of metrics. -+ * @return {@code this} - */ -- public static class Builder { -- private final MetricRegistry registry; -- private Clock clock; -- private String prefix; -- private TimeUnit rateUnit; -- private TimeUnit durationUnit; -- private MetricFilter filter; -- private ScheduledExecutorService executor; -- private boolean shutdownExecutorOnStop; -- private Set disabledMetricAttributes; -- private boolean addMetricAttributesAsTags; -- private DoubleFunction floatingPointFormatter; -- -- private Builder(MetricRegistry registry) { -- this.registry = registry; -- this.clock = Clock.defaultClock(); -- this.prefix = null; -- this.rateUnit = TimeUnit.SECONDS; -- this.durationUnit = TimeUnit.MILLISECONDS; -- this.filter = MetricFilter.ALL; -- this.executor = null; -- this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -- this.addMetricAttributesAsTags = false; -- this.floatingPointFormatter = DEFAULT_FP_FORMATTER; -- } -- -- /** -- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. -- * Default value is true. -- * Setting this parameter to false, has the sense in combining with providing external managed executor via {@link #scheduleOn(ScheduledExecutorService)}. -- * -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- * @return {@code this} -- */ -- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -- this.shutdownExecutorOnStop = shutdownExecutorOnStop; -- return this; -- } -- -- /** -- * Specifies the executor to use while scheduling reporting of metrics. -- * Default value is null. -- * Null value leads to executor will be auto created on start. -- * -- * @param executor the executor to use while scheduling reporting of metrics. -- * @return {@code this} -- */ -- public Builder scheduleOn(ScheduledExecutorService executor) { -- this.executor = executor; -- return this; -- } -- -- /** -- * Use the given {@link Clock} instance for the time. -- * -- * @param clock a {@link Clock} instance -- * @return {@code this} -- */ -- public Builder withClock(Clock clock) { -- this.clock = clock; -- return this; -- } -- -- /** -- * Prefix all metric names with the given string. -- * -- * @param prefix the prefix for all metric names -- * @return {@code this} -- */ -- public Builder prefixedWith(String prefix) { -- this.prefix = prefix; -- return this; -- } -- -- /** -- * Convert rates to the given time unit. -- * -- * @param rateUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertRatesTo(TimeUnit rateUnit) { -- this.rateUnit = rateUnit; -- return this; -- } -- -- /** -- * Convert durations to the given time unit. -- * -- * @param durationUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertDurationsTo(TimeUnit durationUnit) { -- this.durationUnit = durationUnit; -- return this; -- } -- -- /** -- * Only report metrics which match the given filter. -- * -- * @param filter a {@link MetricFilter} -- * @return {@code this} -- */ -- public Builder filter(MetricFilter filter) { -- this.filter = filter; -- return this; -- } -- -- /** -- * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). -- * See {@link MetricAttribute}. -- * -- * @param disabledMetricAttributes a set of {@link MetricAttribute} -- * @return {@code this} -- */ -- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -- this.disabledMetricAttributes = disabledMetricAttributes; -- return this; -- } -- -- -- /** -- * Specifies whether or not metric attributes (e.g. "p999", "stddev" or "m15") should be reported in the traditional dot delimited format or in the tag based format. -- * Without tags (default): `my.metric.p99` -- * With tags: `my.metric;metricattribute=p99` -- *

    -- * Note that this setting only modifies the metric attribute, and will not convert any other portion of the metric name to use tags. -- * For mor information on Graphite tag support see https://graphite.readthedocs.io/en/latest/tags.html -- * See {@link MetricAttribute}. -- * -- * @param addMetricAttributesAsTags if true, then metric attributes will be added as tags -- * @return {@code this} -- */ -- public Builder addMetricAttributesAsTags(boolean addMetricAttributesAsTags) { -- this.addMetricAttributesAsTags = addMetricAttributesAsTags; -- return this; -- } -- -- /** -- * Use custom floating point formatter. -- * -- * @param floatingPointFormatter a custom formatter for floating point values -- * @return {@code this} -- */ -- public Builder withFloatingPointFormatter(DoubleFunction floatingPointFormatter) { -- this.floatingPointFormatter = floatingPointFormatter; -- return this; -- } -- -- /** -- * Builds a {@link GraphiteReporter} with the given properties, sending metrics using the -- * given {@link GraphiteSender}. -- *

    -- * Present for binary compatibility -- * -- * @param graphite a {@link Graphite} -- * @return a {@link GraphiteReporter} -- */ -- public GraphiteReporter build(Graphite graphite) { -- return build((GraphiteSender) graphite); -- } -- -- /** -- * Builds a {@link GraphiteReporter} with the given properties, sending metrics using the -- * given {@link GraphiteSender}. -- * -- * @param graphite a {@link GraphiteSender} -- * @return a {@link GraphiteReporter} -- */ -- public GraphiteReporter build(GraphiteSender graphite) { -- return new GraphiteReporter(registry, -- graphite, -- clock, -- prefix, -- rateUnit, -- durationUnit, -- filter, -- executor, -- shutdownExecutorOnStop, -- disabledMetricAttributes, -- addMetricAttributesAsTags, -- floatingPointFormatter); -- } -+ public Builder scheduleOn(ScheduledExecutorService executor) { -+ this.executor = executor; -+ return this; - } - -- private static final Logger LOGGER = LoggerFactory.getLogger(GraphiteReporter.class); -- // the Carbon plaintext format is pretty underspecified, but it seems like it just wants US-formatted digits -- private static final DoubleFunction DEFAULT_FP_FORMATTER = fp -> String.format(Locale.US, "%2.2f", fp); -- -- private final GraphiteSender graphite; -- private final Clock clock; -- private final String prefix; -- private final boolean addMetricAttributesAsTags; -- private final DoubleFunction floatingPointFormatter; -- - /** -- * Creates a new {@link GraphiteReporter} instance. -+ * Use the given {@link Clock} instance for the time. - * -- * @param registry the {@link MetricRegistry} containing the metrics this -- * reporter will report -- * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon server -- * via a transport protocol -- * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default -- * @param prefix the prefix of all metric names (may be null) -- * @param rateUnit the time unit of in which rates will be converted -- * @param durationUnit the time unit of in which durations will be converted -- * @param filter the filter for which metrics to report -- * @param executor the executor to use while scheduling reporting of metrics (may be null). -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- * @param disabledMetricAttributes do not report specific metric attributes -+ * @param clock a {@link Clock} instance -+ * @return {@code this} - */ -- protected GraphiteReporter(MetricRegistry registry, -- GraphiteSender graphite, -- Clock clock, -- String prefix, -- TimeUnit rateUnit, -- TimeUnit durationUnit, -- MetricFilter filter, -- ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop, -- Set disabledMetricAttributes) { -- this(registry, graphite, clock, prefix, rateUnit, durationUnit, filter, executor, shutdownExecutorOnStop, -- disabledMetricAttributes, false); -+ public Builder withClock(Clock clock) { -+ this.clock = clock; -+ return this; - } - -- - /** -- * Creates a new {@link GraphiteReporter} instance. -+ * Prefix all metric names with the given string. - * -- * @param registry the {@link MetricRegistry} containing the metrics this -- * reporter will report -- * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon server -- * via a transport protocol -- * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default -- * @param prefix the prefix of all metric names (may be null) -- * @param rateUnit the time unit of in which rates will be converted -- * @param durationUnit the time unit of in which durations will be converted -- * @param filter the filter for which metrics to report -- * @param executor the executor to use while scheduling reporting of metrics (may be null). -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- * @param disabledMetricAttributes do not report specific metric attributes -- * @param addMetricAttributesAsTags if true, then add metric attributes as tags instead of suffixes -+ * @param prefix the prefix for all metric names -+ * @return {@code this} - */ -- protected GraphiteReporter(MetricRegistry registry, -- GraphiteSender graphite, -- Clock clock, -- String prefix, -- TimeUnit rateUnit, -- TimeUnit durationUnit, -- MetricFilter filter, -- ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop, -- Set disabledMetricAttributes, -- boolean addMetricAttributesAsTags) { -- this(registry, graphite, clock, prefix, rateUnit, durationUnit, filter, executor, shutdownExecutorOnStop, -- disabledMetricAttributes, addMetricAttributesAsTags, DEFAULT_FP_FORMATTER); -+ public Builder prefixedWith(String prefix) { -+ this.prefix = prefix; -+ return this; - } - - /** -- * Creates a new {@link GraphiteReporter} instance. -+ * Convert rates to the given time unit. - * -- * @param registry the {@link MetricRegistry} containing the metrics this -- * reporter will report -- * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon server -- * via a transport protocol -- * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default -- * @param prefix the prefix of all metric names (may be null) -- * @param rateUnit the time unit of in which rates will be converted -- * @param durationUnit the time unit of in which durations will be converted -- * @param filter the filter for which metrics to report -- * @param executor the executor to use while scheduling reporting of metrics (may be null). -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- * @param disabledMetricAttributes do not report specific metric attributes -- * @param addMetricAttributesAsTags if true, then add metric attributes as tags instead of suffixes -- * @param floatingPointFormatter custom floating point formatter -+ * @param rateUnit a unit of time -+ * @return {@code this} - */ -- protected GraphiteReporter(MetricRegistry registry, -- GraphiteSender graphite, -- Clock clock, -- String prefix, -- TimeUnit rateUnit, -- TimeUnit durationUnit, -- MetricFilter filter, -- ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop, -- Set disabledMetricAttributes, -- boolean addMetricAttributesAsTags, -- DoubleFunction floatingPointFormatter) { -- super(registry, "graphite-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, -- disabledMetricAttributes); -- this.graphite = graphite; -- this.clock = clock; -- this.prefix = prefix; -- this.addMetricAttributesAsTags = addMetricAttributesAsTags; -- this.floatingPointFormatter = floatingPointFormatter; -+ public Builder convertRatesTo(TimeUnit rateUnit) { -+ this.rateUnit = rateUnit; -+ return this; - } - -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap> gauges, -- SortedMap counters, -- SortedMap histograms, -- SortedMap meters, -- SortedMap timers) { -- final long timestamp = clock.getTime() / 1000; -- -- // oh it'd be lovely to use Java 7 here -- try { -- graphite.connect(); -- -- for (Map.Entry> entry : gauges.entrySet()) { -- reportGauge(entry.getKey(), entry.getValue(), timestamp); -- } -- -- for (Map.Entry entry : counters.entrySet()) { -- reportCounter(entry.getKey(), entry.getValue(), timestamp); -- } -- -- for (Map.Entry entry : histograms.entrySet()) { -- reportHistogram(entry.getKey(), entry.getValue(), timestamp); -- } -- -- for (Map.Entry entry : meters.entrySet()) { -- reportMetered(entry.getKey(), entry.getValue(), timestamp, false); -- } -- -- for (Map.Entry entry : timers.entrySet()) { -- reportTimer(entry.getKey(), entry.getValue(), timestamp); -- } -- graphite.flush(); -- } catch (IOException e) { -- LOGGER.warn("Unable to report to Graphite", graphite, e); -- } finally { -- try { -- graphite.close(); -- } catch (IOException e1) { -- LOGGER.warn("Error closing Graphite", graphite, e1); -- } -- } -+ /** -+ * Convert durations to the given time unit. -+ * -+ * @param durationUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertDurationsTo(TimeUnit durationUnit) { -+ this.durationUnit = durationUnit; -+ return this; - } - -- @Override -- public void stop() { -- try { -- super.stop(); -- } finally { -- try { -- graphite.close(); -- } catch (IOException e) { -- LOGGER.debug("Error disconnecting from Graphite", graphite, e); -- } -- } -+ /** -+ * Only report metrics which match the given filter. -+ * -+ * @param filter a {@link MetricFilter} -+ * @return {@code this} -+ */ -+ public Builder filter(MetricFilter filter) { -+ this.filter = filter; -+ return this; - } - -- private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { -- final Snapshot snapshot = timer.getSnapshot(); -- sendIfEnabled(MAX, name, convertDuration(snapshot.getMax()), timestamp); -- sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); -- sendIfEnabled(MIN, name, convertDuration(snapshot.getMin()), timestamp); -- sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); -- sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); -- sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); -- sendIfEnabled(P95, name, convertDuration(snapshot.get95thPercentile()), timestamp); -- sendIfEnabled(P98, name, convertDuration(snapshot.get98thPercentile()), timestamp); -- sendIfEnabled(P99, name, convertDuration(snapshot.get99thPercentile()), timestamp); -- sendIfEnabled(P999, name, convertDuration(snapshot.get999thPercentile()), timestamp); -- reportMetered(name, timer, timestamp, true); -+ /** -+ * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). -+ * See {@link MetricAttribute}. -+ * -+ * @param disabledMetricAttributes a set of {@link MetricAttribute} -+ * @return {@code this} -+ */ -+ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -+ this.disabledMetricAttributes = disabledMetricAttributes; -+ return this; - } - -- private void reportMetered(MetricName name, Metered meter, long timestamp, boolean sumIsDuration) throws IOException { -- sendIfEnabled(COUNT, name, meter.getCount(), timestamp); -- sendIfEnabled(SUM, name, sumIsDuration ? convertDuration(meter.getSum()) : meter.getSum(), timestamp); -- sendIfEnabled(M1_RATE, name, convertRate(meter.getOneMinuteRate()), timestamp); -- sendIfEnabled(M5_RATE, name, convertRate(meter.getFiveMinuteRate()), timestamp); -- sendIfEnabled(M15_RATE, name, convertRate(meter.getFifteenMinuteRate()), timestamp); -- sendIfEnabled(MEAN_RATE, name, convertRate(meter.getMeanRate()), timestamp); -+ /** -+ * Specifies whether or not metric attributes (e.g. "p999", "stddev" or "m15") should be -+ * reported in the traditional dot delimited format or in the tag based format. Without tags -+ * (default): `my.metric.p99` With tags: `my.metric;metricattribute=p99` -+ * -+ *

    Note that this setting only modifies the metric attribute, and will not convert any other -+ * portion of the metric name to use tags. For mor information on Graphite tag support see -+ * https://graphite.readthedocs.io/en/latest/tags.html See {@link MetricAttribute}. -+ * -+ * @param addMetricAttributesAsTags if true, then metric attributes will be added as tags -+ * @return {@code this} -+ */ -+ public Builder addMetricAttributesAsTags(boolean addMetricAttributesAsTags) { -+ this.addMetricAttributesAsTags = addMetricAttributesAsTags; -+ return this; - } - -- private void reportHistogram(MetricName name, Histogram histogram, long timestamp) throws IOException { -- final Snapshot snapshot = histogram.getSnapshot(); -- sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); -- sendIfEnabled(SUM, name, histogram.getSum(), timestamp); -- sendIfEnabled(MAX, name, snapshot.getMax(), timestamp); -- sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); -- sendIfEnabled(MIN, name, snapshot.getMin(), timestamp); -- sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); -- sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); -- sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); -- sendIfEnabled(P95, name, snapshot.get95thPercentile(), timestamp); -- sendIfEnabled(P98, name, snapshot.get98thPercentile(), timestamp); -- sendIfEnabled(P99, name, snapshot.get99thPercentile(), timestamp); -- sendIfEnabled(P999, name, snapshot.get999thPercentile(), timestamp); -+ /** -+ * Use custom floating point formatter. -+ * -+ * @param floatingPointFormatter a custom formatter for floating point values -+ * @return {@code this} -+ */ -+ public Builder withFloatingPointFormatter(DoubleFunction floatingPointFormatter) { -+ this.floatingPointFormatter = floatingPointFormatter; -+ return this; - } - -- private void sendIfEnabled(MetricAttribute type, MetricName name, double value, long timestamp) throws IOException { -- if (getDisabledMetricAttributes().contains(type)) { -- return; -- } -- graphite.send(prefix(appendMetricAttribute(name, type.getCode())), format(value), timestamp); -+ /** -+ * Builds a {@link GraphiteReporter} with the given properties, sending metrics using the given -+ * {@link GraphiteSender}. -+ * -+ *

    Present for binary compatibility -+ * -+ * @param graphite a {@link Graphite} -+ * @return a {@link GraphiteReporter} -+ */ -+ public GraphiteReporter build(Graphite graphite) { -+ return build((GraphiteSender) graphite); - } - -- private void sendIfEnabled(MetricAttribute type, MetricName name, long value, long timestamp) throws IOException { -- if (getDisabledMetricAttributes().contains(type)) { -- return; -- } -- graphite.send(prefix(appendMetricAttribute(name, type.getCode())), format(value), timestamp); -+ /** -+ * Builds a {@link GraphiteReporter} with the given properties, sending metrics using the given -+ * {@link GraphiteSender}. -+ * -+ * @param graphite a {@link GraphiteSender} -+ * @return a {@link GraphiteReporter} -+ */ -+ public GraphiteReporter build(GraphiteSender graphite) { -+ return new GraphiteReporter( -+ registry, -+ graphite, -+ clock, -+ prefix, -+ rateUnit, -+ durationUnit, -+ filter, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes, -+ addMetricAttributesAsTags, -+ floatingPointFormatter); - } -- -- private void reportCounter(MetricName name, Counter counter, long timestamp) throws IOException { -- graphite.send(prefix(appendMetricAttribute(name, COUNT.getCode())), format(counter.getCount()), timestamp); -+ } -+ -+ private static final Logger LOG = LoggerFactory.getLogger(GraphiteReporter.class); -+ // the Carbon plaintext format is pretty underspecified, but it seems like it just wants -+ // US-formatted digits -+ private static final DoubleFunction DEFAULT_FP_FORMATTER = -+ fp -> String.format(Locale.US, "%2.2f", fp); -+ -+ private final GraphiteSender graphite; -+ private final Clock clock; -+ private final String prefix; -+ private final boolean addMetricAttributesAsTags; -+ private final DoubleFunction floatingPointFormatter; -+ -+ /** -+ * Creates a new {@link GraphiteReporter} instance. -+ * -+ * @param registry the {@link MetricRegistry} containing the metrics this reporter will report -+ * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon -+ * server via a transport protocol -+ * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default -+ * @param prefix the prefix of all metric names (may be null) -+ * @param rateUnit the time unit of in which rates will be converted -+ * @param durationUnit the time unit of in which durations will be converted -+ * @param filter the filter for which metrics to report -+ * @param executor the executor to use while scheduling reporting of metrics (may be null). -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ * @param disabledMetricAttributes do not report specific metric attributes -+ */ -+ protected GraphiteReporter( -+ MetricRegistry registry, -+ GraphiteSender graphite, -+ Clock clock, -+ String prefix, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ MetricFilter filter, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes) { -+ this( -+ registry, -+ graphite, -+ clock, -+ prefix, -+ rateUnit, -+ durationUnit, -+ filter, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes, -+ false); -+ } -+ -+ /** -+ * Creates a new {@link GraphiteReporter} instance. -+ * -+ * @param registry the {@link MetricRegistry} containing the metrics this reporter will report -+ * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon -+ * server via a transport protocol -+ * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default -+ * @param prefix the prefix of all metric names (may be null) -+ * @param rateUnit the time unit of in which rates will be converted -+ * @param durationUnit the time unit of in which durations will be converted -+ * @param filter the filter for which metrics to report -+ * @param executor the executor to use while scheduling reporting of metrics (may be null). -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ * @param disabledMetricAttributes do not report specific metric attributes -+ * @param addMetricAttributesAsTags if true, then add metric attributes as tags instead of -+ * suffixes -+ */ -+ protected GraphiteReporter( -+ MetricRegistry registry, -+ GraphiteSender graphite, -+ Clock clock, -+ String prefix, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ MetricFilter filter, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes, -+ boolean addMetricAttributesAsTags) { -+ this( -+ registry, -+ graphite, -+ clock, -+ prefix, -+ rateUnit, -+ durationUnit, -+ filter, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes, -+ addMetricAttributesAsTags, -+ DEFAULT_FP_FORMATTER); -+ } -+ -+ /** -+ * Creates a new {@link GraphiteReporter} instance. -+ * -+ * @param registry the {@link MetricRegistry} containing the metrics this reporter will report -+ * @param graphite the {@link GraphiteSender} which is responsible for sending metrics to a Carbon -+ * server via a transport protocol -+ * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default -+ * @param prefix the prefix of all metric names (may be null) -+ * @param rateUnit the time unit of in which rates will be converted -+ * @param durationUnit the time unit of in which durations will be converted -+ * @param filter the filter for which metrics to report -+ * @param executor the executor to use while scheduling reporting of metrics (may be null). -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ * @param disabledMetricAttributes do not report specific metric attributes -+ * @param addMetricAttributesAsTags if true, then add metric attributes as tags instead of -+ * suffixes -+ * @param floatingPointFormatter custom floating point formatter -+ */ -+ protected GraphiteReporter( -+ MetricRegistry registry, -+ GraphiteSender graphite, -+ Clock clock, -+ String prefix, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ MetricFilter filter, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes, -+ boolean addMetricAttributesAsTags, -+ DoubleFunction floatingPointFormatter) { -+ super( -+ registry, -+ "graphite-reporter", -+ filter, -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes); -+ this.graphite = graphite; -+ this.clock = clock; -+ this.prefix = prefix; -+ this.addMetricAttributesAsTags = addMetricAttributesAsTags; -+ this.floatingPointFormatter = floatingPointFormatter; -+ } -+ -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap> gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ final long timestamp = clock.getTime() / 1000; -+ -+ // oh it'd be lovely to use Java 7 here -+ try { -+ graphite.connect(); -+ -+ for (Map.Entry> entry : gauges.entrySet()) { -+ reportGauge(entry.getKey(), entry.getValue(), timestamp); -+ } -+ -+ for (Map.Entry entry : counters.entrySet()) { -+ reportCounter(entry.getKey(), entry.getValue(), timestamp); -+ } -+ -+ for (Map.Entry entry : histograms.entrySet()) { -+ reportHistogram(entry.getKey(), entry.getValue(), timestamp); -+ } -+ -+ for (Map.Entry entry : meters.entrySet()) { -+ reportMetered(entry.getKey(), entry.getValue(), timestamp, false); -+ } -+ -+ for (Map.Entry entry : timers.entrySet()) { -+ reportTimer(entry.getKey(), entry.getValue(), timestamp); -+ } -+ graphite.flush(); -+ } catch (IOException e) { -+ LOG.warn("Unable to report to Graphite", graphite, e); -+ } finally { -+ try { -+ graphite.close(); -+ } catch (IOException e1) { -+ LOG.warn("Error closing Graphite", graphite, e1); -+ } - } -- -- private void reportGauge(MetricName name, Gauge gauge, long timestamp) throws IOException { -- final String value = format(gauge.getValue()); -- if (value != null) { -- graphite.send(prefix(name.getKey()), value, timestamp); -- } -+ } -+ -+ @Override -+ public void stop() { -+ try { -+ super.stop(); -+ } finally { -+ try { -+ graphite.close(); -+ } catch (IOException e) { -+ LOG.debug("Error disconnecting from Graphite", graphite, e); -+ } - } -- -- private String format(Object o) { -- if (o instanceof Float) { -- return format(((Float) o).doubleValue()); -- } else if (o instanceof Double) { -- return format(((Double) o).doubleValue()); -- } else if (o instanceof Byte) { -- return format(((Byte) o).longValue()); -- } else if (o instanceof Short) { -- return format(((Short) o).longValue()); -- } else if (o instanceof Integer) { -- return format(((Integer) o).longValue()); -- } else if (o instanceof Long) { -- return format(((Long) o).longValue()); -- } else if (o instanceof Number) { -- return format(((Number) o).doubleValue()); -- } else if (o instanceof Boolean) { -- return format(((Boolean) o) ? 1 : 0); -- } -- return null; -+ } -+ -+ private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { -+ final Snapshot snapshot = timer.getSnapshot(); -+ sendIfEnabled(MetricAttribute.MAX, name, convertDuration(snapshot.getMax()), timestamp); -+ sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); -+ sendIfEnabled(MetricAttribute.MIN, name, convertDuration(snapshot.getMin()), timestamp); -+ sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); -+ sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); -+ sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); -+ sendIfEnabled(P95, name, convertDuration(snapshot.get95thPercentile()), timestamp); -+ sendIfEnabled(P98, name, convertDuration(snapshot.get98thPercentile()), timestamp); -+ sendIfEnabled(P99, name, convertDuration(snapshot.get99thPercentile()), timestamp); -+ sendIfEnabled(P999, name, convertDuration(snapshot.get999thPercentile()), timestamp); -+ reportMetered(name, timer, timestamp, true); -+ } -+ -+ private void reportMetered(MetricName name, Metered meter, long timestamp, boolean sumIsDuration) -+ throws IOException { -+ sendIfEnabled(COUNT, name, meter.getCount(), timestamp); -+ sendIfEnabled( -+ SUM, name, sumIsDuration ? convertDuration(meter.getSum()) : meter.getSum(), timestamp); -+ sendIfEnabled(M1_RATE, name, convertRate(meter.getOneMinuteRate()), timestamp); -+ sendIfEnabled(M5_RATE, name, convertRate(meter.getFiveMinuteRate()), timestamp); -+ sendIfEnabled(M15_RATE, name, convertRate(meter.getFifteenMinuteRate()), timestamp); -+ sendIfEnabled(MEAN_RATE, name, convertRate(meter.getMeanRate()), timestamp); -+ } -+ -+ private void reportHistogram(MetricName name, Histogram histogram, long timestamp) -+ throws IOException { -+ final Snapshot snapshot = histogram.getSnapshot(); -+ sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); -+ sendIfEnabled(SUM, name, histogram.getSum(), timestamp); -+ sendIfEnabled(MetricAttribute.MAX, name, snapshot.getMax(), timestamp); -+ sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); -+ sendIfEnabled(MetricAttribute.MIN, name, snapshot.getMin(), timestamp); -+ sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); -+ sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); -+ sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); -+ sendIfEnabled(P95, name, snapshot.get95thPercentile(), timestamp); -+ sendIfEnabled(P98, name, snapshot.get98thPercentile(), timestamp); -+ sendIfEnabled(P99, name, snapshot.get99thPercentile(), timestamp); -+ sendIfEnabled(P999, name, snapshot.get999thPercentile(), timestamp); -+ } -+ -+ private void sendIfEnabled(MetricAttribute type, MetricName name, double value, long timestamp) -+ throws IOException { -+ if (getDisabledMetricAttributes().contains(type)) { -+ return; - } -+ graphite.send(prefix(appendMetricAttribute(name, type.getCode())), format(value), timestamp); -+ } - -- private String prefix(String name) { -- return prefix + "." + name; -+ private void sendIfEnabled(MetricAttribute type, MetricName name, long value, long timestamp) -+ throws IOException { -+ if (getDisabledMetricAttributes().contains(type)) { -+ return; - } -- -- private String appendMetricAttribute(MetricName name, String metricAttribute) { -- if (addMetricAttributesAsTags) { -- return name.getKey() + ";metricattribute=" + metricAttribute; -- } -- return name.getKey() + "." + metricAttribute; -+ graphite.send(prefix(appendMetricAttribute(name, type.getCode())), format(value), timestamp); -+ } -+ -+ private void reportCounter(MetricName name, Counter counter, long timestamp) throws IOException { -+ graphite.send( -+ prefix(appendMetricAttribute(name, COUNT.getCode())), -+ format(counter.getCount()), -+ timestamp); -+ } -+ -+ private void reportGauge(MetricName name, Gauge gauge, long timestamp) throws IOException { -+ final String value = format(gauge.getValue()); -+ if (value != null) { -+ graphite.send(prefix(name.getKey()), value, timestamp); - } -- -- private String format(long n) { -- return Long.toString(n); -+ } -+ -+ private String format(Object o) { -+ if (o instanceof Float) { -+ return format(((Float) o).doubleValue()); -+ } else if (o instanceof Double) { -+ return format(((Double) o).doubleValue()); -+ } else if (o instanceof Byte) { -+ return format(((Byte) o).longValue()); -+ } else if (o instanceof Short) { -+ return format(((Short) o).longValue()); -+ } else if (o instanceof Integer) { -+ return format(((Integer) o).longValue()); -+ } else if (o instanceof Long) { -+ return format(((Long) o).longValue()); -+ } else if (o instanceof Number) { -+ return format(((Number) o).doubleValue()); -+ } else if (o instanceof Boolean) { -+ return format(((Boolean) o) ? 1 : 0); - } -+ return null; -+ } -+ -+ private String prefix(String name) { -+ return prefix + "." + name; -+ } - -- protected String format(double v) { -- return floatingPointFormatter.apply(v); -+ private String appendMetricAttribute(MetricName name, String metricAttribute) { -+ if (addMetricAttributesAsTags) { -+ return name.getKey() + ";metricattribute=" + metricAttribute; - } -+ return name.getKey() + "." + metricAttribute; -+ } -+ -+ private String format(long n) { -+ return Long.toString(n); -+ } -+ -+ protected String format(double v) { -+ return floatingPointFormatter.apply(v); -+ } - } ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteSanitize.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteSanitize.java -@@ -4,13 +4,11 @@ import java.util.regex.Pattern; - - class GraphiteSanitize { - -- private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); -- private static final String DASH = "-"; -+ private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); -+ private static final String DASH = "-"; - -- /** -- * Trims the string and replaces all whitespace characters with the provided symbol -- */ -- static String sanitize(String string) { -- return WHITESPACE.matcher(string.trim()).replaceAll(DASH); -- } -+ /** Trims the string and replaces all whitespace characters with the provided symbol */ -+ static String sanitize(String string) { -+ return WHITESPACE.matcher(string.trim()).replaceAll(DASH); -+ } - } ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteSender.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteSender.java -@@ -5,41 +5,38 @@ import java.io.IOException; - - public interface GraphiteSender extends Closeable { - -- /** -- * Connects to the server. -- * -- * @throws IllegalStateException if the client is already connected -- * @throws IOException if there is an error connecting -- */ -- void connect() throws IllegalStateException, IOException; -- -- /** -- * Sends the given measurement to the server. -- * -- * @param name the name of the metric -- * @param value the value of the metric -- * @param timestamp the timestamp of the metric -- * @throws IOException if there was an error sending the metric -- */ -- void send(String name, String value, long timestamp) throws IOException; -- -- /** -- * Flushes buffer, if applicable -- * -- * @throws IOException if there was an error during flushing metrics to the socket -- */ -- void flush() throws IOException; -- -- /** -- * Returns true if ready to send data -- */ -- boolean isConnected(); -- -- /** -- * Returns the number of failed writes to the server. -- * -- * @return the number of failed writes to the server -- */ -- int getFailures(); -- --} -\ No newline at end of file -+ /** -+ * Connects to the server. -+ * -+ * @throws IllegalStateException if the client is already connected -+ * @throws IOException if there is an error connecting -+ */ -+ void connect() throws IllegalStateException, IOException; -+ -+ /** -+ * Sends the given measurement to the server. -+ * -+ * @param name the name of the metric -+ * @param value the value of the metric -+ * @param timestamp the timestamp of the metric -+ * @throws IOException if there was an error sending the metric -+ */ -+ void send(String name, String value, long timestamp) throws IOException; -+ -+ /** -+ * Flushes buffer, if applicable -+ * -+ * @throws IOException if there was an error during flushing metrics to the socket -+ */ -+ void flush() throws IOException; -+ -+ /** Returns true if ready to send data */ -+ boolean isConnected(); -+ -+ /** -+ * Returns the number of failed writes to the server. -+ * -+ * @return the number of failed writes to the server -+ */ -+ int getFailures(); -+} ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java -@@ -1,118 +1,115 @@ - package io.dropwizard.metrics5.graphite; - -+import static com.google.common.base.Preconditions.checkState; -+import static java.nio.charset.StandardCharsets.UTF_8; -+ - import java.io.IOException; --import java.net.InetSocketAddress; - import java.net.InetAddress; -+import java.net.InetSocketAddress; - import java.nio.ByteBuffer; - import java.nio.channels.DatagramChannel; - --import static java.nio.charset.StandardCharsets.UTF_8; -- --/** -- * A client to a Carbon server using unconnected UDP -- */ -+/** A client to a Carbon server using unconnected UDP */ - public class GraphiteUDP implements GraphiteSender { - -- private final String hostname; -- private final int port; -- private InetSocketAddress address; -- -- private DatagramChannel datagramChannel = null; -- private int failures; -- -- /** -- * Creates a new client which sends data to given address using UDP -- * -- * @param hostname The hostname of the Carbon server -- * @param port The port of the Carbon server -- */ -- public GraphiteUDP(String hostname, int port) { -- this.hostname = hostname; -- this.port = port; -- this.address = null; -- } -- -- /** -- * Creates a new client which sends data to given address using UDP -- * -- * @param address the address of the Carbon server -- */ -- public GraphiteUDP(InetSocketAddress address) { -- this.hostname = null; -- this.port = -1; -- this.address = address; -- } -- -- @Override -- public void connect() throws IllegalStateException, IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -- -- // Resolve hostname -- if (hostname != null) { -- address = new InetSocketAddress(InetAddress.getByName(hostname), port); -- } -- -- datagramChannel = DatagramChannel.open(); -+ private final String hostname; -+ private final int port; -+ private InetSocketAddress address; -+ -+ private DatagramChannel datagramChannel = null; -+ private int failures; -+ -+ /** -+ * Creates a new client which sends data to given address using UDP -+ * -+ * @param hostname The hostname of the Carbon server -+ * @param port The port of the Carbon server -+ */ -+ public GraphiteUDP(String hostname, int port) { -+ this.hostname = hostname; -+ this.port = port; -+ this.address = null; -+ } -+ -+ /** -+ * Creates a new client which sends data to given address using UDP -+ * -+ * @param address the address of the Carbon server -+ */ -+ public GraphiteUDP(InetSocketAddress address) { -+ this.hostname = null; -+ this.port = -1; -+ this.address = address; -+ } -+ -+ @Override -+ public void connect() throws IllegalStateException, IOException { -+ checkState(!isConnected(), "Already connected"); -+ -+ // Resolve hostname -+ if (hostname != null) { -+ address = new InetSocketAddress(InetAddress.getByName(hostname), port); - } - -- @Override -- public boolean isConnected() { -- return datagramChannel != null && !datagramChannel.socket().isClosed(); -+ datagramChannel = DatagramChannel.open(); -+ } -+ -+ @Override -+ public boolean isConnected() { -+ return datagramChannel != null && !datagramChannel.socket().isClosed(); -+ } -+ -+ @Override -+ public void send(String name, String value, long timestamp) throws IOException { -+ try { -+ String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n'; -+ ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); -+ datagramChannel.send(byteBuffer, address); -+ this.failures = 0; -+ } catch (IOException e) { -+ failures++; -+ throw e; - } -- -- @Override -- public void send(String name, String value, long timestamp) throws IOException { -- try { -- String str = sanitize(name) + ' ' + sanitize(value) + ' ' + Long.toString(timestamp) + '\n'; -- ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); -- datagramChannel.send(byteBuffer, address); -- this.failures = 0; -- } catch (IOException e) { -- failures++; -- throw e; -- } -- } -- -- @Override -- public int getFailures() { -- return failures; -- } -- -- @Override -- public void flush() throws IOException { -- // Nothing to do -- } -- -- @Override -- public void close() throws IOException { -- if (datagramChannel != null) { -- try { -- datagramChannel.close(); -- } finally { -- datagramChannel = null; -- } -- } -+ } -+ -+ @Override -+ public int getFailures() { -+ return failures; -+ } -+ -+ @Override -+ public void flush() throws IOException { -+ // Nothing to do -+ } -+ -+ @Override -+ public void close() throws IOException { -+ if (datagramChannel != null) { -+ try { -+ datagramChannel.close(); -+ } finally { -+ datagramChannel = null; -+ } - } -+ } - -- protected String sanitize(String s) { -- return GraphiteSanitize.sanitize(s); -- } -+ protected String sanitize(String s) { -+ return GraphiteSanitize.sanitize(s); -+ } - -- DatagramChannel getDatagramChannel() { -- return datagramChannel; -- } -+ DatagramChannel getDatagramChannel() { -+ return datagramChannel; -+ } - -- void setDatagramChannel(DatagramChannel datagramChannel) { -- this.datagramChannel = datagramChannel; -- } -+ void setDatagramChannel(DatagramChannel datagramChannel) { -+ this.datagramChannel = datagramChannel; -+ } - -- InetSocketAddress getAddress() { -- return address; -- } -+ InetSocketAddress getAddress() { -+ return address; -+ } - -- void setAddress(InetSocketAddress address) { -- this.address = address; -- } -+ void setAddress(InetSocketAddress address) { -+ this.address = address; -+ } - } ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java -@@ -1,9 +1,7 @@ - package io.dropwizard.metrics5.graphite; - --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -- --import javax.net.SocketFactory; -+import static com.google.common.base.Preconditions.checkState; -+import static java.nio.charset.StandardCharsets.UTF_8; - - import java.io.BufferedWriter; - import java.io.ByteArrayOutputStream; -@@ -18,320 +16,320 @@ import java.nio.ByteBuffer; - import java.nio.charset.Charset; - import java.util.ArrayList; - import java.util.List; -- --import static java.nio.charset.StandardCharsets.UTF_8; -+import javax.net.SocketFactory; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; - - /** -- * A client to a Carbon server that sends all metrics after they have been pickled in configurable sized batches -+ * A client to a Carbon server that sends all metrics after they have been pickled in configurable -+ * sized batches - */ - public class PickledGraphite implements GraphiteSender { - -- static class MetricTuple { -- String name; -- long timestamp; -- String value; -+ static class MetricTuple { -+ String name; -+ long timestamp; -+ String value; - -- MetricTuple(String name, long timestamp, String value) { -- this.name = name; -- this.timestamp = timestamp; -- this.value = value; -- } -+ MetricTuple(String name, long timestamp, String value) { -+ this.name = name; -+ this.timestamp = timestamp; -+ this.value = value; - } -- -- /** -- * Minimally necessary pickle opcodes. -- */ -- private static final char -- MARK = '(', -- STOP = '.', -- LONG = 'L', -- STRING = 'S', -- APPEND = 'a', -- LIST = 'l', -- TUPLE = 't', -- QUOTE = '\'', -- LF = '\n'; -- -- private static final Logger LOGGER = LoggerFactory.getLogger(PickledGraphite.class); -- private final static int DEFAULT_BATCH_SIZE = 100; -- -- private int batchSize; -- // graphite expects a python-pickled list of nested tuples. -- private List metrics = new ArrayList<>(); -- -- private final String hostname; -- private final int port; -- private final InetSocketAddress address; -- private final SocketFactory socketFactory; -- private final Charset charset; -- -- private Socket socket; -- private Writer writer; -- private int failures; -- -- /** -- * Creates a new client which connects to the given address using the default {@link SocketFactory}. This defaults -- * to a batchSize of 100 -- * -- * @param address the address of the Carbon server -- */ -- public PickledGraphite(InetSocketAddress address) { -- this(address, DEFAULT_BATCH_SIZE); -+ } -+ -+ /** Minimally necessary pickle opcodes. */ -+ private static final char MARK = '(', -+ STOP = '.', -+ LONG = 'L', -+ STRING = 'S', -+ APPEND = 'a', -+ LIST = 'l', -+ TUPLE = 't', -+ QUOTE = '\'', -+ LF = '\n'; -+ -+ private static final Logger LOG = LoggerFactory.getLogger(PickledGraphite.class); -+ private static final int DEFAULT_BATCH_SIZE = 100; -+ -+ private int batchSize; -+ // graphite expects a python-pickled list of nested tuples. -+ private List metrics = new ArrayList<>(); -+ -+ private final String hostname; -+ private final int port; -+ private final InetSocketAddress address; -+ private final SocketFactory socketFactory; -+ private final Charset charset; -+ -+ private Socket socket; -+ private Writer writer; -+ private int failures; -+ -+ /** -+ * Creates a new client which connects to the given address using the default {@link -+ * SocketFactory}. This defaults to a batchSize of 100 -+ * -+ * @param address the address of the Carbon server -+ */ -+ public PickledGraphite(InetSocketAddress address) { -+ this(address, DEFAULT_BATCH_SIZE); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address using the default {@link -+ * SocketFactory}. -+ * -+ * @param address the address of the Carbon server -+ * @param batchSize how many metrics are bundled into a single pickle request to graphite -+ */ -+ public PickledGraphite(InetSocketAddress address, int batchSize) { -+ this(address, SocketFactory.getDefault(), batchSize); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address and socket factory. -+ * -+ * @param address the address of the Carbon server -+ * @param socketFactory the socket factory -+ * @param batchSize how many metrics are bundled into a single pickle request to graphite -+ */ -+ public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, int batchSize) { -+ this(address, socketFactory, UTF_8, batchSize); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address and socket factory using the given -+ * character set. -+ * -+ * @param address the address of the Carbon server -+ * @param socketFactory the socket factory -+ * @param charset the character set used by the server -+ * @param batchSize how many metrics are bundled into a single pickle request to graphite -+ */ -+ public PickledGraphite( -+ InetSocketAddress address, SocketFactory socketFactory, Charset charset, int batchSize) { -+ this.address = address; -+ this.hostname = null; -+ this.port = -1; -+ this.socketFactory = socketFactory; -+ this.charset = charset; -+ this.batchSize = batchSize; -+ } -+ -+ /** -+ * Creates a new client which connects to the given address using the default {@link -+ * SocketFactory}. This defaults to a batchSize of 100 -+ * -+ * @param hostname the hostname of the Carbon server -+ * @param port the port of the Carbon server -+ */ -+ public PickledGraphite(String hostname, int port) { -+ this(hostname, port, DEFAULT_BATCH_SIZE); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address using the default {@link -+ * SocketFactory}. -+ * -+ * @param hostname the hostname of the Carbon server -+ * @param port the port of the Carbon server -+ * @param batchSize how many metrics are bundled into a single pickle request to graphite -+ */ -+ public PickledGraphite(String hostname, int port, int batchSize) { -+ this(hostname, port, SocketFactory.getDefault(), batchSize); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address and socket factory. -+ * -+ * @param hostname the hostname of the Carbon server -+ * @param port the port of the Carbon server -+ * @param socketFactory the socket factory -+ * @param batchSize how many metrics are bundled into a single pickle request to graphite -+ */ -+ public PickledGraphite(String hostname, int port, SocketFactory socketFactory, int batchSize) { -+ this(hostname, port, socketFactory, UTF_8, batchSize); -+ } -+ -+ /** -+ * Creates a new client which connects to the given address and socket factory using the given -+ * character set. -+ * -+ * @param hostname the hostname of the Carbon server -+ * @param port the port of the Carbon server -+ * @param socketFactory the socket factory -+ * @param charset the character set used by the server -+ * @param batchSize how many metrics are bundled into a single pickle request to graphite -+ */ -+ public PickledGraphite( -+ String hostname, int port, SocketFactory socketFactory, Charset charset, int batchSize) { -+ this.address = null; -+ this.hostname = hostname; -+ this.port = port; -+ this.socketFactory = socketFactory; -+ this.charset = charset; -+ this.batchSize = batchSize; -+ } -+ -+ @Override -+ public void connect() throws IllegalStateException, IOException { -+ checkState(!isConnected(), "Already connected"); -+ InetSocketAddress address = this.address; -+ if (address == null) { -+ address = new InetSocketAddress(hostname, port); - } -- -- /** -- * Creates a new client which connects to the given address using the default {@link SocketFactory}. -- * -- * @param address the address of the Carbon server -- * @param batchSize how many metrics are bundled into a single pickle request to graphite -- */ -- public PickledGraphite(InetSocketAddress address, int batchSize) { -- this(address, SocketFactory.getDefault(), batchSize); -- } -- -- /** -- * Creates a new client which connects to the given address and socket factory. -- * -- * @param address the address of the Carbon server -- * @param socketFactory the socket factory -- * @param batchSize how many metrics are bundled into a single pickle request to graphite -- */ -- public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, int batchSize) { -- this(address, socketFactory, UTF_8, batchSize); -+ if (address.getAddress() == null) { -+ throw new UnknownHostException(address.getHostName()); - } - -- /** -- * Creates a new client which connects to the given address and socket factory using the given character set. -- * -- * @param address the address of the Carbon server -- * @param socketFactory the socket factory -- * @param charset the character set used by the server -- * @param batchSize how many metrics are bundled into a single pickle request to graphite -- */ -- public PickledGraphite(InetSocketAddress address, SocketFactory socketFactory, Charset charset, int batchSize) { -- this.address = address; -- this.hostname = null; -- this.port = -1; -- this.socketFactory = socketFactory; -- this.charset = charset; -- this.batchSize = batchSize; -+ this.socket = socketFactory.createSocket(address.getAddress(), address.getPort()); -+ this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); -+ } -+ -+ @Override -+ public boolean isConnected() { -+ return socket != null && socket.isConnected() && !socket.isClosed(); -+ } -+ -+ /** -+ * Convert the metric to a python tuple of the form: -+ * -+ *

    (timestamp, (name, value)) -+ * -+ *

    And add it to the list of metrics. If we reach the batch size, write them out. -+ * -+ * @param name the name of the metric -+ * @param value the value of the metric -+ * @param timestamp the timestamp of the metric -+ * @throws IOException if there was an error sending the metric -+ */ -+ @Override -+ public void send(String name, String value, long timestamp) throws IOException { -+ metrics.add(new MetricTuple(sanitize(name), timestamp, sanitize(value))); -+ -+ if (metrics.size() >= batchSize) { -+ writeMetrics(); - } -+ } - -- /** -- * Creates a new client which connects to the given address using the default {@link SocketFactory}. This defaults -- * to a batchSize of 100 -- * -- * @param hostname the hostname of the Carbon server -- * @param port the port of the Carbon server -- */ -- public PickledGraphite(String hostname, int port) { -- this(hostname, port, DEFAULT_BATCH_SIZE); -+ @Override -+ public void flush() throws IOException { -+ writeMetrics(); -+ if (writer != null) { -+ writer.flush(); - } -- -- /** -- * Creates a new client which connects to the given address using the default {@link SocketFactory}. -- * -- * @param hostname the hostname of the Carbon server -- * @param port the port of the Carbon server -- * @param batchSize how many metrics are bundled into a single pickle request to graphite -- */ -- public PickledGraphite(String hostname, int port, int batchSize) { -- this(hostname, port, SocketFactory.getDefault(), batchSize); -- } -- -- /** -- * Creates a new client which connects to the given address and socket factory. -- * -- * @param hostname the hostname of the Carbon server -- * @param port the port of the Carbon server -- * @param socketFactory the socket factory -- * @param batchSize how many metrics are bundled into a single pickle request to graphite -- */ -- public PickledGraphite(String hostname, int port, SocketFactory socketFactory, int batchSize) { -- this(hostname, port, socketFactory, UTF_8, batchSize); -+ } -+ -+ @Override -+ public void close() throws IOException { -+ try { -+ flush(); -+ if (writer != null) { -+ writer.close(); -+ } -+ } catch (IOException ex) { -+ if (socket != null) { -+ socket.close(); -+ } -+ } finally { -+ this.socket = null; -+ this.writer = null; - } -- -- /** -- * Creates a new client which connects to the given address and socket factory using the given character set. -- * -- * @param hostname the hostname of the Carbon server -- * @param port the port of the Carbon server -- * @param socketFactory the socket factory -- * @param charset the character set used by the server -- * @param batchSize how many metrics are bundled into a single pickle request to graphite -- */ -- public PickledGraphite(String hostname, int port, SocketFactory socketFactory, Charset charset, int batchSize) { -- this.address = null; -- this.hostname = hostname; -- this.port = port; -- this.socketFactory = socketFactory; -- this.charset = charset; -- this.batchSize = batchSize; -- } -- -- @Override -- public void connect() throws IllegalStateException, IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -- InetSocketAddress address = this.address; -- if (address == null) { -- address = new InetSocketAddress(hostname, port); -- } -- if (address.getAddress() == null) { -- throw new UnknownHostException(address.getHostName()); -- } -- -- this.socket = socketFactory.createSocket(address.getAddress(), address.getPort()); -- this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)); -- } -- -- @Override -- public boolean isConnected() { -- return socket != null && socket.isConnected() && !socket.isClosed(); -- } -- -- /** -- * Convert the metric to a python tuple of the form: -- *

    -- * (timestamp, (name, value)) -- *

    -- * And add it to the list of metrics. If we reach the batch size, write them out. -- * -- * @param name the name of the metric -- * @param value the value of the metric -- * @param timestamp the timestamp of the metric -- * @throws IOException if there was an error sending the metric -- */ -- @Override -- public void send(String name, String value, long timestamp) throws IOException { -- metrics.add(new MetricTuple(sanitize(name), timestamp, sanitize(value))); -- -- if (metrics.size() >= batchSize) { -- writeMetrics(); -- } -- } -- -- @Override -- public void flush() throws IOException { -- writeMetrics(); -- if (writer != null) { -- writer.flush(); -- } -- } -- -- @Override -- public void close() throws IOException { -- try { -- flush(); -- if (writer != null) { -- writer.close(); -- } -- } catch (IOException ex) { -- if (socket != null) { -- socket.close(); -- } -- } finally { -- this.socket = null; -- this.writer = null; -+ } -+ -+ @Override -+ public int getFailures() { -+ return failures; -+ } -+ -+ /** -+ * 1. Run the pickler script to package all the pending metrics into a single message 2. Send the -+ * message to graphite 3. Clear out the list of metrics -+ */ -+ private void writeMetrics() throws IOException { -+ if (!metrics.isEmpty()) { -+ try { -+ byte[] payload = pickleMetrics(metrics); -+ byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); -+ -+ @SuppressWarnings("resource") -+ OutputStream outputStream = socket.getOutputStream(); -+ outputStream.write(header); -+ outputStream.write(payload); -+ outputStream.flush(); -+ -+ if (LOG.isDebugEnabled()) { -+ LOG.debug("Wrote {} metrics", metrics.size()); - } -+ } catch (IOException e) { -+ this.failures++; -+ throw e; -+ } finally { -+ // if there was an error, we might miss some data. for now, drop those on the floor and -+ // try to keep going. -+ metrics.clear(); -+ } - } -- -- @Override -- public int getFailures() { -- return failures; -+ } -+ -+ /** -+ * See: http://readthedocs.org/docs/graphite/en/1.0/feeding-carbon.html -+ * -+ * @throws IOException shouldn't happen because we write to memory. -+ */ -+ byte[] pickleMetrics(List metrics) throws IOException { -+ // Extremely rough estimate of 75 bytes per message -+ ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75); -+ Writer pickled = new OutputStreamWriter(out, charset); -+ -+ pickled.append(MARK); -+ pickled.append(LIST); -+ -+ for (MetricTuple tuple : metrics) { -+ // start the outer tuple -+ pickled.append(MARK); -+ -+ // the metric name is a string. -+ pickled.append(STRING); -+ // the single quotes are to match python's repr("abcd") -+ pickled.append(QUOTE); -+ pickled.append(tuple.name); -+ pickled.append(QUOTE); -+ pickled.append(LF); -+ -+ // start the inner tuple -+ pickled.append(MARK); -+ -+ // timestamp is a long -+ pickled.append(LONG); -+ pickled.append(Long.toString(tuple.timestamp)); -+ // the trailing L is to match python's repr(long(1234)) -+ pickled.append(LONG); -+ pickled.append(LF); -+ -+ // and the value is a string. -+ pickled.append(STRING); -+ pickled.append(QUOTE); -+ pickled.append(tuple.value); -+ pickled.append(QUOTE); -+ pickled.append(LF); -+ -+ pickled.append(TUPLE); // inner close -+ pickled.append(TUPLE); // outer close -+ -+ pickled.append(APPEND); - } - -- /** -- * 1. Run the pickler script to package all the pending metrics into a single message -- * 2. Send the message to graphite -- * 3. Clear out the list of metrics -- */ -- private void writeMetrics() throws IOException { -- if (metrics.size() > 0) { -- try { -- byte[] payload = pickleMetrics(metrics); -- byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); -- -- @SuppressWarnings("resource") -- OutputStream outputStream = socket.getOutputStream(); -- outputStream.write(header); -- outputStream.write(payload); -- outputStream.flush(); -- -- if (LOGGER.isDebugEnabled()) { -- LOGGER.debug("Wrote {} metrics", metrics.size()); -- } -- } catch (IOException e) { -- this.failures++; -- throw e; -- } finally { -- // if there was an error, we might miss some data. for now, drop those on the floor and -- // try to keep going. -- metrics.clear(); -- } -- -- } -- } -+ // every pickle ends with STOP -+ pickled.append(STOP); - -- /** -- * See: http://readthedocs.org/docs/graphite/en/1.0/feeding-carbon.html -- * -- * @throws IOException shouldn't happen because we write to memory. -- */ -- byte[] pickleMetrics(List metrics) throws IOException { -- // Extremely rough estimate of 75 bytes per message -- ByteArrayOutputStream out = new ByteArrayOutputStream(metrics.size() * 75); -- Writer pickled = new OutputStreamWriter(out, charset); -- -- pickled.append(MARK); -- pickled.append(LIST); -- -- for (MetricTuple tuple : metrics) { -- // start the outer tuple -- pickled.append(MARK); -- -- // the metric name is a string. -- pickled.append(STRING); -- // the single quotes are to match python's repr("abcd") -- pickled.append(QUOTE); -- pickled.append(tuple.name); -- pickled.append(QUOTE); -- pickled.append(LF); -- -- // start the inner tuple -- pickled.append(MARK); -- -- // timestamp is a long -- pickled.append(LONG); -- pickled.append(Long.toString(tuple.timestamp)); -- // the trailing L is to match python's repr(long(1234)) -- pickled.append(LONG); -- pickled.append(LF); -- -- // and the value is a string. -- pickled.append(STRING); -- pickled.append(QUOTE); -- pickled.append(tuple.value); -- pickled.append(QUOTE); -- pickled.append(LF); -- -- pickled.append(TUPLE); // inner close -- pickled.append(TUPLE); // outer close -- -- pickled.append(APPEND); -- } -+ pickled.flush(); - -- // every pickle ends with STOP -- pickled.append(STOP); -- -- pickled.flush(); -- -- return out.toByteArray(); -- } -- -- protected String sanitize(String s) { -- return GraphiteSanitize.sanitize(s); -- } -+ return out.toByteArray(); -+ } - -+ protected String sanitize(String s) { -+ return GraphiteSanitize.sanitize(s); -+ } - } ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java -@@ -1,14 +1,5 @@ - package io.dropwizard.metrics5.graphite; - --import com.rabbitmq.client.Channel; --import com.rabbitmq.client.Connection; --import com.rabbitmq.client.ConnectionFactory; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import java.io.IOException; --import java.net.UnknownHostException; -- - import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown; -@@ -17,111 +8,118 @@ import static org.mockito.Mockito.anyString; - import static org.mockito.Mockito.atMost; - import static org.mockito.Mockito.doThrow; - import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - --class GraphiteRabbitMQTest { -- private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); -- private final Connection connection = mock(Connection.class); -- private final Channel channel = mock(Channel.class); -- -- private final ConnectionFactory bogusConnectionFactory = mock(ConnectionFactory.class); -- private final Connection bogusConnection = mock(Connection.class); -- private final Channel bogusChannel = mock(Channel.class); -- -- private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); -- -- @BeforeEach -- void setUp() throws Exception { -- when(connectionFactory.newConnection()).thenReturn(connection); -- when(connection.createChannel()).thenReturn(channel); -- when(connection.isOpen()).thenReturn(true); -- -- when(bogusConnectionFactory.newConnection()).thenReturn(bogusConnection); -- when(bogusConnection.createChannel()).thenReturn(bogusChannel); -- doThrow(new IOException()) -- .when(bogusChannel) -- .basicPublish(anyString(), anyString(), any(), any(byte[].class)); -- } -- -- @Test -- void shouldConnectToGraphiteServer() throws Exception { -- graphite.connect(); -- -- verify(connectionFactory, atMost(1)).newConnection(); -- verify(connection, atMost(1)).createChannel(); -- -- } -+import com.rabbitmq.client.Channel; -+import com.rabbitmq.client.Connection; -+import com.rabbitmq.client.ConnectionFactory; -+import java.io.IOException; -+import java.net.UnknownHostException; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - -- @Test -- void measuresFailures() throws Exception { -- try (final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(bogusConnectionFactory, "graphite")) { -- graphite.connect(); -- try { -- graphite.send("name", "value", 0); -- failBecauseExceptionWasNotThrown(IOException.class); -- } catch (IOException e) { -- assertThat(graphite.getFailures()).isEqualTo(1); -- } -- } -+final class GraphiteRabbitMQTest { -+ private final ConnectionFactory connectionFactory = mock(); -+ private final Connection connection = mock(); -+ private final Channel channel = mock(); -+ -+ private final ConnectionFactory bogusConnectionFactory = mock(); -+ private final Connection bogusConnection = mock(); -+ private final Channel bogusChannel = mock(); -+ -+ private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ when(connectionFactory.newConnection()).thenReturn(connection); -+ when(connection.createChannel()).thenReturn(channel); -+ when(connection.isOpen()).thenReturn(true); -+ -+ when(bogusConnectionFactory.newConnection()).thenReturn(bogusConnection); -+ when(bogusConnection.createChannel()).thenReturn(bogusChannel); -+ doThrow(new IOException()) -+ .when(bogusChannel) -+ .basicPublish(anyString(), anyString(), any(), any(byte[].class)); -+ } -+ -+ @Test -+ void shouldConnectToGraphiteServer() throws Exception { -+ graphite.connect(); -+ -+ verify(connectionFactory, atMost(1)).newConnection(); -+ verify(connection, atMost(1)).createChannel(); -+ } -+ -+ @Test -+ void measuresFailures() throws Exception { -+ try (final GraphiteRabbitMQ graphite = -+ new GraphiteRabbitMQ(bogusConnectionFactory, "graphite")) { -+ graphite.connect(); -+ try { -+ graphite.send("name", "value", 0); -+ failBecauseExceptionWasNotThrown(IOException.class); -+ } catch (IOException e) { -+ assertThat(graphite.getFailures()).isEqualTo(1); -+ } - } -- -- @Test -- void shouldDisconnectsFromGraphiteServer() throws Exception { -- graphite.connect(); -- graphite.close(); -- -- verify(connection).close(); -+ } -+ -+ @Test -+ void shouldDisconnectsFromGraphiteServer() throws Exception { -+ graphite.connect(); -+ graphite.close(); -+ -+ verify(connection).close(); -+ } -+ -+ @Test -+ void shouldNotConnectToGraphiteServerMoreThenOnce() throws Exception { -+ graphite.connect(); -+ try { -+ graphite.connect(); -+ failBecauseExceptionWasNotThrown(IllegalStateException.class); -+ } catch (IllegalStateException e) { -+ assertThat(e.getMessage()).isEqualTo("Already connected"); - } -+ } - -- @Test -- void shouldNotConnectToGraphiteServerMoreThenOnce() throws Exception { -- graphite.connect(); -- try { -- graphite.connect(); -- failBecauseExceptionWasNotThrown(IllegalStateException.class); -- } catch (IllegalStateException e) { -- assertThat(e.getMessage()).isEqualTo("Already connected"); -- } -- } -+ @Test -+ void shouldSendMetricsToGraphiteServer() throws Exception { -+ graphite.connect(); -+ graphite.send("name", "value", 100); - -- @Test -- void shouldSendMetricsToGraphiteServer() throws Exception { -- graphite.connect(); -- graphite.send("name", "value", 100); -+ String expectedMessage = "name value 100\n"; - -- String expectedMessage = "name value 100\n"; -+ verify(channel).basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); - -- verify(channel, times(1)).basicPublish("graphite", "name", null, -- expectedMessage.getBytes(UTF_8)); -+ assertThat(graphite.getFailures()).isEqualTo(0); -+ } - -- assertThat(graphite.getFailures()).isZero(); -- } -+ @Test -+ void shouldSanitizeAndSendMetricsToGraphiteServer() throws Exception { -+ graphite.connect(); -+ graphite.send("name to sanitize", "value to sanitize", 100); - -- @Test -- void shouldSanitizeAndSendMetricsToGraphiteServer() throws Exception { -- graphite.connect(); -- graphite.send("name to sanitize", "value to sanitize", 100); -+ String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; - -- String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; -+ verify(channel) -+ .basicPublish("graphite", "name-to-sanitize", null, expectedMessage.getBytes(UTF_8)); - -- verify(channel, times(1)).basicPublish("graphite", "name-to-sanitize", null, -- expectedMessage.getBytes(UTF_8)); -+ assertThat(graphite.getFailures()).isEqualTo(0); -+ } - -- assertThat(graphite.getFailures()).isZero(); -- } -+ @Test -+ void shouldFailWhenGraphiteHostUnavailable() { -+ ConnectionFactory connectionFactory = new ConnectionFactory(); -+ connectionFactory.setHost("some-unknown-host"); - -- @Test -- void shouldFailWhenGraphiteHostUnavailable() { -- ConnectionFactory connectionFactory = new ConnectionFactory(); -- connectionFactory.setHost("some-unknown-host"); -- -- try (GraphiteRabbitMQ unavailableGraphite = new GraphiteRabbitMQ(connectionFactory, "graphite")) { -- unavailableGraphite.connect(); -- failBecauseExceptionWasNotThrown(UnknownHostException.class); -- } catch (Exception e) { -- assertThat(e.getMessage()).contains("some-unknown-host"); -- } -+ try (GraphiteRabbitMQ unavailableGraphite = -+ new GraphiteRabbitMQ(connectionFactory, "graphite")) { -+ unavailableGraphite.connect(); -+ failBecauseExceptionWasNotThrown(UnknownHostException.class); -+ } catch (Exception e) { -+ assertThat(e.getMessage()).contains("some-unknown-host"); - } -+ } - } ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java -@@ -1,5 +1,14 @@ - package io.dropwizard.metrics5.graphite; - -+import static org.mockito.Mockito.doThrow; -+import static org.mockito.Mockito.inOrder; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.never; -+import static org.mockito.Mockito.times; -+import static org.mockito.Mockito.verifyNoMoreInteractions; -+import static org.mockito.Mockito.when; -+ -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -11,479 +20,411 @@ import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; --import org.mockito.InOrder; -- - import java.net.UnknownHostException; - import java.text.DecimalFormat; - import java.text.DecimalFormatSymbols; --import java.util.Collections; - import java.util.EnumSet; - import java.util.Locale; - import java.util.Set; - import java.util.SortedMap; - import java.util.TreeMap; - import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; -+import org.mockito.InOrder; - --import static org.mockito.Mockito.doThrow; --import static org.mockito.Mockito.inOrder; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; --import static org.mockito.Mockito.verifyNoMoreInteractions; --import static org.mockito.Mockito.when; -- --class GraphiteReporterTest { -- private static final MetricName GAUGE = MetricName.build("gauge"); -- private static final MetricName METER = MetricName.build("meter"); -- private static final MetricName COUNTER = MetricName.build("counter"); -- -- private final long timestamp = 1000198; -- private final Clock clock = mock(Clock.class); -- private final Graphite graphite = mock(Graphite.class); -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final GraphiteReporter reporter = GraphiteReporter.forRegistry(registry) -- .withClock(clock) -- .prefixedWith("prefix") -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -- .build(graphite); -- -- private final GraphiteReporter minuteRateReporter = GraphiteReporter -- .forRegistry(registry) -- .withClock(clock) -- .prefixedWith("prefix") -- .convertRatesTo(TimeUnit.MINUTES) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -- .build(graphite); -- -- @BeforeEach -- void setUp() { -- when(clock.getTime()).thenReturn(timestamp * 1000); -- } -- -- @Test -- void doesNotReportStringGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge("value")), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite, never()).send("prefix.gauge", "value", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsByteGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge((byte) 1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsShortGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge((short) 1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsIntegerGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsLongGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(1L)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsFloatGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(1.1f)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.gauge", "1.10", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsDoubleGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(1.1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.gauge", "1.10", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsDoubleGaugeValuesWithCustomFormat() throws Exception { -- try (final GraphiteReporter graphiteReporter = getReporterWithCustomFormat()) { -- reportGaugeValue(graphiteReporter, 1.13574); -- verifyGraphiteSentCorrectMetricValue("prefix.gauge", "1.1357", timestamp); -- verifyNoMoreInteractions(graphite); -- } -+final class GraphiteReporterTest { -+ private static final MetricName GAUGE = MetricName.build("gauge"); -+ private static final MetricName METER = MetricName.build("meter"); -+ private static final MetricName COUNTER = MetricName.build("counter"); -+ -+ private final long timestamp = 1000198; -+ private final Clock clock = mock(); -+ private final Graphite graphite = mock(); -+ private final MetricRegistry registry = mock(); -+ private final GraphiteReporter reporter = -+ GraphiteReporter.forRegistry(registry) -+ .withClock(clock) -+ .prefixedWith("prefix") -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(ImmutableSet.of()) -+ .build(graphite); -+ -+ private final GraphiteReporter minuteRateReporter = -+ GraphiteReporter.forRegistry(registry) -+ .withClock(clock) -+ .prefixedWith("prefix") -+ .convertRatesTo(TimeUnit.MINUTES) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(ImmutableSet.of()) -+ .build(graphite); -+ -+ @BeforeEach -+ void setUp() { -+ when(clock.getTime()).thenReturn(timestamp * 1000); -+ } -+ -+ @Test -+ void doesNotReportStringGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge("value")), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite, never()).send("prefix.gauge", "value", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsByteGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge((byte) 1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsShortGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge((short) 1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsIntegerGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsLongGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(1L)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsFloatGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(1.1f)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.gauge", "1.10", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsDoubleGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(1.1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.gauge", "1.10", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsDoubleGaugeValuesWithCustomFormat() throws Exception { -+ try (final GraphiteReporter graphiteReporter = getReporterWithCustomFormat()) { -+ reportGaugeValue(graphiteReporter, 1.13574); -+ verifyGraphiteSentCorrectMetricValue("prefix.gauge", "1.1357", timestamp); -+ verifyNoMoreInteractions(graphite); - } -+ } - -- @Test -- void reportDoubleGaugeValuesUsingCustomFormatter() throws Exception { -- DecimalFormat formatter = new DecimalFormat("##.##########", DecimalFormatSymbols.getInstance(Locale.US)); -+ @Test -+ void reportDoubleGaugeValuesUsingCustomFormatter() throws Exception { -+ DecimalFormat formatter = -+ new DecimalFormat("##.##########", DecimalFormatSymbols.getInstance(Locale.US)); - -- try (GraphiteReporter graphiteReporter = GraphiteReporter.forRegistry(registry) -+ try (GraphiteReporter graphiteReporter = -+ GraphiteReporter.forRegistry(registry) - .withClock(clock) - .prefixedWith("prefix") - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(ImmutableSet.of()) - .withFloatingPointFormatter(formatter::format) - .build(graphite)) { -- reportGaugeValue(graphiteReporter, 0.000045322); -- verifyGraphiteSentCorrectMetricValue("prefix.gauge", "0.000045322", timestamp); -- verifyNoMoreInteractions(graphite); -- } -+ reportGaugeValue(graphiteReporter, 0.000045322); -+ verifyGraphiteSentCorrectMetricValue("prefix.gauge", "0.000045322", timestamp); -+ verifyNoMoreInteractions(graphite); - } -- -- private void reportGaugeValue(GraphiteReporter graphiteReporter, double value) { -- graphiteReporter.report(map(MetricName.build("gauge"), gauge(value)), -- map(), -- map(), -- map(), -- map()); -- } -- -- private void verifyGraphiteSentCorrectMetricValue(String metricName, String value, long timestamp) throws Exception { -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send(metricName, value, timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- } -- -- @Test -- void reportsBooleanGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(true)), -- map(), -- map(), -- map(), -- map()); -- -- reporter.report(map(GAUGE, gauge(false)), -- map(), -- map(), -- map(), -- map()); -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.gauge", "0", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsCounters() throws Exception { -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(100L); -- -- reporter.report(map(), -- map(COUNTER, counter), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.counter.count", "100", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -- when(histogram.getCount()).thenReturn(1L); -- when(histogram.getSum()).thenReturn(12L); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(2L); -- when(snapshot.getMean()).thenReturn(3.0); -- when(snapshot.getMin()).thenReturn(4L); -- when(snapshot.getStdDev()).thenReturn(5.0); -- when(snapshot.getMedian()).thenReturn(6.0); -- when(snapshot.get75thPercentile()).thenReturn(7.0); -- when(snapshot.get95thPercentile()).thenReturn(8.0); -- when(snapshot.get98thPercentile()).thenReturn(9.0); -- when(snapshot.get99thPercentile()).thenReturn(10.0); -- when(snapshot.get999thPercentile()).thenReturn(11.0); -- -- when(histogram.getSnapshot()).thenReturn(snapshot); -- -- reporter.report(map(), -- map(), -- map(MetricName.build("histogram"), histogram), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.histogram.count", "1", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.sum", "12", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.max", "2", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.mean", "3.00", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.min", "4", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.stddev", "5.00", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.p50", "6.00", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.p75", "7.00", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.p95", "8.00", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.p98", "9.00", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.p99", "10.00", timestamp); -- inOrder.verify(graphite).send("prefix.histogram.p999", "11.00", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsMeters() throws Exception { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(6L); -- when(meter.getOneMinuteRate()).thenReturn(2.0); -- when(meter.getFiveMinuteRate()).thenReturn(3.0); -- when(meter.getFifteenMinuteRate()).thenReturn(4.0); -- when(meter.getMeanRate()).thenReturn(5.0); -- -- reporter.report(map(), -- map(), -- map(), -- map(METER, meter), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); -- inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.m1_rate", "2.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.m5_rate", "3.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.m15_rate", "4.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.mean_rate", "5.00", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsMetersInMinutes() throws Exception { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(6L); -- when(meter.getOneMinuteRate()).thenReturn(2.0); -- when(meter.getFiveMinuteRate()).thenReturn(3.0); -- when(meter.getFifteenMinuteRate()).thenReturn(4.0); -- when(meter.getMeanRate()).thenReturn(5.0); -- -- minuteRateReporter.report(this.map(), -- this.map(), -- this.map(), -- this.map(METER, meter), -- this.map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); -- inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.m1_rate", "120.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.m5_rate", "180.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.m15_rate", "240.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.mean_rate", "300.00", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void reportsTimers() throws Exception { -- final Timer timer = mock(Timer.class); -- when(timer.getCount()).thenReturn(1L); -- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); -- when(timer.getMeanRate()).thenReturn(2.0); -- when(timer.getOneMinuteRate()).thenReturn(3.0); -- when(timer.getFiveMinuteRate()).thenReturn(4.0); -- when(timer.getFifteenMinuteRate()).thenReturn(5.0); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS -- .toNanos(1000)); -- -- when(timer.getSnapshot()).thenReturn(snapshot); -- -- reporter.report(map(), -- map(), -- map(), -- map(), -- map(MetricName.build("timer"), timer)); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.timer.max", "100.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.mean", "200.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.min", "300.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.stddev", "400.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.p50", "500.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.p75", "600.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.p95", "700.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.p98", "800.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.p99", "900.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.p999", "1000.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.count", "1", timestamp); -- inOrder.verify(graphite).send("prefix.timer.sum", "6.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.m1_rate", "3.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.m5_rate", "4.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.m15_rate", "5.00", timestamp); -- inOrder.verify(graphite).send("prefix.timer.mean_rate", "2.00", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- -- reporter.close(); -- } -- -- @Test -- void closesConnectionIfGraphiteIsUnavailable() throws Exception { -- doThrow(new UnknownHostException("UNKNOWN-HOST")).when(graphite).connect(); -- reporter.report(map(GAUGE, gauge(1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).close(); -- -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void closesConnectionOnReporterStop() throws Exception { -- reporter.start(1, TimeUnit.SECONDS); -- reporter.stop(); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite, times(2)).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void disabledMetricsAttribute() throws Exception { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(6L); -- when(meter.getOneMinuteRate()).thenReturn(2.0); -- when(meter.getFiveMinuteRate()).thenReturn(3.0); -- when(meter.getFifteenMinuteRate()).thenReturn(4.0); -- when(meter.getMeanRate()).thenReturn(5.0); -- -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(11L); -- -- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE); -- GraphiteReporter reporterWithdisabledMetricAttributes = GraphiteReporter.forRegistry(registry) -+ } -+ -+ private void reportGaugeValue(GraphiteReporter graphiteReporter, double value) { -+ graphiteReporter.report( -+ map(MetricName.build("gauge"), gauge(value)), map(), map(), map(), map()); -+ } -+ -+ private void verifyGraphiteSentCorrectMetricValue(String metricName, String value, long timestamp) -+ throws Exception { -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send(metricName, value, timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ } -+ -+ @Test -+ void reportsBooleanGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(true)), map(), map(), map(), map()); -+ -+ reporter.report(map(GAUGE, gauge(false)), map(), map(), map(), map()); -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.gauge", "1", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.gauge", "0", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsCounters() throws Exception { -+ final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(100L); -+ -+ reporter.report(map(), map(COUNTER, counter), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.counter.count", "100", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsHistograms() throws Exception { -+ final Histogram histogram = mock(); -+ when(histogram.getCount()).thenReturn(1L); -+ when(histogram.getSum()).thenReturn(12L); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(2L); -+ when(snapshot.getMean()).thenReturn(3.0); -+ when(snapshot.getMin()).thenReturn(4L); -+ when(snapshot.getStdDev()).thenReturn(5.0); -+ when(snapshot.getMedian()).thenReturn(6.0); -+ when(snapshot.get75thPercentile()).thenReturn(7.0); -+ when(snapshot.get95thPercentile()).thenReturn(8.0); -+ when(snapshot.get98thPercentile()).thenReturn(9.0); -+ when(snapshot.get99thPercentile()).thenReturn(10.0); -+ when(snapshot.get999thPercentile()).thenReturn(11.0); -+ -+ when(histogram.getSnapshot()).thenReturn(snapshot); -+ -+ reporter.report(map(), map(), map(MetricName.build("histogram"), histogram), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.histogram.count", "1", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.sum", "12", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.max", "2", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.mean", "3.00", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.min", "4", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.stddev", "5.00", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.p50", "6.00", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.p75", "7.00", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.p95", "8.00", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.p98", "9.00", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.p99", "10.00", timestamp); -+ inOrder.verify(graphite).send("prefix.histogram.p999", "11.00", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsMeters() throws Exception { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(6L); -+ when(meter.getOneMinuteRate()).thenReturn(2.0); -+ when(meter.getFiveMinuteRate()).thenReturn(3.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(4.0); -+ when(meter.getMeanRate()).thenReturn(5.0); -+ -+ reporter.report(map(), map(), map(), map(METER, meter), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.m1_rate", "2.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.m5_rate", "3.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.m15_rate", "4.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.mean_rate", "5.00", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsMetersInMinutes() throws Exception { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(6L); -+ when(meter.getOneMinuteRate()).thenReturn(2.0); -+ when(meter.getFiveMinuteRate()).thenReturn(3.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(4.0); -+ when(meter.getMeanRate()).thenReturn(5.0); -+ -+ minuteRateReporter.report( -+ this.map(), this.map(), this.map(), this.map(METER, meter), this.map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.m1_rate", "120.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.m5_rate", "180.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.m15_rate", "240.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.mean_rate", "300.00", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void reportsTimers() throws Exception { -+ final Timer timer = mock(); -+ when(timer.getCount()).thenReturn(1L); -+ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); -+ when(timer.getMeanRate()).thenReturn(2.0); -+ when(timer.getOneMinuteRate()).thenReturn(3.0); -+ when(timer.getFiveMinuteRate()).thenReturn(4.0); -+ when(timer.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -+ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -+ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -+ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -+ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -+ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -+ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -+ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -+ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -+ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -+ -+ when(timer.getSnapshot()).thenReturn(snapshot); -+ -+ reporter.report(map(), map(), map(), map(), map(MetricName.build("timer"), timer)); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.timer.max", "100.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.mean", "200.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.min", "300.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.stddev", "400.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.p50", "500.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.p75", "600.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.p95", "700.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.p98", "800.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.p99", "900.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.p999", "1000.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.count", "1", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.sum", "6.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.m1_rate", "3.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.m5_rate", "4.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.m15_rate", "5.00", timestamp); -+ inOrder.verify(graphite).send("prefix.timer.mean_rate", "2.00", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ -+ reporter.close(); -+ } -+ -+ @Test -+ void closesConnectionIfGraphiteIsUnavailable() throws Exception { -+ doThrow(new UnknownHostException("UNKNOWN-HOST")).when(graphite).connect(); -+ reporter.report(map(GAUGE, gauge(1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void closesConnectionOnReporterStop() throws Exception { -+ reporter.start(1, TimeUnit.SECONDS); -+ reporter.stop(); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite, times(2)).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void disabledMetricsAttribute() throws Exception { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(6L); -+ when(meter.getOneMinuteRate()).thenReturn(2.0); -+ when(meter.getFiveMinuteRate()).thenReturn(3.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(4.0); -+ when(meter.getMeanRate()).thenReturn(5.0); -+ -+ final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(11L); -+ -+ Set disabledMetricAttributes = -+ EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE); -+ GraphiteReporter reporterWithdisabledMetricAttributes = -+ GraphiteReporter.forRegistry(registry) - .withClock(clock) - .prefixedWith("prefix") - .convertRatesTo(TimeUnit.SECONDS) -@@ -491,79 +432,82 @@ class GraphiteReporterTest { - .filter(MetricFilter.ALL) - .disabledMetricAttributes(disabledMetricAttributes) - .build(graphite); -- reporterWithdisabledMetricAttributes.report(map(), -- map(COUNTER, counter), -- map(), -- map(METER, meter), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.counter.count", "11", timestamp); -- inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); -- inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.m1_rate", "2.00", timestamp); -- inOrder.verify(graphite).send("prefix.meter.mean_rate", "5.00", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- @Test -- void sendsMetricAttributesAsTagsIfEnabled() throws Exception { -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(100L); -- -- getReporterThatSendsMetricAttributesAsTags().report(map(), -- map(COUNTER, counter), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(graphite); -- inOrder.verify(graphite).connect(); -- inOrder.verify(graphite).send("prefix.counter;metricattribute=count", "100", timestamp); -- inOrder.verify(graphite).flush(); -- inOrder.verify(graphite).close(); -- -- verifyNoMoreInteractions(graphite); -- } -- -- private GraphiteReporter getReporterWithCustomFormat() { -- return new GraphiteReporter(registry, graphite, clock, "prefix", -- TimeUnit.SECONDS, TimeUnit.MICROSECONDS, MetricFilter.ALL, null, false, -- Collections.emptySet(), false) { -- @Override -- protected String format(double v) { -- return String.format(Locale.US, "%4.4f", v); -- } -- }; -- } -- -- private GraphiteReporter getReporterThatSendsMetricAttributesAsTags() { -- return GraphiteReporter.forRegistry(registry) -- .withClock(clock) -- .prefixedWith("prefix") -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -- .addMetricAttributesAsTags(true) -- .build(graphite); -- } -+ reporterWithdisabledMetricAttributes.report( -+ map(), map(COUNTER, counter), map(), map(METER, meter), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.counter.count", "11", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.count", "1", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.sum", "6.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.m1_rate", "2.00", timestamp); -+ inOrder.verify(graphite).send("prefix.meter.mean_rate", "5.00", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ @Test -+ void sendsMetricAttributesAsTagsIfEnabled() throws Exception { -+ final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(100L); -+ -+ getReporterThatSendsMetricAttributesAsTags() -+ .report(map(), map(COUNTER, counter), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(graphite); -+ inOrder.verify(graphite).connect(); -+ inOrder.verify(graphite).send("prefix.counter;metricattribute=count", "100", timestamp); -+ inOrder.verify(graphite).flush(); -+ inOrder.verify(graphite).close(); -+ -+ verifyNoMoreInteractions(graphite); -+ } -+ -+ private GraphiteReporter getReporterWithCustomFormat() { -+ return new GraphiteReporter( -+ registry, -+ graphite, -+ clock, -+ "prefix", -+ TimeUnit.SECONDS, -+ TimeUnit.MICROSECONDS, -+ MetricFilter.ALL, -+ null, -+ false, -+ ImmutableSet.of(), -+ false) { -+ @Override -+ protected String format(double v) { -+ return String.format(Locale.US, "%4.4f", v); -+ } -+ }; -+ } -+ -+ private GraphiteReporter getReporterThatSendsMetricAttributesAsTags() { -+ return GraphiteReporter.forRegistry(registry) -+ .withClock(clock) -+ .prefixedWith("prefix") -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(ImmutableSet.of()) -+ .addMetricAttributesAsTags(true) -+ .build(graphite); -+ } - -- private SortedMap map() { -- return new TreeMap<>(); -- } -+ private SortedMap map() { -+ return new TreeMap<>(); -+ } - -- private SortedMap map(MetricName name, T metric) { -- final TreeMap map = new TreeMap<>(); -- map.put(name, metric); -- return map; -- } -+ private SortedMap map(MetricName name, T metric) { -+ final TreeMap map = new TreeMap<>(); -+ map.put(name, metric); -+ return map; -+ } - -- private Gauge gauge(T value) { -- return () -> value; -- } -+ private Gauge gauge(T value) { -+ return () -> value; -+ } - } ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java -@@ -3,25 +3,27 @@ package io.dropwizard.metrics5.graphite; - import org.assertj.core.api.SoftAssertions; - import org.junit.jupiter.api.Test; - --class GraphiteSanitizeTest { -- @Test -- void sanitizeGraphiteValues() { -- SoftAssertions softly = new SoftAssertions(); -+final class GraphiteSanitizeTest { -+ @Test -+ void sanitizeGraphiteValues() { -+ SoftAssertions softly = new SoftAssertions(); - -- softly.assertThat(GraphiteSanitize.sanitize("Foo Bar")).isEqualTo("Foo-Bar"); -- softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar ")).isEqualTo("Foo-Bar"); -- softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar")).isEqualTo("Foo-Bar"); -- softly.assertThat(GraphiteSanitize.sanitize("Foo Bar ")).isEqualTo("Foo-Bar"); -- softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar ")).isEqualTo("Foo-Bar"); -- softly.assertThat(GraphiteSanitize.sanitize("Foo@Bar")).isEqualTo("Foo@Bar"); -- softly.assertThat(GraphiteSanitize.sanitize("Foó Bar")).isEqualTo("Foó-Bar"); -- softly.assertThat(GraphiteSanitize.sanitize("||ó/.")).isEqualTo("||ó/."); -- softly.assertThat(GraphiteSanitize.sanitize("${Foo:Bar:baz}")).isEqualTo("${Foo:Bar:baz}"); -- softly.assertThat(GraphiteSanitize.sanitize("St. Foo's of Bar")).isEqualTo("St.-Foo's-of-Bar"); -- softly.assertThat(GraphiteSanitize.sanitize("(Foo and (Bar and (Baz)))")).isEqualTo("(Foo-and-(Bar-and-(Baz)))"); -- softly.assertThat(GraphiteSanitize.sanitize("Foo.bar.baz")).isEqualTo("Foo.bar.baz"); -- softly.assertThat(GraphiteSanitize.sanitize("FooBar")).isEqualTo("FooBar"); -+ softly.assertThat(GraphiteSanitize.sanitize("Foo Bar")).isEqualTo("Foo-Bar"); -+ softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar ")).isEqualTo("Foo-Bar"); -+ softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar")).isEqualTo("Foo-Bar"); -+ softly.assertThat(GraphiteSanitize.sanitize("Foo Bar ")).isEqualTo("Foo-Bar"); -+ softly.assertThat(GraphiteSanitize.sanitize(" Foo Bar ")).isEqualTo("Foo-Bar"); -+ softly.assertThat(GraphiteSanitize.sanitize("Foo@Bar")).isEqualTo("Foo@Bar"); -+ softly.assertThat(GraphiteSanitize.sanitize("Foó Bar")).isEqualTo("Foó-Bar"); -+ softly.assertThat(GraphiteSanitize.sanitize("||ó/.")).isEqualTo("||ó/."); -+ softly.assertThat(GraphiteSanitize.sanitize("${Foo:Bar:baz}")).isEqualTo("${Foo:Bar:baz}"); -+ softly.assertThat(GraphiteSanitize.sanitize("St. Foo's of Bar")).isEqualTo("St.-Foo's-of-Bar"); -+ softly -+ .assertThat(GraphiteSanitize.sanitize("(Foo and (Bar and (Baz)))")) -+ .isEqualTo("(Foo-and-(Bar-and-(Baz)))"); -+ softly.assertThat(GraphiteSanitize.sanitize("Foo.bar.baz")).isEqualTo("Foo.bar.baz"); -+ softly.assertThat(GraphiteSanitize.sanitize("FooBar")).isEqualTo("FooBar"); - -- softly.assertAll(); -- } -+ softly.assertAll(); -+ } - } ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java -@@ -1,17 +1,5 @@ - package io.dropwizard.metrics5.graphite; - --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import javax.net.SocketFactory; --import java.io.ByteArrayOutputStream; --import java.io.IOException; --import java.net.InetAddress; --import java.net.InetSocketAddress; --import java.net.Socket; --import java.net.UnknownHostException; --import java.util.concurrent.atomic.AtomicBoolean; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatNoException; - import static org.assertj.core.api.Assertions.assertThatThrownBy; -@@ -24,120 +12,137 @@ import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - --class GraphiteTest { -- private final String host = "example.com"; -- private final int port = 1234; -- private final SocketFactory socketFactory = mock(SocketFactory.class); -- private final InetSocketAddress address = new InetSocketAddress(host, port); -- -- private final Socket socket = mock(Socket.class); -- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); -- -- @BeforeEach -- void setUp() throws Exception { -- final AtomicBoolean connected = new AtomicBoolean(true); -- final AtomicBoolean closed = new AtomicBoolean(false); -- -- when(socket.isConnected()).thenAnswer(invocation -> connected.get()); -- -- when(socket.isClosed()).thenAnswer(invocation -> closed.get()); -- -- doAnswer(invocation -> { -- connected.set(false); -- closed.set(true); -- return null; -- }).when(socket).close(); -- -- when(socket.getOutputStream()).thenReturn(output); -- -- // Mock behavior of socket.getOutputStream().close() calling socket.close(); -- doAnswer(invocation -> { -- invocation.callRealMethod(); -- socket.close(); -- return null; -- }).when(output).close(); -+import java.io.ByteArrayOutputStream; -+import java.io.IOException; -+import java.net.InetAddress; -+import java.net.InetSocketAddress; -+import java.net.Socket; -+import java.net.UnknownHostException; -+import java.util.concurrent.atomic.AtomicBoolean; -+import javax.net.SocketFactory; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - -- when(socketFactory.createSocket(any(InetAddress.class), anyInt())).thenReturn(socket); -+final class GraphiteTest { -+ private final String host = "example.com"; -+ private final int port = 1234; -+ private final SocketFactory socketFactory = mock(); -+ private final InetSocketAddress address = new InetSocketAddress(host, port); -+ -+ private final Socket socket = mock(); -+ private final ByteArrayOutputStream output = spy(); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ final AtomicBoolean connected = new AtomicBoolean(true); -+ final AtomicBoolean closed = new AtomicBoolean(false); -+ -+ when(socket.isConnected()).thenAnswer(invocation -> connected.get()); -+ -+ when(socket.isClosed()).thenAnswer(invocation -> closed.get()); -+ -+ doAnswer( -+ invocation -> { -+ connected.set(false); -+ closed.set(true); -+ return null; -+ }) -+ .when(socket) -+ .close(); -+ -+ when(socket.getOutputStream()).thenReturn(output); -+ -+ // Mock behavior of socket.getOutputStream().close() calling socket.close(); -+ doAnswer( -+ invocation -> { -+ invocation.callRealMethod(); -+ socket.close(); -+ return null; -+ }) -+ .when(output) -+ .close(); -+ -+ when(socketFactory.createSocket(any(InetAddress.class), anyInt())).thenReturn(socket); -+ } -+ -+ @Test -+ void connectsToGraphiteWithInetSocketAddress() throws Exception { -+ try (Graphite graphite = new Graphite(address, socketFactory)) { -+ graphite.connect(); - } -+ verify(socketFactory).createSocket(address.getAddress(), address.getPort()); -+ } - -- @Test -- void connectsToGraphiteWithInetSocketAddress() throws Exception { -- try (Graphite graphite = new Graphite(address, socketFactory)) { -- graphite.connect(); -- } -- verify(socketFactory).createSocket(address.getAddress(), address.getPort()); -+ @Test -+ void connectsToGraphiteWithHostAndPort() throws Exception { -+ try (Graphite graphite = new Graphite(host, port, socketFactory)) { -+ graphite.connect(); - } -+ verify(socketFactory).createSocket(address.getAddress(), port); -+ } - -- @Test -- void connectsToGraphiteWithHostAndPort() throws Exception { -- try (Graphite graphite = new Graphite(host, port, socketFactory)) { -- graphite.connect(); -- } -- verify(socketFactory).createSocket(address.getAddress(), port); -+ @Test -+ void measuresFailures() throws IOException { -+ try (Graphite graphite = new Graphite(address, socketFactory)) { -+ assertThat(graphite.getFailures()).isEqualTo(0); - } -+ } - -- @Test -- void measuresFailures() throws IOException { -- try (Graphite graphite = new Graphite(address, socketFactory)) { -- assertThat(graphite.getFailures()).isZero(); -- } -+ @Test -+ void disconnectsFromGraphite() throws Exception { -+ try (Graphite graphite = new Graphite(address, socketFactory)) { -+ graphite.connect(); - } - -- @Test -- void disconnectsFromGraphite() throws Exception { -- try (Graphite graphite = new Graphite(address, socketFactory)) { -- graphite.connect(); -- } -- -- verify(socket, times(2)).close(); -- } -+ verify(socket, times(2)).close(); -+ } - -- @Test -- void doesNotAllowDoubleConnections() throws Exception { -- try (Graphite graphite = new Graphite(address, socketFactory)) { -- assertThatNoException().isThrownBy(graphite::connect); -- assertThatThrownBy(graphite::connect) -- .isInstanceOf(IllegalStateException.class) -- .hasMessage("Already connected"); -- } -+ @Test -+ void doesNotAllowDoubleConnections() throws Exception { -+ try (Graphite graphite = new Graphite(address, socketFactory)) { -+ assertThatNoException().isThrownBy(graphite::connect); -+ assertThatThrownBy(graphite::connect) -+ .isInstanceOf(IllegalStateException.class) -+ .hasMessage("Already connected"); - } -+ } - -- @Test -- void writesValuesToGraphite() throws Exception { -- try (Graphite graphite = new Graphite(address, socketFactory)) { -- graphite.connect(); -- graphite.send("name", "value", 100); -- } -- assertThat(output).hasToString("name value 100\n"); -+ @Test -+ void writesValuesToGraphite() throws Exception { -+ try (Graphite graphite = new Graphite(address, socketFactory)) { -+ graphite.connect(); -+ graphite.send("name", "value", 100); - } -- -- @Test -- void sanitizesNames() throws Exception { -- try (Graphite graphite = new Graphite(address, socketFactory)) { -- graphite.connect(); -- graphite.send("name woo", "value", 100); -- } -- assertThat(output).hasToString("name-woo value 100\n"); -+ assertThat(output).hasToString("name value 100\n"); -+ } -+ -+ @Test -+ void sanitizesNames() throws Exception { -+ try (Graphite graphite = new Graphite(address, socketFactory)) { -+ graphite.connect(); -+ graphite.send("name woo", "value", 100); - } -- -- @Test -- void sanitizesValues() throws Exception { -- try (Graphite graphite = new Graphite(address, socketFactory)) { -- graphite.connect(); -- graphite.send("name", "value woo", 100); -- } -- assertThat(output).hasToString("name value-woo 100\n"); -+ assertThat(output).hasToString("name-woo value 100\n"); -+ } -+ -+ @Test -+ void sanitizesValues() throws Exception { -+ try (Graphite graphite = new Graphite(address, socketFactory)) { -+ graphite.connect(); -+ graphite.send("name", "value woo", 100); - } -- -- @Test -- void notifiesIfGraphiteIsUnavailable() throws IOException { -- final String unavailableHost = "unknown-host-10el6m7yg56ge7dmcom"; -- InetSocketAddress unavailableAddress = new InetSocketAddress(unavailableHost, 1234); -- -- try (Graphite unavailableGraphite = new Graphite(unavailableAddress, socketFactory)) { -- assertThatThrownBy(unavailableGraphite::connect) -- .isInstanceOf(UnknownHostException.class) -- .hasMessage(unavailableHost); -- } -+ assertThat(output).hasToString("name value-woo 100\n"); -+ } -+ -+ @Test -+ void notifiesIfGraphiteIsUnavailable() throws IOException { -+ final String unavailableHost = "unknown-host-10el6m7yg56ge7dmcom"; -+ InetSocketAddress unavailableAddress = new InetSocketAddress(unavailableHost, 1234); -+ -+ try (Graphite unavailableGraphite = new Graphite(unavailableAddress, socketFactory)) { -+ assertThatThrownBy(unavailableGraphite::connect) -+ .isInstanceOf(UnknownHostException.class) -+ .hasMessage(unavailableHost); - } -+ } - } ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java -@@ -1,43 +1,43 @@ - package io.dropwizard.metrics5.graphite; - --import org.junit.jupiter.api.Test; --import org.mockito.Mockito; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import java.net.InetSocketAddress; - import java.nio.ByteBuffer; - import java.nio.channels.DatagramChannel; -+import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.verify; -- --class GraphiteUDPTest { -+final class GraphiteUDPTest { - -- private final String host = "example.com"; -- private final int port = 1234; -+ private final String host = "example.com"; -+ private final int port = 1234; - -- private GraphiteUDP graphiteUDP; -+ private GraphiteUDP graphiteUDP; - -- @Test -- void connects() throws Exception { -- graphiteUDP = new GraphiteUDP(host, port); -- graphiteUDP.connect(); -+ @Test -+ void connects() throws Exception { -+ graphiteUDP = new GraphiteUDP(host, port); -+ graphiteUDP.connect(); - -- assertThat(graphiteUDP.getDatagramChannel()).isNotNull(); -- assertThat(graphiteUDP.getAddress()).isEqualTo(new InetSocketAddress(host, port)); -+ assertThat(graphiteUDP.getDatagramChannel()).isNotNull(); -+ assertThat(graphiteUDP.getAddress()).isEqualTo(new InetSocketAddress(host, port)); - -- graphiteUDP.close(); -- } -+ graphiteUDP.close(); -+ } - -- @Test -- void writesValue() throws Exception { -- graphiteUDP = new GraphiteUDP(host, port); -- DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); -- graphiteUDP.setDatagramChannel(mockDatagramChannel); -- graphiteUDP.setAddress(new InetSocketAddress(host, port)); -+ @Test -+ void writesValue() throws Exception { -+ graphiteUDP = new GraphiteUDP(host, port); -+ DatagramChannel mockDatagramChannel = mock(); -+ graphiteUDP.setDatagramChannel(mockDatagramChannel); -+ graphiteUDP.setAddress(new InetSocketAddress(host, port)); - -- graphiteUDP.send("name woo", "value", 100); -- verify(mockDatagramChannel).send(ByteBuffer.wrap("name-woo value 100\n".getBytes("UTF-8")), -+ graphiteUDP.send("name woo", "value", 100); -+ verify(mockDatagramChannel) -+ .send( -+ ByteBuffer.wrap("name-woo value 100\n".getBytes("UTF-8")), - new InetSocketAddress(host, port)); -- } -- --} -\ No newline at end of file -+ } -+} ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java -@@ -1,26 +1,5 @@ - package io.dropwizard.metrics5.graphite; - --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; --import org.python.core.PyList; --import org.python.core.PyTuple; -- --import javax.net.SocketFactory; --import javax.script.Bindings; --import javax.script.Compilable; --import javax.script.CompiledScript; --import javax.script.ScriptEngine; --import javax.script.ScriptEngineManager; --import javax.script.SimpleBindings; --import java.io.ByteArrayOutputStream; --import java.io.InputStream; --import java.io.InputStreamReader; --import java.math.BigInteger; --import java.net.InetAddress; --import java.net.InetSocketAddress; --import java.net.Socket; --import java.util.concurrent.atomic.AtomicBoolean; -- - import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown; -@@ -32,150 +11,169 @@ import static org.mockito.Mockito.spy; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - --class PickledGraphiteTest { -- private final SocketFactory socketFactory = mock(SocketFactory.class); -- private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); -- private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); -- -- private final Socket socket = mock(Socket.class); -- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); -- -- private CompiledScript unpickleScript; -- -- @BeforeEach -- void setUp() throws Exception { -- final AtomicBoolean connected = new AtomicBoolean(true); -- final AtomicBoolean closed = new AtomicBoolean(false); -- -- when(socket.isConnected()).thenAnswer(invocation -> connected.get()); -- -- when(socket.isClosed()).thenAnswer(invocation -> closed.get()); -+import java.io.ByteArrayOutputStream; -+import java.io.InputStream; -+import java.io.InputStreamReader; -+import java.math.BigInteger; -+import java.net.InetAddress; -+import java.net.InetSocketAddress; -+import java.net.Socket; -+import java.util.concurrent.atomic.AtomicBoolean; -+import javax.net.SocketFactory; -+import javax.script.Bindings; -+import javax.script.Compilable; -+import javax.script.CompiledScript; -+import javax.script.ScriptEngine; -+import javax.script.ScriptEngineManager; -+import javax.script.SimpleBindings; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; -+import org.python.core.PyList; -+import org.python.core.PyTuple; - -- doAnswer(invocation -> { -- connected.set(false); -- closed.set(true); -- return null; -- }).when(socket).close(); -+final class PickledGraphiteTest { -+ private final SocketFactory socketFactory = mock(); -+ private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); -+ private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); - -- when(socket.getOutputStream()).thenReturn(output); -+ private final Socket socket = mock(); -+ private final ByteArrayOutputStream output = spy(); - -- // Mock behavior of socket.getOutputStream().close() calling socket.close(); -- doAnswer(invocation -> { -- invocation.callRealMethod(); -- socket.close(); -- return null; -- }).when(output).close(); -+ private CompiledScript unpickleScript; - -- when(socketFactory.createSocket(any(InetAddress.class), -- anyInt())).thenReturn(socket); -+ @BeforeEach -+ void setUp() throws Exception { -+ final AtomicBoolean connected = new AtomicBoolean(true); -+ final AtomicBoolean closed = new AtomicBoolean(false); - -- ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); -- Compilable compilable = (Compilable) engine; -- try (InputStream is = PickledGraphiteTest.class.getResource("/upickle.py").openStream()) { -- unpickleScript = compilable.compile(new InputStreamReader(is, UTF_8)); -- } -- } -+ when(socket.isConnected()).thenAnswer(invocation -> connected.get()); - -- @Test -- void disconnectsFromGraphite() throws Exception { -- graphite.connect(); -- graphite.close(); -+ when(socket.isClosed()).thenAnswer(invocation -> closed.get()); - -- verify(socket).close(); -- } -+ doAnswer( -+ invocation -> { -+ connected.set(false); -+ closed.set(true); -+ return null; -+ }) -+ .when(socket) -+ .close(); - -- @Test -- void writesValuesToGraphite() throws Exception { -- graphite.connect(); -- graphite.send("name", "value", 100); -- graphite.close(); -+ when(socket.getOutputStream()).thenReturn(output); - -- assertThat(unpickleOutput()) -- .isEqualTo("name value 100\n"); -- } -+ // Mock behavior of socket.getOutputStream().close() calling socket.close(); -+ doAnswer( -+ invocation -> { -+ invocation.callRealMethod(); -+ socket.close(); -+ return null; -+ }) -+ .when(output) -+ .close(); - -- @Test -- void writesFullBatch() throws Exception { -- graphite.connect(); -- graphite.send("name", "value", 100); -- graphite.send("name", "value2", 100); -- graphite.close(); -+ when(socketFactory.createSocket(any(InetAddress.class), anyInt())).thenReturn(socket); - -- assertThat(unpickleOutput()) -- .isEqualTo("name value 100\nname value2 100\n"); -+ ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); -+ Compilable compilable = (Compilable) engine; -+ try (InputStream is = PickledGraphiteTest.class.getResource("/upickle.py").openStream()) { -+ unpickleScript = compilable.compile(new InputStreamReader(is, UTF_8)); - } -- -- @Test -- void writesPastFullBatch() throws Exception { -- graphite.connect(); -- graphite.send("name", "value", 100); -- graphite.send("name", "value2", 100); -- graphite.send("name", "value3", 100); -- graphite.close(); -- -- assertThat(unpickleOutput()) -- .isEqualTo("name value 100\nname value2 100\nname value3 100\n"); -+ } -+ -+ @Test -+ void disconnectsFromGraphite() throws Exception { -+ graphite.connect(); -+ graphite.close(); -+ -+ verify(socket).close(); -+ } -+ -+ @Test -+ void writesValuesToGraphite() throws Exception { -+ graphite.connect(); -+ graphite.send("name", "value", 100); -+ graphite.close(); -+ -+ assertThat(unpickleOutput()).isEqualTo("name value 100\n"); -+ } -+ -+ @Test -+ void writesFullBatch() throws Exception { -+ graphite.connect(); -+ graphite.send("name", "value", 100); -+ graphite.send("name", "value2", 100); -+ graphite.close(); -+ -+ assertThat(unpickleOutput()).isEqualTo("name value 100\nname value2 100\n"); -+ } -+ -+ @Test -+ void writesPastFullBatch() throws Exception { -+ graphite.connect(); -+ graphite.send("name", "value", 100); -+ graphite.send("name", "value2", 100); -+ graphite.send("name", "value3", 100); -+ graphite.close(); -+ -+ assertThat(unpickleOutput()).isEqualTo("name value 100\nname value2 100\nname value3 100\n"); -+ } -+ -+ @Test -+ void sanitizesNames() throws Exception { -+ graphite.connect(); -+ graphite.send("name woo", "value", 100); -+ graphite.close(); -+ -+ assertThat(unpickleOutput()).isEqualTo("name-woo value 100\n"); -+ } -+ -+ @Test -+ void sanitizesValues() throws Exception { -+ graphite.connect(); -+ graphite.send("name", "value woo", 100); -+ graphite.close(); -+ -+ assertThat(unpickleOutput()).isEqualTo("name value-woo 100\n"); -+ } -+ -+ @Test -+ void doesNotAllowDoubleConnections() throws Exception { -+ graphite.connect(); -+ try { -+ graphite.connect(); -+ failBecauseExceptionWasNotThrown(IllegalStateException.class); -+ } catch (IllegalStateException e) { -+ assertThat(e.getMessage()).isEqualTo("Already connected"); - } -- -- @Test -- void sanitizesNames() throws Exception { -- graphite.connect(); -- graphite.send("name woo", "value", 100); -- graphite.close(); -- -- assertThat(unpickleOutput()) -- .isEqualTo("name-woo value 100\n"); -+ } -+ -+ private String unpickleOutput() throws Exception { -+ StringBuilder results = new StringBuilder(); -+ -+ // the charset is important. if the GraphitePickleReporter and this test -+ // don't agree, the header is not always correctly unpacked. -+ String payload = output.toString("UTF-8"); -+ -+ PyList result = new PyList(); -+ int nextIndex = 0; -+ while (nextIndex < payload.length()) { -+ Bindings bindings = new SimpleBindings(); -+ bindings.put("payload", payload.substring(nextIndex)); -+ unpickleScript.eval(bindings); -+ result.addAll(result.size(), (PyList) bindings.get("metrics")); -+ nextIndex += ((BigInteger) bindings.get("batchLength")).intValue(); - } - -- @Test -- void sanitizesValues() throws Exception { -- graphite.connect(); -- graphite.send("name", "value woo", 100); -- graphite.close(); -+ for (Object aResult : result) { -+ PyTuple datapoint = (PyTuple) aResult; -+ String name = datapoint.get(0).toString(); -+ PyTuple valueTuple = (PyTuple) datapoint.get(1); -+ Object timestamp = valueTuple.get(0); -+ Object value = valueTuple.get(1); - -- assertThat(unpickleOutput()) -- .isEqualTo("name value-woo 100\n"); -+ results.append(name).append(" ").append(value).append(" ").append(timestamp).append("\n"); - } - -- @Test -- void doesNotAllowDoubleConnections() throws Exception { -- graphite.connect(); -- try { -- graphite.connect(); -- failBecauseExceptionWasNotThrown(IllegalStateException.class); -- } catch (IllegalStateException e) { -- assertThat(e.getMessage()) -- .isEqualTo("Already connected"); -- } -- } -- -- private String unpickleOutput() throws Exception { -- StringBuilder results = new StringBuilder(); -- -- // the charset is important. if the GraphitePickleReporter and this test -- // don't agree, the header is not always correctly unpacked. -- String payload = output.toString("UTF-8"); -- -- PyList result = new PyList(); -- int nextIndex = 0; -- while (nextIndex < payload.length()) { -- Bindings bindings = new SimpleBindings(); -- bindings.put("payload", payload.substring(nextIndex)); -- unpickleScript.eval(bindings); -- result.addAll(result.size(), (PyList) bindings.get("metrics")); -- nextIndex += ((BigInteger) bindings.get("batchLength")).intValue(); -- } -- -- for (Object aResult : result) { -- PyTuple datapoint = (PyTuple) aResult; -- String name = datapoint.get(0).toString(); -- PyTuple valueTuple = (PyTuple) datapoint.get(1); -- Object timestamp = valueTuple.get(0); -- Object value = valueTuple.get(1); -- -- results.append(name).append(" ").append(value).append(" ").append(timestamp).append("\n"); -- } -- -- return results.toString(); -- } -+ return results.toString(); -+ } - } ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java -@@ -1,81 +1,84 @@ - package io.dropwizard.metrics5.health; - --import io.dropwizard.metrics5.health.annotation.Async; --import io.dropwizard.metrics5.Clock; -- -+import static com.google.common.base.Preconditions.checkArgument; - -+import io.dropwizard.metrics5.Clock; -+import io.dropwizard.metrics5.health.annotation.Async; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.ScheduledFuture; - --/** -- * A health check decorator to manage asynchronous executions. -- */ -+/** A health check decorator to manage asynchronous executions. */ - public class AsyncHealthCheckDecorator implements HealthCheck, Runnable { -- private static final String NO_RESULT_YET_MESSAGE = "Waiting for first asynchronous check result."; -- private final HealthCheck healthCheck; -- private final ScheduledFuture future; -- private final long healthyTtl; -- private final Clock clock; -- private volatile Result result; -- -- AsyncHealthCheckDecorator(HealthCheck healthCheck, ScheduledExecutorService executorService, Clock clock) { -- check(healthCheck != null, "healthCheck cannot be null"); -- check(executorService != null, "executorService cannot be null"); -- Async async = healthCheck.getClass().getAnnotation(Async.class); -- check(async != null, "healthCheck must contain Async annotation"); -- check(async.period() > 0, "period cannot be less than or equal to zero"); -- check(async.initialDelay() >= 0, "initialDelay cannot be less than zero"); -- -+ private static final String NO_RESULT_YET_MESSAGE = -+ "Waiting for first asynchronous check result."; -+ private final HealthCheck healthCheck; -+ private final ScheduledFuture future; -+ private final long healthyTtl; -+ private final Clock clock; -+ private volatile Result result; - -- this.clock = clock; -- this.healthCheck = healthCheck; -- this.healthyTtl = async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); -- result = Async.InitialState.HEALTHY.equals(async.initialState()) ? Result.healthy(NO_RESULT_YET_MESSAGE) : -- Result.unhealthy(NO_RESULT_YET_MESSAGE); -- if (Async.ScheduleType.FIXED_RATE.equals(async.scheduleType())) { -- future = executorService.scheduleAtFixedRate(this, async.initialDelay(), async.period(), async.unit()); -- } else { -- future = executorService.scheduleWithFixedDelay(this, async.initialDelay(), async.period(), async.unit()); -- } -+ AsyncHealthCheckDecorator( -+ HealthCheck healthCheck, ScheduledExecutorService executorService, Clock clock) { -+ check(healthCheck != null, "healthCheck cannot be null"); -+ check(executorService != null, "executorService cannot be null"); -+ Async async = healthCheck.getClass().getAnnotation(Async.class); -+ check(async != null, "healthCheck must contain Async annotation"); -+ check(async.period() > 0, "period cannot be less than or equal to zero"); -+ check(async.initialDelay() >= 0, "initialDelay cannot be less than zero"); - -+ this.clock = clock; -+ this.healthCheck = healthCheck; -+ this.healthyTtl = -+ async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); -+ result = -+ Async.InitialState.HEALTHY == async.initialState() -+ ? Result.healthy(NO_RESULT_YET_MESSAGE) -+ : Result.unhealthy(NO_RESULT_YET_MESSAGE); -+ if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) { -+ future = -+ executorService.scheduleAtFixedRate( -+ this, async.initialDelay(), async.period(), async.unit()); -+ } else { -+ future = -+ executorService.scheduleWithFixedDelay( -+ this, async.initialDelay(), async.period(), async.unit()); - } -+ } - -- AsyncHealthCheckDecorator(HealthCheck healthCheck, ScheduledExecutorService executorService) { -- this(healthCheck, executorService, Clock.defaultClock()); -- } -- -- @Override -- public void run() { -- result = healthCheck.execute(); -- } -+ AsyncHealthCheckDecorator(HealthCheck healthCheck, ScheduledExecutorService executorService) { -+ this(healthCheck, executorService, Clock.defaultClock()); -+ } - -- @Override -- public Result check() throws Exception { -- long expiration = clock.getTime() - result.getTime() - healthyTtl; -- if (expiration > 0) { -- return Result.builder() -- .unhealthy() -- .usingClock(clock) -- .withMessage("Result was %s but it expired %d milliseconds ago", -- result.isHealthy() ? "healthy" : "unhealthy", -- expiration) -- .build(); -- } -+ @Override -+ public void run() { -+ result = healthCheck.execute(); -+ } - -- return result; -+ @Override -+ public Result check() throws Exception { -+ long expiration = clock.getTime() - result.getTime() - healthyTtl; -+ if (expiration > 0) { -+ return Result.builder() -+ .unhealthy() -+ .usingClock(clock) -+ .withMessage( -+ "Result was %s but it expired %d milliseconds ago", -+ result.isHealthy() ? "healthy" : "unhealthy", expiration) -+ .build(); - } - -- boolean tearDown() { -- return future.cancel(true); -- } -+ return result; -+ } - -- public HealthCheck getHealthCheck() { -- return healthCheck; -- } -+ boolean tearDown() { -+ return future.cancel(true); -+ } - -- private static void check(boolean expression, String message) { -- if (!expression) { -- throw new IllegalArgumentException(message); -- } -- } -+ public HealthCheck getHealthCheck() { -+ return healthCheck; -+ } -+ -+ private static void check(boolean expression, String message) { -+ checkArgument(expression, message); -+ } - } ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java -@@ -1,384 +1,386 @@ - package io.dropwizard.metrics5.health; - --import io.dropwizard.metrics5.Clock; -+import static java.util.Collections.unmodifiableMap; - -+import io.dropwizard.metrics5.Clock; - import java.time.Instant; - import java.time.ZoneId; - import java.time.ZonedDateTime; - import java.time.format.DateTimeFormatter; --import java.util.Collections; - import java.util.LinkedHashMap; - import java.util.Map; - import java.util.concurrent.TimeUnit; - --/** -- * A health check for a component of your application. -- */ -+/** A health check for a component of your application. */ - public interface HealthCheck { -+ /** -+ * The result of a {@link HealthCheck} being run. It can be healthy (with an optional message and -+ * optional details) or unhealthy (with either an error message or a thrown exception and optional -+ * details). -+ */ -+ class Result { -+ private static final DateTimeFormatter DATE_FORMAT_PATTERN = -+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); -+ private static final int PRIME = 31; -+ - /** -- * The result of a {@link HealthCheck} being run. It can be healthy (with an optional message and optional details) -- * or unhealthy (with either an error message or a thrown exception and optional details). -+ * Returns a healthy {@link Result} with no additional message. -+ * -+ * @return a healthy {@link Result} with no additional message - */ -- class Result { -- private static final DateTimeFormatter DATE_FORMAT_PATTERN = -- DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); -- private static final int PRIME = 31; -- -- /** -- * Returns a healthy {@link Result} with no additional message. -- * -- * @return a healthy {@link Result} with no additional message -- */ -- public static Result healthy() { -- return new Result(true, null, null); -- } -- -- /** -- * Returns a healthy {@link Result} with an additional message. -- * -- * @param message an informative message -- * @return a healthy {@link Result} with an additional message -- */ -- public static Result healthy(String message) { -- return new Result(true, message, null); -- } -+ public static Result healthy() { -+ return new Result(true, null, null); -+ } - -- /** -- * Returns a healthy {@link Result} with a formatted message. -- *

    -- * Message formatting follows the same rules as {@link String#format(String, Object...)}. -- * -- * @param message a message format -- * @param args the arguments apply to the message format -- * @return a healthy {@link Result} with an additional message -- * @see String#format(String, Object...) -- */ -- public static Result healthy(String message, Object... args) { -- return healthy(String.format(message, args)); -- } -+ /** -+ * Returns a healthy {@link Result} with an additional message. -+ * -+ * @param message an informative message -+ * @return a healthy {@link Result} with an additional message -+ */ -+ public static Result healthy(String message) { -+ return new Result(true, message, null); -+ } - -- /** -- * Returns an unhealthy {@link Result} with the given message. -- * -- * @param message an informative message describing how the health check failed -- * @return an unhealthy {@link Result} with the given message -- */ -- public static Result unhealthy(String message) { -- return new Result(false, message, null); -- } -+ /** -+ * Returns a healthy {@link Result} with a formatted message. -+ * -+ *

    Message formatting follows the same rules as {@link String#format(String, Object...)}. -+ * -+ * @param message a message format -+ * @param args the arguments apply to the message format -+ * @return a healthy {@link Result} with an additional message -+ * @see String#format(String, Object...) -+ */ -+ public static Result healthy(String message, Object... args) { -+ return healthy(String.format(message, args)); -+ } - -- /** -- * Returns an unhealthy {@link Result} with a formatted message. -- *

    -- * Message formatting follows the same rules as {@link String#format(String, Object...)}. -- * -- * @param message a message format -- * @param args the arguments apply to the message format -- * @return an unhealthy {@link Result} with an additional message -- * @see String#format(String, Object...) -- */ -- public static Result unhealthy(String message, Object... args) { -- return unhealthy(String.format(message, args)); -- } -+ /** -+ * Returns an unhealthy {@link Result} with the given message. -+ * -+ * @param message an informative message describing how the health check failed -+ * @return an unhealthy {@link Result} with the given message -+ */ -+ public static Result unhealthy(String message) { -+ return new Result(false, message, null); -+ } - -- /** -- * Returns an unhealthy {@link Result} with the given error. -- * -- * @param error an exception thrown during the health check -- * @return an unhealthy {@link Result} with the given {@code error} -- */ -- public static Result unhealthy(Throwable error) { -- return new Result(false, error.getMessage(), error); -- } -+ /** -+ * Returns an unhealthy {@link Result} with a formatted message. -+ * -+ *

    Message formatting follows the same rules as {@link String#format(String, Object...)}. -+ * -+ * @param message a message format -+ * @param args the arguments apply to the message format -+ * @return an unhealthy {@link Result} with an additional message -+ * @see String#format(String, Object...) -+ */ -+ public static Result unhealthy(String message, Object... args) { -+ return unhealthy(String.format(message, args)); -+ } - -+ /** -+ * Returns an unhealthy {@link Result} with the given error. -+ * -+ * @param error an exception thrown during the health check -+ * @return an unhealthy {@link Result} with the given {@code error} -+ */ -+ public static Result unhealthy(Throwable error) { -+ return new Result(false, error.getMessage(), error); -+ } - -- /** -- * Returns a new {@link ResultBuilder} -- * -- * @return the {@link ResultBuilder} -- */ -- public static ResultBuilder builder() { -- return new ResultBuilder(); -- } -+ /** -+ * Returns a new {@link ResultBuilder} -+ * -+ * @return the {@link ResultBuilder} -+ */ -+ public static ResultBuilder builder() { -+ return new ResultBuilder(); -+ } - -- private final boolean healthy; -- private final String message; -- private final Throwable error; -- private final Map details; -- private final long time; -+ private final boolean healthy; -+ private final String message; -+ private final Throwable error; -+ private final Map details; -+ private final long time; - -- private long duration; // Calculated field -+ private long duration; // Calculated field - -- private Result(boolean isHealthy, String message, Throwable error) { -- this(isHealthy, message, error, null, Clock.defaultClock()); -- } -+ private Result(boolean isHealthy, String message, Throwable error) { -+ this(isHealthy, message, error, null, Clock.defaultClock()); -+ } - -- private Result(ResultBuilder builder) { -- this(builder.healthy, builder.message, builder.error, builder.details, builder.clock); -- } -+ private Result(ResultBuilder builder) { -+ this(builder.healthy, builder.message, builder.error, builder.details, builder.clock); -+ } - -- private Result(boolean isHealthy, String message, Throwable error, Map details, Clock clock) { -- this.healthy = isHealthy; -- this.message = message; -- this.error = error; -- this.details = details == null ? null : Collections.unmodifiableMap(details); -- this.time = clock.getTime(); -- } -+ private Result( -+ boolean isHealthy, -+ String message, -+ Throwable error, -+ Map details, -+ Clock clock) { -+ this.healthy = isHealthy; -+ this.message = message; -+ this.error = error; -+ this.details = details == null ? null : unmodifiableMap(details); -+ this.time = clock.getTime(); -+ } - -- /** -- * Returns {@code true} if the result indicates the component is healthy; {@code false} -- * otherwise. -- * -- * @return {@code true} if the result indicates the component is healthy -- */ -- public boolean isHealthy() { -- return healthy; -- } -+ /** -+ * Returns {@code true} if the result indicates the component is healthy; {@code false} -+ * otherwise. -+ * -+ * @return {@code true} if the result indicates the component is healthy -+ */ -+ public boolean isHealthy() { -+ return healthy; -+ } - -- /** -- * Returns any additional message for the result, or {@code null} if the result has no -- * message. -- * -- * @return any additional message for the result, or {@code null} -- */ -- public String getMessage() { -- return message; -- } -+ /** -+ * Returns any additional message for the result, or {@code null} if the result has no message. -+ * -+ * @return any additional message for the result, or {@code null} -+ */ -+ public String getMessage() { -+ return message; -+ } - -- /** -- * Returns any exception for the result, or {@code null} if the result has no exception. -- * -- * @return any exception for the result, or {@code null} -- */ -- public Throwable getError() { -- return error; -- } -+ /** -+ * Returns any exception for the result, or {@code null} if the result has no exception. -+ * -+ * @return any exception for the result, or {@code null} -+ */ -+ public Throwable getError() { -+ return error; -+ } - -- /** -- * Returns the timestamp when the result was created as a formatted String. -- * -- * @return a formatted timestamp -- */ -- public String getTimestamp() { -- Instant currentInstant = Instant.ofEpochMilli(time); -- ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(currentInstant, ZoneId.systemDefault()); -- return DATE_FORMAT_PATTERN.format(zonedDateTime); -- } -+ /** -+ * Returns the timestamp when the result was created as a formatted String. -+ * -+ * @return a formatted timestamp -+ */ -+ public String getTimestamp() { -+ Instant currentInstant = Instant.ofEpochMilli(time); -+ ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault()); -+ return DATE_FORMAT_PATTERN.format(zonedDateTime); -+ } - -- /** -- * Returns the time when the result was created, in milliseconds since Epoch -- * -- * @return the time when the result was created -- */ -- public long getTime() { -- return time; -- } -+ /** -+ * Returns the time when the result was created, in milliseconds since Epoch -+ * -+ * @return the time when the result was created -+ */ -+ public long getTime() { -+ return time; -+ } - -- /** -- * Returns the duration in milliseconds that the healthcheck took to run -- * -- * @return the duration -- */ -- public long getDuration() { -- return duration; -- } -+ /** -+ * Returns the duration in milliseconds that the healthcheck took to run -+ * -+ * @return the duration -+ */ -+ public long getDuration() { -+ return duration; -+ } - -- /** -- * Sets the duration in milliseconds. This will indicate the time it took to run the individual healthcheck -- * -- * @param duration The duration in milliseconds -- */ -- public void setDuration(long duration) { -- this.duration = duration; -- } -+ /** -+ * Sets the duration in milliseconds. This will indicate the time it took to run the individual -+ * healthcheck -+ * -+ * @param duration The duration in milliseconds -+ */ -+ public void setDuration(long duration) { -+ this.duration = duration; -+ } - -- public Map getDetails() { -- return details; -- } -+ public Map getDetails() { -+ return details; -+ } - -- @Override -- public boolean equals(Object o) { -- if (this == o) { -- return true; -- } -- if (o == null || getClass() != o.getClass()) { -- return false; -- } -- final Result result = (Result) o; -- return healthy == result.healthy && -- !(error != null ? !error.equals(result.error) : result.error != null) && -- !(message != null ? !message.equals(result.message) : result.message != null) && -- time == result.time; -- } -+ @Override -+ public boolean equals(Object o) { -+ if (this == o) { -+ return true; -+ } -+ if (o == null || getClass() != o.getClass()) { -+ return false; -+ } -+ final Result result = (Result) o; -+ return healthy == result.healthy -+ && !(error != null ? !error.equals(result.error) : result.error != null) -+ && !(message != null ? !message.equals(result.message) : result.message != null) -+ && time == result.time; -+ } - -- @Override -- public int hashCode() { -- int result = healthy ? 1 : 0; -- result = PRIME * result + (message != null ? message.hashCode() : 0); -- result = PRIME * result + (error != null ? error.hashCode() : 0); -- result = PRIME * result + (Long.hashCode(time)); -- return result; -- } -+ @Override -+ public int hashCode() { -+ int result = healthy ? 1 : 0; -+ result = PRIME * result + (message != null ? message.hashCode() : 0); -+ result = PRIME * result + (error != null ? error.hashCode() : 0); -+ return PRIME * result + (Long.hashCode(time)); -+ } - -- @Override -- public String toString() { -- final StringBuilder builder = new StringBuilder("Result{isHealthy="); -- builder.append(healthy); -- if (message != null) { -- builder.append(", message=").append(message); -- } -- if (error != null) { -- builder.append(", error=").append(error); -- } -- builder.append(", duration=").append(duration); -- builder.append(", timestamp=").append(getTimestamp()); -- if (details != null) { -- for (Map.Entry e : details.entrySet()) { -- builder.append(", "); -- builder.append(e.getKey()) -- .append("=") -- .append(String.valueOf(e.getValue())); -- } -- } -- builder.append('}'); -- return builder.toString(); -+ @Override -+ public String toString() { -+ final StringBuilder builder = new StringBuilder("Result{isHealthy="); -+ builder.append(healthy); -+ if (message != null) { -+ builder.append(", message=").append(message); -+ } -+ if (error != null) { -+ builder.append(", error=").append(error); -+ } -+ builder.append(", duration=").append(duration); -+ builder.append(", timestamp=").append(getTimestamp()); -+ if (details != null) { -+ for (Map.Entry e : details.entrySet()) { -+ builder.append(", "); -+ builder.append(e.getKey()).append("=").append(e.getValue()); - } -+ } -+ builder.append('}'); -+ return builder.toString(); -+ } -+ } -+ -+ /** -+ * This a convenient builder for an {@link HealthCheck.Result}. It can be health (with optional -+ * message and detail) or unhealthy (with optional message, error and detail) -+ */ -+ class ResultBuilder { -+ private boolean healthy; -+ private String message; -+ private Throwable error; -+ private Map details; -+ private Clock clock; -+ -+ protected ResultBuilder() { -+ this.healthy = true; -+ this.details = new LinkedHashMap<>(); -+ this.clock = Clock.defaultClock(); - } - - /** -- * This a convenient builder for an {@link HealthCheck.Result}. It can be health (with optional message and detail) -- * or unhealthy (with optional message, error and detail) -+ * Configure an healthy result -+ * -+ * @return this builder with healthy status - */ -- class ResultBuilder { -- private boolean healthy; -- private String message; -- private Throwable error; -- private Map details; -- private Clock clock; -- -- protected ResultBuilder() { -- this.healthy = true; -- this.details = new LinkedHashMap<>(); -- this.clock = Clock.defaultClock(); -- } -- -- /** -- * Configure an healthy result -- * -- * @return this builder with healthy status -- */ -- public ResultBuilder healthy() { -- this.healthy = true; -- return this; -- } -- -- /** -- * Configure an unhealthy result -- * -- * @return this builder with unhealthy status -- */ -- public ResultBuilder unhealthy() { -- this.healthy = false; -- return this; -- } -- -- /** -- * Configure an unhealthy result with an {@code error} -- * -- * @param error the error -- * @return this builder with the given error -- */ -- public ResultBuilder unhealthy(Throwable error) { -- this.error = error; -- return this.unhealthy().withMessage(error.getMessage()); -- } -- -- /** -- * Set an optional message -- * -- * @param message an informative message -- * @return this builder with the given {@code message} -- */ -- public ResultBuilder withMessage(String message) { -- this.message = message; -- return this; -- } -+ public ResultBuilder healthy() { -+ this.healthy = true; -+ return this; -+ } - -- /** -- * Set an optional formatted message -- *

    -- * Message formatting follows the same rules as {@link String#format(String, Object...)}. -- * -- * @param message a message format -- * @param args the arguments apply to the message format -- * @return this builder with the given formatted {@code message} -- * @see String#format(String, Object...) -- */ -- public ResultBuilder withMessage(String message, Object... args) { -- return withMessage(String.format(message, args)); -- } -+ /** -+ * Configure an unhealthy result -+ * -+ * @return this builder with unhealthy status -+ */ -+ public ResultBuilder unhealthy() { -+ this.healthy = false; -+ return this; -+ } - -- /** -- * Add an optional detail -- * -- * @param key a key for this detail -- * @param data an object representing the detail data -- * @return this builder with the given detail added -- */ -- public ResultBuilder withDetail(String key, Object data) { -- if (this.details == null) { -- this.details = new LinkedHashMap<>(); -- } -- this.details.put(key, data); -- return this; -- } -+ /** -+ * Configure an unhealthy result with an {@code error} -+ * -+ * @param error the error -+ * @return this builder with the given error -+ */ -+ public ResultBuilder unhealthy(Throwable error) { -+ this.error = error; -+ return this.unhealthy().withMessage(error.getMessage()); -+ } - -- /** -- * Configure this {@link ResultBuilder} to use the given {@code clock} instead of the default clock. -- * If not specified, the default clock is {@link Clock#defaultClock()}. -- * -- * @param clock the {@link Clock} to use when generating the health check timestamp (useful for unit testing) -- * @return this builder configured to use the given {@code clock} -- */ -- public ResultBuilder usingClock(Clock clock) { -- this.clock = clock; -- return this; -- } -+ /** -+ * Set an optional message -+ * -+ * @param message an informative message -+ * @return this builder with the given {@code message} -+ */ -+ public ResultBuilder withMessage(String message) { -+ this.message = message; -+ return this; -+ } - -- public Result build() { -- return new Result(this); -- } -+ /** -+ * Set an optional formatted message -+ * -+ *

    Message formatting follows the same rules as {@link String#format(String, Object...)}. -+ * -+ * @param message a message format -+ * @param args the arguments apply to the message format -+ * @return this builder with the given formatted {@code message} -+ * @see String#format(String, Object...) -+ */ -+ public ResultBuilder withMessage(String message, Object... args) { -+ return withMessage(String.format(message, args)); - } - - /** -- * Perform a check of the application component. -+ * Add an optional detail - * -- * @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link -- * Result} with a descriptive error message or exception -- * @throws Exception if there is an unhandled error during the health check; this will result in -- * a failed health check -+ * @param key a key for this detail -+ * @param data an object representing the detail data -+ * @return this builder with the given detail added - */ -- Result check() throws Exception; -+ public ResultBuilder withDetail(String key, Object data) { -+ if (this.details == null) { -+ this.details = new LinkedHashMap<>(); -+ } -+ this.details.put(key, data); -+ return this; -+ } - - /** -- * Executes the health check, catching and handling any exceptions raised by {@link #check()}. -+ * Configure this {@link ResultBuilder} to use the given {@code clock} instead of the default -+ * clock. If not specified, the default clock is {@link Clock#defaultClock()}. - * -- * @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link -- * Result} with a descriptive error message or exception -+ * @param clock the {@link Clock} to use when generating the health check timestamp (useful for -+ * unit testing) -+ * @return this builder configured to use the given {@code clock} - */ -- default Result execute() { -- long start = clock().getTick(); -- Result result; -- try { -- result = check(); -- } catch (Exception e) { -- result = Result.unhealthy(e); -- } -- result.setDuration(TimeUnit.MILLISECONDS.convert(clock().getTick() - start, TimeUnit.NANOSECONDS)); -- return result; -+ public ResultBuilder usingClock(Clock clock) { -+ this.clock = clock; -+ return this; - } - -- default Clock clock() { -- return Clock.defaultClock(); -+ public Result build() { -+ return new Result(this); -+ } -+ } -+ -+ /** -+ * Perform a check of the application component. -+ * -+ * @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link -+ * Result} with a descriptive error message or exception -+ * @throws Exception if there is an unhandled error during the health check; this will result in a -+ * failed health check -+ */ -+ Result check() throws Exception; -+ -+ /** -+ * Executes the health check, catching and handling any exceptions raised by {@link #check()}. -+ * -+ * @return if the component is healthy, a healthy {@link Result}; otherwise, an unhealthy {@link -+ * Result} with a descriptive error message or exception -+ */ -+ default Result execute() { -+ long start = clock().getTick(); -+ Result result; -+ try { -+ result = check(); -+ } catch (Exception e) { -+ result = Result.unhealthy(e); - } -+ result.setDuration( -+ TimeUnit.MILLISECONDS.convert(clock().getTick() - start, TimeUnit.NANOSECONDS)); -+ return result; -+ } -+ -+ default Clock clock() { -+ return Clock.defaultClock(); -+ } - } ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckFilter.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckFilter.java -@@ -1,21 +1,17 @@ - package io.dropwizard.metrics5.health; - --/** -- * A filter used to determine whether or not a health check should be reported. -- */ -+/** A filter used to determine whether or not a health check should be reported. */ - @FunctionalInterface - public interface HealthCheckFilter { -- /** -- * Matches all health checks, regardless of type or name. -- */ -- HealthCheckFilter ALL = (name, healthCheck) -> true; -+ /** Matches all health checks, regardless of type or name. */ -+ HealthCheckFilter ALL = (name, healthCheck) -> true; - -- /** -- * Returns {@code true} if the health check matches the filter; {@code false} otherwise. -- * -- * @param name the health check's name -- * @param healthCheck the health check -- * @return {@code true} if the health check matches the filter -- */ -- boolean matches(String name, HealthCheck healthCheck); -+ /** -+ * Returns {@code true} if the health check matches the filter; {@code false} otherwise. -+ * -+ * @param name the health check's name -+ * @param healthCheck the health check -+ * @return {@code true} if the health check matches the filter -+ */ -+ boolean matches(String name, HealthCheck healthCheck); - } ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java -@@ -1,10 +1,11 @@ - package io.dropwizard.metrics5.health; - --import io.dropwizard.metrics5.health.annotation.Async; --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -+import static com.google.common.base.Preconditions.checkArgument; -+import static io.dropwizard.metrics5.health.HealthCheck.Result; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Collections.unmodifiableSortedSet; - --import java.util.Collections; -+import io.dropwizard.metrics5.health.annotation.Async; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -23,266 +24,260 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; - import java.util.concurrent.ThreadFactory; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicInteger; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; - --import static io.dropwizard.metrics5.health.HealthCheck.Result; -- --/** -- * A registry for health checks. -- */ -+/** A registry for health checks. */ - public class HealthCheckRegistry { -- private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckRegistry.class); -- private static final int ASYNC_EXECUTOR_POOL_SIZE = 2; -+ private static final Logger LOG = LoggerFactory.getLogger(HealthCheckRegistry.class); -+ private static final int ASYNC_EXECUTOR_POOL_SIZE = 2; - -- private final ConcurrentMap healthChecks; -- private final List listeners; -- private final ScheduledExecutorService asyncExecutorService; -- private final Object lock = new Object(); -+ private final ConcurrentMap healthChecks; -+ private final List listeners; -+ private final ScheduledExecutorService asyncExecutorService; -+ private final Object lock = new Object(); - -- /** -- * Creates a new {@link HealthCheckRegistry}. -- */ -- public HealthCheckRegistry() { -- this(ASYNC_EXECUTOR_POOL_SIZE); -- } -+ /** Creates a new {@link HealthCheckRegistry}. */ -+ public HealthCheckRegistry() { -+ this(ASYNC_EXECUTOR_POOL_SIZE); -+ } - -- /** -- * Creates a new {@link HealthCheckRegistry}. -- * -- * @param asyncExecutorPoolSize core pool size for async health check executions -- */ -- public HealthCheckRegistry(int asyncExecutorPoolSize) { -- this(createExecutorService(asyncExecutorPoolSize)); -- } -+ /** -+ * Creates a new {@link HealthCheckRegistry}. -+ * -+ * @param asyncExecutorPoolSize core pool size for async health check executions -+ */ -+ public HealthCheckRegistry(int asyncExecutorPoolSize) { -+ this(createExecutorService(asyncExecutorPoolSize)); -+ } - -- /** -- * Creates a new {@link HealthCheckRegistry}. -- * -- * @param asyncExecutorService executor service for async health check executions -- */ -- public HealthCheckRegistry(ScheduledExecutorService asyncExecutorService) { -- this.healthChecks = new ConcurrentHashMap<>(); -- this.listeners = new CopyOnWriteArrayList<>(); -- this.asyncExecutorService = asyncExecutorService; -- } -+ /** -+ * Creates a new {@link HealthCheckRegistry}. -+ * -+ * @param asyncExecutorService executor service for async health check executions -+ */ -+ public HealthCheckRegistry(ScheduledExecutorService asyncExecutorService) { -+ this.healthChecks = new ConcurrentHashMap<>(); -+ this.listeners = new CopyOnWriteArrayList<>(); -+ this.asyncExecutorService = asyncExecutorService; -+ } - -- /** -- * Adds a {@link HealthCheckRegistryListener} to a collection of listeners that will be notified on health check -- * registration. Listeners will be notified in the order in which they are added. The listener will be notified of all -- * existing health checks when it first registers. -- * -- * @param listener listener to add -- */ -- public void addListener(HealthCheckRegistryListener listener) { -- listeners.add(listener); -- for (Map.Entry entry : healthChecks.entrySet()) { -- listener.onHealthCheckAdded(entry.getKey(), entry.getValue()); -- } -+ /** -+ * Adds a {@link HealthCheckRegistryListener} to a collection of listeners that will be notified -+ * on health check registration. Listeners will be notified in the order in which they are added. -+ * The listener will be notified of all existing health checks when it first registers. -+ * -+ * @param listener listener to add -+ */ -+ public void addListener(HealthCheckRegistryListener listener) { -+ listeners.add(listener); -+ for (Map.Entry entry : healthChecks.entrySet()) { -+ listener.onHealthCheckAdded(entry.getKey(), entry.getValue()); - } -+ } - -- /** -- * Removes a {@link HealthCheckRegistryListener} from this registry's collection of listeners. -- * -- * @param listener listener to remove -- */ -- public void removeListener(HealthCheckRegistryListener listener) { -- listeners.remove(listener); -- } -+ /** -+ * Removes a {@link HealthCheckRegistryListener} from this registry's collection of listeners. -+ * -+ * @param listener listener to remove -+ */ -+ public void removeListener(HealthCheckRegistryListener listener) { -+ listeners.remove(listener); -+ } - -- /** -- * Registers an application {@link HealthCheck}. -- * -- * @param name the name of the health check -- * @param healthCheck the {@link HealthCheck} instance -- */ -- public void register(String name, HealthCheck healthCheck) { -- HealthCheck registered; -- synchronized (lock) { -- if (healthChecks.containsKey(name)) { -- throw new IllegalArgumentException("A health check named " + name + " already exists"); -- } -- registered = healthCheck; -- if (healthCheck.getClass().isAnnotationPresent(Async.class)) { -- registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); -- } -- healthChecks.put(name, registered); -- } -- onHealthCheckAdded(name, registered); -+ /** -+ * Registers an application {@link HealthCheck}. -+ * -+ * @param name the name of the health check -+ * @param healthCheck the {@link HealthCheck} instance -+ */ -+ public void register(String name, HealthCheck healthCheck) { -+ HealthCheck registered; -+ synchronized (lock) { -+ checkArgument( -+ !healthChecks.containsKey(name), "A health check named %s already exists", name); -+ registered = healthCheck; -+ if (healthCheck.getClass().isAnnotationPresent(Async.class)) { -+ registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); -+ } -+ healthChecks.put(name, registered); - } -+ onHealthCheckAdded(name, registered); -+ } - -- /** -- * Unregisters the application {@link HealthCheck} with the given name. -- * -- * @param name the name of the {@link HealthCheck} instance -- */ -- public void unregister(String name) { -- HealthCheck healthCheck; -- synchronized (lock) { -- healthCheck = healthChecks.remove(name); -- if (healthCheck instanceof AsyncHealthCheckDecorator) { -- ((AsyncHealthCheckDecorator) healthCheck).tearDown(); -- } -- } -- if (healthCheck != null) { -- onHealthCheckRemoved(name, healthCheck); -- } -+ /** -+ * Unregisters the application {@link HealthCheck} with the given name. -+ * -+ * @param name the name of the {@link HealthCheck} instance -+ */ -+ public void unregister(String name) { -+ HealthCheck healthCheck; -+ synchronized (lock) { -+ healthCheck = healthChecks.remove(name); -+ if (healthCheck instanceof AsyncHealthCheckDecorator) { -+ ((AsyncHealthCheckDecorator) healthCheck).tearDown(); -+ } - } -- -- /** -- * Returns a set of the names of all registered health checks. -- * -- * @return the names of all registered health checks -- */ -- public SortedSet getNames() { -- return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); -+ if (healthCheck != null) { -+ onHealthCheckRemoved(name, healthCheck); - } -+ } - -- /** -- * Returns the {@link HealthCheck} instance with a given name -- * -- * @param name the name of the {@link HealthCheck} instance -- */ -- public HealthCheck getHealthCheck(String name) { -- return healthChecks.get(name); -- } -+ /** -+ * Returns a set of the names of all registered health checks. -+ * -+ * @return the names of all registered health checks -+ */ -+ public SortedSet getNames() { -+ return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); -+ } - -- /** -- * Runs the health check with the given name. -- * -- * @param name the health check's name -- * @return the result of the health check -- * @throws NoSuchElementException if there is no health check with the given name -- */ -- public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException { -- final HealthCheck healthCheck = healthChecks.get(name); -- if (healthCheck == null) { -- throw new NoSuchElementException("No health check named " + name + " exists"); -- } -- return healthCheck.execute(); -- } -+ /** -+ * Returns the {@link HealthCheck} instance with a given name -+ * -+ * @param name the name of the {@link HealthCheck} instance -+ */ -+ public HealthCheck getHealthCheck(String name) { -+ return healthChecks.get(name); -+ } - -- /** -- * Runs the registered health checks and returns a map of the results. -- * -- * @return a map of the health check results -- */ -- public SortedMap runHealthChecks() { -- return runHealthChecks(HealthCheckFilter.ALL); -+ /** -+ * Runs the health check with the given name. -+ * -+ * @param name the health check's name -+ * @return the result of the health check -+ * @throws NoSuchElementException if there is no health check with the given name -+ */ -+ public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException { -+ final HealthCheck healthCheck = healthChecks.get(name); -+ if (healthCheck == null) { -+ throw new NoSuchElementException("No health check named " + name + " exists"); - } -+ return healthCheck.execute(); -+ } - -- /** -- * Runs the registered health checks matching the filter and returns a map of the results. -- * -- * @param filter health check filter -- * @return a map of the health check results -- */ -- public SortedMap runHealthChecks(HealthCheckFilter filter) { -- final SortedMap results = new TreeMap<>(); -- for (Map.Entry entry : healthChecks.entrySet()) { -- final String name = entry.getKey(); -- final HealthCheck healthCheck = entry.getValue(); -- if (filter.matches(name, healthCheck)) { -- final Result result = entry.getValue().execute(); -- results.put(entry.getKey(), result); -- } -- } -- return Collections.unmodifiableSortedMap(results); -- } -+ /** -+ * Runs the registered health checks and returns a map of the results. -+ * -+ * @return a map of the health check results -+ */ -+ public SortedMap runHealthChecks() { -+ return runHealthChecks(HealthCheckFilter.ALL); -+ } - -- /** -- * Runs the registered health checks in parallel and returns a map of the results. -- * -- * @param executor object to launch and track health checks progress -- * @return a map of the health check results -- */ -- public SortedMap runHealthChecks(ExecutorService executor) { -- return runHealthChecks(executor, HealthCheckFilter.ALL); -+ /** -+ * Runs the registered health checks matching the filter and returns a map of the results. -+ * -+ * @param filter health check filter -+ * @return a map of the health check results -+ */ -+ public SortedMap runHealthChecks(HealthCheckFilter filter) { -+ final SortedMap results = new TreeMap<>(); -+ for (Map.Entry entry : healthChecks.entrySet()) { -+ final String name = entry.getKey(); -+ final HealthCheck healthCheck = entry.getValue(); -+ if (filter.matches(name, healthCheck)) { -+ final Result result = entry.getValue().execute(); -+ results.put(entry.getKey(), result); -+ } - } -+ return unmodifiableSortedMap(results); -+ } - -- /** -- * Runs the registered health checks matching the filter in parallel and returns a map of the results. -- * -- * @param executor object to launch and track health checks progress -- * @param filter health check filter -- * @return a map of the health check results -- */ -- public SortedMap runHealthChecks(ExecutorService executor, HealthCheckFilter filter) { -- final Map> futures = new HashMap<>(); -- for (final Map.Entry entry : healthChecks.entrySet()) { -- final String name = entry.getKey(); -- final HealthCheck healthCheck = entry.getValue(); -- if (filter.matches(name, healthCheck)) { -- futures.put(name, executor.submit(healthCheck::execute)); -- } -- } -+ /** -+ * Runs the registered health checks in parallel and returns a map of the results. -+ * -+ * @param executor object to launch and track health checks progress -+ * @return a map of the health check results -+ */ -+ public SortedMap runHealthChecks(ExecutorService executor) { -+ return runHealthChecks(executor, HealthCheckFilter.ALL); -+ } - -- final SortedMap results = new TreeMap<>(); -- for (Map.Entry> entry : futures.entrySet()) { -- try { -- results.put(entry.getKey(), entry.getValue().get()); -- } catch (Exception e) { -- LOGGER.warn("Error executing health check {}", entry.getKey(), e); -- results.put(entry.getKey(), HealthCheck.Result.unhealthy(e)); -- } -- } -+ /** -+ * Runs the registered health checks matching the filter in parallel and returns a map of the -+ * results. -+ * -+ * @param executor object to launch and track health checks progress -+ * @param filter health check filter -+ * @return a map of the health check results -+ */ -+ public SortedMap runHealthChecks( -+ ExecutorService executor, HealthCheckFilter filter) { -+ final Map> futures = new HashMap<>(); -+ for (final Map.Entry entry : healthChecks.entrySet()) { -+ final String name = entry.getKey(); -+ final HealthCheck healthCheck = entry.getValue(); -+ if (filter.matches(name, healthCheck)) { -+ futures.put(name, executor.submit(healthCheck::execute)); -+ } -+ } - -- return Collections.unmodifiableSortedMap(results); -+ final SortedMap results = new TreeMap<>(); -+ for (Map.Entry> entry : futures.entrySet()) { -+ try { -+ results.put(entry.getKey(), entry.getValue().get()); -+ } catch (Exception e) { -+ LOG.warn("Error executing health check {}", entry.getKey(), e); -+ results.put(entry.getKey(), HealthCheck.Result.unhealthy(e)); -+ } - } - -+ return unmodifiableSortedMap(results); -+ } - -- private void onHealthCheckAdded(String name, HealthCheck healthCheck) { -- for (HealthCheckRegistryListener listener : listeners) { -- listener.onHealthCheckAdded(name, healthCheck); -- } -+ private void onHealthCheckAdded(String name, HealthCheck healthCheck) { -+ for (HealthCheckRegistryListener listener : listeners) { -+ listener.onHealthCheckAdded(name, healthCheck); - } -+ } - -- private void onHealthCheckRemoved(String name, HealthCheck healthCheck) { -- for (HealthCheckRegistryListener listener : listeners) { -- listener.onHealthCheckRemoved(name, healthCheck); -- } -+ private void onHealthCheckRemoved(String name, HealthCheck healthCheck) { -+ for (HealthCheckRegistryListener listener : listeners) { -+ listener.onHealthCheckRemoved(name, healthCheck); - } -+ } - -- /** -- * Shuts down the scheduled executor for async health checks -- */ -- public void shutdown() { -- asyncExecutorService.shutdown(); // Disable new health checks from being submitted -- try { -- // Give some time to the current healtch checks to finish gracefully -- if (!asyncExecutorService.awaitTermination(1, TimeUnit.SECONDS)) { -- asyncExecutorService.shutdownNow(); -- } -- } catch (InterruptedException ie) { -- asyncExecutorService.shutdownNow(); -- Thread.currentThread().interrupt(); -- } -+ /** Shuts down the scheduled executor for async health checks */ -+ public void shutdown() { -+ asyncExecutorService.shutdown(); // Disable new health checks from being submitted -+ try { -+ // Give some time to the current healtch checks to finish gracefully -+ if (!asyncExecutorService.awaitTermination(1, TimeUnit.SECONDS)) { -+ asyncExecutorService.shutdownNow(); -+ } -+ } catch (InterruptedException ie) { -+ asyncExecutorService.shutdownNow(); -+ Thread.currentThread().interrupt(); - } -+ } - -- private static ScheduledExecutorService createExecutorService(int corePoolSize) { -- final ScheduledThreadPoolExecutor asyncExecutorService = new ScheduledThreadPoolExecutor(corePoolSize, -- new NamedThreadFactory("healthcheck-async-executor-")); -- asyncExecutorService.setRemoveOnCancelPolicy(true); -- return asyncExecutorService; -- } -+ private static ScheduledExecutorService createExecutorService(int corePoolSize) { -+ final ScheduledThreadPoolExecutor asyncExecutorService = -+ new ScheduledThreadPoolExecutor( -+ corePoolSize, new NamedThreadFactory("healthcheck-async-executor-")); -+ asyncExecutorService.setRemoveOnCancelPolicy(true); -+ return asyncExecutorService; -+ } - -- private static class NamedThreadFactory implements ThreadFactory { -+ private static class NamedThreadFactory implements ThreadFactory { - -- private final ThreadGroup group; -- private final AtomicInteger threadNumber = new AtomicInteger(1); -- private final String namePrefix; -+ private final ThreadGroup group; -+ private final AtomicInteger threadNumber = new AtomicInteger(1); -+ private final String namePrefix; - -- NamedThreadFactory(String namePrefix) { -- SecurityManager s = System.getSecurityManager(); -- group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); -- this.namePrefix = namePrefix; -- } -+ NamedThreadFactory(String namePrefix) { -+ SecurityManager s = System.getSecurityManager(); -+ group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); -+ this.namePrefix = namePrefix; -+ } - -- @Override -- public Thread newThread(Runnable r) { -- Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); -- t.setDaemon(true); -- if (t.getPriority() != Thread.NORM_PRIORITY) -- t.setPriority(Thread.NORM_PRIORITY); -- return t; -- } -+ @Override -+ public Thread newThread(Runnable r) { -+ Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); -+ t.setDaemon(true); -+ if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); -+ return t; - } -+ } - } ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistryListener.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistryListener.java -@@ -2,25 +2,22 @@ package io.dropwizard.metrics5.health; - - import java.util.EventListener; - --/** -- * A listener contract for {@link HealthCheckRegistry} events. -- */ -+/** A listener contract for {@link HealthCheckRegistry} events. */ - public interface HealthCheckRegistryListener extends EventListener { - -- /** -- * Called when a new {@link HealthCheck} is added to the registry. -- * -- * @param name the name of the health check -- * @param healthCheck the health check -- */ -- void onHealthCheckAdded(String name, HealthCheck healthCheck); -- -- /** -- * Called when a {@link HealthCheck} is removed from the registry. -- * -- * @param name the name of the health check -- * @param healthCheck the health check -- */ -- void onHealthCheckRemoved(String name, HealthCheck healthCheck); -+ /** -+ * Called when a new {@link HealthCheck} is added to the registry. -+ * -+ * @param name the name of the health check -+ * @param healthCheck the health check -+ */ -+ void onHealthCheckAdded(String name, HealthCheck healthCheck); - -+ /** -+ * Called when a {@link HealthCheck} is removed from the registry. -+ * -+ * @param name the name of the health check -+ * @param healthCheck the health check -+ */ -+ void onHealthCheckRemoved(String name, HealthCheck healthCheck); - } ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistries.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistries.java -@@ -5,102 +5,103 @@ import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.ConcurrentMap; - import java.util.concurrent.atomic.AtomicReference; - --/** -- * A map of shared, named health registries. -- */ -+/** A map of shared, named health registries. */ - public class SharedHealthCheckRegistries { -- private static final ConcurrentMap REGISTRIES = -- new ConcurrentHashMap<>(); -+ private static final ConcurrentMap REGISTRIES = -+ new ConcurrentHashMap<>(); - -- private static AtomicReference defaultRegistryName = new AtomicReference<>(); -+ private static AtomicReference defaultRegistryName = new AtomicReference<>(); - -- /* Visible for testing */ -- static void setDefaultRegistryName(AtomicReference defaultRegistryName) { -- SharedHealthCheckRegistries.defaultRegistryName = defaultRegistryName; -- } -+ /* Visible for testing */ -+ static void setDefaultRegistryName(AtomicReference defaultRegistryName) { -+ SharedHealthCheckRegistries.defaultRegistryName = defaultRegistryName; -+ } - -- private SharedHealthCheckRegistries() { /* singleton */ } -+ private SharedHealthCheckRegistries() { -+ /* singleton */ -+ } - -- public static void clear() { -- REGISTRIES.clear(); -- } -+ public static void clear() { -+ REGISTRIES.clear(); -+ } - -- public static Set names() { -- return REGISTRIES.keySet(); -- } -+ public static Set names() { -+ return REGISTRIES.keySet(); -+ } - -- public static void remove(String key) { -- REGISTRIES.remove(key); -- } -+ public static void remove(String key) { -+ REGISTRIES.remove(key); -+ } - -- public static HealthCheckRegistry add(String name, HealthCheckRegistry registry) { -- return REGISTRIES.putIfAbsent(name, registry); -- } -+ public static HealthCheckRegistry add(String name, HealthCheckRegistry registry) { -+ return REGISTRIES.putIfAbsent(name, registry); -+ } - -- public static HealthCheckRegistry getOrCreate(String name) { -- final HealthCheckRegistry existing = REGISTRIES.get(name); -- if (existing == null) { -- final HealthCheckRegistry created = new HealthCheckRegistry(); -- final HealthCheckRegistry raced = add(name, created); -- if (raced == null) { -- return created; -- } -- return raced; -- } -- return existing; -+ public static HealthCheckRegistry getOrCreate(String name) { -+ final HealthCheckRegistry existing = REGISTRIES.get(name); -+ if (existing == null) { -+ final HealthCheckRegistry created = new HealthCheckRegistry(); -+ final HealthCheckRegistry raced = add(name, created); -+ if (raced == null) { -+ return created; -+ } -+ return raced; - } -+ return existing; -+ } - -- /** -- * Creates a new registry and sets it as the default one under the provided name. -- * -- * @param name the registry name -- * @return the default registry -- * @throws IllegalStateException if the name has already been set -- */ -- public synchronized static HealthCheckRegistry setDefault(String name) { -- final HealthCheckRegistry registry = getOrCreate(name); -- return setDefault(name, registry); -- } -+ /** -+ * Creates a new registry and sets it as the default one under the provided name. -+ * -+ * @param name the registry name -+ * @return the default registry -+ * @throws IllegalStateException if the name has already been set -+ */ -+ public static synchronized HealthCheckRegistry setDefault(String name) { -+ final HealthCheckRegistry registry = getOrCreate(name); -+ return setDefault(name, registry); -+ } - -- /** -- * Sets the provided registry as the default one under the provided name -- * -- * @param name the default registry name -- * @param healthCheckRegistry the default registry -- * @throws IllegalStateException if the default registry has already been set -- */ -- public static HealthCheckRegistry setDefault(String name, HealthCheckRegistry healthCheckRegistry) { -- if (defaultRegistryName.compareAndSet(null, name)) { -- add(name, healthCheckRegistry); -- return healthCheckRegistry; -- } -- throw new IllegalStateException("Default health check registry is already set."); -+ /** -+ * Sets the provided registry as the default one under the provided name -+ * -+ * @param name the default registry name -+ * @param healthCheckRegistry the default registry -+ * @throws IllegalStateException if the default registry has already been set -+ */ -+ public static HealthCheckRegistry setDefault( -+ String name, HealthCheckRegistry healthCheckRegistry) { -+ if (defaultRegistryName.compareAndSet(null, name)) { -+ add(name, healthCheckRegistry); -+ return healthCheckRegistry; - } -+ throw new IllegalStateException("Default health check registry is already set."); -+ } - -- /** -- * Gets the name of the default registry, if it has been set -- * -- * @return the default registry -- * @throws IllegalStateException if the default has not been set -- */ -- public static HealthCheckRegistry getDefault() { -- final HealthCheckRegistry healthCheckRegistry = tryGetDefault(); -- if (healthCheckRegistry != null) { -- return healthCheckRegistry; -- } -- throw new IllegalStateException("Default registry name has not been set."); -+ /** -+ * Gets the name of the default registry, if it has been set -+ * -+ * @return the default registry -+ * @throws IllegalStateException if the default has not been set -+ */ -+ public static HealthCheckRegistry getDefault() { -+ final HealthCheckRegistry healthCheckRegistry = tryGetDefault(); -+ if (healthCheckRegistry != null) { -+ return healthCheckRegistry; - } -+ throw new IllegalStateException("Default registry name has not been set."); -+ } - -- /** -- * Same as {@link #getDefault()} except returns null when the default registry has not been set. -- * -- * @return the default registry or null -- */ -- public static HealthCheckRegistry tryGetDefault() { -- final String name = defaultRegistryName.get(); -- if (name != null) { -- return getOrCreate(name); -- } -- return null; -+ /** -+ * Same as {@link #getDefault()} except returns null when the default registry has not been set. -+ * -+ * @return the default registry or null -+ */ -+ public static HealthCheckRegistry tryGetDefault() { -+ final String name = defaultRegistryName.get(); -+ if (name != null) { -+ return getOrCreate(name); - } -+ return null; -+ } - } ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/annotation/Async.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/annotation/Async.java -@@ -6,70 +6,66 @@ import java.lang.annotation.RetentionPolicy; - import java.lang.annotation.Target; - import java.util.concurrent.TimeUnit; - --/** -- * An annotation for marking asynchronous health check execution. -- */ -+/** An annotation for marking asynchronous health check execution. */ - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.TYPE) - public @interface Async { -- /** -- * Enum representing the initial health states. -- */ -- enum InitialState { -- HEALTHY, UNHEALTHY -- } -+ /** Enum representing the initial health states. */ -+ enum InitialState { -+ HEALTHY, -+ UNHEALTHY -+ } - -- /** -- * Enum representing the possible schedule types. -- */ -- enum ScheduleType { -- FIXED_RATE, FIXED_DELAY -- } -+ /** Enum representing the possible schedule types. */ -+ enum ScheduleType { -+ FIXED_RATE, -+ FIXED_DELAY -+ } - -- /** -- * Period between executions. -- * -- * @return period -- */ -- long period(); -+ /** -+ * Period between executions. -+ * -+ * @return period -+ */ -+ long period(); - -- /** -- * Scheduling type of asynchronous executions. -- * -- * @return schedule type -- */ -- ScheduleType scheduleType() default ScheduleType.FIXED_RATE; -+ /** -+ * Scheduling type of asynchronous executions. -+ * -+ * @return schedule type -+ */ -+ ScheduleType scheduleType() default ScheduleType.FIXED_RATE; - -- /** -- * Initial delay of first execution. -- * -- * @return initial delay -- */ -- long initialDelay() default 0; -+ /** -+ * Initial delay of first execution. -+ * -+ * @return initial delay -+ */ -+ long initialDelay() default 0; - -- /** -- * Time unit of initial delay, period and healthyTtl. -- * -- * @return time unit -- */ -- TimeUnit unit() default TimeUnit.SECONDS; -+ /** -+ * Time unit of initial delay, period and healthyTtl. -+ * -+ * @return time unit -+ */ -+ TimeUnit unit() default TimeUnit.SECONDS; - -- /** -- * Initial health state until first asynchronous execution completes. -- * -- * @return initial health state -- */ -- InitialState initialState() default InitialState.HEALTHY; -- -- /** -- * How long a healthy result is considered valid before being ignored. -- * -- * Handles cases where the asynchronous healthcheck did not run (for example thread starvation). -- * -- * Defaults to 2 * period -- * -- * @return healthy result time to live -- */ -- long healthyTtl() default -1; -+ /** -+ * Initial health state until first asynchronous execution completes. -+ * -+ * @return initial health state -+ */ -+ InitialState initialState() default InitialState.HEALTHY; - -+ /** -+ * How long a healthy result is considered valid before being ignored. -+ * -+ *

    Handles cases where the asynchronous healthcheck did not run (for example thread -+ * starvation). -+ * -+ *

    Defaults to 2 * period -+ * -+ * @return healthy result time to live -+ */ -+ long healthyTtl() default -1; - } ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheck.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheck.java -@@ -2,37 +2,32 @@ package io.dropwizard.metrics5.health.jvm; - - import io.dropwizard.metrics5.health.HealthCheck; - import io.dropwizard.metrics5.jvm.ThreadDeadlockDetector; -- - import java.util.Set; - --/** -- * A health check which returns healthy if no threads are deadlocked. -- */ -+/** A health check which returns healthy if no threads are deadlocked. */ - public class ThreadDeadlockHealthCheck implements HealthCheck { -- private final ThreadDeadlockDetector detector; -+ private final ThreadDeadlockDetector detector; - -- /** -- * Creates a new health check. -- */ -- public ThreadDeadlockHealthCheck() { -- this(new ThreadDeadlockDetector()); -- } -+ /** Creates a new health check. */ -+ public ThreadDeadlockHealthCheck() { -+ this(new ThreadDeadlockDetector()); -+ } - -- /** -- * Creates a new health check with the given detector. -- * -- * @param detector a thread deadlock detector -- */ -- public ThreadDeadlockHealthCheck(ThreadDeadlockDetector detector) { -- this.detector = detector; -- } -+ /** -+ * Creates a new health check with the given detector. -+ * -+ * @param detector a thread deadlock detector -+ */ -+ public ThreadDeadlockHealthCheck(ThreadDeadlockDetector detector) { -+ this.detector = detector; -+ } - -- @Override -- public Result check() throws Exception { -- final Set threads = detector.getDeadlockedThreads(); -- if (threads.isEmpty()) { -- return Result.healthy(); -- } -- return Result.unhealthy(threads.toString()); -+ @Override -+ public Result check() throws Exception { -+ final Set threads = detector.getDeadlockedThreads(); -+ if (threads.isEmpty()) { -+ return Result.healthy(); - } -+ return Result.unhealthy(threads.toString()); -+ } - } ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java -@@ -1,340 +1,388 @@ - package io.dropwizard.metrics5.health; - --import io.dropwizard.metrics5.Clock; --import io.dropwizard.metrics5.health.annotation.Async; --import org.junit.jupiter.api.Test; --import org.mockito.ArgumentCaptor; -- --import java.util.concurrent.ScheduledExecutorService; --import java.util.concurrent.ScheduledFuture; --import java.util.concurrent.TimeUnit; -- - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.ArgumentCaptor.forClass; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.*; -+import static org.mockito.Mockito.verify; - --/** -- * Unit tests for {@link AsyncHealthCheckDecorator}. -- */ --class AsyncHealthCheckDecoratorTest { -- -- private static final long CURRENT_TIME = 1551002401000L; -- -- private static final Clock FIXED_CLOCK = clockWithFixedTime(CURRENT_TIME); -- -- private static final HealthCheck.Result EXPECTED_EXPIRED_RESULT = HealthCheck.Result -- .builder() -- .usingClock(FIXED_CLOCK) -- .unhealthy() -- .withMessage("Result was healthy but it expired 1 milliseconds ago") -- .build(); -- -- private final HealthCheck mockHealthCheck = mock(HealthCheck.class); -- private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); -- -- @SuppressWarnings("rawtypes") -- private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); -- -- @Test -- void nullHealthCheckTriggersInstantiationFailure() { -- assertThrows(IllegalArgumentException.class, () -> { -- new AsyncHealthCheckDecorator(null, mockExecutorService); -- }); -- } -- -- @Test -- void nullExecutorServiceTriggersInstantiationFailure() { -- assertThrows(IllegalArgumentException.class, () -> { -- new AsyncHealthCheckDecorator(mockHealthCheck, null); -- }); -- } -- -- @Test -- void nonAsyncHealthCheckTriggersInstantiationFailure() { -- assertThrows(IllegalArgumentException.class, () -> { -- new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); -- }); -- } -- -- @Test -- void negativePeriodTriggersInstantiationFailure() { -- assertThrows(IllegalArgumentException.class, () -> { -- new AsyncHealthCheckDecorator(new NegativePeriodAsyncHealthCheck(), mockExecutorService); -- }); -- } -- -- @Test -- void zeroPeriodTriggersInstantiationFailure() { -- assertThrows(IllegalArgumentException.class, () -> { -- new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); -- }); -- } -- -- @Test -- void negativeInitialValueTriggersInstantiationFailure() { -- assertThrows(IllegalArgumentException.class, () -> { -- new AsyncHealthCheckDecorator(new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); -- }); -- } -- -- @Test -- void defaultAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedRateAndHealthyState() throws Exception { -- HealthCheck asyncHealthCheck = new DefaultAsyncHealthCheck(); -- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); -- -- verify(mockExecutorService, times(1)).scheduleAtFixedRate(any(Runnable.class), eq(0L), -- eq(1L), eq(TimeUnit.SECONDS)); -- assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); -- assertThat(asyncDecorator.check().isHealthy()).isTrue(); -- } -- -- @Test -- void fixedDelayAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedDelay() throws Exception { -- HealthCheck asyncHealthCheck = new FixedDelayAsyncHealthCheck(); -- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); -- -- verify(mockExecutorService, times(1)).scheduleWithFixedDelay(any(Runnable.class), eq(0L), -- eq(1L), eq(TimeUnit.SECONDS)); -- assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); -- } -- -- @Test -- void unhealthyAsyncHealthCheckTriggersSuccessfulInstantiationWithUnhealthyState() throws Exception { -- HealthCheck asyncHealthCheck = new UnhealthyAsyncHealthCheck(); -- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); -- -- assertThat(asyncDecorator.check().isHealthy()).isFalse(); -- } -- -- @Test -- @SuppressWarnings("unchecked") -- void tearDownTriggersCancellation() throws Exception { -- when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))). -- thenReturn(mockFuture); -- when(mockFuture.cancel(true)).thenReturn(true); -- -- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); -- asyncDecorator.tearDown(); -- -- verify(mockExecutorService, times(1)).scheduleAtFixedRate(any(Runnable.class), eq(0L), -- eq(1L), eq(TimeUnit.SECONDS)); -- verify(mockFuture, times(1)).cancel(eq(true)); -- } -- -- @Test -- @SuppressWarnings("unchecked") -- void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { -- HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); -- when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) -- .thenReturn(mockFuture); -- -- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(new ConfigurableAsyncHealthCheck(expectedResult), -- mockExecutorService); -- HealthCheck.Result initialResult = asyncDecorator.check(); -- -- ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), -- eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -- Runnable capturedRunnable = runnableCaptor.getValue(); -- capturedRunnable.run(); -- HealthCheck.Result actualResult = asyncDecorator.check(); -- -- assertThat(actualResult).isEqualTo(expectedResult); -- assertThat(actualResult).isNotEqualTo(initialResult); -- } -- -- @Test -- @SuppressWarnings("unchecked") -- void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { -- Exception exception = new Exception("TestException"); -- when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) -- .thenReturn(mockFuture); -- -- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(new ConfigurableAsyncHealthCheck(exception), -- mockExecutorService); -- -- ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), -- eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -- Runnable capturedRunnable = runnableCaptor.getValue(); -- capturedRunnable.run(); -- HealthCheck.Result result = asyncDecorator.check(); -- -- assertThat(result.isHealthy()).isFalse(); -- assertThat(result.getError()).isEqualTo(exception); -- } -- -- @Test -- void returnUnhealthyIfPreviousResultIsExpiredBasedOnTtl() throws Exception { -- HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInMilliseconds(); -- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); -- -- ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), -- eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); -- Runnable capturedRunnable = runnableCaptor.getValue(); -- capturedRunnable.run(); -- -- HealthCheck.Result result = asyncDecorator.check(); -- -- assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); -- } -- -- @Test -- void returnUnhealthyIfPreviousResultIsExpiredBasedOnPeriod() throws Exception { -- HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredTtlInMillisecondsBasedOnPeriod(); -- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); -- -- ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), -- eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); -- Runnable capturedRunnable = runnableCaptor.getValue(); -- capturedRunnable.run(); -- -- HealthCheck.Result result = asyncDecorator.check(); -+import io.dropwizard.metrics5.Clock; -+import io.dropwizard.metrics5.health.annotation.Async; -+import java.util.concurrent.ScheduledExecutorService; -+import java.util.concurrent.ScheduledFuture; -+import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.Test; -+import org.mockito.ArgumentCaptor; - -- assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); -+/** Unit tests for {@link AsyncHealthCheckDecorator}. */ -+final class AsyncHealthCheckDecoratorTest { -+ -+ private static final long CURRENT_TIME = 1551002401000L; -+ -+ private static final Clock FIXED_CLOCK = clockWithFixedTime(CURRENT_TIME); -+ -+ private static final HealthCheck.Result EXPECTED_EXPIRED_RESULT = -+ HealthCheck.Result.builder() -+ .usingClock(FIXED_CLOCK) -+ .unhealthy() -+ .withMessage("Result was healthy but it expired 1 milliseconds ago") -+ .build(); -+ -+ private final HealthCheck mockHealthCheck = mock(); -+ private final ScheduledExecutorService mockExecutorService = mock(); -+ -+ @SuppressWarnings("rawtypes") -+ private final ScheduledFuture mockFuture = mock(); -+ -+ @Test -+ void nullHealthCheckTriggersInstantiationFailure() { -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator(null, mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void nullExecutorServiceTriggersInstantiationFailure() { -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator(mockHealthCheck, null); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void nonAsyncHealthCheckTriggersInstantiationFailure() { -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void negativePeriodTriggersInstantiationFailure() { -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator( -+ new NegativePeriodAsyncHealthCheck(), mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void zeroPeriodTriggersInstantiationFailure() { -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void negativeInitialValueTriggersInstantiationFailure() { -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator( -+ new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void defaultAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedRateAndHealthyState() -+ throws Exception { -+ HealthCheck asyncHealthCheck = new DefaultAsyncHealthCheck(); -+ AsyncHealthCheckDecorator asyncDecorator = -+ new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); -+ -+ verify(mockExecutorService) -+ .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -+ assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); -+ assertThat(asyncDecorator.check().isHealthy()).isTrue(); -+ } -+ -+ @Test -+ void fixedDelayAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedDelay() throws Exception { -+ HealthCheck asyncHealthCheck = new FixedDelayAsyncHealthCheck(); -+ AsyncHealthCheckDecorator asyncDecorator = -+ new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); -+ -+ verify(mockExecutorService) -+ .scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -+ assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); -+ } -+ -+ @Test -+ void unhealthyAsyncHealthCheckTriggersSuccessfulInstantiationWithUnhealthyState() -+ throws Exception { -+ HealthCheck asyncHealthCheck = new UnhealthyAsyncHealthCheck(); -+ AsyncHealthCheckDecorator asyncDecorator = -+ new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); -+ -+ assertThat(asyncDecorator.check().isHealthy()).isFalse(); -+ } -+ -+ @SuppressWarnings("unchecked") -+ @Test -+ void tearDownTriggersCancellation() throws Exception { -+ when(mockExecutorService.scheduleAtFixedRate( -+ any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) -+ .thenReturn(mockFuture); -+ when(mockFuture.cancel(true)).thenReturn(true); -+ -+ AsyncHealthCheckDecorator asyncDecorator = -+ new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); -+ asyncDecorator.tearDown(); -+ -+ verify(mockExecutorService) -+ .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -+ verify(mockFuture).cancel(true); -+ } -+ -+ @SuppressWarnings("unchecked") -+ @Test -+ void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { -+ HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); -+ when(mockExecutorService.scheduleAtFixedRate( -+ any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) -+ .thenReturn(mockFuture); -+ -+ AsyncHealthCheckDecorator asyncDecorator = -+ new AsyncHealthCheckDecorator( -+ new ConfigurableAsyncHealthCheck(expectedResult), mockExecutorService); -+ HealthCheck.Result initialResult = asyncDecorator.check(); -+ -+ ArgumentCaptor runnableCaptor = forClass(Runnable.class); -+ verify(mockExecutorService) -+ .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -+ Runnable capturedRunnable = runnableCaptor.getValue(); -+ capturedRunnable.run(); -+ HealthCheck.Result actualResult = asyncDecorator.check(); -+ -+ assertThat(actualResult).isEqualTo(expectedResult); -+ assertThat(actualResult).isNotEqualTo(initialResult); -+ } -+ -+ @SuppressWarnings("unchecked") -+ @Test -+ void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { -+ Exception exception = new Exception("TestException"); -+ when(mockExecutorService.scheduleAtFixedRate( -+ any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) -+ .thenReturn(mockFuture); -+ -+ AsyncHealthCheckDecorator asyncDecorator = -+ new AsyncHealthCheckDecorator( -+ new ConfigurableAsyncHealthCheck(exception), mockExecutorService); -+ -+ ArgumentCaptor runnableCaptor = forClass(Runnable.class); -+ verify(mockExecutorService) -+ .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -+ Runnable capturedRunnable = runnableCaptor.getValue(); -+ capturedRunnable.run(); -+ HealthCheck.Result result = asyncDecorator.check(); -+ -+ assertThat(result.isHealthy()).isFalse(); -+ assertThat(result.getError()).isEqualTo(exception); -+ } -+ -+ @Test -+ void returnUnhealthyIfPreviousResultIsExpiredBasedOnTtl() throws Exception { -+ HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInMilliseconds(); -+ AsyncHealthCheckDecorator asyncDecorator = -+ new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); -+ -+ ArgumentCaptor runnableCaptor = forClass(Runnable.class); -+ verify(mockExecutorService) -+ .scheduleAtFixedRate( -+ runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); -+ Runnable capturedRunnable = runnableCaptor.getValue(); -+ capturedRunnable.run(); -+ -+ HealthCheck.Result result = asyncDecorator.check(); -+ -+ assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); -+ } -+ -+ @Test -+ void returnUnhealthyIfPreviousResultIsExpiredBasedOnPeriod() throws Exception { -+ HealthCheck healthCheck = -+ new HealthyAsyncHealthCheckWithExpiredTtlInMillisecondsBasedOnPeriod(); -+ AsyncHealthCheckDecorator asyncDecorator = -+ new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); -+ -+ ArgumentCaptor runnableCaptor = forClass(Runnable.class); -+ verify(mockExecutorService) -+ .scheduleAtFixedRate( -+ runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); -+ Runnable capturedRunnable = runnableCaptor.getValue(); -+ capturedRunnable.run(); -+ -+ HealthCheck.Result result = asyncDecorator.check(); -+ -+ assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); -+ } -+ -+ @Test -+ void convertTtlToMillisecondsWhenCheckingExpiration() throws Exception { -+ HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInSeconds(); -+ AsyncHealthCheckDecorator asyncDecorator = -+ new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); -+ -+ ArgumentCaptor runnableCaptor = forClass(Runnable.class); -+ verify(mockExecutorService) -+ .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -+ Runnable capturedRunnable = runnableCaptor.getValue(); -+ capturedRunnable.run(); -+ -+ HealthCheck.Result result = asyncDecorator.check(); -+ -+ assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); -+ } -+ -+ @Async(period = -1) -+ private static class NegativePeriodAsyncHealthCheck implements HealthCheck { -+ -+ @Override -+ public Result check() { -+ return null; - } -+ } - -- @Test -- void convertTtlToMillisecondsWhenCheckingExpiration() throws Exception { -- HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInSeconds(); -- AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); -- -- ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), -- eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -- Runnable capturedRunnable = runnableCaptor.getValue(); -- capturedRunnable.run(); -- -- HealthCheck.Result result = asyncDecorator.check(); -+ @Async(period = 0) -+ private static class ZeroPeriodAsyncHealthCheck implements HealthCheck { - -- assertThat(result).isEqualTo(EXPECTED_EXPIRED_RESULT); -+ @Override -+ public Result check() { -+ return null; - } -+ } - -- @Async(period = -1) -- private static class NegativePeriodAsyncHealthCheck implements HealthCheck { -+ @Async(period = 1, initialDelay = -1) -+ private static class NegativeInitialDelayAsyncHealthCheck implements HealthCheck { - -- @Override -- public Result check() { -- return null; -- } -+ @Override -+ public Result check() { -+ return null; - } -+ } - -- @Async(period = 0) -- private static class ZeroPeriodAsyncHealthCheck implements HealthCheck { -+ @Async(period = 1) -+ private static class DefaultAsyncHealthCheck implements HealthCheck { - -- @Override -- public Result check() { -- return null; -- } -+ @Override -+ public Result check() { -+ return null; - } -+ } - -- @Async(period = 1, initialDelay = -1) -- private static class NegativeInitialDelayAsyncHealthCheck implements HealthCheck { -+ @Async(period = 1, scheduleType = Async.ScheduleType.FIXED_DELAY) -+ private static class FixedDelayAsyncHealthCheck implements HealthCheck { - -- @Override -- public Result check() { -- return null; -- } -+ @Override -+ public Result check() { -+ return null; - } -+ } - -- @Async(period = 1) -- private static class DefaultAsyncHealthCheck implements HealthCheck { -+ @Async(period = 1, initialState = Async.InitialState.UNHEALTHY) -+ private static class UnhealthyAsyncHealthCheck implements HealthCheck { - -- @Override -- public Result check() { -- return null; -- } -+ @Override -+ public Result check() { -+ return null; - } -+ } - -- @Async(period = 1, scheduleType = Async.ScheduleType.FIXED_DELAY) -- private static class FixedDelayAsyncHealthCheck implements HealthCheck { -+ @Async(period = 1, initialState = Async.InitialState.UNHEALTHY) -+ private static class ConfigurableAsyncHealthCheck implements HealthCheck { -+ private final Result result; -+ private final Exception exception; - -- @Override -- public Result check() { -- return null; -- } -+ ConfigurableAsyncHealthCheck(Result result) { -+ this(result, null); - } - -- @Async(period = 1, initialState = Async.InitialState.UNHEALTHY) -- private static class UnhealthyAsyncHealthCheck implements HealthCheck { -- -- @Override -- public Result check() { -- return null; -- } -+ ConfigurableAsyncHealthCheck(Exception exception) { -+ this(null, exception); - } - -- @Async(period = 1, initialState = Async.InitialState.UNHEALTHY) -- private static class ConfigurableAsyncHealthCheck implements HealthCheck { -- private final Result result; -- private final Exception exception; -- -- ConfigurableAsyncHealthCheck(Result result) { -- this(result, null); -- } -- -- ConfigurableAsyncHealthCheck(Exception exception) { -- this(null, exception); -- } -- -- private ConfigurableAsyncHealthCheck(Result result, Exception exception) { -- this.result = result; -- this.exception = exception; -- } -- -- @Override -- public Result check() throws Exception { -- if (exception != null) { -- throw exception; -- } -- return result; -- } -+ private ConfigurableAsyncHealthCheck(Result result, Exception exception) { -+ this.result = result; -+ this.exception = exception; - } - -- @Async(period = 1000, initialState = Async.InitialState.UNHEALTHY, healthyTtl = 3000, unit = TimeUnit.MILLISECONDS) -- private static class HealthyAsyncHealthCheckWithExpiredExplicitTtlInMilliseconds implements HealthCheck { -- -- @Override -- public Result check() { -- return Result.builder().usingClock(clockWithFixedTime(CURRENT_TIME - 3001L)).healthy().build(); -- } -+ @Override -+ public Result check() throws Exception { -+ if (exception != null) { -+ throw exception; -+ } -+ return result; - } -- -- @Async(period = 1, initialState = Async.InitialState.UNHEALTHY, healthyTtl = 5, unit = TimeUnit.SECONDS) -- private static class HealthyAsyncHealthCheckWithExpiredExplicitTtlInSeconds implements HealthCheck { -- -- @Override -- public Result check() { -- return Result.builder().usingClock(clockWithFixedTime(CURRENT_TIME - 5001L)).healthy().build(); -- } -+ } -+ -+ @Async( -+ period = 1000, -+ initialState = Async.InitialState.UNHEALTHY, -+ healthyTtl = 3000, -+ unit = TimeUnit.MILLISECONDS) -+ private static class HealthyAsyncHealthCheckWithExpiredExplicitTtlInMilliseconds -+ implements HealthCheck { -+ -+ @Override -+ public Result check() { -+ return Result.builder() -+ .usingClock(clockWithFixedTime(CURRENT_TIME - 3001L)) -+ .healthy() -+ .build(); - } -- -- @Async(period = 1000, initialState = Async.InitialState.UNHEALTHY, unit = TimeUnit.MILLISECONDS) -- private static class HealthyAsyncHealthCheckWithExpiredTtlInMillisecondsBasedOnPeriod implements HealthCheck { -- -- @Override -- public Result check() { -- return Result.builder().usingClock(clockWithFixedTime(CURRENT_TIME - 2001L)).healthy().build(); -- } -+ } -+ -+ @Async( -+ period = 1, -+ initialState = Async.InitialState.UNHEALTHY, -+ healthyTtl = 5, -+ unit = TimeUnit.SECONDS) -+ private static class HealthyAsyncHealthCheckWithExpiredExplicitTtlInSeconds -+ implements HealthCheck { -+ -+ @Override -+ public Result check() { -+ return Result.builder() -+ .usingClock(clockWithFixedTime(CURRENT_TIME - 5001L)) -+ .healthy() -+ .build(); - } -- -- private static Clock clockWithFixedTime(final long time) { -- return new Clock() { -- @Override -- public long getTick() { -- return 0; -- } -- -- @Override -- public long getTime() { -- return time; -- } -- }; -+ } -+ -+ @Async(period = 1000, initialState = Async.InitialState.UNHEALTHY, unit = TimeUnit.MILLISECONDS) -+ private static class HealthyAsyncHealthCheckWithExpiredTtlInMillisecondsBasedOnPeriod -+ implements HealthCheck { -+ -+ @Override -+ public Result check() { -+ return Result.builder() -+ .usingClock(clockWithFixedTime(CURRENT_TIME - 2001L)) -+ .healthy() -+ .build(); - } -- -+ } -+ -+ private static Clock clockWithFixedTime(final long time) { -+ return new Clock() { -+ @Override -+ public long getTick() { -+ return 0; -+ } -+ -+ @Override -+ public long getTime() { -+ return time; -+ } -+ }; -+ } - } ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java -@@ -5,10 +5,10 @@ import static org.mockito.Mockito.mock; - - import org.junit.jupiter.api.Test; - --class HealthCheckFilterTest { -+final class HealthCheckFilterTest { - -- @Test -- void theAllFilterMatchesAllHealthChecks() { -- assertThat(HealthCheckFilter.ALL.matches("", mock(HealthCheck.class))).isTrue(); -- } -+ @Test -+ void theAllFilterMatchesAllHealthChecks() { -+ assertThat(HealthCheckFilter.ALL.matches("", mock(HealthCheck.class))).isTrue(); -+ } - } ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java -@@ -1,22 +1,9 @@ - package io.dropwizard.metrics5.health; - --import io.dropwizard.metrics5.health.annotation.Async; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; --import org.mockito.ArgumentCaptor; -- --import java.util.Map; --import java.util.NoSuchElementException; --import java.util.concurrent.ExecutorService; --import java.util.concurrent.Executors; --import java.util.concurrent.ScheduledExecutorService; --import java.util.concurrent.ScheduledFuture; --import java.util.concurrent.TimeUnit; -- - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.assertj.core.api.Assertions.entry; - import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; --import static org.junit.jupiter.api.Assertions.assertThrows; - import static org.mockito.ArgumentCaptor.forClass; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; -@@ -24,206 +11,224 @@ import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - --class HealthCheckRegistryTest { -- private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); -- private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); -- private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -- -- private final HealthCheck hc1 = mock(HealthCheck.class); -- private final HealthCheck hc2 = mock(HealthCheck.class); -- -- private final HealthCheck.Result r1 = mock(HealthCheck.Result.class); -- private final HealthCheck.Result r2 = mock(HealthCheck.Result.class); -- -- private final HealthCheck.Result ar = mock(HealthCheck.Result.class); -- private final HealthCheck ahc = new TestAsyncHealthCheck(ar); -- -- @SuppressWarnings("rawtypes") -- private final ScheduledFuture af = mock(ScheduledFuture.class); -- -- @BeforeEach -- @SuppressWarnings("unchecked") -- void setUp() { -- registry.addListener(listener); -- -- when(hc1.execute()).thenReturn(r1); -- when(hc2.execute()).thenReturn(r2); -- when(executorService.scheduleAtFixedRate(any(AsyncHealthCheckDecorator.class), eq(0L), eq(10L), eq(TimeUnit.SECONDS))) -- .thenReturn(af); -- -- registry.register("hc1", hc1); -- registry.register("hc2", hc2); -- registry.register("ahc", ahc); -- } -- -- @Test -- void asyncHealthCheckIsScheduledOnExecutor() { -- ArgumentCaptor decoratorCaptor = forClass(AsyncHealthCheckDecorator.class); -- verify(executorService).scheduleAtFixedRate(decoratorCaptor.capture(), eq(0L), eq(10L), eq(TimeUnit.SECONDS)); -- assertThat(decoratorCaptor.getValue().getHealthCheck()).isEqualTo(ahc); -- } -- -- @Test -- void asyncHealthCheckIsCanceledOnRemove() { -- registry.unregister("ahc"); -- -- verify(af).cancel(true); -- } -- -- @Test -- void registeringHealthCheckTwiceThrowsException() { -- assertThrows(IllegalArgumentException.class, () -> { -- registry.register("hc1", hc1); -- }); -- } -- -- @Test -- void registeringHealthCheckTriggersNotification() { -- verify(listener).onHealthCheckAdded("hc1", hc1); -- verify(listener).onHealthCheckAdded("hc2", hc2); -- verify(listener).onHealthCheckAdded(eq("ahc"), any(AsyncHealthCheckDecorator.class)); -- } -- -- @Test -- void removingHealthCheckTriggersNotification() { -- registry.unregister("hc1"); -- registry.unregister("hc2"); -- registry.unregister("ahc"); -- -- verify(listener).onHealthCheckRemoved("hc1", hc1); -- verify(listener).onHealthCheckRemoved("hc2", hc2); -- verify(listener).onHealthCheckRemoved(eq("ahc"), any(AsyncHealthCheckDecorator.class)); -- } -- -- @Test -- void addingListenerCatchesExistingHealthChecks() { -- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -- HealthCheckRegistry registry = new HealthCheckRegistry(); -- registry.register("hc1", hc1); -- registry.register("hc2", hc2); -- registry.register("ahc", ahc); -- registry.addListener(listener); -- -- verify(listener).onHealthCheckAdded("hc1", hc1); -- verify(listener).onHealthCheckAdded("hc2", hc2); -- verify(listener).onHealthCheckAdded(eq("ahc"), any(AsyncHealthCheckDecorator.class)); -- } -- -- @Test -- void removedListenerDoesNotReceiveUpdates() { -- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -- HealthCheckRegistry registry = new HealthCheckRegistry(); -- registry.addListener(listener); -- registry.register("hc1", hc1); -- registry.removeListener(listener); -- registry.register("hc2", hc2); -- -- verify(listener).onHealthCheckAdded("hc1", hc1); -- } -- -- @Test -- void runsRegisteredHealthChecks() { -- final Map results = registry.runHealthChecks(); -- -- assertThat(results).contains(entry("hc1", r1)); -- assertThat(results).contains(entry("hc2", r2)); -- assertThat(results).containsKey("ahc"); -- } -- -- @Test -- void runsRegisteredHealthChecksWithFilter() { -- final Map results = registry.runHealthChecks((name, healthCheck) -> "hc1".equals(name)); -- -- assertThat(results).containsOnly(entry("hc1", r1)); -- } -- -- @Test -- void runsRegisteredHealthChecksWithNonMatchingFilter() { -- final Map results = registry.runHealthChecks((name, healthCheck) -> false); -- -- assertThat(results).isEmpty(); -- } -- -- @Test -- void runsRegisteredHealthChecksInParallel() throws Exception { -- final ExecutorService executor = Executors.newFixedThreadPool(10); -- final Map results = registry.runHealthChecks(executor); -- -- executor.shutdown(); -- executor.awaitTermination(1, TimeUnit.SECONDS); -- -- assertThat(results).contains(entry("hc1", r1)); -- assertThat(results).contains(entry("hc2", r2)); -- assertThat(results).containsKey("ahc"); -- } -- -- @Test -- void runsRegisteredHealthChecksInParallelWithNonMatchingFilter() throws Exception { -- final ExecutorService executor = Executors.newFixedThreadPool(10); -- final Map results = registry.runHealthChecks(executor, (name, healthCheck) -> false); -- -- executor.shutdown(); -- executor.awaitTermination(1, TimeUnit.SECONDS); -- -- assertThat(results).isEmpty(); -- } -- -- @Test -- void runsRegisteredHealthChecksInParallelWithFilter() throws Exception { -- final ExecutorService executor = Executors.newFixedThreadPool(10); -- final Map results = registry.runHealthChecks(executor, -- (name, healthCheck) -> "hc2".equals(name)); -- -- executor.shutdown(); -- executor.awaitTermination(1, TimeUnit.SECONDS); -- -- assertThat(results).containsOnly(entry("hc2", r2)); -- } -- -- @Test -- void removesRegisteredHealthChecks() { -- registry.unregister("hc1"); -- -- final Map results = registry.runHealthChecks(); -- -- assertThat(results).doesNotContainKey("hc1"); -- assertThat(results).containsKey("hc2"); -- assertThat(results).containsKey("ahc"); -- } -- -- @Test -- void hasASetOfHealthCheckNames() { -- assertThat(registry.getNames()).containsOnly("hc1", "hc2", "ahc"); -- } -+import io.dropwizard.metrics5.health.annotation.Async; -+import java.util.Map; -+import java.util.NoSuchElementException; -+import java.util.concurrent.ExecutorService; -+import java.util.concurrent.Executors; -+import java.util.concurrent.ScheduledExecutorService; -+import java.util.concurrent.ScheduledFuture; -+import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; -+import org.mockito.ArgumentCaptor; - -- @Test -- void runsHealthChecksByName() { -- assertThat(registry.runHealthCheck("hc1")).isEqualTo(r1); -- } -+final class HealthCheckRegistryTest { -+ private final ScheduledExecutorService executorService = mock(); -+ private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); -+ private final HealthCheckRegistryListener listener = mock(); -+ -+ private final HealthCheck hc1 = mock(); -+ private final HealthCheck hc2 = mock(); -+ -+ private final HealthCheck.Result r1 = mock(); -+ private final HealthCheck.Result r2 = mock(); -+ -+ private final HealthCheck.Result ar = mock(); -+ private final HealthCheck ahc = new TestAsyncHealthCheck(ar); -+ -+ @SuppressWarnings("rawtypes") -+ private final ScheduledFuture af = mock(); -+ -+ @BeforeEach -+ @SuppressWarnings("unchecked") -+ void setUp() { -+ registry.addListener(listener); -+ -+ when(hc1.execute()).thenReturn(r1); -+ when(hc2.execute()).thenReturn(r2); -+ when(executorService.scheduleAtFixedRate( -+ any(AsyncHealthCheckDecorator.class), eq(0L), eq(10L), eq(TimeUnit.SECONDS))) -+ .thenReturn(af); -+ -+ registry.register("hc1", hc1); -+ registry.register("hc2", hc2); -+ registry.register("ahc", ahc); -+ } -+ -+ @Test -+ void asyncHealthCheckIsScheduledOnExecutor() { -+ ArgumentCaptor decoratorCaptor = -+ forClass(AsyncHealthCheckDecorator.class); -+ verify(executorService) -+ .scheduleAtFixedRate(decoratorCaptor.capture(), eq(0L), eq(10L), eq(TimeUnit.SECONDS)); -+ assertThat(decoratorCaptor.getValue().getHealthCheck()).isEqualTo(ahc); -+ } -+ -+ @Test -+ void asyncHealthCheckIsCanceledOnRemove() { -+ registry.unregister("ahc"); -+ -+ verify(af).cancel(true); -+ } -+ -+ @Test -+ void registeringHealthCheckTwiceThrowsException() { -+ assertThatThrownBy( -+ () -> { -+ registry.register("hc1", hc1); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); -+ } -+ -+ @Test -+ void registeringHealthCheckTriggersNotification() { -+ verify(listener).onHealthCheckAdded("hc1", hc1); -+ verify(listener).onHealthCheckAdded("hc2", hc2); -+ verify(listener).onHealthCheckAdded(eq("ahc"), any(AsyncHealthCheckDecorator.class)); -+ } -+ -+ @Test -+ void removingHealthCheckTriggersNotification() { -+ registry.unregister("hc1"); -+ registry.unregister("hc2"); -+ registry.unregister("ahc"); -+ -+ verify(listener).onHealthCheckRemoved("hc1", hc1); -+ verify(listener).onHealthCheckRemoved("hc2", hc2); -+ verify(listener).onHealthCheckRemoved(eq("ahc"), any(AsyncHealthCheckDecorator.class)); -+ } -+ -+ @Test -+ void addingListenerCatchesExistingHealthChecks() { -+ HealthCheckRegistryListener listener = mock(); -+ HealthCheckRegistry registry = new HealthCheckRegistry(); -+ registry.register("hc1", hc1); -+ registry.register("hc2", hc2); -+ registry.register("ahc", ahc); -+ registry.addListener(listener); -+ -+ verify(listener).onHealthCheckAdded("hc1", hc1); -+ verify(listener).onHealthCheckAdded("hc2", hc2); -+ verify(listener).onHealthCheckAdded(eq("ahc"), any(AsyncHealthCheckDecorator.class)); -+ } -+ -+ @Test -+ void removedListenerDoesNotReceiveUpdates() { -+ HealthCheckRegistryListener listener = mock(); -+ HealthCheckRegistry registry = new HealthCheckRegistry(); -+ registry.addListener(listener); -+ registry.register("hc1", hc1); -+ registry.removeListener(listener); -+ registry.register("hc2", hc2); -+ -+ verify(listener).onHealthCheckAdded("hc1", hc1); -+ } -+ -+ @Test -+ void runsRegisteredHealthChecks() { -+ final Map results = registry.runHealthChecks(); -+ -+ assertThat(results).contains(entry("hc1", r1)); -+ assertThat(results).contains(entry("hc2", r2)); -+ assertThat(results).containsKey("ahc"); -+ } -+ -+ @Test -+ void runsRegisteredHealthChecksWithFilter() { -+ final Map results = -+ registry.runHealthChecks((name, healthCheck) -> "hc1".equals(name)); -+ -+ assertThat(results).containsOnly(entry("hc1", r1)); -+ } -+ -+ @Test -+ void runsRegisteredHealthChecksWithNonMatchingFilter() { -+ final Map results = -+ registry.runHealthChecks((name, healthCheck) -> false); -+ -+ assertThat(results).isEmpty(); -+ } -+ -+ @Test -+ void runsRegisteredHealthChecksInParallel() throws Exception { -+ final ExecutorService executor = Executors.newFixedThreadPool(10); -+ final Map results = registry.runHealthChecks(executor); -+ -+ executor.shutdown(); -+ executor.awaitTermination(1, TimeUnit.SECONDS); -+ -+ assertThat(results).contains(entry("hc1", r1)); -+ assertThat(results).contains(entry("hc2", r2)); -+ assertThat(results).containsKey("ahc"); -+ } -+ -+ @Test -+ void runsRegisteredHealthChecksInParallelWithNonMatchingFilter() throws Exception { -+ final ExecutorService executor = Executors.newFixedThreadPool(10); -+ final Map results = -+ registry.runHealthChecks(executor, (name, healthCheck) -> false); -+ -+ executor.shutdown(); -+ executor.awaitTermination(1, TimeUnit.SECONDS); -+ -+ assertThat(results).isEmpty(); -+ } -+ -+ @Test -+ void runsRegisteredHealthChecksInParallelWithFilter() throws Exception { -+ final ExecutorService executor = Executors.newFixedThreadPool(10); -+ final Map results = -+ registry.runHealthChecks(executor, (name, healthCheck) -> "hc2".equals(name)); -+ -+ executor.shutdown(); -+ executor.awaitTermination(1, TimeUnit.SECONDS); -+ -+ assertThat(results).containsOnly(entry("hc2", r2)); -+ } -+ -+ @Test -+ void removesRegisteredHealthChecks() { -+ registry.unregister("hc1"); -+ -+ final Map results = registry.runHealthChecks(); -+ -+ assertThat(results).doesNotContainKey("hc1"); -+ assertThat(results).containsKey("hc2"); -+ assertThat(results).containsKey("ahc"); -+ } -+ -+ @Test -+ void hasASetOfHealthCheckNames() { -+ assertThat(registry.getNames()).containsOnly("hc1", "hc2", "ahc"); -+ } -+ -+ @Test -+ void runsHealthChecksByName() { -+ assertThat(registry.runHealthCheck("hc1")).isEqualTo(r1); -+ } -+ -+ @Test -+ void doesNotRunNonexistentHealthChecks() { -+ try { -+ registry.runHealthCheck("what"); -+ failBecauseExceptionWasNotThrown(NoSuchElementException.class); -+ } catch (NoSuchElementException e) { -+ assertThat(e.getMessage()).isEqualTo("No health check named what exists"); -+ } -+ } - -- @Test -- void doesNotRunNonexistentHealthChecks() { -- try { -- registry.runHealthCheck("what"); -- failBecauseExceptionWasNotThrown(NoSuchElementException.class); -- } catch (NoSuchElementException e) { -- assertThat(e.getMessage()) -- .isEqualTo("No health check named what exists"); -- } -+ @Async(period = 10) -+ private static class TestAsyncHealthCheck implements HealthCheck { -+ private final Result result; - -+ TestAsyncHealthCheck(Result result) { -+ this.result = result; - } - -- @Async(period = 10) -- private static class TestAsyncHealthCheck implements HealthCheck { -- private final Result result; -- -- TestAsyncHealthCheck(Result result) { -- this.result = result; -- } -- -- @Override -- public Result check() { -- return result; -- } -+ @Override -+ public Result check() { -+ return result; - } -+ } - } ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java -@@ -1,279 +1,231 @@ - package io.dropwizard.metrics5.health; - --import io.dropwizard.metrics5.Clock; --import org.junit.jupiter.api.Test; -- --import java.time.ZonedDateTime; --import java.time.format.DateTimeFormatter; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.ArgumentMatchers.anyLong; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - --class HealthCheckTest { -+import io.dropwizard.metrics5.Clock; -+import java.time.ZonedDateTime; -+import java.time.format.DateTimeFormatter; -+import org.junit.jupiter.api.Test; - -- private static final DateTimeFormatter DATE_TIME_FORMATTER = -- DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); -+final class HealthCheckTest { - -- private static class ExampleHealthCheck implements HealthCheck { -- private final HealthCheck underlying; -+ private static final DateTimeFormatter DATE_TIME_FORMATTER = -+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - -- private ExampleHealthCheck(HealthCheck underlying) { -- this.underlying = underlying; -- } -+ private static class ExampleHealthCheck implements HealthCheck { -+ private final HealthCheck underlying; - -- @Override -- public Result check() { -- return underlying.execute(); -- } -+ private ExampleHealthCheck(HealthCheck underlying) { -+ this.underlying = underlying; - } - -- private final HealthCheck underlying = mock(HealthCheck.class); -- private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); -+ @Override -+ public Result check() { -+ return underlying.execute(); -+ } -+ } - -- @Test -- void canHaveHealthyResults() { -- final HealthCheck.Result result = HealthCheck.Result.healthy(); -+ private final HealthCheck underlying = mock(); -+ private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); - -- assertThat(result.isHealthy()) -- .isTrue(); -+ @Test -+ void canHaveHealthyResults() { -+ final HealthCheck.Result result = HealthCheck.Result.healthy(); - -- assertThat(result.getMessage()) -- .isNull(); -+ assertThat(result.isHealthy()).isTrue(); - -- assertThat(result.getError()) -- .isNull(); -- } -+ assertThat(result.getMessage()).isNull(); - -- @Test -- void canHaveHealthyResultsWithMessages() { -- final HealthCheck.Result result = HealthCheck.Result.healthy("woo"); -+ assertThat(result.getError()).isNull(); -+ } - -- assertThat(result.isHealthy()) -- .isTrue(); -+ @Test -+ void canHaveHealthyResultsWithMessages() { -+ final HealthCheck.Result result = HealthCheck.Result.healthy("woo"); - -- assertThat(result.getMessage()) -- .isEqualTo("woo"); -+ assertThat(result.isHealthy()).isTrue(); - -- assertThat(result.getError()) -- .isNull(); -- } -+ assertThat(result.getMessage()).isEqualTo("woo"); - -- @Test -- void canHaveHealthyResultsWithFormattedMessages() { -- final HealthCheck.Result result = HealthCheck.Result.healthy("foo %s", "bar"); -+ assertThat(result.getError()).isNull(); -+ } - -- assertThat(result.isHealthy()) -- .isTrue(); -+ @Test -+ void canHaveHealthyResultsWithFormattedMessages() { -+ final HealthCheck.Result result = HealthCheck.Result.healthy("foo %s", "bar"); - -- assertThat(result.getMessage()) -- .isEqualTo("foo bar"); -+ assertThat(result.isHealthy()).isTrue(); - -- assertThat(result.getError()) -- .isNull(); -- } -+ assertThat(result.getMessage()).isEqualTo("foo bar"); - -- @Test -- void canHaveUnhealthyResults() { -- final HealthCheck.Result result = HealthCheck.Result.unhealthy("bad"); -+ assertThat(result.getError()).isNull(); -+ } - -- assertThat(result.isHealthy()) -- .isFalse(); -+ @Test -+ void canHaveUnhealthyResults() { -+ final HealthCheck.Result result = HealthCheck.Result.unhealthy("bad"); - -- assertThat(result.getMessage()) -- .isEqualTo("bad"); -+ assertThat(result.isHealthy()).isFalse(); - -- assertThat(result.getError()) -- .isNull(); -- } -+ assertThat(result.getMessage()).isEqualTo("bad"); - -- @Test -- void canHaveUnhealthyResultsWithFormattedMessages() { -- final HealthCheck.Result result = HealthCheck.Result.unhealthy("foo %s %d", "bar", 123); -+ assertThat(result.getError()).isNull(); -+ } - -- assertThat(result.isHealthy()) -- .isFalse(); -+ @Test -+ void canHaveUnhealthyResultsWithFormattedMessages() { -+ final HealthCheck.Result result = HealthCheck.Result.unhealthy("foo %s %d", "bar", 123); - -- assertThat(result.getMessage()) -- .isEqualTo("foo bar 123"); -+ assertThat(result.isHealthy()).isFalse(); - -- assertThat(result.getError()) -- .isNull(); -- } -+ assertThat(result.getMessage()).isEqualTo("foo bar 123"); - -- @Test -- void canHaveUnhealthyResultsWithExceptions() { -- final RuntimeException e = mock(RuntimeException.class); -- when(e.getMessage()).thenReturn("oh noes"); -+ assertThat(result.getError()).isNull(); -+ } - -- final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); -+ @Test -+ void canHaveUnhealthyResultsWithExceptions() { -+ final RuntimeException e = mock(); -+ when(e.getMessage()).thenReturn("oh noes"); - -- assertThat(result.isHealthy()) -- .isFalse(); -+ final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); - -- assertThat(result.getMessage()) -- .isEqualTo("oh noes"); -+ assertThat(result.isHealthy()).isFalse(); - -- assertThat(result.getError()) -- .isEqualTo(e); -- } -+ assertThat(result.getMessage()).isEqualTo("oh noes"); - -- @Test -- void canHaveHealthyBuilderWithFormattedMessage() { -- final HealthCheck.Result result = HealthCheck.Result.builder() -- .healthy() -- .withMessage("There are %d %s in the %s", 42, "foos", "bar") -- .build(); -+ assertThat(result.getError()).isEqualTo(e); -+ } - -- assertThat(result.isHealthy()) -- .isTrue(); -+ @Test -+ void canHaveHealthyBuilderWithFormattedMessage() { -+ final HealthCheck.Result result = -+ HealthCheck.Result.builder() -+ .healthy() -+ .withMessage("There are %d %s in the %s", 42, "foos", "bar") -+ .build(); - -- assertThat(result.getMessage()) -- .isEqualTo("There are 42 foos in the bar"); -- } -+ assertThat(result.isHealthy()).isTrue(); - -- @Test -- void canHaveHealthyBuilderWithDetail() { -- final HealthCheck.Result result = HealthCheck.Result.builder() -- .healthy() -- .withDetail("detail", "value") -- .build(); -+ assertThat(result.getMessage()).isEqualTo("There are 42 foos in the bar"); -+ } - -- assertThat(result.isHealthy()) -- .isTrue(); -+ @Test -+ void canHaveHealthyBuilderWithDetail() { -+ final HealthCheck.Result result = -+ HealthCheck.Result.builder().healthy().withDetail("detail", "value").build(); - -- assertThat(result.getMessage()) -- .isNull(); -+ assertThat(result.isHealthy()).isTrue(); - -- assertThat(result.getError()) -- .isNull(); -+ assertThat(result.getMessage()).isNull(); - -- assertThat(result.getDetails()) -- .containsEntry("detail", "value"); -- } -+ assertThat(result.getError()).isNull(); - -- @Test -- void canHaveUnHealthyBuilderWithDetail() { -- final HealthCheck.Result result = HealthCheck.Result.builder() -- .unhealthy() -- .withDetail("detail", "value") -- .build(); -+ assertThat(result.getDetails()).containsEntry("detail", "value"); -+ } - -- assertThat(result.isHealthy()) -- .isFalse(); -+ @Test -+ void canHaveUnHealthyBuilderWithDetail() { -+ final HealthCheck.Result result = -+ HealthCheck.Result.builder().unhealthy().withDetail("detail", "value").build(); - -- assertThat(result.getMessage()) -- .isNull(); -+ assertThat(result.isHealthy()).isFalse(); - -- assertThat(result.getError()) -- .isNull(); -+ assertThat(result.getMessage()).isNull(); - -- assertThat(result.getDetails()) -- .containsEntry("detail", "value"); -- } -+ assertThat(result.getError()).isNull(); - -- @Test -- void canHaveUnHealthyBuilderWithDetailAndError() { -- final RuntimeException e = mock(RuntimeException.class); -- when(e.getMessage()).thenReturn("oh noes"); -+ assertThat(result.getDetails()).containsEntry("detail", "value"); -+ } - -- final HealthCheck.Result result = HealthCheck.Result -- .builder() -- .unhealthy(e) -- .withDetail("detail", "value") -- .build(); -+ @Test -+ void canHaveUnHealthyBuilderWithDetailAndError() { -+ final RuntimeException e = mock(); -+ when(e.getMessage()).thenReturn("oh noes"); - -- assertThat(result.isHealthy()) -- .isFalse(); -+ final HealthCheck.Result result = -+ HealthCheck.Result.builder().unhealthy(e).withDetail("detail", "value").build(); - -- assertThat(result.getMessage()) -- .isEqualTo("oh noes"); -+ assertThat(result.isHealthy()).isFalse(); - -- assertThat(result.getError()) -- .isEqualTo(e); -+ assertThat(result.getMessage()).isEqualTo("oh noes"); - -- assertThat(result.getDetails()) -- .containsEntry("detail", "value"); -- } -+ assertThat(result.getError()).isEqualTo(e); - -- @Test -- void returnsResultsWhenExecuted() { -- final HealthCheck.Result result = mock(HealthCheck.Result.class); -- when(underlying.execute()).thenReturn(result); -+ assertThat(result.getDetails()).containsEntry("detail", "value"); -+ } - -- assertThat(healthCheck.execute()) -- .isEqualTo(result); -+ @Test -+ void returnsResultsWhenExecuted() { -+ final HealthCheck.Result result = mock(); -+ when(underlying.execute()).thenReturn(result); - -- verify(result).setDuration(anyLong()); -- } -+ assertThat(healthCheck.execute()).isEqualTo(result); - -- @Test -- void wrapsExceptionsWhenExecuted() { -- final RuntimeException e = mock(RuntimeException.class); -- when(e.getMessage()).thenReturn("oh noes"); -- -- when(underlying.execute()).thenThrow(e); -- HealthCheck.Result actual = healthCheck.execute(); -- -- assertThat(actual.isHealthy()) -- .isFalse(); -- assertThat(actual.getMessage()) -- .isEqualTo("oh noes"); -- assertThat(actual.getError()) -- .isEqualTo(e); -- assertThat(actual.getDetails()) -- .isNull(); -- assertThat(actual.getDuration()) -- .isGreaterThanOrEqualTo(0); -- } -+ verify(result).setDuration(anyLong()); -+ } - -- @Test -- void canHaveUserSuppliedClockForTimestamp() { -- ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(10); -- Clock clock = clockWithFixedTime(dateTime); -+ @Test -+ void wrapsExceptionsWhenExecuted() { -+ final RuntimeException e = mock(); -+ when(e.getMessage()).thenReturn("oh noes"); - -- HealthCheck.Result result = HealthCheck.Result.builder() -- .healthy() -- .usingClock(clock) -- .build(); -+ when(underlying.execute()).thenThrow(e); -+ HealthCheck.Result actual = healthCheck.execute(); - -- assertThat(result.isHealthy()).isTrue(); -+ assertThat(actual.isHealthy()).isFalse(); -+ assertThat(actual.getMessage()).isEqualTo("oh noes"); -+ assertThat(actual.getError()).isEqualTo(e); -+ assertThat(actual.getDetails()).isNull(); -+ assertThat(actual.getDuration()).isNotNegative(); -+ } - -- assertThat(result.getTime()).isEqualTo(clock.getTime()); -+ @Test -+ void canHaveUserSuppliedClockForTimestamp() { -+ ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(10); -+ Clock clock = clockWithFixedTime(dateTime); - -- assertThat(result.getTimestamp()) -- .isEqualTo(DATE_TIME_FORMATTER.format(dateTime)); -- } -+ HealthCheck.Result result = HealthCheck.Result.builder().healthy().usingClock(clock).build(); - -- @Test -- void toStringWorksEvenForNullAttributes() { -- ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(25); -- Clock clock = clockWithFixedTime(dateTime); -- -- final HealthCheck.Result resultWithNullDetailValue = HealthCheck.Result.builder() -- .unhealthy() -- .withDetail("aNullDetail", null) -- .usingClock(clock) -- .build(); -- assertThat(resultWithNullDetailValue.toString()) -- .contains( -- "Result{isHealthy=false, duration=0, timestamp=" + DATE_TIME_FORMATTER.format(dateTime), -- ", aNullDetail=null}"); -- } -+ assertThat(result.isHealthy()).isTrue(); - -- private static Clock clockWithFixedTime(ZonedDateTime dateTime) { -- return new Clock() { -- @Override -- public long getTick() { -- return 0; -- } -- -- @Override -- public long getTime() { -- return dateTime.toInstant().toEpochMilli(); -- } -- }; -- } -+ assertThat(result.getTime()).isEqualTo(clock.getTime()); -+ -+ assertThat(result.getTimestamp()).isEqualTo(DATE_TIME_FORMATTER.format(dateTime)); -+ } -+ -+ @Test -+ void toStringWorksEvenForNullAttributes() { -+ ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(25); -+ Clock clock = clockWithFixedTime(dateTime); -+ -+ final HealthCheck.Result resultWithNullDetailValue = -+ HealthCheck.Result.builder() -+ .unhealthy() -+ .withDetail("aNullDetail", null) -+ .usingClock(clock) -+ .build(); -+ assertThat(resultWithNullDetailValue.toString()) -+ .contains( -+ "Result{isHealthy=false, duration=0, timestamp=" + DATE_TIME_FORMATTER.format(dateTime), -+ ", aNullDetail=null}"); -+ } -+ -+ private static Clock clockWithFixedTime(ZonedDateTime dateTime) { -+ return new Clock() { -+ @Override -+ public long getTick() { -+ return 0; -+ } -+ -+ @Override -+ public long getTime() { -+ return dateTime.toInstant().toEpochMilli(); -+ } -+ }; -+ } - } ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java -@@ -1,97 +1,103 @@ - package io.dropwizard.metrics5.health; - --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import java.util.concurrent.atomic.AtomicReference; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.junit.jupiter.api.Assertions.assertTrue; -- --class SharedHealthCheckRegistriesTest { -- -- @BeforeEach -- void setUp() { -- SharedHealthCheckRegistries.setDefaultRegistryName(new AtomicReference<>()); -- SharedHealthCheckRegistries.clear(); -- } -- -- @Test -- void savesCreatedRegistry() { -- final HealthCheckRegistry one = SharedHealthCheckRegistries.getOrCreate("db"); -- final HealthCheckRegistry two = SharedHealthCheckRegistries.getOrCreate("db"); -- -- assertThat(one).isSameAs(two); -- } -- -- @Test -- void returnsSetOfCreatedRegistries() { -- SharedHealthCheckRegistries.getOrCreate("db"); -- -- assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); -- } -- -- @Test -- void registryCanBeRemoved() { -- final HealthCheckRegistry first = SharedHealthCheckRegistries.getOrCreate("db"); -- SharedHealthCheckRegistries.remove("db"); -- -- assertThat(SharedHealthCheckRegistries.names()).isEmpty(); -- assertThat(SharedHealthCheckRegistries.getOrCreate("db")).isNotEqualTo(first); -- } -- -- @Test -- void registryCanBeCleared() { -- SharedHealthCheckRegistries.getOrCreate("db"); -- SharedHealthCheckRegistries.getOrCreate("web"); - -- SharedHealthCheckRegistries.clear(); -- -- assertThat(SharedHealthCheckRegistries.names()).isEmpty(); -- } -- -- @Test -- void defaultRegistryIsNotSetByDefault() { -- Throwable exception = assertThrows(IllegalStateException.class, () -> { -- -- SharedHealthCheckRegistries.getDefault(); -- }); -- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); -- } -- -- @Test -- void defaultRegistryCanBeSet() { -- HealthCheckRegistry registry = SharedHealthCheckRegistries.setDefault("default"); -- -- assertThat(SharedHealthCheckRegistries.getDefault()).isEqualTo(registry); -- } -- -- @Test -- void specificRegistryCanBeSetAsDefault() { -- HealthCheckRegistry registry = new HealthCheckRegistry(); -- SharedHealthCheckRegistries.setDefault("default", registry); -- -- assertThat(SharedHealthCheckRegistries.getDefault()).isEqualTo(registry); -- } -- -- @Test -- void unableToSetDefaultRegistryTwice() { -- Throwable exception = assertThrows(IllegalStateException.class, () -> { -- -- SharedHealthCheckRegistries.setDefault("default"); -- SharedHealthCheckRegistries.setDefault("default"); -- }); -- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); -- } -- -- @Test -- void unableToSetCustomDefaultRegistryTwice() { -- Throwable exception = assertThrows(IllegalStateException.class, () -> { -+import java.util.concurrent.atomic.AtomicReference; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - -- SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); -- SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); -- }); -- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); -- } -+final class SharedHealthCheckRegistriesTest { -+ -+ @BeforeEach -+ void setUp() { -+ SharedHealthCheckRegistries.setDefaultRegistryName(new AtomicReference<>()); -+ SharedHealthCheckRegistries.clear(); -+ } -+ -+ @Test -+ void savesCreatedRegistry() { -+ final HealthCheckRegistry one = SharedHealthCheckRegistries.getOrCreate("db"); -+ final HealthCheckRegistry two = SharedHealthCheckRegistries.getOrCreate("db"); -+ -+ assertThat(one).isSameAs(two); -+ } -+ -+ @Test -+ void returnsSetOfCreatedRegistries() { -+ SharedHealthCheckRegistries.getOrCreate("db"); -+ -+ assertThat(SharedHealthCheckRegistries.names()).containsExactly("db"); -+ } -+ -+ @Test -+ void registryCanBeRemoved() { -+ final HealthCheckRegistry first = SharedHealthCheckRegistries.getOrCreate("db"); -+ SharedHealthCheckRegistries.remove("db"); -+ -+ assertThat(SharedHealthCheckRegistries.names()).isEmpty(); -+ assertThat(SharedHealthCheckRegistries.getOrCreate("db")).isNotEqualTo(first); -+ } -+ -+ @Test -+ void registryCanBeCleared() { -+ SharedHealthCheckRegistries.getOrCreate("db"); -+ SharedHealthCheckRegistries.getOrCreate("web"); -+ -+ SharedHealthCheckRegistries.clear(); -+ -+ assertThat(SharedHealthCheckRegistries.names()).isEmpty(); -+ } -+ -+ @Test -+ void defaultRegistryIsNotSetByDefault() { -+ Throwable exception = -+ assertThrows( -+ IllegalStateException.class, -+ () -> { -+ SharedHealthCheckRegistries.getDefault(); -+ }); -+ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); -+ } -+ -+ @Test -+ void defaultRegistryCanBeSet() { -+ HealthCheckRegistry registry = SharedHealthCheckRegistries.setDefault("default"); -+ -+ assertThat(SharedHealthCheckRegistries.getDefault()).isEqualTo(registry); -+ } -+ -+ @Test -+ void specificRegistryCanBeSetAsDefault() { -+ HealthCheckRegistry registry = new HealthCheckRegistry(); -+ SharedHealthCheckRegistries.setDefault("default", registry); -+ -+ assertThat(SharedHealthCheckRegistries.getDefault()).isEqualTo(registry); -+ } -+ -+ @Test -+ void unableToSetDefaultRegistryTwice() { -+ Throwable exception = -+ assertThrows( -+ IllegalStateException.class, -+ () -> { -+ SharedHealthCheckRegistries.setDefault("default"); -+ SharedHealthCheckRegistries.setDefault("default"); -+ }); -+ assertThat(exception.getMessage().contains("Default health check registry is already set.")) -+ .isTrue(); -+ } -+ -+ @Test -+ void unableToSetCustomDefaultRegistryTwice() { -+ Throwable exception = -+ assertThrows( -+ IllegalStateException.class, -+ () -> { -+ SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); -+ SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); -+ }); -+ assertThat(exception.getMessage().contains("Default health check registry is already set.")) -+ .isTrue(); -+ } - } ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java -@@ -1,54 +1,48 @@ - package io.dropwizard.metrics5.health.jvm; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.health.HealthCheck; - import io.dropwizard.metrics5.jvm.ThreadDeadlockDetector; --import org.assertj.core.api.Assertions; --import org.junit.jupiter.api.Test; -- --import java.util.Collections; - import java.util.Set; - import java.util.TreeSet; -+import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- --class ThreadDeadlockHealthCheckTest { -- @Test -- void isHealthyIfNoThreadsAreDeadlocked() { -- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -- final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); -+final class ThreadDeadlockHealthCheckTest { -+ @Test -+ void isHealthyIfNoThreadsAreDeadlocked() { -+ final ThreadDeadlockDetector detector = mock(); -+ final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); - -- when(detector.getDeadlockedThreads()).thenReturn(Collections.emptySet()); -+ when(detector.getDeadlockedThreads()).thenReturn(ImmutableSet.of()); - -- Assertions.assertThat(healthCheck.execute().isHealthy()) -- .isTrue(); -- } -+ assertThat(healthCheck.execute().isHealthy()).isTrue(); -+ } - -- @Test -- void isUnhealthyIfThreadsAreDeadlocked() { -- final Set threads = new TreeSet<>(); -- threads.add("one"); -- threads.add("two"); -+ @Test -+ void isUnhealthyIfThreadsAreDeadlocked() { -+ final Set threads = new TreeSet<>(); -+ threads.add("one"); -+ threads.add("two"); - -- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -- final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); -+ final ThreadDeadlockDetector detector = mock(); -+ final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); - -- when(detector.getDeadlockedThreads()).thenReturn(threads); -+ when(detector.getDeadlockedThreads()).thenReturn(threads); - -- final HealthCheck.Result result = healthCheck.execute(); -+ final HealthCheck.Result result = healthCheck.execute(); - -- assertThat(result.isHealthy()) -- .isFalse(); -+ assertThat(result.isHealthy()).isFalse(); - -- assertThat(result.getMessage()) -- .isEqualTo("[one, two]"); -- } -+ assertThat(result.getMessage()).isEqualTo("[one, two]"); -+ } - -- @Test -- void automaticallyUsesThePlatformThreadBeans() { -- final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(); -- Assertions.assertThat(healthCheck.execute().isHealthy()) -- .isTrue(); -- } -+ @Test -+ void automaticallyUsesThePlatformThreadBeans() { -+ final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(); -+ assertThat(healthCheck.execute().isHealthy()).isTrue(); -+ } - } ---- a/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java -+++ b/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java -@@ -1,6 +1,9 @@ - package io.dropwizard.metrics5.httpasyncclient; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import io.dropwizard.metrics5.MetricRegistry; -+import java.util.concurrent.TimeUnit; - import org.apache.http.config.Registry; - import org.apache.http.conn.DnsResolver; - import org.apache.http.conn.SchemePortResolver; -@@ -11,26 +14,41 @@ import org.apache.http.nio.conn.NHttpConnectionFactory; - import org.apache.http.nio.conn.SchemeIOSessionStrategy; - import org.apache.http.nio.reactor.ConnectingIOReactor; - --import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -- - public class InstrumentedNClientConnManager extends PoolingNHttpClientConnectionManager { - -- public InstrumentedNClientConnManager(final ConnectingIOReactor ioreactor, final NHttpConnectionFactory connFactory, final SchemePortResolver schemePortResolver, final MetricRegistry metricRegistry, final Registry iosessionFactoryRegistry, final long timeToLive, final TimeUnit tunit, final DnsResolver dnsResolver, final String name) { -- super(ioreactor, connFactory, iosessionFactoryRegistry, schemePortResolver, dnsResolver, timeToLive, tunit); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "available-connections"), -- () -> getTotalStats().getAvailable()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "leased-connections"), -- () -> getTotalStats().getLeased()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "max-connections"), -- () -> getTotalStats().getMax()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(NHttpClientConnectionManager.class, name, "pending-connections"), -- () -> getTotalStats().getPending()); -- } -- -+ public InstrumentedNClientConnManager( -+ final ConnectingIOReactor ioreactor, -+ final NHttpConnectionFactory connFactory, -+ final SchemePortResolver schemePortResolver, -+ final MetricRegistry metricRegistry, -+ final Registry iosessionFactoryRegistry, -+ final long timeToLive, -+ final TimeUnit tunit, -+ final DnsResolver dnsResolver, -+ final String name) { -+ super( -+ ioreactor, -+ connFactory, -+ iosessionFactoryRegistry, -+ schemePortResolver, -+ dnsResolver, -+ timeToLive, -+ tunit); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(NHttpClientConnectionManager.class, name, "available-connections"), -+ () -> getTotalStats().getAvailable()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(NHttpClientConnectionManager.class, name, "leased-connections"), -+ () -> getTotalStats().getLeased()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(NHttpClientConnectionManager.class, name, "max-connections"), -+ () -> getTotalStats().getMax()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(NHttpClientConnectionManager.class, name, "pending-connections"), -+ () -> getTotalStats().getPending()); -+ } - } ---- a/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNHttpClientBuilder.java -+++ b/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNHttpClientBuilder.java -@@ -1,10 +1,14 @@ - package io.dropwizard.metrics5.httpasyncclient; - -+import static java.util.Objects.requireNonNull; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies; - import io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategy; -+import java.io.IOException; -+import java.util.concurrent.Future; - import org.apache.http.HttpException; - import org.apache.http.HttpRequest; - import org.apache.http.concurrent.FutureCallback; -@@ -14,107 +18,109 @@ import org.apache.http.nio.protocol.HttpAsyncRequestProducer; - import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; - import org.apache.http.protocol.HttpContext; - --import java.io.IOException; --import java.util.concurrent.Future; -- --import static java.util.Objects.requireNonNull; -- - public class InstrumentedNHttpClientBuilder extends HttpAsyncClientBuilder { -- private final MetricRegistry metricRegistry; -- private final String name; -- private final HttpClientMetricNameStrategy metricNameStrategy; -- -- public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy, String name) { -- super(); -- this.metricRegistry = metricRegistry; -- this.metricNameStrategy = metricNameStrategy; -- this.name = name; -- } -- -- public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry) { -- this(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY, null); -- } -- -- public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { -- this(metricRegistry, metricNameStrategy, null); -- } -- -- public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry, String name) { -- this(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY, name); -+ private final MetricRegistry metricRegistry; -+ private final String name; -+ private final HttpClientMetricNameStrategy metricNameStrategy; -+ -+ public InstrumentedNHttpClientBuilder( -+ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy, String name) { -+ super(); -+ this.metricRegistry = metricRegistry; -+ this.metricNameStrategy = metricNameStrategy; -+ this.name = name; -+ } -+ -+ public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry) { -+ this(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY, null); -+ } -+ -+ public InstrumentedNHttpClientBuilder( -+ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { -+ this(metricRegistry, metricNameStrategy, null); -+ } -+ -+ public InstrumentedNHttpClientBuilder(MetricRegistry metricRegistry, String name) { -+ this(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY, name); -+ } -+ -+ private Timer timer(HttpRequest request) { -+ MetricName nameFor = metricNameStrategy.getNameFor(name, request); -+ return metricRegistry.timer(nameFor); -+ } -+ -+ @Override -+ public CloseableHttpAsyncClient build() { -+ final CloseableHttpAsyncClient ac = super.build(); -+ return new CloseableHttpAsyncClient() { -+ -+ @Override -+ public boolean isRunning() { -+ return ac.isRunning(); -+ } -+ -+ @Override -+ public void start() { -+ ac.start(); -+ } -+ -+ @Override -+ public Future execute( -+ HttpAsyncRequestProducer requestProducer, -+ HttpAsyncResponseConsumer responseConsumer, -+ HttpContext context, -+ FutureCallback callback) { -+ final Timer.Context timerContext; -+ try { -+ timerContext = timer(requestProducer.generateRequest()).time(); -+ } catch (IOException | HttpException ex) { -+ throw new RuntimeException(ex); -+ } -+ return ac.execute( -+ requestProducer, -+ responseConsumer, -+ context, -+ new TimingFutureCallback<>(callback, timerContext)); -+ } -+ -+ @Override -+ public void close() throws IOException { -+ ac.close(); -+ } -+ }; -+ } -+ -+ private static class TimingFutureCallback implements FutureCallback { -+ private final FutureCallback callback; -+ private final Timer.Context timerContext; -+ -+ private TimingFutureCallback(FutureCallback callback, Timer.Context timerContext) { -+ this.callback = callback; -+ this.timerContext = requireNonNull(timerContext, "timerContext"); - } - -- private Timer timer(HttpRequest request) { -- MetricName nameFor = metricNameStrategy.getNameFor(name, request); -- return metricRegistry.timer(nameFor); -+ @Override -+ public void completed(T result) { -+ timerContext.stop(); -+ if (callback != null) { -+ callback.completed(result); -+ } - } - - @Override -- public CloseableHttpAsyncClient build() { -- final CloseableHttpAsyncClient ac = super.build(); -- return new CloseableHttpAsyncClient() { -- -- @Override -- public boolean isRunning() { -- return ac.isRunning(); -- } -- -- @Override -- public void start() { -- ac.start(); -- } -- -- @Override -- public Future execute(HttpAsyncRequestProducer requestProducer, HttpAsyncResponseConsumer responseConsumer, HttpContext context, FutureCallback callback) { -- final Timer.Context timerContext; -- try { -- timerContext = timer(requestProducer.generateRequest()).time(); -- } catch (IOException | HttpException ex) { -- throw new RuntimeException(ex); -- } -- return ac.execute(requestProducer, responseConsumer, context, -- new TimingFutureCallback<>(callback, timerContext)); -- } -- -- @Override -- public void close() throws IOException { -- ac.close(); -- } -- }; -+ public void failed(Exception ex) { -+ timerContext.stop(); -+ if (callback != null) { -+ callback.failed(ex); -+ } - } - -- private static class TimingFutureCallback implements FutureCallback { -- private final FutureCallback callback; -- private final Timer.Context timerContext; -- -- private TimingFutureCallback(FutureCallback callback, -- Timer.Context timerContext) { -- this.callback = callback; -- this.timerContext = requireNonNull(timerContext, "timerContext"); -- } -- -- @Override -- public void completed(T result) { -- timerContext.stop(); -- if (callback != null) { -- callback.completed(result); -- } -- } -- -- @Override -- public void failed(Exception ex) { -- timerContext.stop(); -- if (callback != null) { -- callback.failed(ex); -- } -- } -- -- @Override -- public void cancelled() { -- timerContext.stop(); -- if (callback != null) { -- callback.cancelled(); -- } -- } -+ @Override -+ public void cancelled() { -+ timerContext.stop(); -+ if (callback != null) { -+ callback.cancelled(); -+ } - } -- -+ } - } ---- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/HttpClientTestBase.java -+++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/HttpClientTestBase.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.httpasyncclient; - -+import java.io.IOException; -+import java.net.InetSocketAddress; -+import java.net.ServerSocket; -+import java.util.concurrent.TimeUnit; - import org.apache.http.HttpHost; - import org.apache.http.impl.nio.bootstrap.HttpServer; - import org.apache.http.impl.nio.bootstrap.ServerBootstrap; -@@ -8,64 +12,59 @@ import org.apache.http.nio.reactor.ListenerEndpoint; - import org.apache.http.protocol.HttpRequestHandler; - import org.junit.jupiter.api.AfterEach; - --import java.io.IOException; --import java.net.InetSocketAddress; --import java.net.ServerSocket; --import java.util.concurrent.TimeUnit; -- - public abstract class HttpClientTestBase { - -- /** -- * {@link HttpRequestHandler} that responds with a {@code 200 OK}. -- */ -- public static final HttpRequestHandler STATUS_OK = (request, response, context) -> response.setStatusCode(200); -+ /** {@link HttpRequestHandler} that responds with a {@code 200 OK}. */ -+ public static final HttpRequestHandler STATUS_OK = -+ (request, response, context) -> response.setStatusCode(200); - -- private HttpServer server; -+ private HttpServer server; - -- /** -- * @return A free local port or {@code -1} on error. -- */ -- public static int findAvailableLocalPort() { -- try (ServerSocket socket = new ServerSocket(0)) { -- return socket.getLocalPort(); -- } catch (IOException e) { -- return -1; -- } -+ /** -+ * @return A free local port or {@code -1} on error. -+ */ -+ public static int findAvailableLocalPort() { -+ try (ServerSocket socket = new ServerSocket(0)) { -+ return socket.getLocalPort(); -+ } catch (IOException e) { -+ return -1; - } -+ } - -- /** -- * Start a local server that uses the {@code handler} to handle requests. -- *

    -- * The server will be (if started) terminated in the {@link #tearDown()} {@link AfterEach} method. -- * -- * @param handler The request handler that will be used to respond to every request. -- * @return The {@link HttpHost} of the server -- * @throws IOException in case it's not possible to start the server -- * @throws InterruptedException in case the server's main thread was interrupted -- */ -- public HttpHost startServerWithGlobalRequestHandler(HttpRequestHandler handler) -- throws IOException, InterruptedException { -- // If there is an existing instance, terminate it -- tearDown(); -+ /** -+ * Start a local server that uses the {@code handler} to handle requests. -+ * -+ *

    The server will be (if started) terminated in the {@link #tearDown()} {@link AfterEach} -+ * method. -+ * -+ * @param handler The request handler that will be used to respond to every request. -+ * @return The {@link HttpHost} of the server -+ * @throws IOException in case it's not possible to start the server -+ * @throws InterruptedException in case the server's main thread was interrupted -+ */ -+ public HttpHost startServerWithGlobalRequestHandler(HttpRequestHandler handler) -+ throws IOException, InterruptedException { -+ // If there is an existing instance, terminate it -+ tearDown(); - -- ServerBootstrap serverBootstrap = ServerBootstrap.bootstrap(); -+ ServerBootstrap serverBootstrap = ServerBootstrap.bootstrap(); - -- serverBootstrap.registerHandler("/*", new BasicAsyncRequestHandler(handler)); -+ serverBootstrap.registerHandler("/*", new BasicAsyncRequestHandler(handler)); - -- server = serverBootstrap.create(); -- server.start(); -+ server = serverBootstrap.create(); -+ server.start(); - -- ListenerEndpoint endpoint = server.getEndpoint(); -- endpoint.waitFor(); -+ ListenerEndpoint endpoint = server.getEndpoint(); -+ endpoint.waitFor(); - -- InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); -- return new HttpHost("localhost", address.getPort(), "http"); -- } -+ InetSocketAddress address = (InetSocketAddress) endpoint.getAddress(); -+ return new HttpHost("localhost", address.getPort(), "http"); -+ } - -- @AfterEach -- public void tearDown() { -- if (server != null) { -- server.shutdown(5, TimeUnit.SECONDS); -- } -+ @AfterEach -+ public void tearDown() { -+ if (server != null) { -+ server.shutdown(5, TimeUnit.SECONDS); - } -+ } - } ---- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java -+++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java -@@ -1,5 +1,10 @@ - package io.dropwizard.metrics5.httpasyncclient; - -+import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.ArgumentMatchers.eq; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricRegistryListener; -@@ -16,43 +21,34 @@ import org.junit.jupiter.api.extension.ExtendWith; - import org.mockito.Mock; - import org.mockito.junit.jupiter.MockitoExtension; - --import static org.mockito.ArgumentMatchers.any; --import static org.mockito.ArgumentMatchers.eq; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- -- - @ExtendWith(MockitoExtension.class) --class InstrumentedHttpClientsTest extends HttpClientTestBase { -- -- private final MetricRegistry metricRegistry = new MetricRegistry(); -+final class InstrumentedHttpClientsTest extends HttpClientTestBase { - -+ private final MetricRegistry metricRegistry = new MetricRegistry(); - -- private HttpAsyncClient asyncHttpClient; -- @Mock -- private HttpClientMetricNameStrategy metricNameStrategy; -- @Mock -- private MetricRegistryListener registryListener; -+ private HttpAsyncClient asyncHttpClient; -+ @Mock private HttpClientMetricNameStrategy metricNameStrategy; -+ @Mock private MetricRegistryListener registryListener; - -- @Test -- void registersExpectedMetricsGivenNameStrategy() throws Exception { -- HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); -- final HttpGet get = new HttpGet("/q=anything"); -- final MetricName metricName = MetricName.build("some.made.up.metric.name"); -+ @Test -+ void registersExpectedMetricsGivenNameStrategy() throws Exception { -+ HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); -+ final HttpGet get = new HttpGet("/q=anything"); -+ final MetricName metricName = MetricName.build("some.made.up.metric.name"); - -- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) -- .thenReturn(metricName); -+ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); - -- asyncHttpClient.execute(host, get, null).get(); -+ asyncHttpClient.execute(host, get, null).get(); - -- verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); -- } -+ verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); -+ } - -- @BeforeEach -- void setUp() throws Exception { -- CloseableHttpAsyncClient chac = new InstrumentedNHttpClientBuilder(metricRegistry, metricNameStrategy).build(); -- chac.start(); -- asyncHttpClient = chac; -- metricRegistry.addListener(registryListener); -- } -+ @BeforeEach -+ void setUp() throws Exception { -+ CloseableHttpAsyncClient chac = -+ new InstrumentedNHttpClientBuilder(metricRegistry, metricNameStrategy).build(); -+ chac.start(); -+ asyncHttpClient = chac; -+ metricRegistry.addListener(registryListener); -+ } - } ---- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java -+++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java -@@ -1,8 +1,19 @@ - package io.dropwizard.metrics5.httpasyncclient; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; -+import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.never; -+import static org.mockito.Mockito.timeout; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -+import java.util.concurrent.Future; -+import java.util.concurrent.TimeUnit; - import org.apache.http.HttpHost; - import org.apache.http.HttpResponse; - import org.apache.http.client.methods.HttpGet; -@@ -16,119 +27,105 @@ import org.junit.jupiter.api.extension.ExtendWith; - import org.mockito.Mock; - import org.mockito.junit.jupiter.MockitoExtension; - --import java.util.concurrent.Future; --import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; --import static org.mockito.ArgumentMatchers.any; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.never; --import static org.mockito.Mockito.timeout; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- - @ExtendWith(MockitoExtension.class) - @Disabled("The tests are flaky") --class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { -+final class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - -- private HttpAsyncClient asyncHttpClient; -+ private HttpAsyncClient asyncHttpClient; - -- @Mock -- private Timer.Context context; -+ @Mock private Timer.Context context; - -- @Mock -- private MetricRegistry metricRegistry; -+ @Mock private MetricRegistry metricRegistry; - -+ @BeforeEach -+ void setUp() throws Exception { -+ CloseableHttpAsyncClient chac = -+ new InstrumentedNHttpClientBuilder( -+ metricRegistry, (name, request) -> MetricName.build("test")) -+ .build(); -+ chac.start(); -+ asyncHttpClient = chac; - -- @BeforeEach -- void setUp() throws Exception { -- CloseableHttpAsyncClient chac = new InstrumentedNHttpClientBuilder(metricRegistry, -- (name, request) -> MetricName.build("test")).build(); -- chac.start(); -- asyncHttpClient = chac; -+ Timer timer = mock(); -+ when(timer.time()).thenReturn(context); -+ when(metricRegistry.timer(MetricName.build("test"))).thenReturn(timer); -+ } - -- Timer timer = mock(Timer.class); -- when(timer.time()).thenReturn(context); -- when(metricRegistry.timer(MetricName.build("test"))).thenReturn(timer); -- } -+ @Test -+ void timerIsStoppedCorrectly() throws Exception { -+ HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); -+ HttpGet get = new HttpGet("/?q=anything"); - -- @Test -- void timerIsStoppedCorrectly() throws Exception { -- HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); -- HttpGet get = new HttpGet("/?q=anything"); -+ // Timer hasn't been stopped prior to executing the request -+ verify(context, never()).stop(); - -- // Timer hasn't been stopped prior to executing the request -- verify(context, never()).stop(); -+ Future responseFuture = asyncHttpClient.execute(host, get, null); - -- Future responseFuture = asyncHttpClient.execute(host, get, null); -+ // Timer should still be running -+ verify(context, never()).stop(); - -- // Timer should still be running -- verify(context, never()).stop(); -+ responseFuture.get(20, TimeUnit.SECONDS); - -- responseFuture.get(20, TimeUnit.SECONDS); -+ // After the computation is complete timer must be stopped -+ // Materialzing the future and calling the future callback is not an atomic operation so -+ // we need to wait for callback to succeed -+ verify(context, timeout(200).times(1)).stop(); -+ } - -- // After the computation is complete timer must be stopped -- // Materialzing the future and calling the future callback is not an atomic operation so -- // we need to wait for callback to succeed -- verify(context, timeout(200).times(1)).stop(); -- } -+ @SuppressWarnings("unchecked") -+ @Test -+ void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { -+ HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); -+ HttpGet get = new HttpGet("/?q=something"); - -- @Test -- @SuppressWarnings("unchecked") -- void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { -- HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); -- HttpGet get = new HttpGet("/?q=something"); -+ FutureCallback futureCallback = mock(); - -- FutureCallback futureCallback = mock(FutureCallback.class); -+ // Timer hasn't been stopped prior to executing the request -+ verify(context, never()).stop(); - -- // Timer hasn't been stopped prior to executing the request -- verify(context, never()).stop(); -+ Future responseFuture = asyncHttpClient.execute(host, get, futureCallback); - -- Future responseFuture = asyncHttpClient.execute(host, get, futureCallback); -+ // Timer should still be running -+ verify(context, never()).stop(); - -- // Timer should still be running -- verify(context, never()).stop(); -+ responseFuture.get(20, TimeUnit.SECONDS); - -- responseFuture.get(20, TimeUnit.SECONDS); -+ // Callback must have been called -+ assertThat(responseFuture.isDone()).isTrue(); -+ // After the computation is complete timer must be stopped -+ // Materialzing the future and calling the future callback is not an atomic operation so -+ // we need to wait for callback to succeed -+ verify(futureCallback, timeout(200).times(1)).completed(any(HttpResponse.class)); -+ verify(context, timeout(200).times(1)).stop(); -+ } - -- // Callback must have been called -- assertThat(responseFuture.isDone()).isTrue(); -- // After the computation is complete timer must be stopped -- // Materialzing the future and calling the future callback is not an atomic operation so -- // we need to wait for callback to succeed -- verify(futureCallback, timeout(200).times(1)).completed(any(HttpResponse.class)); -- verify(context, timeout(200).times(1)).stop(); -- } -+ @SuppressWarnings("unchecked") -+ @Test -+ void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { -+ // There should be nothing listening on this port -+ HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); -+ HttpGet get = new HttpGet("/?q=something"); - -- @Test -- @SuppressWarnings("unchecked") -- void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { -- // There should be nothing listening on this port -- HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); -- HttpGet get = new HttpGet("/?q=something"); -- -- FutureCallback futureCallback = mock(FutureCallback.class); -- -- // Timer hasn't been stopped prior to executing the request -- verify(context, never()).stop(); -- -- Future responseFuture = asyncHttpClient.execute(host, get, futureCallback); -- -- // Timer should still be running -- verify(context, never()).stop(); -- -- try { -- responseFuture.get(20, TimeUnit.SECONDS); -- fail("This should fail as the client should not be able to connect"); -- } catch (Exception e) { -- // Ignore -- } -- // After the computation is complete timer must be stopped -- // Materialzing the future and calling the future callback is not an atomic operation so -- // we need to wait for callback to succeed -- verify(futureCallback, timeout(200).times(1)).failed(any(Exception.class)); -- verify(context, timeout(200).times(1)).stop(); -- } -+ FutureCallback futureCallback = mock(); -+ -+ // Timer hasn't been stopped prior to executing the request -+ verify(context, never()).stop(); - -+ Future responseFuture = asyncHttpClient.execute(host, get, futureCallback); -+ -+ // Timer should still be running -+ verify(context, never()).stop(); -+ -+ try { -+ responseFuture.get(20, TimeUnit.SECONDS); -+ fail("This should fail as the client should not be able to connect"); -+ } catch (Exception e) { -+ // Ignore -+ } -+ // After the computation is complete timer must be stopped -+ // Materialzing the future and calling the future callback is not an atomic operation so -+ // we need to wait for callback to succeed -+ verify(futureCallback, timeout(200).times(1)).failed(any(Exception.class)); -+ verify(context, timeout(200).times(1)).stop(); -+ } - } ---- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategies.java -+++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategies.java -@@ -1,61 +1,54 @@ - package io.dropwizard.metrics5.httpclient; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ -+import java.net.URI; -+import java.net.URISyntaxException; - import org.apache.http.HttpRequest; - import org.apache.http.client.HttpClient; - import org.apache.http.client.methods.HttpRequestWrapper; - import org.apache.http.client.methods.HttpUriRequest; - import org.apache.http.client.utils.URIBuilder; - --import java.net.URI; --import java.net.URISyntaxException; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -- - public class HttpClientMetricNameStrategies { - -- public static final HttpClientMetricNameStrategy METHOD_ONLY = -- (name, request) -> name(HttpClient.class, -- name, -- methodNameString(request)); -- -- public static final HttpClientMetricNameStrategy HOST_AND_METHOD = -- (name, request) -> name(HttpClient.class, -- name, -- requestURI(request).getHost(), -- methodNameString(request)); -- -- public static final HttpClientMetricNameStrategy PATH_AND_METHOD = -- (name, request) -> { -- final URIBuilder url = new URIBuilder(requestURI(request)); -- return name(HttpClient.class, -- name, -- url.getPath(), -- methodNameString(request)); -- }; -- -- public static final HttpClientMetricNameStrategy QUERYLESS_URL_AND_METHOD = -- (name, request) -> { -- try { -- final URIBuilder url = new URIBuilder(requestURI(request)); -- return name(HttpClient.class, -- name, -- url.removeQuery().build().toString(), -- methodNameString(request)); -- } catch (URISyntaxException e) { -- throw new IllegalArgumentException(e); -- } -- }; -- -- private static String methodNameString(HttpRequest request) { -- return request.getRequestLine().getMethod().toLowerCase() + "-requests"; -- } -- -- private static URI requestURI(HttpRequest request) { -- if (request instanceof HttpRequestWrapper) -- return requestURI(((HttpRequestWrapper) request).getOriginal()); -- -- return (request instanceof HttpUriRequest) ? -- ((HttpUriRequest) request).getURI() : -- URI.create(request.getRequestLine().getUri()); -- } -+ public static final HttpClientMetricNameStrategy METHOD_ONLY = -+ (name, request) -> name(HttpClient.class, name, methodNameString(request)); -+ -+ public static final HttpClientMetricNameStrategy HOST_AND_METHOD = -+ (name, request) -> -+ name(HttpClient.class, name, requestURI(request).getHost(), methodNameString(request)); -+ -+ public static final HttpClientMetricNameStrategy PATH_AND_METHOD = -+ (name, request) -> { -+ final URIBuilder url = new URIBuilder(requestURI(request)); -+ return name(HttpClient.class, name, url.getPath(), methodNameString(request)); -+ }; -+ -+ public static final HttpClientMetricNameStrategy QUERYLESS_URL_AND_METHOD = -+ (name, request) -> { -+ try { -+ final URIBuilder url = new URIBuilder(requestURI(request)); -+ return name( -+ HttpClient.class, -+ name, -+ url.removeQuery().build().toString(), -+ methodNameString(request)); -+ } catch (URISyntaxException e) { -+ throw new IllegalArgumentException(e); -+ } -+ }; -+ -+ private static String methodNameString(HttpRequest request) { -+ return request.getRequestLine().getMethod().toLowerCase() + "-requests"; -+ } -+ -+ private static URI requestURI(HttpRequest request) { -+ if (request instanceof HttpRequestWrapper) -+ return requestURI(((HttpRequestWrapper) request).getOriginal()); -+ -+ return (request instanceof HttpUriRequest) -+ ? ((HttpUriRequest) request).getURI() -+ : URI.create(request.getRequestLine().getUri()); -+ } - } ---- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategy.java -+++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategy.java -@@ -8,11 +8,9 @@ import org.apache.http.client.HttpClient; - @FunctionalInterface - public interface HttpClientMetricNameStrategy { - -- MetricName getNameFor(String name, HttpRequest request); -+ MetricName getNameFor(String name, HttpRequest request); - -- default MetricName getNameFor(String name, Exception exception) { -- return MetricRegistry.name(HttpClient.class, -- name, -- exception.getClass().getSimpleName()); -- } -+ default MetricName getNameFor(String name, Exception exception) { -+ return MetricRegistry.name(HttpClient.class, name, exception.getClass().getSimpleName()); -+ } - } ---- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java -+++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java -@@ -1,6 +1,9 @@ - package io.dropwizard.metrics5.httpclient; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import io.dropwizard.metrics5.MetricRegistry; -+import java.util.concurrent.TimeUnit; - import org.apache.http.config.Registry; - import org.apache.http.config.RegistryBuilder; - import org.apache.http.conn.DnsResolver; -@@ -17,184 +20,198 @@ import org.apache.http.impl.conn.DefaultHttpClientConnectionOperator; - import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; - import org.apache.http.impl.conn.SystemDefaultDnsResolver; - --import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -- --/** -- * A {@link HttpClientConnectionManager} which monitors the number of open connections. -- */ -+/** A {@link HttpClientConnectionManager} which monitors the number of open connections. */ - public class InstrumentedHttpClientConnectionManager extends PoolingHttpClientConnectionManager { - -- -- protected static Registry getDefaultRegistry() { -- return RegistryBuilder.create() -- .register("http", PlainConnectionSocketFactory.getSocketFactory()) -- .register("https", SSLConnectionSocketFactory.getSocketFactory()) -- .build(); -+ protected static Registry getDefaultRegistry() { -+ return RegistryBuilder.create() -+ .register("http", PlainConnectionSocketFactory.getSocketFactory()) -+ .register("https", SSLConnectionSocketFactory.getSocketFactory()) -+ .build(); -+ } -+ -+ private final MetricRegistry metricsRegistry; -+ private final String name; -+ -+ /** -+ * @deprecated Use {@link #builder(MetricRegistry)} instead. -+ */ -+ @Deprecated -+ public InstrumentedHttpClientConnectionManager(MetricRegistry metricRegistry) { -+ this(metricRegistry, getDefaultRegistry()); -+ } -+ -+ /** -+ * @deprecated Use {@link #builder(MetricRegistry)} instead. -+ */ -+ @Deprecated -+ public InstrumentedHttpClientConnectionManager( -+ MetricRegistry metricsRegistry, Registry socketFactoryRegistry) { -+ this(metricsRegistry, socketFactoryRegistry, -1, TimeUnit.MILLISECONDS); -+ } -+ -+ /** -+ * @deprecated Use {@link #builder(MetricRegistry)} instead. -+ */ -+ @Deprecated -+ public InstrumentedHttpClientConnectionManager( -+ MetricRegistry metricsRegistry, -+ Registry socketFactoryRegistry, -+ long connTTL, -+ TimeUnit connTTLTimeUnit) { -+ this( -+ metricsRegistry, -+ socketFactoryRegistry, -+ null, -+ null, -+ SystemDefaultDnsResolver.INSTANCE, -+ connTTL, -+ connTTLTimeUnit, -+ null); -+ } -+ -+ /** -+ * @deprecated Use {@link #builder(MetricRegistry)} instead. -+ */ -+ @Deprecated -+ public InstrumentedHttpClientConnectionManager( -+ MetricRegistry metricsRegistry, -+ Registry socketFactoryRegistry, -+ HttpConnectionFactory connFactory, -+ SchemePortResolver schemePortResolver, -+ DnsResolver dnsResolver, -+ long connTTL, -+ TimeUnit connTTLTimeUnit, -+ String name) { -+ this( -+ metricsRegistry, -+ new DefaultHttpClientConnectionOperator( -+ socketFactoryRegistry, schemePortResolver, dnsResolver), -+ connFactory, -+ connTTL, -+ connTTLTimeUnit, -+ name); -+ } -+ -+ /** -+ * @deprecated Use {@link #builder(MetricRegistry)} instead. -+ */ -+ @Deprecated -+ public InstrumentedHttpClientConnectionManager( -+ MetricRegistry metricsRegistry, -+ HttpClientConnectionOperator httpClientConnectionOperator, -+ HttpConnectionFactory connFactory, -+ long connTTL, -+ TimeUnit connTTLTimeUnit, -+ String name) { -+ super(httpClientConnectionOperator, connFactory, connTTL, connTTLTimeUnit); -+ this.metricsRegistry = metricsRegistry; -+ this.name = name; -+ -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricsRegistry.registerGauge( -+ name(HttpClientConnectionManager.class, name, "available-connections"), -+ () -> getTotalStats().getAvailable()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricsRegistry.registerGauge( -+ name(HttpClientConnectionManager.class, name, "leased-connections"), -+ () -> getTotalStats().getLeased()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricsRegistry.registerGauge( -+ name(HttpClientConnectionManager.class, name, "max-connections"), -+ () -> getTotalStats().getMax()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricsRegistry.registerGauge( -+ name(HttpClientConnectionManager.class, name, "pending-connections"), -+ () -> getTotalStats().getPending()); -+ } -+ -+ @Override -+ public void shutdown() { -+ super.shutdown(); -+ metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "available-connections")); -+ metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "leased-connections")); -+ metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "max-connections")); -+ metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "pending-connections")); -+ } -+ -+ public static Builder builder(MetricRegistry metricsRegistry) { -+ return new Builder().metricsRegistry(metricsRegistry); -+ } -+ -+ public static class Builder { -+ private MetricRegistry metricsRegistry; -+ private HttpClientConnectionOperator httpClientConnectionOperator; -+ private Registry socketFactoryRegistry = getDefaultRegistry(); -+ private HttpConnectionFactory connFactory; -+ private SchemePortResolver schemePortResolver; -+ private DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE; -+ private long connTTL = -1; -+ private TimeUnit connTTLTimeUnit = TimeUnit.MILLISECONDS; -+ private String name; -+ -+ Builder() {} -+ -+ public Builder metricsRegistry(MetricRegistry metricsRegistry) { -+ this.metricsRegistry = metricsRegistry; -+ return this; - } - -- private final MetricRegistry metricsRegistry; -- private final String name; -- -- /** -- * @deprecated Use {@link #builder(MetricRegistry)} instead. -- */ -- @Deprecated -- public InstrumentedHttpClientConnectionManager(MetricRegistry metricRegistry) { -- this(metricRegistry, getDefaultRegistry()); -+ public Builder socketFactoryRegistry(Registry socketFactoryRegistry) { -+ this.socketFactoryRegistry = socketFactoryRegistry; -+ return this; - } - -- /** -- * @deprecated Use {@link #builder(MetricRegistry)} instead. -- */ -- @Deprecated -- public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, -- Registry socketFactoryRegistry) { -- this(metricsRegistry, socketFactoryRegistry, -1, TimeUnit.MILLISECONDS); -+ public Builder connFactory( -+ HttpConnectionFactory connFactory) { -+ this.connFactory = connFactory; -+ return this; - } - -- -- /** -- * @deprecated Use {@link #builder(MetricRegistry)} instead. -- */ -- @Deprecated -- public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, -- Registry socketFactoryRegistry, -- long connTTL, -- TimeUnit connTTLTimeUnit) { -- this(metricsRegistry, socketFactoryRegistry, null, null, SystemDefaultDnsResolver.INSTANCE, connTTL, connTTLTimeUnit, null); -+ public Builder schemePortResolver(SchemePortResolver schemePortResolver) { -+ this.schemePortResolver = schemePortResolver; -+ return this; - } - -- -- /** -- * @deprecated Use {@link #builder(MetricRegistry)} instead. -- */ -- @Deprecated -- public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, -- Registry socketFactoryRegistry, -- HttpConnectionFactory -- connFactory, -- SchemePortResolver schemePortResolver, -- DnsResolver dnsResolver, -- long connTTL, -- TimeUnit connTTLTimeUnit, -- String name) { -- this(metricsRegistry, -- new DefaultHttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver), -- connFactory, -- connTTL, -- connTTLTimeUnit, -- name); -+ public Builder dnsResolver(DnsResolver dnsResolver) { -+ this.dnsResolver = dnsResolver; -+ return this; - } - -- /** -- * @deprecated Use {@link #builder(MetricRegistry)} instead. -- */ -- @Deprecated -- public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, -- HttpClientConnectionOperator httpClientConnectionOperator, -- HttpConnectionFactory -- connFactory, -- long connTTL, -- TimeUnit connTTLTimeUnit, -- String name) { -- super(httpClientConnectionOperator, connFactory, connTTL, connTTLTimeUnit); -- this.metricsRegistry = metricsRegistry; -- this.name = name; -- -- // this acquires a lock on the connection pool; remove if contention sucks -- metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "available-connections"), -- () -> getTotalStats().getAvailable()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "leased-connections"), -- () -> getTotalStats().getLeased()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "max-connections"), -- () -> getTotalStats().getMax()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricsRegistry.registerGauge(name(HttpClientConnectionManager.class, name, "pending-connections"), -- () -> getTotalStats().getPending()); -+ public Builder connTTL(long connTTL) { -+ this.connTTL = connTTL; -+ return this; - } - -- @Override -- public void shutdown() { -- super.shutdown(); -- metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "available-connections")); -- metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "leased-connections")); -- metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "max-connections")); -- metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "pending-connections")); -+ public Builder connTTLTimeUnit(TimeUnit connTTLTimeUnit) { -+ this.connTTLTimeUnit = connTTLTimeUnit; -+ return this; - } - -- public static Builder builder(MetricRegistry metricsRegistry) { -- return new Builder().metricsRegistry(metricsRegistry); -+ public Builder httpClientConnectionOperator( -+ HttpClientConnectionOperator httpClientConnectionOperator) { -+ this.httpClientConnectionOperator = httpClientConnectionOperator; -+ return this; - } - -- public static class Builder { -- private MetricRegistry metricsRegistry; -- private HttpClientConnectionOperator httpClientConnectionOperator; -- private Registry socketFactoryRegistry = getDefaultRegistry(); -- private HttpConnectionFactory connFactory; -- private SchemePortResolver schemePortResolver; -- private DnsResolver dnsResolver = SystemDefaultDnsResolver.INSTANCE; -- private long connTTL = -1; -- private TimeUnit connTTLTimeUnit = TimeUnit.MILLISECONDS; -- private String name; -- -- Builder() { -- } -- -- public Builder metricsRegistry(MetricRegistry metricsRegistry) { -- this.metricsRegistry = metricsRegistry; -- return this; -- } -- -- public Builder socketFactoryRegistry(Registry socketFactoryRegistry) { -- this.socketFactoryRegistry = socketFactoryRegistry; -- return this; -- } -- -- public Builder connFactory(HttpConnectionFactory connFactory) { -- this.connFactory = connFactory; -- return this; -- } -- -- public Builder schemePortResolver(SchemePortResolver schemePortResolver) { -- this.schemePortResolver = schemePortResolver; -- return this; -- } -- -- public Builder dnsResolver(DnsResolver dnsResolver) { -- this.dnsResolver = dnsResolver; -- return this; -- } -- -- public Builder connTTL(long connTTL) { -- this.connTTL = connTTL; -- return this; -- } -- -- public Builder connTTLTimeUnit(TimeUnit connTTLTimeUnit) { -- this.connTTLTimeUnit = connTTLTimeUnit; -- return this; -- } -- -- public Builder httpClientConnectionOperator(HttpClientConnectionOperator httpClientConnectionOperator) { -- this.httpClientConnectionOperator = httpClientConnectionOperator; -- return this; -- } -- -- public Builder name(final String name) { -- this.name = name; -- return this; -- } -- -- public InstrumentedHttpClientConnectionManager build() { -- if (httpClientConnectionOperator == null) { -- httpClientConnectionOperator = new DefaultHttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver); -- } -- return new InstrumentedHttpClientConnectionManager(metricsRegistry, httpClientConnectionOperator, connFactory, connTTL, connTTLTimeUnit, name); -- } -+ public Builder name(final String name) { -+ this.name = name; -+ return this; - } - -+ public InstrumentedHttpClientConnectionManager build() { -+ if (httpClientConnectionOperator == null) { -+ httpClientConnectionOperator = -+ new DefaultHttpClientConnectionOperator( -+ socketFactoryRegistry, schemePortResolver, dnsResolver); -+ } -+ return new InstrumentedHttpClientConnectionManager( -+ metricsRegistry, -+ httpClientConnectionOperator, -+ connFactory, -+ connTTL, -+ connTTLTimeUnit, -+ name); -+ } -+ } - } ---- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClients.java -+++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClients.java -@@ -5,28 +5,28 @@ import org.apache.http.impl.client.CloseableHttpClient; - import org.apache.http.impl.client.HttpClientBuilder; - - public class InstrumentedHttpClients { -- private InstrumentedHttpClients() { -- super(); -- } -+ private InstrumentedHttpClients() { -+ super(); -+ } - -- public static CloseableHttpClient createDefault(MetricRegistry metricRegistry) { -- return createDefault(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY); -- } -+ public static CloseableHttpClient createDefault(MetricRegistry metricRegistry) { -+ return createDefault(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY); -+ } - -- public static CloseableHttpClient createDefault(MetricRegistry metricRegistry, -- HttpClientMetricNameStrategy metricNameStrategy) { -- return custom(metricRegistry, metricNameStrategy).build(); -- } -+ public static CloseableHttpClient createDefault( -+ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { -+ return custom(metricRegistry, metricNameStrategy).build(); -+ } - -- public static HttpClientBuilder custom(MetricRegistry metricRegistry) { -- return custom(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY); -- } -- -- public static HttpClientBuilder custom(MetricRegistry metricRegistry, -- HttpClientMetricNameStrategy metricNameStrategy) { -- return HttpClientBuilder.create() -- .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy)) -- .setConnectionManager(InstrumentedHttpClientConnectionManager.builder(metricRegistry).build()); -- } -+ public static HttpClientBuilder custom(MetricRegistry metricRegistry) { -+ return custom(metricRegistry, HttpClientMetricNameStrategies.METHOD_ONLY); -+ } - -+ public static HttpClientBuilder custom( -+ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { -+ return HttpClientBuilder.create() -+ .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy)) -+ .setConnectionManager( -+ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build()); -+ } - } ---- a/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpRequestExecutor.java -+++ b/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpRequestExecutor.java -@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.httpclient; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -+import java.io.IOException; - import org.apache.http.HttpClientConnection; - import org.apache.http.HttpException; - import org.apache.http.HttpRequest; -@@ -10,52 +11,51 @@ import org.apache.http.HttpResponse; - import org.apache.http.protocol.HttpContext; - import org.apache.http.protocol.HttpRequestExecutor; - --import java.io.IOException; -- - public class InstrumentedHttpRequestExecutor extends HttpRequestExecutor { -- private final MetricRegistry registry; -- private final HttpClientMetricNameStrategy metricNameStrategy; -- private final String name; -- -- public InstrumentedHttpRequestExecutor(MetricRegistry registry, -- HttpClientMetricNameStrategy metricNameStrategy) { -- this(registry, metricNameStrategy, null); -- } -- -- public InstrumentedHttpRequestExecutor(MetricRegistry registry, -- HttpClientMetricNameStrategy metricNameStrategy, -- String name) { -- this(registry, metricNameStrategy, name, HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE); -+ private final MetricRegistry registry; -+ private final HttpClientMetricNameStrategy metricNameStrategy; -+ private final String name; -+ -+ public InstrumentedHttpRequestExecutor( -+ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy) { -+ this(registry, metricNameStrategy, null); -+ } -+ -+ public InstrumentedHttpRequestExecutor( -+ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy, String name) { -+ this(registry, metricNameStrategy, name, HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE); -+ } -+ -+ public InstrumentedHttpRequestExecutor( -+ MetricRegistry registry, -+ HttpClientMetricNameStrategy metricNameStrategy, -+ String name, -+ int waitForContinue) { -+ super(waitForContinue); -+ this.registry = registry; -+ this.name = name; -+ this.metricNameStrategy = metricNameStrategy; -+ } -+ -+ @Override -+ public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context) -+ throws HttpException, IOException { -+ final Timer.Context timerContext = timer(request).time(); -+ try { -+ return super.execute(request, conn, context); -+ } catch (HttpException | IOException e) { -+ meter(e).mark(); -+ throw e; -+ } finally { -+ timerContext.stop(); - } -+ } - -- public InstrumentedHttpRequestExecutor(MetricRegistry registry, -- HttpClientMetricNameStrategy metricNameStrategy, -- String name, -- int waitForContinue) { -- super(waitForContinue); -- this.registry = registry; -- this.name = name; -- this.metricNameStrategy = metricNameStrategy; -- } -- -- @Override -- public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context) throws HttpException, IOException { -- final Timer.Context timerContext = timer(request).time(); -- try { -- return super.execute(request, conn, context); -- } catch (HttpException | IOException e) { -- meter(e).mark(); -- throw e; -- } finally { -- timerContext.stop(); -- } -- } -+ private Timer timer(HttpRequest request) { -+ return registry.timer(metricNameStrategy.getNameFor(name, request)); -+ } - -- private Timer timer(HttpRequest request) { -- return registry.timer(metricNameStrategy.getNameFor(name, request)); -- } -- -- private Meter meter(Exception e) { -- return registry.meter(metricNameStrategy.getNameFor(name, e)); -- } -+ private Meter meter(Exception e) { -+ return registry.meter(metricNameStrategy.getNameFor(name, e)); -+ } - } ---- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java -+++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java -@@ -1,6 +1,14 @@ - package io.dropwizard.metrics5.httpclient; - -+import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.HOST_AND_METHOD; -+import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.METHOD_ONLY; -+import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.PATH_AND_METHOD; -+import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricName; -+import java.net.URI; -+import java.net.URISyntaxException; - import org.apache.http.HttpRequest; - import org.apache.http.client.methods.HttpGet; - import org.apache.http.client.methods.HttpPost; -@@ -9,103 +17,113 @@ import org.apache.http.client.methods.HttpRequestWrapper; - import org.apache.http.client.utils.URIUtils; - import org.junit.jupiter.api.Test; - --import java.net.URI; --import java.net.URISyntaxException; -- --import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.HOST_AND_METHOD; --import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.METHOD_ONLY; --import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.PATH_AND_METHOD; --import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; --import static org.assertj.core.api.Assertions.assertThat; -- --class HttpClientMetricNameStrategiesTest { -- -- @Test -- void methodOnlyWithName() { -- assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever"))) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.get-requests")); -- } -- -- @Test -- void methodOnlyWithoutName() { -- assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever"))) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.get-requests")); -- } -- -- @Test -- void hostAndMethodWithName() { -- assertThat(HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever"))) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.my.host.com.post-requests")); -- } -- -- @Test -- void hostAndMethodWithoutName() { -- assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever"))) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.my.host.com.post-requests")); -- } -- -- @Test -- void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { -- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); -- -- assertThat(HOST_AND_METHOD.getNameFor("some-service", request)) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.my.host.com.post-requests")); -- } -- -- @Test -- void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { -- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); -- -- assertThat(HOST_AND_METHOD.getNameFor(null, request)) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.my.host.com.post-requests")); -- } -- -- @Test -- void pathAndMethodWithName() { -- assertThat(PATH_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever/happens"))) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests")); -- } -- -- @Test -- void pathAndMethodWithoutName() { -- assertThat(PATH_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever/happens"))) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests")); -- } -- -- @Test -- void pathAndMethodWithNameInWrappedRequest() throws URISyntaxException { -- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); -- assertThat(PATH_AND_METHOD.getNameFor("some-service", request)) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests")); -- } -- -- @Test -- void pathAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { -- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); -- assertThat(PATH_AND_METHOD.getNameFor(null, request)) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests")); -- } -- -- @Test -- void querylessUrlAndMethodWithName() { -- assertThat(QUERYLESS_URL_AND_METHOD.getNameFor( -- "some-service", -- new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this"))) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); -- } -- -- @Test -- void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { -- HttpRequest request = rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); -- assertThat(QUERYLESS_URL_AND_METHOD.getNameFor("some-service", request)) -- .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); -- } -- -- private static HttpRequest rewriteRequestURI(HttpRequest request) throws URISyntaxException { -- HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request); -- URI uri = URIUtils.rewriteURI(wrapper.getURI(), null, true); -- wrapper.setURI(uri); -- -- return wrapper; -- } -+final class HttpClientMetricNameStrategiesTest { -+ -+ @Test -+ void methodOnlyWithName() { -+ assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever"))) -+ .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.some-service.get-requests")); -+ } -+ -+ @Test -+ void methodOnlyWithoutName() { -+ assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever"))) -+ .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.get-requests")); -+ } -+ -+ @Test -+ void hostAndMethodWithName() { -+ assertThat( -+ HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever"))) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.http.client.HttpClient.some-service.my.host.com.post-requests")); -+ } -+ -+ @Test -+ void hostAndMethodWithoutName() { -+ assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever"))) -+ .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.my.host.com.post-requests")); -+ } -+ -+ @Test -+ void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { -+ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); -+ -+ assertThat(HOST_AND_METHOD.getNameFor("some-service", request)) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.http.client.HttpClient.some-service.my.host.com.post-requests")); -+ } -+ -+ @Test -+ void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { -+ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); -+ -+ assertThat(HOST_AND_METHOD.getNameFor(null, request)) -+ .isEqualTo(MetricName.build("org.apache.http.client.HttpClient.my.host.com.post-requests")); -+ } -+ -+ @Test -+ void pathAndMethodWithName() { -+ assertThat( -+ PATH_AND_METHOD.getNameFor( -+ "some-service", new HttpPost("http://my.host.com/whatever/happens"))) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests")); -+ } -+ -+ @Test -+ void pathAndMethodWithoutName() { -+ assertThat( -+ PATH_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever/happens"))) -+ .isEqualTo( -+ MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests")); -+ } -+ -+ @Test -+ void pathAndMethodWithNameInWrappedRequest() throws URISyntaxException { -+ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); -+ assertThat(PATH_AND_METHOD.getNameFor("some-service", request)) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests")); -+ } -+ -+ @Test -+ void pathAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { -+ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); -+ assertThat(PATH_AND_METHOD.getNameFor(null, request)) -+ .isEqualTo( -+ MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests")); -+ } -+ -+ @Test -+ void querylessUrlAndMethodWithName() { -+ assertThat( -+ QUERYLESS_URL_AND_METHOD.getNameFor( -+ "some-service", new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this"))) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); -+ } -+ -+ @Test -+ void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { -+ HttpRequest request = -+ rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); -+ assertThat(QUERYLESS_URL_AND_METHOD.getNameFor("some-service", request)) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); -+ } -+ -+ private static HttpRequest rewriteRequestURI(HttpRequest request) throws URISyntaxException { -+ HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request); -+ URI uri = URIUtils.rewriteURI(wrapper.getURI(), null, true); -+ wrapper.setURI(uri); -+ -+ return wrapper; -+ } - } ---- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java -+++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java -@@ -1,50 +1,53 @@ - package io.dropwizard.metrics5.httpclient; - --import io.dropwizard.metrics5.MetricName; --import io.dropwizard.metrics5.MetricRegistry; --import org.junit.jupiter.api.Test; --import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.junit.jupiter.api.Assertions.assertEquals; --import static org.junit.jupiter.api.Assertions.assertTrue; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - -+import io.dropwizard.metrics5.MetricName; -+import io.dropwizard.metrics5.MetricRegistry; -+import org.junit.jupiter.api.Test; -+import org.mockito.ArgumentCaptor; - --class InstrumentedHttpClientConnectionManagerTest { -- private final MetricRegistry metricRegistry = new MetricRegistry(); -+final class InstrumentedHttpClientConnectionManagerTest { -+ private final MetricRegistry metricRegistry = new MetricRegistry(); - -- @Test -- void shouldRemoveGauges() { -- final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); -- assertThat(metricRegistry.getGauges().entrySet().stream() -+ @Test -+ void shouldRemoveGauges() { -+ final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = -+ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); -+ assertThat( -+ metricRegistry.getGauges().entrySet().stream() - .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) -- .containsOnly(entry("org.apache.http.conn.HttpClientConnectionManager.available-connections", 0), -- entry("org.apache.http.conn.HttpClientConnectionManager.leased-connections", 0), -- entry("org.apache.http.conn.HttpClientConnectionManager.max-connections", 20), -- entry("org.apache.http.conn.HttpClientConnectionManager.pending-connections", 0)); -- -- instrumentedHttpClientConnectionManager.close(); -- assertEquals(0, metricRegistry.getGauges().size()); -- -- // should be able to create another one with the same name ("") -- InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); -- } -- -- @Test -- void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -- -- InstrumentedHttpClientConnectionManager.builder(registry) -- .name("some-name") -- .name("some-other-name") -- .build() -- .close(); -- -- ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); -- } -+ .containsOnly( -+ entry("org.apache.http.conn.HttpClientConnectionManager.available-connections", 0), -+ entry("org.apache.http.conn.HttpClientConnectionManager.leased-connections", 0), -+ entry("org.apache.http.conn.HttpClientConnectionManager.max-connections", 20), -+ entry("org.apache.http.conn.HttpClientConnectionManager.pending-connections", 0)); -+ -+ instrumentedHttpClientConnectionManager.close(); -+ assertEquals(0, metricRegistry.getGauges().size()); -+ -+ // should be able to create another one with the same name ("") -+ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); -+ } -+ -+ @Test -+ void configurableViaBuilder() { -+ final MetricRegistry registry = mock(); -+ -+ InstrumentedHttpClientConnectionManager.builder(registry) -+ .name("some-name") -+ .name("some-other-name") -+ .build() -+ .close(); -+ -+ ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); -+ } - } ---- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java -@@ -1,11 +1,20 @@ - package io.dropwizard.metrics5.httpclient; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; -+import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.ArgumentMatchers.eq; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import com.sun.net.httpserver.HttpExchange; - import com.sun.net.httpserver.HttpServer; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricRegistryListener; - import io.dropwizard.metrics5.Timer; -+import java.net.InetSocketAddress; - import org.apache.http.HttpRequest; - import org.apache.http.NoHttpResponseException; - import org.apache.http.client.HttpClient; -@@ -13,66 +22,55 @@ import org.apache.http.client.methods.HttpGet; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import java.net.InetSocketAddress; -+final class InstrumentedHttpClientsTest { -+ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); -+ private final MetricRegistryListener registryListener = mock(); -+ private final MetricRegistry metricRegistry = new MetricRegistry(); -+ private final HttpClient client = -+ InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) -+ .disableAutomaticRetries() -+ .build(); - --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; --import static org.mockito.ArgumentMatchers.any; --import static org.mockito.ArgumentMatchers.eq; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -+ @BeforeEach -+ void setUp() { -+ metricRegistry.addListener(registryListener); -+ } - --class InstrumentedHttpClientsTest { -- private final HttpClientMetricNameStrategy metricNameStrategy = -- mock(HttpClientMetricNameStrategy.class); -- private final MetricRegistryListener registryListener = -- mock(MetricRegistryListener.class); -- private final MetricRegistry metricRegistry = new MetricRegistry(); -- private final HttpClient client = -- InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); -+ @Test -+ void registersExpectedMetricsGivenNameStrategy() throws Exception { -+ final HttpGet get = new HttpGet("http://example.com?q=anything"); -+ final MetricName metricName = MetricName.build("some.made.up.metric.name"); - -- @BeforeEach -- void setUp() { -- metricRegistry.addListener(registryListener); -- } -- -- @Test -- void registersExpectedMetricsGivenNameStrategy() throws Exception { -- final HttpGet get = new HttpGet("http://example.com?q=anything"); -- final MetricName metricName = MetricName.build("some.made.up.metric.name"); -+ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); - -- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) -- .thenReturn(metricName); -+ client.execute(get); - -- client.execute(get); -- -- verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); -- } -+ verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); -+ } - -- @Test -- void registersExpectedExceptionMetrics() throws Exception { -- HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); -+ @Test -+ void registersExpectedExceptionMetrics() throws Exception { -+ HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); - -- final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); -- final MetricName requestMetricName = MetricName.build("request"); -- final MetricName exceptionMetricName = MetricName.build("exception"); -+ final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); -+ final MetricName requestMetricName = MetricName.build("request"); -+ final MetricName exceptionMetricName = MetricName.build("exception"); - -- httpServer.createContext("/", HttpExchange::close); -- httpServer.start(); -+ httpServer.createContext("/", HttpExchange::close); -+ httpServer.start(); - -- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) -- .thenReturn(requestMetricName); -- when(metricNameStrategy.getNameFor(any(), any(Exception.class))) -- .thenReturn(exceptionMetricName); -+ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) -+ .thenReturn(requestMetricName); -+ when(metricNameStrategy.getNameFor(any(), any(Exception.class))) -+ .thenReturn(exceptionMetricName); - -- try { -- client.execute(get); -- fail(); -- } catch (NoHttpResponseException expected) { -- assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); -- } finally { -- httpServer.stop(0); -- } -+ try { -+ client.execute(get); -+ fail(); -+ } catch (NoHttpResponseException expected) { -+ assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); -+ } finally { -+ httpServer.stop(0); - } -+ } - } ---- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategies.java -+++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategies.java -@@ -1,48 +1,43 @@ - package io.dropwizard.metrics5.httpclient5; - --import org.apache.hc.client5.http.classic.HttpClient; --import org.apache.hc.core5.http.HttpRequest; --import org.apache.hc.core5.net.URIBuilder; -+import static io.dropwizard.metrics5.MetricRegistry.name; - - import java.net.URISyntaxException; - import java.util.Locale; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -+import org.apache.hc.client5.http.classic.HttpClient; -+import org.apache.hc.core5.http.HttpRequest; -+import org.apache.hc.core5.net.URIBuilder; - - public class HttpClientMetricNameStrategies { - -- public static final HttpClientMetricNameStrategy METHOD_ONLY = -- (name, request) -> name(HttpClient.class, -- name, -- methodNameString(request)); -- -- public static final HttpClientMetricNameStrategy HOST_AND_METHOD = -- (name, request) -> { -- try { -- return name(HttpClient.class, -- name, -- request.getUri().getHost(), -- methodNameString(request)); -- } catch (URISyntaxException e) { -- throw new IllegalArgumentException(e); -- } -- }; -- -- public static final HttpClientMetricNameStrategy QUERYLESS_URL_AND_METHOD = -- (name, request) -> { -- try { -- final URIBuilder url = new URIBuilder(request.getUri()); -- return name(HttpClient.class, -- name, -- url.removeQuery().build().toString(), -- methodNameString(request)); -- } catch (URISyntaxException e) { -- throw new IllegalArgumentException(e); -- } -- }; -- -- private static String methodNameString(HttpRequest request) { -- return request.getMethod().toLowerCase(Locale.ROOT) + "-requests"; -- } -- -+ public static final HttpClientMetricNameStrategy METHOD_ONLY = -+ (name, request) -> name(HttpClient.class, name, methodNameString(request)); -+ -+ public static final HttpClientMetricNameStrategy HOST_AND_METHOD = -+ (name, request) -> { -+ try { -+ return name( -+ HttpClient.class, name, request.getUri().getHost(), methodNameString(request)); -+ } catch (URISyntaxException e) { -+ throw new IllegalArgumentException(e); -+ } -+ }; -+ -+ public static final HttpClientMetricNameStrategy QUERYLESS_URL_AND_METHOD = -+ (name, request) -> { -+ try { -+ final URIBuilder url = new URIBuilder(request.getUri()); -+ return name( -+ HttpClient.class, -+ name, -+ url.removeQuery().build().toString(), -+ methodNameString(request)); -+ } catch (URISyntaxException e) { -+ throw new IllegalArgumentException(e); -+ } -+ }; -+ -+ private static String methodNameString(HttpRequest request) { -+ return request.getMethod().toLowerCase(Locale.ROOT) + "-requests"; -+ } - } ---- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategy.java -+++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategy.java -@@ -8,11 +8,9 @@ import org.apache.hc.core5.http.HttpRequest; - @FunctionalInterface - public interface HttpClientMetricNameStrategy { - -- MetricName getNameFor(String name, HttpRequest request); -+ MetricName getNameFor(String name, HttpRequest request); - -- default MetricName getNameFor(String name, Exception exception) { -- return MetricRegistry.name(HttpClient.class, -- name, -- exception.getClass().getSimpleName()); -- } -+ default MetricName getNameFor(String name, Exception exception) { -+ return MetricRegistry.name(HttpClient.class, name, exception.getClass().getSimpleName()); -+ } - } ---- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java -+++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java -@@ -1,5 +1,8 @@ - package io.dropwizard.metrics5.httpclient5; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static java.util.Objects.requireNonNull; -+ - import io.dropwizard.metrics5.MetricRegistry; - import org.apache.hc.client5.http.DnsResolver; - import org.apache.hc.client5.http.SchemePortResolver; -@@ -17,139 +20,135 @@ import org.apache.hc.core5.pool.PoolConcurrencyPolicy; - import org.apache.hc.core5.pool.PoolReusePolicy; - import org.apache.hc.core5.util.TimeValue; - --import static io.dropwizard.metrics5.MetricRegistry.name; --import static java.util.Objects.requireNonNull; -- --/** -- * A {@link HttpClientConnectionManager} which monitors the number of open connections. -- */ -+/** A {@link HttpClientConnectionManager} which monitors the number of open connections. */ - public class InstrumentedAsyncClientConnectionManager extends PoolingAsyncClientConnectionManager { -- private static final String METRICS_PREFIX = AsyncClientConnectionManager.class.getName(); -+ private static final String METRICS_PREFIX = AsyncClientConnectionManager.class.getName(); -+ -+ protected static Registry getDefaultTlsStrategy() { -+ return RegistryBuilder.create() -+ .register(URIScheme.HTTPS.id, DefaultClientTlsStrategy.getDefault()) -+ .build(); -+ } -+ -+ private final MetricRegistry metricsRegistry; -+ private final String name; -+ -+ InstrumentedAsyncClientConnectionManager( -+ final MetricRegistry metricRegistry, -+ final String name, -+ final Lookup tlsStrategyLookup, -+ final PoolConcurrencyPolicy poolConcurrencyPolicy, -+ final PoolReusePolicy poolReusePolicy, -+ final TimeValue timeToLive, -+ final SchemePortResolver schemePortResolver, -+ final DnsResolver dnsResolver) { -+ -+ super( -+ tlsStrategyLookup, -+ poolConcurrencyPolicy, -+ poolReusePolicy, -+ timeToLive, -+ schemePortResolver, -+ dnsResolver); -+ this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); -+ this.name = name; -+ -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(METRICS_PREFIX, name, "available-connections"), () -> getTotalStats().getAvailable()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(METRICS_PREFIX, name, "leased-connections"), () -> getTotalStats().getLeased()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(METRICS_PREFIX, name, "max-connections"), () -> getTotalStats().getMax()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(METRICS_PREFIX, name, "pending-connections"), () -> getTotalStats().getPending()); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void close() { -+ close(CloseMode.GRACEFUL); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void close(CloseMode closeMode) { -+ super.close(closeMode); -+ metricsRegistry.remove(name(METRICS_PREFIX, name, "available-connections")); -+ metricsRegistry.remove(name(METRICS_PREFIX, name, "leased-connections")); -+ metricsRegistry.remove(name(METRICS_PREFIX, name, "max-connections")); -+ metricsRegistry.remove(name(METRICS_PREFIX, name, "pending-connections")); -+ } -+ -+ public static Builder builder(MetricRegistry metricsRegistry) { -+ return new Builder().metricsRegistry(metricsRegistry); -+ } -+ -+ public static class Builder { -+ private MetricRegistry metricsRegistry; -+ private String name; -+ private Lookup tlsStrategyLookup = getDefaultTlsStrategy(); -+ private SchemePortResolver schemePortResolver; -+ private DnsResolver dnsResolver; -+ private PoolConcurrencyPolicy poolConcurrencyPolicy; -+ private PoolReusePolicy poolReusePolicy; -+ private TimeValue timeToLive = TimeValue.NEG_ONE_MILLISECOND; -+ -+ Builder() {} -+ -+ public Builder metricsRegistry(MetricRegistry metricRegistry) { -+ this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); -+ return this; -+ } - -- protected static Registry getDefaultTlsStrategy() { -- return RegistryBuilder.create() -- .register(URIScheme.HTTPS.id, DefaultClientTlsStrategy.getDefault()) -- .build(); -+ public Builder name(final String name) { -+ this.name = name; -+ return this; - } - -- private final MetricRegistry metricsRegistry; -- private final String name; -- -- InstrumentedAsyncClientConnectionManager(final MetricRegistry metricRegistry, -- final String name, -- final Lookup tlsStrategyLookup, -- final PoolConcurrencyPolicy poolConcurrencyPolicy, -- final PoolReusePolicy poolReusePolicy, -- final TimeValue timeToLive, -- final SchemePortResolver schemePortResolver, -- final DnsResolver dnsResolver) { -- -- super(tlsStrategyLookup, poolConcurrencyPolicy, poolReusePolicy, timeToLive, schemePortResolver, dnsResolver); -- this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); -- this.name = name; -- -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "available-connections"), -- () -> getTotalStats().getAvailable()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "leased-connections"), -- () -> getTotalStats().getLeased()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "max-connections"), -- () -> getTotalStats().getMax()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "pending-connections"), -- () -> getTotalStats().getPending()); -+ public Builder schemePortResolver(SchemePortResolver schemePortResolver) { -+ this.schemePortResolver = schemePortResolver; -+ return this; - } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void close() { -- close(CloseMode.GRACEFUL); -+ public Builder dnsResolver(DnsResolver dnsResolver) { -+ this.dnsResolver = dnsResolver; -+ return this; - } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void close(CloseMode closeMode) { -- super.close(closeMode); -- metricsRegistry.remove(name(METRICS_PREFIX, name, "available-connections")); -- metricsRegistry.remove(name(METRICS_PREFIX, name, "leased-connections")); -- metricsRegistry.remove(name(METRICS_PREFIX, name, "max-connections")); -- metricsRegistry.remove(name(METRICS_PREFIX, name, "pending-connections")); -+ public Builder timeToLive(TimeValue timeToLive) { -+ this.timeToLive = timeToLive; -+ return this; - } - -- public static Builder builder(MetricRegistry metricsRegistry) { -- return new Builder().metricsRegistry(metricsRegistry); -+ public Builder tlsStrategyLookup(Lookup tlsStrategyLookup) { -+ this.tlsStrategyLookup = tlsStrategyLookup; -+ return this; - } - -- public static class Builder { -- private MetricRegistry metricsRegistry; -- private String name; -- private Lookup tlsStrategyLookup = getDefaultTlsStrategy(); -- private SchemePortResolver schemePortResolver; -- private DnsResolver dnsResolver; -- private PoolConcurrencyPolicy poolConcurrencyPolicy; -- private PoolReusePolicy poolReusePolicy; -- private TimeValue timeToLive = TimeValue.NEG_ONE_MILLISECOND; -- -- Builder() { -- } -- -- public Builder metricsRegistry(MetricRegistry metricRegistry) { -- this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); -- return this; -- } -- -- public Builder name(final String name) { -- this.name = name; -- return this; -- } -- -- public Builder schemePortResolver(SchemePortResolver schemePortResolver) { -- this.schemePortResolver = schemePortResolver; -- return this; -- } -- -- public Builder dnsResolver(DnsResolver dnsResolver) { -- this.dnsResolver = dnsResolver; -- return this; -- } -- -- public Builder timeToLive(TimeValue timeToLive) { -- this.timeToLive = timeToLive; -- return this; -- } -- -- public Builder tlsStrategyLookup(Lookup tlsStrategyLookup) { -- this.tlsStrategyLookup = tlsStrategyLookup; -- return this; -- } -- -- public Builder poolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) { -- this.poolConcurrencyPolicy = poolConcurrencyPolicy; -- return this; -- } -- -- public Builder poolReusePolicy(PoolReusePolicy poolReusePolicy) { -- this.poolReusePolicy = poolReusePolicy; -- return this; -- } -- -- public InstrumentedAsyncClientConnectionManager build() { -- return new InstrumentedAsyncClientConnectionManager( -- metricsRegistry, -- name, -- tlsStrategyLookup, -- poolConcurrencyPolicy, -- poolReusePolicy, -- timeToLive, -- schemePortResolver, -- dnsResolver); -- } -+ public Builder poolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) { -+ this.poolConcurrencyPolicy = poolConcurrencyPolicy; -+ return this; - } - -+ public Builder poolReusePolicy(PoolReusePolicy poolReusePolicy) { -+ this.poolReusePolicy = poolReusePolicy; -+ return this; -+ } -+ -+ public InstrumentedAsyncClientConnectionManager build() { -+ return new InstrumentedAsyncClientConnectionManager( -+ metricsRegistry, -+ name, -+ tlsStrategyLookup, -+ poolConcurrencyPolicy, -+ poolReusePolicy, -+ timeToLive, -+ schemePortResolver, -+ dnsResolver); -+ } -+ } - } ---- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncExecChainHandler.java -+++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncExecChainHandler.java -@@ -1,8 +1,11 @@ - package io.dropwizard.metrics5.httpclient5; - -+import static java.util.Objects.requireNonNull; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -+import java.io.IOException; - import org.apache.hc.client5.http.async.AsyncExecCallback; - import org.apache.hc.client5.http.async.AsyncExecChain; - import org.apache.hc.client5.http.async.AsyncExecChainHandler; -@@ -13,87 +16,87 @@ import org.apache.hc.core5.http.HttpResponse; - import org.apache.hc.core5.http.nio.AsyncDataConsumer; - import org.apache.hc.core5.http.nio.AsyncEntityProducer; - --import java.io.IOException; -- --import static java.util.Objects.requireNonNull; -- - class InstrumentedAsyncExecChainHandler implements AsyncExecChainHandler { -+ private final MetricRegistry registry; -+ private final HttpClientMetricNameStrategy metricNameStrategy; -+ private final String name; -+ -+ public InstrumentedAsyncExecChainHandler( -+ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy) { -+ this(registry, metricNameStrategy, null); -+ } -+ -+ public InstrumentedAsyncExecChainHandler( -+ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy, String name) { -+ this.registry = requireNonNull(registry, "registry"); -+ this.metricNameStrategy = requireNonNull(metricNameStrategy, "metricNameStrategy"); -+ this.name = name; -+ } -+ -+ @Override -+ public void execute( -+ HttpRequest request, -+ AsyncEntityProducer entityProducer, -+ AsyncExecChain.Scope scope, -+ AsyncExecChain chain, -+ AsyncExecCallback asyncExecCallback) -+ throws HttpException, IOException { -+ final InstrumentedAsyncExecCallback instrumentedAsyncExecCallback = -+ new InstrumentedAsyncExecCallback( -+ registry, metricNameStrategy, name, asyncExecCallback, request); -+ chain.proceed(request, entityProducer, scope, instrumentedAsyncExecCallback); -+ } -+ -+ static final class InstrumentedAsyncExecCallback implements AsyncExecCallback { - private final MetricRegistry registry; - private final HttpClientMetricNameStrategy metricNameStrategy; - private final String name; -- -- public InstrumentedAsyncExecChainHandler(MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy) { -- this(registry, metricNameStrategy, null); -+ private final AsyncExecCallback delegate; -+ private final Timer.Context timerContext; -+ -+ public InstrumentedAsyncExecCallback( -+ MetricRegistry registry, -+ HttpClientMetricNameStrategy metricNameStrategy, -+ String name, -+ AsyncExecCallback delegate, -+ HttpRequest request) { -+ this.registry = registry; -+ this.metricNameStrategy = metricNameStrategy; -+ this.name = name; -+ this.delegate = delegate; -+ this.timerContext = timer(request).time(); - } - -- public InstrumentedAsyncExecChainHandler(MetricRegistry registry, -- HttpClientMetricNameStrategy metricNameStrategy, -- String name) { -- this.registry = requireNonNull(registry, "registry"); -- this.metricNameStrategy = requireNonNull(metricNameStrategy, "metricNameStrategy"); -- this.name = name; -+ @Override -+ public AsyncDataConsumer handleResponse(HttpResponse response, EntityDetails entityDetails) -+ throws HttpException, IOException { -+ return delegate.handleResponse(response, entityDetails); - } - - @Override -- public void execute(HttpRequest request, -- AsyncEntityProducer entityProducer, -- AsyncExecChain.Scope scope, -- AsyncExecChain chain, -- AsyncExecCallback asyncExecCallback) throws HttpException, IOException { -- final InstrumentedAsyncExecCallback instrumentedAsyncExecCallback = -- new InstrumentedAsyncExecCallback(registry, metricNameStrategy, name, asyncExecCallback, request); -- chain.proceed(request, entityProducer, scope, instrumentedAsyncExecCallback); -- -+ public void handleInformationResponse(HttpResponse response) throws HttpException, IOException { -+ delegate.handleInformationResponse(response); - } - -- final static class InstrumentedAsyncExecCallback implements AsyncExecCallback { -- private final MetricRegistry registry; -- private final HttpClientMetricNameStrategy metricNameStrategy; -- private final String name; -- private final AsyncExecCallback delegate; -- private final Timer.Context timerContext; -- -- public InstrumentedAsyncExecCallback(MetricRegistry registry, -- HttpClientMetricNameStrategy metricNameStrategy, -- String name, -- AsyncExecCallback delegate, -- HttpRequest request) { -- this.registry = registry; -- this.metricNameStrategy = metricNameStrategy; -- this.name = name; -- this.delegate = delegate; -- this.timerContext = timer(request).time(); -- } -- -- @Override -- public AsyncDataConsumer handleResponse(HttpResponse response, EntityDetails entityDetails) throws HttpException, IOException { -- return delegate.handleResponse(response, entityDetails); -- } -- -- @Override -- public void handleInformationResponse(HttpResponse response) throws HttpException, IOException { -- delegate.handleInformationResponse(response); -- } -- -- @Override -- public void completed() { -- delegate.completed(); -- timerContext.stop(); -- } -+ @Override -+ public void completed() { -+ delegate.completed(); -+ timerContext.stop(); -+ } - -- @Override -- public void failed(Exception cause) { -- delegate.failed(cause); -- meter(cause).mark(); -- timerContext.stop(); -- } -+ @Override -+ public void failed(Exception cause) { -+ delegate.failed(cause); -+ meter(cause).mark(); -+ timerContext.stop(); -+ } - -- private Timer timer(HttpRequest request) { -- return registry.timer(metricNameStrategy.getNameFor(name, request)); -- } -+ private Timer timer(HttpRequest request) { -+ return registry.timer(metricNameStrategy.getNameFor(name, request)); -+ } - -- private Meter meter(Exception e) { -- return registry.meter(metricNameStrategy.getNameFor(name, e)); -- } -+ private Meter meter(Exception e) { -+ return registry.meter(metricNameStrategy.getNameFor(name, e)); - } -+ } - } ---- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClients.java -+++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClients.java -@@ -1,43 +1,48 @@ - package io.dropwizard.metrics5.httpclient5; - -+import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; -+ - import io.dropwizard.metrics5.MetricRegistry; - import org.apache.hc.client5.http.impl.ChainElement; - import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; - import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder; - import org.apache.hc.client5.http.nio.AsyncClientConnectionManager; - --import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; -- - public class InstrumentedHttpAsyncClients { -- private InstrumentedHttpAsyncClients() { -- super(); -- } -- -- public static CloseableHttpAsyncClient createDefault(MetricRegistry metricRegistry) { -- return createDefault(metricRegistry, METHOD_ONLY); -- } -- -- public static CloseableHttpAsyncClient createDefault(MetricRegistry metricRegistry, -- HttpClientMetricNameStrategy metricNameStrategy) { -- return custom(metricRegistry, metricNameStrategy).build(); -- } -- -- public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry) { -- return custom(metricRegistry, METHOD_ONLY); -- } -- -- public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry, -- HttpClientMetricNameStrategy metricNameStrategy) { -- return custom(metricRegistry, metricNameStrategy, InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build()); -- } -- -- public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry, -- HttpClientMetricNameStrategy metricNameStrategy, -- AsyncClientConnectionManager clientConnectionManager) { -- return HttpAsyncClientBuilder.create() -- .setConnectionManager(clientConnectionManager) -- .addExecInterceptorBefore(ChainElement.CONNECT.name(), "dropwizard-metrics", -- new InstrumentedAsyncExecChainHandler(metricRegistry, metricNameStrategy)); -- } -- -+ private InstrumentedHttpAsyncClients() { -+ super(); -+ } -+ -+ public static CloseableHttpAsyncClient createDefault(MetricRegistry metricRegistry) { -+ return createDefault(metricRegistry, METHOD_ONLY); -+ } -+ -+ public static CloseableHttpAsyncClient createDefault( -+ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { -+ return custom(metricRegistry, metricNameStrategy).build(); -+ } -+ -+ public static HttpAsyncClientBuilder custom(MetricRegistry metricRegistry) { -+ return custom(metricRegistry, METHOD_ONLY); -+ } -+ -+ public static HttpAsyncClientBuilder custom( -+ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { -+ return custom( -+ metricRegistry, -+ metricNameStrategy, -+ InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build()); -+ } -+ -+ public static HttpAsyncClientBuilder custom( -+ MetricRegistry metricRegistry, -+ HttpClientMetricNameStrategy metricNameStrategy, -+ AsyncClientConnectionManager clientConnectionManager) { -+ return HttpAsyncClientBuilder.create() -+ .setConnectionManager(clientConnectionManager) -+ .addExecInterceptorBefore( -+ ChainElement.CONNECT.name(), -+ "dropwizard-metrics", -+ new InstrumentedAsyncExecChainHandler(metricRegistry, metricNameStrategy)); -+ } - } ---- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java -+++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java -@@ -1,5 +1,8 @@ - package io.dropwizard.metrics5.httpclient5; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static java.util.Objects.requireNonNull; -+ - import io.dropwizard.metrics5.MetricRegistry; - import org.apache.hc.client5.http.DnsResolver; - import org.apache.hc.client5.http.SchemePortResolver; -@@ -20,156 +23,152 @@ import org.apache.hc.core5.pool.PoolConcurrencyPolicy; - import org.apache.hc.core5.pool.PoolReusePolicy; - import org.apache.hc.core5.util.TimeValue; - --import static io.dropwizard.metrics5.MetricRegistry.name; --import static java.util.Objects.requireNonNull; -- --/** -- * A {@link HttpClientConnectionManager} which monitors the number of open connections. -- */ -+/** A {@link HttpClientConnectionManager} which monitors the number of open connections. */ - public class InstrumentedHttpClientConnectionManager extends PoolingHttpClientConnectionManager { -- private static final String METRICS_PREFIX = HttpClientConnectionManager.class.getName(); -+ private static final String METRICS_PREFIX = HttpClientConnectionManager.class.getName(); -+ -+ protected static Registry getDefaultRegistry() { -+ return RegistryBuilder.create() -+ .register(URIScheme.HTTP.id, PlainConnectionSocketFactory.getSocketFactory()) -+ .register(URIScheme.HTTPS.id, SSLConnectionSocketFactory.getSocketFactory()) -+ .build(); -+ } -+ -+ private final MetricRegistry metricsRegistry; -+ private final String name; -+ -+ InstrumentedHttpClientConnectionManager( -+ final MetricRegistry metricRegistry, -+ final String name, -+ final HttpClientConnectionOperator httpClientConnectionOperator, -+ final PoolConcurrencyPolicy poolConcurrencyPolicy, -+ final PoolReusePolicy poolReusePolicy, -+ final TimeValue timeToLive, -+ final HttpConnectionFactory connFactory) { -+ -+ super( -+ httpClientConnectionOperator, -+ poolConcurrencyPolicy, -+ poolReusePolicy, -+ timeToLive, -+ connFactory); -+ this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); -+ this.name = name; -+ -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(METRICS_PREFIX, name, "available-connections"), () -> getTotalStats().getAvailable()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(METRICS_PREFIX, name, "leased-connections"), () -> getTotalStats().getLeased()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(METRICS_PREFIX, name, "max-connections"), () -> getTotalStats().getMax()); -+ // this acquires a lock on the connection pool; remove if contention sucks -+ metricRegistry.registerGauge( -+ name(METRICS_PREFIX, name, "pending-connections"), () -> getTotalStats().getPending()); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void close() { -+ close(CloseMode.GRACEFUL); -+ } -+ -+ /** {@inheritDoc} */ -+ @Override -+ public void close(CloseMode closeMode) { -+ super.close(closeMode); -+ metricsRegistry.remove(name(METRICS_PREFIX, name, "available-connections")); -+ metricsRegistry.remove(name(METRICS_PREFIX, name, "leased-connections")); -+ metricsRegistry.remove(name(METRICS_PREFIX, name, "max-connections")); -+ metricsRegistry.remove(name(METRICS_PREFIX, name, "pending-connections")); -+ } -+ -+ public static Builder builder(MetricRegistry metricsRegistry) { -+ return new Builder().metricsRegistry(metricsRegistry); -+ } -+ -+ public static class Builder { -+ private MetricRegistry metricsRegistry; -+ private String name; -+ private HttpClientConnectionOperator httpClientConnectionOperator; -+ private Registry socketFactoryRegistry = getDefaultRegistry(); -+ private SchemePortResolver schemePortResolver; -+ private DnsResolver dnsResolver; -+ private PoolConcurrencyPolicy poolConcurrencyPolicy; -+ private PoolReusePolicy poolReusePolicy; -+ private TimeValue timeToLive = TimeValue.NEG_ONE_MILLISECOND; -+ private HttpConnectionFactory connFactory; -+ -+ Builder() {} -+ -+ public Builder metricsRegistry(MetricRegistry metricRegistry) { -+ this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); -+ return this; -+ } -+ -+ public Builder name(final String name) { -+ this.name = name; -+ return this; -+ } -+ -+ public Builder socketFactoryRegistry(Registry socketFactoryRegistry) { -+ this.socketFactoryRegistry = requireNonNull(socketFactoryRegistry, "socketFactoryRegistry"); -+ return this; -+ } -+ -+ public Builder connFactory(HttpConnectionFactory connFactory) { -+ this.connFactory = connFactory; -+ return this; -+ } -+ -+ public Builder schemePortResolver(SchemePortResolver schemePortResolver) { -+ this.schemePortResolver = schemePortResolver; -+ return this; -+ } - -- protected static Registry getDefaultRegistry() { -- return RegistryBuilder.create() -- .register(URIScheme.HTTP.id, PlainConnectionSocketFactory.getSocketFactory()) -- .register(URIScheme.HTTPS.id, SSLConnectionSocketFactory.getSocketFactory()) -- .build(); -+ public Builder dnsResolver(DnsResolver dnsResolver) { -+ this.dnsResolver = dnsResolver; -+ return this; - } - -- private final MetricRegistry metricsRegistry; -- private final String name; -- -- InstrumentedHttpClientConnectionManager(final MetricRegistry metricRegistry, -- final String name, -- final HttpClientConnectionOperator httpClientConnectionOperator, -- final PoolConcurrencyPolicy poolConcurrencyPolicy, -- final PoolReusePolicy poolReusePolicy, -- final TimeValue timeToLive, -- final HttpConnectionFactory connFactory) { -- -- super(httpClientConnectionOperator, poolConcurrencyPolicy, poolReusePolicy, timeToLive, connFactory); -- this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); -- this.name = name; -- -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "available-connections"), -- () -> getTotalStats().getAvailable()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "leased-connections"), -- () -> getTotalStats().getLeased()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "max-connections"), -- () -> getTotalStats().getMax()); -- // this acquires a lock on the connection pool; remove if contention sucks -- metricRegistry.registerGauge(name(METRICS_PREFIX, name, "pending-connections"), -- () -> getTotalStats().getPending()); -+ public Builder timeToLive(TimeValue timeToLive) { -+ this.timeToLive = timeToLive; -+ return this; - } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void close() { -- close(CloseMode.GRACEFUL); -+ public Builder httpClientConnectionOperator( -+ HttpClientConnectionOperator httpClientConnectionOperator) { -+ this.httpClientConnectionOperator = httpClientConnectionOperator; -+ return this; - } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public void close(CloseMode closeMode) { -- super.close(closeMode); -- metricsRegistry.remove(name(METRICS_PREFIX, name, "available-connections")); -- metricsRegistry.remove(name(METRICS_PREFIX, name, "leased-connections")); -- metricsRegistry.remove(name(METRICS_PREFIX, name, "max-connections")); -- metricsRegistry.remove(name(METRICS_PREFIX, name, "pending-connections")); -+ public Builder poolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) { -+ this.poolConcurrencyPolicy = poolConcurrencyPolicy; -+ return this; - } - -- public static Builder builder(MetricRegistry metricsRegistry) { -- return new Builder().metricsRegistry(metricsRegistry); -+ public Builder poolReusePolicy(PoolReusePolicy poolReusePolicy) { -+ this.poolReusePolicy = poolReusePolicy; -+ return this; - } - -- public static class Builder { -- private MetricRegistry metricsRegistry; -- private String name; -- private HttpClientConnectionOperator httpClientConnectionOperator; -- private Registry socketFactoryRegistry = getDefaultRegistry(); -- private SchemePortResolver schemePortResolver; -- private DnsResolver dnsResolver; -- private PoolConcurrencyPolicy poolConcurrencyPolicy; -- private PoolReusePolicy poolReusePolicy; -- private TimeValue timeToLive = TimeValue.NEG_ONE_MILLISECOND; -- private HttpConnectionFactory connFactory; -- -- Builder() { -- } -- -- public Builder metricsRegistry(MetricRegistry metricRegistry) { -- this.metricsRegistry = requireNonNull(metricRegistry, "metricRegistry"); -- return this; -- } -- -- public Builder name(final String name) { -- this.name = name; -- return this; -- } -- -- public Builder socketFactoryRegistry(Registry socketFactoryRegistry) { -- this.socketFactoryRegistry = requireNonNull(socketFactoryRegistry, "socketFactoryRegistry"); -- return this; -- } -- -- public Builder connFactory(HttpConnectionFactory connFactory) { -- this.connFactory = connFactory; -- return this; -- } -- -- public Builder schemePortResolver(SchemePortResolver schemePortResolver) { -- this.schemePortResolver = schemePortResolver; -- return this; -- } -- -- public Builder dnsResolver(DnsResolver dnsResolver) { -- this.dnsResolver = dnsResolver; -- return this; -- } -- -- public Builder timeToLive(TimeValue timeToLive) { -- this.timeToLive = timeToLive; -- return this; -- } -- -- public Builder httpClientConnectionOperator(HttpClientConnectionOperator httpClientConnectionOperator) { -- this.httpClientConnectionOperator = httpClientConnectionOperator; -- return this; -- } -- -- public Builder poolConcurrencyPolicy(PoolConcurrencyPolicy poolConcurrencyPolicy) { -- this.poolConcurrencyPolicy = poolConcurrencyPolicy; -- return this; -- } -- -- public Builder poolReusePolicy(PoolReusePolicy poolReusePolicy) { -- this.poolReusePolicy = poolReusePolicy; -- return this; -- } -- -- public InstrumentedHttpClientConnectionManager build() { -- if (httpClientConnectionOperator == null) { -- httpClientConnectionOperator = new DefaultHttpClientConnectionOperator( -- socketFactoryRegistry, -- schemePortResolver, -- dnsResolver); -- } -- -- return new InstrumentedHttpClientConnectionManager( -- metricsRegistry, -- name, -- httpClientConnectionOperator, -- poolConcurrencyPolicy, -- poolReusePolicy, -- timeToLive, -- connFactory); -- } -+ public InstrumentedHttpClientConnectionManager build() { -+ if (httpClientConnectionOperator == null) { -+ httpClientConnectionOperator = -+ new DefaultHttpClientConnectionOperator( -+ socketFactoryRegistry, schemePortResolver, dnsResolver); -+ } -+ -+ return new InstrumentedHttpClientConnectionManager( -+ metricsRegistry, -+ name, -+ httpClientConnectionOperator, -+ poolConcurrencyPolicy, -+ poolReusePolicy, -+ timeToLive, -+ connFactory); - } -+ } - } ---- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClients.java -+++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClients.java -@@ -1,34 +1,34 @@ - package io.dropwizard.metrics5.httpclient5; - -+import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; -+ - import io.dropwizard.metrics5.MetricRegistry; - import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; - import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; - --import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; -- - public class InstrumentedHttpClients { -- private InstrumentedHttpClients() { -- super(); -- } -- -- public static CloseableHttpClient createDefault(MetricRegistry metricRegistry) { -- return createDefault(metricRegistry, METHOD_ONLY); -- } -- -- public static CloseableHttpClient createDefault(MetricRegistry metricRegistry, -- HttpClientMetricNameStrategy metricNameStrategy) { -- return custom(metricRegistry, metricNameStrategy).build(); -- } -- -- public static HttpClientBuilder custom(MetricRegistry metricRegistry) { -- return custom(metricRegistry, METHOD_ONLY); -- } -- -- public static HttpClientBuilder custom(MetricRegistry metricRegistry, -- HttpClientMetricNameStrategy metricNameStrategy) { -- return HttpClientBuilder.create() -- .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy)) -- .setConnectionManager(InstrumentedHttpClientConnectionManager.builder(metricRegistry).build()); -- } -- -+ private InstrumentedHttpClients() { -+ super(); -+ } -+ -+ public static CloseableHttpClient createDefault(MetricRegistry metricRegistry) { -+ return createDefault(metricRegistry, METHOD_ONLY); -+ } -+ -+ public static CloseableHttpClient createDefault( -+ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { -+ return custom(metricRegistry, metricNameStrategy).build(); -+ } -+ -+ public static HttpClientBuilder custom(MetricRegistry metricRegistry) { -+ return custom(metricRegistry, METHOD_ONLY); -+ } -+ -+ public static HttpClientBuilder custom( -+ MetricRegistry metricRegistry, HttpClientMetricNameStrategy metricNameStrategy) { -+ return HttpClientBuilder.create() -+ .setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy)) -+ .setConnectionManager( -+ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build()); -+ } - } ---- a/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java -+++ b/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java -@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.httpclient5; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -+import java.io.IOException; - import org.apache.hc.core5.http.ClassicHttpRequest; - import org.apache.hc.core5.http.ClassicHttpResponse; - import org.apache.hc.core5.http.ConnectionReuseStrategy; -@@ -15,64 +16,66 @@ import org.apache.hc.core5.http.io.HttpResponseInformationCallback; - import org.apache.hc.core5.http.protocol.HttpContext; - import org.apache.hc.core5.util.Timeout; - --import java.io.IOException; -- - public class InstrumentedHttpRequestExecutor extends HttpRequestExecutor { -- private final MetricRegistry registry; -- private final HttpClientMetricNameStrategy metricNameStrategy; -- private final String name; -+ private final MetricRegistry registry; -+ private final HttpClientMetricNameStrategy metricNameStrategy; -+ private final String name; - -- public InstrumentedHttpRequestExecutor(MetricRegistry registry, -- HttpClientMetricNameStrategy metricNameStrategy) { -- this(registry, metricNameStrategy, null); -- } -+ public InstrumentedHttpRequestExecutor( -+ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy) { -+ this(registry, metricNameStrategy, null); -+ } - -- public InstrumentedHttpRequestExecutor(MetricRegistry registry, -- HttpClientMetricNameStrategy metricNameStrategy, -- String name) { -- this(registry, metricNameStrategy, name, HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE); -- } -+ public InstrumentedHttpRequestExecutor( -+ MetricRegistry registry, HttpClientMetricNameStrategy metricNameStrategy, String name) { -+ this(registry, metricNameStrategy, name, HttpRequestExecutor.DEFAULT_WAIT_FOR_CONTINUE); -+ } - -- public InstrumentedHttpRequestExecutor(MetricRegistry registry, -- HttpClientMetricNameStrategy metricNameStrategy, -- String name, -- Timeout waitForContinue) { -- this(registry, metricNameStrategy, name, waitForContinue, null, null); -- } -+ public InstrumentedHttpRequestExecutor( -+ MetricRegistry registry, -+ HttpClientMetricNameStrategy metricNameStrategy, -+ String name, -+ Timeout waitForContinue) { -+ this(registry, metricNameStrategy, name, waitForContinue, null, null); -+ } - -- public InstrumentedHttpRequestExecutor(MetricRegistry registry, -- HttpClientMetricNameStrategy metricNameStrategy, -- String name, -- Timeout waitForContinue, -- ConnectionReuseStrategy connReuseStrategy, -- Http1StreamListener streamListener) { -- super(waitForContinue, connReuseStrategy, streamListener); -- this.registry = registry; -- this.name = name; -- this.metricNameStrategy = metricNameStrategy; -- } -+ public InstrumentedHttpRequestExecutor( -+ MetricRegistry registry, -+ HttpClientMetricNameStrategy metricNameStrategy, -+ String name, -+ Timeout waitForContinue, -+ ConnectionReuseStrategy connReuseStrategy, -+ Http1StreamListener streamListener) { -+ super(waitForContinue, connReuseStrategy, streamListener); -+ this.registry = registry; -+ this.name = name; -+ this.metricNameStrategy = metricNameStrategy; -+ } - -- /** -- * {@inheritDoc} -- */ -- @Override -- public ClassicHttpResponse execute(ClassicHttpRequest request, HttpClientConnection conn, HttpResponseInformationCallback informationCallback, HttpContext context) throws IOException, HttpException { -- final Timer.Context timerContext = timer(request).time(); -- try { -- return super.execute(request, conn, informationCallback, context); -- } catch (HttpException | IOException e) { -- meter(e).mark(); -- throw e; -- } finally { -- timerContext.stop(); -- } -+ /** {@inheritDoc} */ -+ @Override -+ public ClassicHttpResponse execute( -+ ClassicHttpRequest request, -+ HttpClientConnection conn, -+ HttpResponseInformationCallback informationCallback, -+ HttpContext context) -+ throws IOException, HttpException { -+ final Timer.Context timerContext = timer(request).time(); -+ try { -+ return super.execute(request, conn, informationCallback, context); -+ } catch (HttpException | IOException e) { -+ meter(e).mark(); -+ throw e; -+ } finally { -+ timerContext.stop(); - } -+ } - -- private Timer timer(HttpRequest request) { -- return registry.timer(metricNameStrategy.getNameFor(name, request)); -- } -+ private Timer timer(HttpRequest request) { -+ return registry.timer(metricNameStrategy.getNameFor(name, request)); -+ } - -- private Meter meter(Exception e) { -- return registry.meter(metricNameStrategy.getNameFor(name, e)); -- } -+ private Meter meter(Exception e) { -+ return registry.meter(metricNameStrategy.getNameFor(name, e)); -+ } - } ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java -@@ -1,6 +1,13 @@ - package io.dropwizard.metrics5.httpclient5; - -+import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.HOST_AND_METHOD; -+import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; -+import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricName; -+import java.net.URI; -+import java.net.URISyntaxException; - import org.apache.hc.client5.http.classic.methods.HttpGet; - import org.apache.hc.client5.http.classic.methods.HttpPost; - import org.apache.hc.client5.http.classic.methods.HttpPut; -@@ -9,76 +16,84 @@ import org.apache.hc.core5.http.message.HttpRequestWrapper; - import org.apache.hc.core5.net.URIBuilder; - import org.junit.jupiter.api.Test; - --import java.net.URI; --import java.net.URISyntaxException; -- --import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.HOST_AND_METHOD; --import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; --import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; --import static org.assertj.core.api.Assertions.assertThat; -- --class HttpClientMetricNameStrategiesTest { -- -- @Test -- void methodOnlyWithName() { -- assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever"))) -- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.get-requests")); -- } -- -- @Test -- void methodOnlyWithoutName() { -- assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever"))) -- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.get-requests")); -- } -- -- @Test -- void hostAndMethodWithName() { -- assertThat(HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever"))) -- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.my.host.com.post-requests")); -- } -- -- @Test -- void hostAndMethodWithoutName() { -- assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever"))) -- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.my.host.com.post-requests")); -- } -- -- @Test -- void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { -- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); -- -- assertThat(HOST_AND_METHOD.getNameFor("some-service", request)) -- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.my.host.com.post-requests")); -- } -- -- @Test -- void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { -- HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); -- -- assertThat(HOST_AND_METHOD.getNameFor(null, request)) -- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.my.host.com.post-requests")); -- } -- -- @Test -- void querylessUrlAndMethodWithName() { -- assertThat(QUERYLESS_URL_AND_METHOD.getNameFor( -- "some-service", -- new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this"))) -- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); -- } -- -- @Test -- void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { -- HttpRequest request = rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); -- assertThat(QUERYLESS_URL_AND_METHOD.getNameFor("some-service", request)) -- .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); -- } -- -- private static HttpRequest rewriteRequestURI(HttpRequest request) throws URISyntaxException { -- URI uri = new URIBuilder(request.getUri()).setFragment(null).build(); -- HttpRequestWrapper wrapper = new HttpRequestWrapper(request); -- wrapper.setUri(uri); -- -- return wrapper; -- } -+final class HttpClientMetricNameStrategiesTest { -+ -+ @Test -+ void methodOnlyWithName() { -+ assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever"))) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.hc.client5.http.classic.HttpClient.some-service.get-requests")); -+ } -+ -+ @Test -+ void methodOnlyWithoutName() { -+ assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever"))) -+ .isEqualTo(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.get-requests")); -+ } -+ -+ @Test -+ void hostAndMethodWithName() { -+ assertThat( -+ HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever"))) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.hc.client5.http.classic.HttpClient.some-service.my.host.com.post-requests")); -+ } -+ -+ @Test -+ void hostAndMethodWithoutName() { -+ assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever"))) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.hc.client5.http.classic.HttpClient.my.host.com.post-requests")); -+ } -+ -+ @Test -+ void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { -+ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); -+ -+ assertThat(HOST_AND_METHOD.getNameFor("some-service", request)) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.hc.client5.http.classic.HttpClient.some-service.my.host.com.post-requests")); -+ } -+ -+ @Test -+ void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { -+ HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); -+ -+ assertThat(HOST_AND_METHOD.getNameFor(null, request)) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.hc.client5.http.classic.HttpClient.my.host.com.post-requests")); -+ } -+ -+ @Test -+ void querylessUrlAndMethodWithName() { -+ assertThat( -+ QUERYLESS_URL_AND_METHOD.getNameFor( -+ "some-service", new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this"))) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); -+ } -+ -+ @Test -+ void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { -+ HttpRequest request = -+ rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); -+ assertThat(QUERYLESS_URL_AND_METHOD.getNameFor("some-service", request)) -+ .isEqualTo( -+ MetricName.build( -+ "org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests")); -+ } -+ -+ private static HttpRequest rewriteRequestURI(HttpRequest request) throws URISyntaxException { -+ URI uri = new URIBuilder(request.getUri()).setFragment(null).build(); -+ HttpRequestWrapper wrapper = new HttpRequestWrapper(request); -+ wrapper.setUri(uri); -+ -+ return wrapper; -+ } - } ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java -@@ -1,49 +1,60 @@ - package io.dropwizard.metrics5.httpclient5; - --import io.dropwizard.metrics5.MetricName; --import io.dropwizard.metrics5.MetricRegistry; --import org.junit.jupiter.api.Test; --import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.junit.jupiter.api.Assertions.assertEquals; --import static org.junit.jupiter.api.Assertions.assertTrue; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; -+ -+import io.dropwizard.metrics5.MetricName; -+import io.dropwizard.metrics5.MetricRegistry; -+import org.junit.jupiter.api.Test; -+import org.mockito.ArgumentCaptor; - --class InstrumentedAsyncClientConnectionManagerTest { -- private final MetricRegistry metricRegistry = new MetricRegistry(); -+final class InstrumentedAsyncClientConnectionManagerTest { -+ private final MetricRegistry metricRegistry = new MetricRegistry(); - -- @Test -- void shouldRemoveGauges() { -- final InstrumentedAsyncClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build(); -- assertThat(metricRegistry.getGauges().entrySet().stream() -+ @Test -+ void shouldRemoveGauges() { -+ final InstrumentedAsyncClientConnectionManager instrumentedHttpClientConnectionManager = -+ InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build(); -+ assertThat( -+ metricRegistry.getGauges().entrySet().stream() - .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) -- .containsOnly(entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.available-connections", 0), -- entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.leased-connections", 0), -- entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.max-connections", 25), -- entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.pending-connections", 0)); -- -- instrumentedHttpClientConnectionManager.close(); -- assertEquals(0, metricRegistry.getGauges().size()); -- -- // should be able to create another one with the same name ("") -- InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); -- } -- -- @Test -- void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -- -- InstrumentedAsyncClientConnectionManager.builder(registry) -- .name("some-name") -- .name("some-other-name") -- .build() -- .close(); -- -- ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); -- } -+ .containsOnly( -+ entry( -+ "org.apache.hc.client5.http.nio.AsyncClientConnectionManager.available-connections", -+ 0), -+ entry( -+ "org.apache.hc.client5.http.nio.AsyncClientConnectionManager.leased-connections", -+ 0), -+ entry( -+ "org.apache.hc.client5.http.nio.AsyncClientConnectionManager.max-connections", 25), -+ entry( -+ "org.apache.hc.client5.http.nio.AsyncClientConnectionManager.pending-connections", -+ 0)); -+ -+ instrumentedHttpClientConnectionManager.close(); -+ assertEquals(0, metricRegistry.getGauges().size()); -+ -+ // should be able to create another one with the same name ("") -+ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); -+ } -+ -+ @Test -+ void configurableViaBuilder() { -+ final MetricRegistry registry = mock(); -+ -+ InstrumentedAsyncClientConnectionManager.builder(registry) -+ .name("some-name") -+ .name("some-other-name") -+ .build() -+ .close(); -+ -+ ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); -+ } - } ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java -@@ -1,11 +1,28 @@ - package io.dropwizard.metrics5.httpclient5; - -+import static java.nio.charset.StandardCharsets.US_ASCII; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; -+import static org.awaitility.Awaitility.await; -+import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.ArgumentMatchers.eq; -+import static org.mockito.Mockito.atLeastOnce; -+import static org.mockito.Mockito.spy; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import com.sun.net.httpserver.HttpExchange; - import com.sun.net.httpserver.HttpServer; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricRegistryListener; - import io.dropwizard.metrics5.Timer; -+import java.io.IOException; -+import java.net.InetSocketAddress; -+import java.util.concurrent.CountDownLatch; -+import java.util.concurrent.ExecutionException; -+import java.util.concurrent.Future; -+import java.util.concurrent.TimeUnit; - import org.apache.hc.client5.http.async.methods.SimpleHttpRequest; - import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; - import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder; -@@ -21,182 +38,191 @@ import org.junit.jupiter.api.extension.ExtendWith; - import org.mockito.Mock; - import org.mockito.junit.jupiter.MockitoExtension; - --import java.io.IOException; --import java.net.InetSocketAddress; --import java.nio.charset.StandardCharsets; --import java.util.concurrent.CountDownLatch; --import java.util.concurrent.ExecutionException; --import java.util.concurrent.Future; --import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.awaitility.Awaitility.await; --import static org.junit.jupiter.api.Assertions.fail; --import static org.mockito.ArgumentMatchers.any; --import static org.mockito.ArgumentMatchers.eq; --import static org.mockito.Mockito.atLeastOnce; --import static org.mockito.Mockito.spy; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- - @ExtendWith(MockitoExtension.class) --class InstrumentedHttpAsyncClientsTest { -- -- @Mock -- private HttpClientMetricNameStrategy metricNameStrategy; -- @Mock -- private MetricRegistryListener registryListener; -- private HttpServer httpServer; -- private MetricRegistry metricRegistry; -- private CloseableHttpAsyncClient client; -- -- @BeforeEach -- void setUp() throws IOException { -- httpServer = HttpServer.create(new InetSocketAddress(0), 0); -- -- metricRegistry = new MetricRegistry(); -- metricRegistry.addListener(registryListener); -+final class InstrumentedHttpAsyncClientsTest { -+ -+ @Mock private HttpClientMetricNameStrategy metricNameStrategy; -+ @Mock private MetricRegistryListener registryListener; -+ private HttpServer httpServer; -+ private MetricRegistry metricRegistry; -+ private CloseableHttpAsyncClient client; -+ -+ @BeforeEach -+ void setUp() throws IOException { -+ httpServer = HttpServer.create(new InetSocketAddress(0), 0); -+ -+ metricRegistry = new MetricRegistry(); -+ metricRegistry.addListener(registryListener); -+ } -+ -+ @AfterEach -+ void tearDown() throws IOException { -+ if (client != null) { -+ client.close(); - } -- -- @AfterEach -- void tearDown() throws IOException { -- if (client != null) { -- client.close(); -- } -- if (httpServer != null) { -- httpServer.stop(0); -- } -+ if (httpServer != null) { -+ httpServer.stop(0); - } -- -- @Test -- void registersExpectedMetricsGivenNameStrategy() throws Exception { -- client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); -- client.start(); -- -- final SimpleHttpRequest request = SimpleRequestBuilder -- .get("http://localhost:" + httpServer.getAddress().getPort() + "/") -- .build(); -- final MetricName metricName = MetricName.build("some.made.up.metric.name"); -- -- httpServer.createContext("/", exchange -> { -- exchange.sendResponseHeaders(200, 0L); -- exchange.setStreams(null, null); -- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); -- exchange.close(); -+ } -+ -+ @Test -+ void registersExpectedMetricsGivenNameStrategy() throws Exception { -+ client = -+ InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy) -+ .disableAutomaticRetries() -+ .build(); -+ client.start(); -+ -+ final SimpleHttpRequest request = -+ SimpleRequestBuilder.get("http://localhost:" + httpServer.getAddress().getPort() + "/") -+ .build(); -+ final MetricName metricName = MetricName.build("some.made.up.metric.name"); -+ -+ httpServer.createContext( -+ "/", -+ exchange -> { -+ exchange.sendResponseHeaders(200, 0L); -+ exchange.setStreams(null, null); -+ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); -+ exchange.close(); - }); -- httpServer.start(); -+ httpServer.start(); - -- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); -+ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); - -- final Future responseFuture = client.execute(request, new FutureCallback() { -- @Override -- public void completed(SimpleHttpResponse result) { -+ final Future responseFuture = -+ client.execute( -+ request, -+ new FutureCallback() { -+ @Override -+ public void completed(SimpleHttpResponse result) { - assertThat(result.getBodyText()).isEqualTo("TEST"); -- } -+ } - -- @Override -- public void failed(Exception ex) { -+ @Override -+ public void failed(Exception ex) { - fail(); -- } -+ } - -- @Override -- public void cancelled() { -+ @Override -+ public void cancelled() { - fail(); -- } -- }); -- responseFuture.get(1L, TimeUnit.SECONDS); -- -- verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); -- } -- -- @Test -- void registersExpectedExceptionMetrics() throws Exception { -- client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); -- client.start(); -- -- final CountDownLatch countDownLatch = new CountDownLatch(1); -- final SimpleHttpRequest request = SimpleRequestBuilder -- .get("http://localhost:" + httpServer.getAddress().getPort() + "/") -- .build(); -- final MetricName requestMetricName = MetricName.build("request"); -- final MetricName exceptionMetricName = MetricName.build("exception"); -- -- httpServer.createContext("/", HttpExchange::close); -- httpServer.start(); -- -- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) -- .thenReturn(requestMetricName); -- when(metricNameStrategy.getNameFor(any(), any(Exception.class))) -- .thenReturn(exceptionMetricName); -- -- try { -- final Future responseFuture = client.execute(request, new FutureCallback() { -+ } -+ }); -+ responseFuture.get(1L, TimeUnit.SECONDS); -+ -+ verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); -+ } -+ -+ @Test -+ void registersExpectedExceptionMetrics() throws Exception { -+ client = -+ InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy) -+ .disableAutomaticRetries() -+ .build(); -+ client.start(); -+ -+ final CountDownLatch countDownLatch = new CountDownLatch(1); -+ final SimpleHttpRequest request = -+ SimpleRequestBuilder.get("http://localhost:" + httpServer.getAddress().getPort() + "/") -+ .build(); -+ final MetricName requestMetricName = MetricName.build("request"); -+ final MetricName exceptionMetricName = MetricName.build("exception"); -+ -+ httpServer.createContext("/", HttpExchange::close); -+ httpServer.start(); -+ -+ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) -+ .thenReturn(requestMetricName); -+ when(metricNameStrategy.getNameFor(any(), any(Exception.class))) -+ .thenReturn(exceptionMetricName); -+ -+ try { -+ final Future responseFuture = -+ client.execute( -+ request, -+ new FutureCallback() { - @Override - public void completed(SimpleHttpResponse result) { -- fail(); -+ fail(); - } - - @Override - public void failed(Exception ex) { -- countDownLatch.countDown(); -+ countDownLatch.countDown(); - } - - @Override - public void cancelled() { -- fail(); -+ fail(); - } -- }); -- countDownLatch.await(5, TimeUnit.SECONDS); -- responseFuture.get(5, TimeUnit.SECONDS); -- -- fail(); -- } catch (ExecutionException e) { -- assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class); -- await().atMost(5, TimeUnit.SECONDS) -- .untilAsserted(() -> assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception"))); -- } -+ }); -+ countDownLatch.await(5, TimeUnit.SECONDS); -+ responseFuture.get(5, TimeUnit.SECONDS); -+ -+ fail(); -+ } catch (ExecutionException e) { -+ assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class); -+ await() -+ .atMost(5, TimeUnit.SECONDS) -+ .untilAsserted( -+ () -> -+ assertThat(metricRegistry.getMeters()) -+ .containsKey(MetricName.build("exception"))); - } -+ } -+ -+ @Test -+ void usesCustomClientConnectionManager() throws Exception { -+ try (PoolingAsyncClientConnectionManager clientConnectionManager = -+ spy(new PoolingAsyncClientConnectionManager())) { -+ client = -+ InstrumentedHttpAsyncClients.custom( -+ metricRegistry, metricNameStrategy, clientConnectionManager) -+ .disableAutomaticRetries() -+ .build(); -+ client.start(); -+ -+ final SimpleHttpRequest request = -+ SimpleRequestBuilder.get("http://localhost:" + httpServer.getAddress().getPort() + "/") -+ .build(); -+ final MetricName metricName = MetricName.build("some.made.up.metric.name"); -+ -+ httpServer.createContext( -+ "/", -+ exchange -> { -+ exchange.sendResponseHeaders(200, 0L); -+ exchange.setStreams(null, null); -+ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); -+ exchange.close(); -+ }); -+ httpServer.start(); - -- @Test -- void usesCustomClientConnectionManager() throws Exception { -- try (PoolingAsyncClientConnectionManager clientConnectionManager = spy(new PoolingAsyncClientConnectionManager())) { -- client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy, clientConnectionManager).disableAutomaticRetries().build(); -- client.start(); -- -- final SimpleHttpRequest request = SimpleRequestBuilder -- .get("http://localhost:" + httpServer.getAddress().getPort() + "/") -- .build(); -- final MetricName metricName = MetricName.build("some.made.up.metric.name"); -- -- httpServer.createContext("/", exchange -> { -- exchange.sendResponseHeaders(200, 0L); -- exchange.setStreams(null, null); -- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); -- exchange.close(); -- }); -- httpServer.start(); -- -- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); -+ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); - -- final Future responseFuture = client.execute(request, new FutureCallback() { -+ final Future responseFuture = -+ client.execute( -+ request, -+ new FutureCallback() { - @Override - public void completed(SimpleHttpResponse result) { -- assertThat(result.getCode()).isEqualTo(200); -+ assertThat(result.getCode()).isEqualTo(200); - } - - @Override - public void failed(Exception ex) { -- fail(); -+ fail(); - } - - @Override - public void cancelled() { -- fail(); -+ fail(); - } -- }); -- responseFuture.get(1L, TimeUnit.SECONDS); -+ }); -+ responseFuture.get(1L, TimeUnit.SECONDS); - -- verify(clientConnectionManager, atLeastOnce()).connect(any(), any(), any(), any(), any(), any()); -- } -+ verify(clientConnectionManager, atLeastOnce()) -+ .connect(any(), any(), any(), any(), any(), any()); - } -+ } - } ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java -@@ -1,49 +1,58 @@ - package io.dropwizard.metrics5.httpclient5; - --import io.dropwizard.metrics5.MetricName; --import io.dropwizard.metrics5.MetricRegistry; --import org.junit.jupiter.api.Test; --import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.junit.jupiter.api.Assertions.assertEquals; --import static org.junit.jupiter.api.Assertions.assertTrue; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; -+ -+import io.dropwizard.metrics5.MetricName; -+import io.dropwizard.metrics5.MetricRegistry; -+import org.junit.jupiter.api.Test; -+import org.mockito.ArgumentCaptor; - --class InstrumentedHttpClientConnectionManagerTest { -- private final MetricRegistry metricRegistry = new MetricRegistry(); -+final class InstrumentedHttpClientConnectionManagerTest { -+ private final MetricRegistry metricRegistry = new MetricRegistry(); - -- @Test -- void shouldRemoveGauges() { -- final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); -- assertThat(metricRegistry.getGauges().entrySet().stream() -+ @Test -+ void shouldRemoveGauges() { -+ final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = -+ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); -+ assertThat( -+ metricRegistry.getGauges().entrySet().stream() - .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) -- .containsOnly(entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.available-connections", 0), -- entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.leased-connections", 0), -- entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.max-connections", 25), -- entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.pending-connections", 0)); -- -- instrumentedHttpClientConnectionManager.close(); -- assertEquals(0, metricRegistry.getGauges().size()); -- -- // should be able to create another one with the same name ("") -- InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); -- } -- -- @Test -- void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -- -- InstrumentedHttpClientConnectionManager.builder(registry) -- .name("some-name") -- .name("some-other-name") -- .build() -- .close(); -- -- ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); -- } -+ .containsOnly( -+ entry( -+ "org.apache.hc.client5.http.io.HttpClientConnectionManager.available-connections", -+ 0), -+ entry( -+ "org.apache.hc.client5.http.io.HttpClientConnectionManager.leased-connections", 0), -+ entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.max-connections", 25), -+ entry( -+ "org.apache.hc.client5.http.io.HttpClientConnectionManager.pending-connections", -+ 0)); -+ -+ instrumentedHttpClientConnectionManager.close(); -+ assertEquals(0, metricRegistry.getGauges().size()); -+ -+ // should be able to create another one with the same name ("") -+ InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); -+ } -+ -+ @Test -+ void configurableViaBuilder() { -+ final MetricRegistry registry = mock(); -+ -+ InstrumentedHttpClientConnectionManager.builder(registry) -+ .name("some-name") -+ .name("some-other-name") -+ .build() -+ .close(); -+ -+ ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); -+ } - } ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java -@@ -1,11 +1,20 @@ - package io.dropwizard.metrics5.httpclient5; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; -+import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.ArgumentMatchers.eq; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import com.sun.net.httpserver.HttpExchange; - import com.sun.net.httpserver.HttpServer; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricRegistryListener; - import io.dropwizard.metrics5.Timer; -+import java.net.InetSocketAddress; - import org.apache.hc.client5.http.classic.HttpClient; - import org.apache.hc.client5.http.classic.methods.HttpGet; - import org.apache.hc.core5.http.HttpRequest; -@@ -13,66 +22,55 @@ import org.apache.hc.core5.http.NoHttpResponseException; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import java.net.InetSocketAddress; -+final class InstrumentedHttpClientsTest { -+ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); -+ private final MetricRegistryListener registryListener = mock(); -+ private final MetricRegistry metricRegistry = new MetricRegistry(); -+ private final HttpClient client = -+ InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) -+ .disableAutomaticRetries() -+ .build(); - --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; --import static org.mockito.ArgumentMatchers.any; --import static org.mockito.ArgumentMatchers.eq; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -+ @BeforeEach -+ void setUp() { -+ metricRegistry.addListener(registryListener); -+ } - --class InstrumentedHttpClientsTest { -- private final HttpClientMetricNameStrategy metricNameStrategy = -- mock(HttpClientMetricNameStrategy.class); -- private final MetricRegistryListener registryListener = -- mock(MetricRegistryListener.class); -- private final MetricRegistry metricRegistry = new MetricRegistry(); -- private final HttpClient client = -- InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); -+ @Test -+ void registersExpectedMetricsGivenNameStrategy() throws Exception { -+ final HttpGet get = new HttpGet("http://example.com?q=anything"); -+ final MetricName metricName = MetricName.build("some.made.up.metric.name"); - -- @BeforeEach -- void setUp() { -- metricRegistry.addListener(registryListener); -- } -- -- @Test -- void registersExpectedMetricsGivenNameStrategy() throws Exception { -- final HttpGet get = new HttpGet("http://example.com?q=anything"); -- final MetricName metricName = MetricName.build("some.made.up.metric.name"); -+ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); - -- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) -- .thenReturn(metricName); -+ client.execute(get); - -- client.execute(get); -- -- verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); -- } -+ verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); -+ } - -- @Test -- void registersExpectedExceptionMetrics() throws Exception { -- HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); -+ @Test -+ void registersExpectedExceptionMetrics() throws Exception { -+ HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); - -- final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); -- final MetricName requestMetricName = MetricName.build("request"); -- final MetricName exceptionMetricName = MetricName.build("exception"); -+ final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); -+ final MetricName requestMetricName = MetricName.build("request"); -+ final MetricName exceptionMetricName = MetricName.build("exception"); - -- httpServer.createContext("/", HttpExchange::close); -- httpServer.start(); -+ httpServer.createContext("/", HttpExchange::close); -+ httpServer.start(); - -- when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) -- .thenReturn(requestMetricName); -- when(metricNameStrategy.getNameFor(any(), any(Exception.class))) -- .thenReturn(exceptionMetricName); -+ when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) -+ .thenReturn(requestMetricName); -+ when(metricNameStrategy.getNameFor(any(), any(Exception.class))) -+ .thenReturn(exceptionMetricName); - -- try { -- client.execute(get); -- fail(); -- } catch (NoHttpResponseException expected) { -- assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); -- } finally { -- httpServer.stop(0); -- } -+ try { -+ client.execute(get); -+ fail(); -+ } catch (NoHttpResponseException expected) { -+ assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); -+ } finally { -+ httpServer.stop(0); - } -+ } - } ---- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/GarbageFreeScheduledReporter.java -+++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/GarbageFreeScheduledReporter.java -@@ -11,7 +11,6 @@ import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricRegistryListener; - import io.dropwizard.metrics5.ScheduledReporter; - import io.dropwizard.metrics5.Timer; -- - import java.util.Set; - import java.util.SortedMap; - import java.util.concurrent.ConcurrentSkipListMap; -@@ -20,135 +19,149 @@ import java.util.concurrent.TimeUnit; - - abstract class GarbageFreeScheduledReporter extends ScheduledReporter { - -- private final MetricRegistry registry; -- private final RegistryMirror mirror; -+ private final MetricRegistry registry; -+ private final RegistryMirror mirror; -+ -+ protected GarbageFreeScheduledReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes) { -+ super( -+ registry, -+ name, -+ filter, -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes); -+ this.registry = registry; -+ this.mirror = new RegistryMirror(filter); -+ registry.addListener(mirror); -+ } -+ -+ @Override -+ public void stop() { -+ try { -+ super.stop(); -+ } finally { -+ registry.removeListener(mirror); -+ } -+ } -+ -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report() { -+ synchronized (this) { -+ report( -+ mirror.gauges(), -+ mirror.counters(), -+ mirror.histograms(), -+ mirror.meters(), -+ mirror.timers()); -+ } -+ } -+ -+ @SuppressWarnings("rawtypes") // because of signature (for Gauge) in ScheduledReporter#report(..) -+ private static class RegistryMirror implements MetricRegistryListener { -+ -+ private final MetricFilter filter; -+ private final ConcurrentSkipListMap> gauges = -+ new ConcurrentSkipListMap<>(); -+ private final ConcurrentSkipListMap counters = -+ new ConcurrentSkipListMap<>(); -+ private final ConcurrentSkipListMap histograms = -+ new ConcurrentSkipListMap<>(); -+ private final ConcurrentSkipListMap meters = new ConcurrentSkipListMap<>(); -+ private final ConcurrentSkipListMap timers = new ConcurrentSkipListMap<>(); -+ -+ RegistryMirror(MetricFilter filter) { -+ this.filter = filter; -+ } -+ -+ SortedMap> gauges() { -+ return gauges; -+ } -+ -+ SortedMap counters() { -+ return counters; -+ } -+ -+ SortedMap histograms() { -+ return histograms; -+ } -+ -+ SortedMap meters() { -+ return meters; -+ } -+ -+ SortedMap timers() { -+ return timers; -+ } -+ -+ @Override -+ public void onGaugeAdded(MetricName name, Gauge gauge) { -+ if (filter.matches(name, gauge)) { -+ gauges.put(name, gauge); -+ } -+ } -+ -+ @Override -+ public void onGaugeRemoved(MetricName name) { -+ gauges.remove(name); -+ } - -- protected GarbageFreeScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, -- TimeUnit durationUnit, ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop, -- Set disabledMetricAttributes) { -- super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, disabledMetricAttributes); -- this.registry = registry; -- this.mirror = new RegistryMirror(filter); -- registry.addListener(mirror); -+ @Override -+ public void onCounterAdded(MetricName name, Counter counter) { -+ if (filter.matches(name, counter)) { -+ counters.put(name, counter); -+ } - } - - @Override -- public void stop() { -- try { -- super.stop(); -- } finally { -- registry.removeListener(mirror); -- } -+ public void onCounterRemoved(MetricName name) { -+ counters.remove(name); - } - - @Override -- @SuppressWarnings("rawtypes") -- public void report() { -- synchronized (this) { -- report(mirror.gauges(), -- mirror.counters(), -- mirror.histograms(), -- mirror.meters(), -- mirror.timers()); -- } -- } -- -- @SuppressWarnings("rawtypes") // because of signature (for Gauge) in ScheduledReporter#report(..) -- private static class RegistryMirror implements MetricRegistryListener { -- -- private final MetricFilter filter; -- private final ConcurrentSkipListMap> gauges = new ConcurrentSkipListMap<>(); -- private final ConcurrentSkipListMap counters = new ConcurrentSkipListMap<>(); -- private final ConcurrentSkipListMap histograms = new ConcurrentSkipListMap<>(); -- private final ConcurrentSkipListMap meters = new ConcurrentSkipListMap<>(); -- private final ConcurrentSkipListMap timers = new ConcurrentSkipListMap<>(); -- -- RegistryMirror(MetricFilter filter) { -- this.filter = filter; -- } -- -- SortedMap> gauges() { -- return gauges; -- } -- -- SortedMap counters() { -- return counters; -- } -- -- SortedMap histograms() { -- return histograms; -- } -- -- SortedMap meters() { -- return meters; -- } -- -- SortedMap timers() { -- return timers; -- } -- -- -- @Override -- public void onGaugeAdded(MetricName name, Gauge gauge) { -- if (filter.matches(name, gauge)) { -- gauges.put(name, gauge); -- } -- } -- -- @Override -- public void onGaugeRemoved(MetricName name) { -- gauges.remove(name); -- } -- -- @Override -- public void onCounterAdded(MetricName name, Counter counter) { -- if (filter.matches(name, counter)) { -- counters.put(name, counter); -- } -- } -- -- @Override -- public void onCounterRemoved(MetricName name) { -- counters.remove(name); -- } -- -- @Override -- public void onHistogramAdded(MetricName name, Histogram histogram) { -- if (filter.matches(name, histogram)) { -- histograms.put(name, histogram); -- } -- } -- -- @Override -- public void onHistogramRemoved(MetricName name) { -- histograms.remove(name); -- } -- -- @Override -- public void onMeterAdded(MetricName name, Meter meter) { -- if (filter.matches(name, meter)) { -- meters.put(name, meter); -- } -- } -- -- @Override -- public void onMeterRemoved(MetricName name) { -- meters.remove(name); -- } -- -- @Override -- public void onTimerAdded(MetricName name, Timer timer) { -- if (filter.matches(name, timer)) { -- timers.put(name, timer); -- } -- } -- -- @Override -- public void onTimerRemoved(MetricName name) { -- timers.remove(name); -- } -+ public void onHistogramAdded(MetricName name, Histogram histogram) { -+ if (filter.matches(name, histogram)) { -+ histograms.put(name, histogram); -+ } -+ } - -+ @Override -+ public void onHistogramRemoved(MetricName name) { -+ histograms.remove(name); -+ } -+ -+ @Override -+ public void onMeterAdded(MetricName name, Meter meter) { -+ if (filter.matches(name, meter)) { -+ meters.put(name, meter); -+ } - } - -+ @Override -+ public void onMeterRemoved(MetricName name) { -+ meters.remove(name); -+ } -+ -+ @Override -+ public void onTimerAdded(MetricName name, Timer timer) { -+ if (filter.matches(name, timer)) { -+ timers.put(name, timer); -+ } -+ } -+ -+ @Override -+ public void onTimerRemoved(MetricName name) { -+ timers.remove(name); -+ } -+ } - } ---- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilder.java -+++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilder.java -@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.influxdb; - - import io.dropwizard.metrics5.MetricAttribute; - import io.dropwizard.metrics5.MetricName; -- - import java.util.Map; - import java.util.Set; - import java.util.WeakHashMap; -@@ -29,136 +28,135 @@ import java.util.WeakHashMap; - */ - class InfluxDbLineBuilder { - -- private final StringBuilder str = new StringBuilder(); -- private boolean firstField; -- -- private final Set disabledMetricAttributes; -- private final MetricName prefix; -- private final Map encodedNameCache = new WeakHashMap<>(); -- -- InfluxDbLineBuilder(Set disabledMetricAttributes, MetricName prefix) { -- this.disabledMetricAttributes = disabledMetricAttributes; -- this.prefix = prefix != null ? prefix : MetricName.empty(); -- } -- -- InfluxDbLineBuilder writeMeasurement(MetricName name) { -- str.setLength(0); -- str.append(encodedNameCache.computeIfAbsent(name, this::writeMeasurementNoCache)); -- str.append(' '); -- firstField = true; -- return this; -- } -- -- private String writeMeasurementNoCache(MetricName name) { -- StringBuilder sb = new StringBuilder(); -- -- MetricName prefixedName = prefix.append(name); -- appendName(prefixedName.getKey(), sb); -- // InfluxDB Performance and Setup Tips: -- // Sort tags by key before sending them to the database. -- // The sort should match the results from the Go bytes.Compare function. -- // ... tags are already sorted in MetricName -- for (Map.Entry tag : prefixedName.getTags().entrySet()) { -- sb.append(','); -- appendName(tag.getKey(), sb); -- sb.append('='); -- appendName(tag.getValue(), sb); -- } -- return sb.toString(); -- } -- -- InfluxDbLineBuilder writeField(MetricAttribute key) { -- if (!firstField) { -- str.append(','); -- } -- str.append(key.getCode()).append('='); -- firstField = false; -- return this; -- } -- -- InfluxDbLineBuilder writeField(String key) { -- if (!firstField) { -- str.append(','); -- } -- appendName(key, str); -- str.append('='); -- firstField = false; -- return this; -- } -- -- InfluxDbLineBuilder writeFieldValue(double value) { -- str.append(value); -- return this; -- } -- -- InfluxDbLineBuilder writeFieldValue(long value) { -- str.append(value).append('i'); -- return this; -- } -- -- InfluxDbLineBuilder writeFieldValue(String value) { -- str.append('"'); -- appendString(value, str); -- str.append('"'); -- return this; -- } -- -- InfluxDbLineBuilder writeFieldValue(boolean value) { -- str.append(value ? 't' : 'f'); -- return this; -- } -- -- InfluxDbLineBuilder writeTimestampMillis(long utcMillis) { -- str.append(' ').append(utcMillis).append("000000\n"); -- return this; -- } -- -- InfluxDbLineBuilder writeFieldIfEnabled(MetricAttribute key, double value) { -- if (!disabledMetricAttributes.contains(key)) { -- writeField(key); -- writeFieldValue(value); -- } -- return this; -- } -- -- InfluxDbLineBuilder writeFieldIfEnabled(MetricAttribute key, long value) { -- if (!disabledMetricAttributes.contains(key)) { -- writeField(key); -- writeFieldValue(value); -- } -- return this; -- } -- -- boolean hasValues() { -- return !firstField; -- } -- -- StringBuilder get() { -- return str; -- } -- -- private static void appendName(CharSequence field, StringBuilder dst) { -- int len = field.length(); -- for (int i = 0; i < len; i++) { -- char ch = field.charAt(i); -- if (ch == ',' || ch == '=' || ch == ' ') { -- // escape -- dst.append('\\'); -- } -- dst.append(ch); -- } -- } -- -- private static void appendString(CharSequence field, StringBuilder dst) { -- int len = field.length(); -- for (int i = 0; i < len; i++) { -- char ch = field.charAt(i); -- if (ch == '"') { -- // escape -- dst.append('\\'); -- } -- dst.append(ch); -- } -- } -- -+ private final StringBuilder str = new StringBuilder(); -+ private boolean firstField; -+ -+ private final Set disabledMetricAttributes; -+ private final MetricName prefix; -+ private final Map encodedNameCache = new WeakHashMap<>(); -+ -+ InfluxDbLineBuilder(Set disabledMetricAttributes, MetricName prefix) { -+ this.disabledMetricAttributes = disabledMetricAttributes; -+ this.prefix = prefix != null ? prefix : MetricName.empty(); -+ } -+ -+ InfluxDbLineBuilder writeMeasurement(MetricName name) { -+ str.setLength(0); -+ str.append(encodedNameCache.computeIfAbsent(name, this::writeMeasurementNoCache)); -+ str.append(' '); -+ firstField = true; -+ return this; -+ } -+ -+ private String writeMeasurementNoCache(MetricName name) { -+ StringBuilder sb = new StringBuilder(); -+ -+ MetricName prefixedName = prefix.append(name); -+ appendName(prefixedName.getKey(), sb); -+ // InfluxDB Performance and Setup Tips: -+ // Sort tags by key before sending them to the database. -+ // The sort should match the results from the Go bytes.Compare function. -+ // ... tags are already sorted in MetricName -+ for (Map.Entry tag : prefixedName.getTags().entrySet()) { -+ sb.append(','); -+ appendName(tag.getKey(), sb); -+ sb.append('='); -+ appendName(tag.getValue(), sb); -+ } -+ return sb.toString(); -+ } -+ -+ InfluxDbLineBuilder writeField(MetricAttribute key) { -+ if (!firstField) { -+ str.append(','); -+ } -+ str.append(key.getCode()).append('='); -+ firstField = false; -+ return this; -+ } -+ -+ InfluxDbLineBuilder writeField(String key) { -+ if (!firstField) { -+ str.append(','); -+ } -+ appendName(key, str); -+ str.append('='); -+ firstField = false; -+ return this; -+ } -+ -+ InfluxDbLineBuilder writeFieldValue(double value) { -+ str.append(value); -+ return this; -+ } -+ -+ InfluxDbLineBuilder writeFieldValue(long value) { -+ str.append(value).append('i'); -+ return this; -+ } -+ -+ InfluxDbLineBuilder writeFieldValue(String value) { -+ str.append('"'); -+ appendString(value, str); -+ str.append('"'); -+ return this; -+ } -+ -+ InfluxDbLineBuilder writeFieldValue(boolean value) { -+ str.append(value ? 't' : 'f'); -+ return this; -+ } -+ -+ InfluxDbLineBuilder writeTimestampMillis(long utcMillis) { -+ str.append(' ').append(utcMillis).append("000000\n"); -+ return this; -+ } -+ -+ InfluxDbLineBuilder writeFieldIfEnabled(MetricAttribute key, double value) { -+ if (!disabledMetricAttributes.contains(key)) { -+ writeField(key); -+ writeFieldValue(value); -+ } -+ return this; -+ } -+ -+ InfluxDbLineBuilder writeFieldIfEnabled(MetricAttribute key, long value) { -+ if (!disabledMetricAttributes.contains(key)) { -+ writeField(key); -+ writeFieldValue(value); -+ } -+ return this; -+ } -+ -+ boolean hasValues() { -+ return !firstField; -+ } -+ -+ StringBuilder get() { -+ return str; -+ } -+ -+ private static void appendName(CharSequence field, StringBuilder dst) { -+ int len = field.length(); -+ for (int i = 0; i < len; i++) { -+ char ch = field.charAt(i); -+ if (ch == ',' || ch == '=' || ch == ' ') { -+ // escape -+ dst.append('\\'); -+ } -+ dst.append(ch); -+ } -+ } -+ -+ private static void appendString(CharSequence field, StringBuilder dst) { -+ int len = field.length(); -+ for (int i = 0; i < len; i++) { -+ char ch = field.charAt(i); -+ if (ch == '"') { -+ // escape -+ dst.append('\\'); -+ } -+ dst.append(ch); -+ } -+ } - } ---- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java -+++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java -@@ -1,5 +1,8 @@ - package io.dropwizard.metrics5.influxdb; - -+import static io.dropwizard.metrics5.MetricAttribute.*; -+ -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -7,369 +10,393 @@ import io.dropwizard.metrics5.Histogram; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.Metered; - import io.dropwizard.metrics5.MetricAttribute; --import io.dropwizard.metrics5.MetricName; -- --import java.util.Map; -- --import static io.dropwizard.metrics5.MetricAttribute.*; -- - import io.dropwizard.metrics5.MetricFilter; -+import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; -- - import java.io.IOException; --import java.util.Collections; -+import java.util.Map; - import java.util.Set; - import java.util.SortedMap; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; -- - import org.slf4j.Logger; - import org.slf4j.LoggerFactory; - - /** - * A reporter which publishes metric values to InfluxDB. -- *

    -- * Metrics are reported according to the -- * InfluxDB Line Protocol. -- * Brief line protocol syntax as follows: -+ * -+ *

    Metrics are reported according to the InfluxDB -+ * Line Protocol. Brief line protocol syntax as follows: -+ * - *

    -  * measurement(,tag_key=tag_val)* field_key=field_val(,field_key_n=field_value_n)* (nanoseconds-timestamp)?
    -  * 
    -+ * - *

    -- *

    -- * This InfluxDB reporter is "garbage free" in steady state. -- * This means objects and buffers are reused and no temporary objects are allocated as much as possible. -+ * -+ *

    This InfluxDB reporter is "garbage free" in steady state. This means objects and buffers are -+ * reused and no temporary objects are allocated as much as possible. - */ - public class InfluxDbReporter extends GarbageFreeScheduledReporter { - -+ /** -+ * Returns a new Builder for {@link InfluxDbReporter}. -+ * -+ * @param registry the registry to report -+ * @return a Builder instance for a {@link InfluxDbReporter} -+ */ -+ public static Builder forRegistry(MetricRegistry registry) { -+ return new Builder(registry); -+ } -+ -+ /** -+ * A builder for {@link InfluxDbReporter} instances. Defaults to not using a prefix, using the -+ * default clock, converting rates to events/second, converting durations to milliseconds, and not -+ * filtering metrics. -+ */ -+ public static class Builder { -+ -+ private final MetricRegistry registry; -+ private Clock clock; -+ private MetricName prefix; -+ private TimeUnit rateUnit; -+ private TimeUnit durationUnit; -+ private MetricFilter filter; -+ private ScheduledExecutorService executor; -+ private boolean shutdownExecutorOnStop; -+ private Set disabledMetricAttributes; -+ -+ private Builder(MetricRegistry registry) { -+ this.registry = registry; -+ this.clock = Clock.defaultClock(); -+ this.prefix = null; -+ this.rateUnit = TimeUnit.SECONDS; -+ this.durationUnit = TimeUnit.MILLISECONDS; -+ this.filter = MetricFilter.ALL; -+ this.executor = null; -+ this.shutdownExecutorOnStop = true; -+ this.disabledMetricAttributes = ImmutableSet.of(); -+ } -+ - /** -- * Returns a new Builder for {@link InfluxDbReporter}. -+ * Specifies whether or not, the executor (used for reporting) will be stopped with same time -+ * with reporter. Default value is true. Setting this parameter to false, has the sense in -+ * combining with providing external managed executor via {@link -+ * #scheduleOn(ScheduledExecutorService)}. - * -- * @param registry the registry to report -- * @return a Builder instance for a {@link InfluxDbReporter} -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ * @return {@code this} - */ -- public static Builder forRegistry(MetricRegistry registry) { -- return new Builder(registry); -+ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -+ this.shutdownExecutorOnStop = shutdownExecutorOnStop; -+ return this; - } - - /** -- * A builder for {@link InfluxDbReporter} instances. Defaults to not using a prefix, using the -- * default clock, converting rates to events/second, converting durations to milliseconds, and -- * not filtering metrics. -+ * Specifies the executor to use while scheduling reporting of metrics. Default value is null. -+ * Null value leads to executor will be auto created on start. -+ * -+ * @param executor the executor to use while scheduling reporting of metrics. -+ * @return {@code this} - */ -- public static class Builder { -- -- private final MetricRegistry registry; -- private Clock clock; -- private MetricName prefix; -- private TimeUnit rateUnit; -- private TimeUnit durationUnit; -- private MetricFilter filter; -- private ScheduledExecutorService executor; -- private boolean shutdownExecutorOnStop; -- private Set disabledMetricAttributes; -- -- private Builder(MetricRegistry registry) { -- this.registry = registry; -- this.clock = Clock.defaultClock(); -- this.prefix = null; -- this.rateUnit = TimeUnit.SECONDS; -- this.durationUnit = TimeUnit.MILLISECONDS; -- this.filter = MetricFilter.ALL; -- this.executor = null; -- this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -- } -- -- /** -- * Specifies whether or not, the executor (used for reporting) will be stopped with same time with reporter. -- * Default value is true. -- * Setting this parameter to false, has the sense in combining with providing external managed executor via -- * {@link #scheduleOn(ScheduledExecutorService)}. -- * -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- * @return {@code this} -- */ -- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -- this.shutdownExecutorOnStop = shutdownExecutorOnStop; -- return this; -- } -- -- /** -- * Specifies the executor to use while scheduling reporting of metrics. -- * Default value is null. -- * Null value leads to executor will be auto created on start. -- * -- * @param executor the executor to use while scheduling reporting of metrics. -- * @return {@code this} -- */ -- public Builder scheduleOn(ScheduledExecutorService executor) { -- this.executor = executor; -- return this; -- } -- -- /** -- * Use the given {@link Clock} instance for the time. -- * -- * @param clock a {@link Clock} instance -- * @return {@code this} -- */ -- public Builder withClock(Clock clock) { -- this.clock = clock; -- return this; -- } -- -- /** -- * Prefix all metric names with the given name. -- * -- * @param prefix the prefix for all metric names -- * @return {@code this} -- */ -- public Builder prefixedWith(MetricName prefix) { -- this.prefix = prefix; -- return this; -- } -- -- /** -- * Convert rates to the given time unit. -- * -- * @param rateUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertRatesTo(TimeUnit rateUnit) { -- this.rateUnit = rateUnit; -- return this; -- } -- -- /** -- * Convert durations to the given time unit. -- * -- * @param durationUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertDurationsTo(TimeUnit durationUnit) { -- this.durationUnit = durationUnit; -- return this; -- } -- -- /** -- * Only report metrics which match the given filter. -- * -- * @param filter a {@link MetricFilter} -- * @return {@code this} -- */ -- public Builder filter(MetricFilter filter) { -- this.filter = filter; -- return this; -- } -- -- /** -- * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). -- * -- * @param disabledMetricAttributes the disabled metric attributes -- * @return {@code this} -- */ -- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -- this.disabledMetricAttributes = disabledMetricAttributes; -- return this; -- } -- -- /** -- * Builds a InfluxDbReporter with the given properties, sending metrics using the -- * given InfluxDbSender. -- * -- * @param sender the InfluxDbSender -- * @return the InfluxDbReporter -- */ -- public InfluxDbReporter build(InfluxDbSender sender) { -- return new InfluxDbReporter(registry, sender, clock, prefix, rateUnit, durationUnit, filter, executor, -- shutdownExecutorOnStop, disabledMetricAttributes); -- } -+ public Builder scheduleOn(ScheduledExecutorService executor) { -+ this.executor = executor; -+ return this; - } - -- private static final Logger LOGGER = LoggerFactory.getLogger(InfluxDbReporter.class); -- private static final String VALUE = "value"; -- -- private final Clock clock; -- private final InfluxDbSender sender; -- private final InfluxDbLineBuilder builder; -- - /** -- * Creates a new InfluxDbReporter instance. -+ * Use the given {@link Clock} instance for the time. - * -- * @param registry the MetricRegistry containing the metrics this reporter will report -- * @param sender the InfluxDbSender which is responsible for sending metrics to a influxdb -- * server via a transport protocol -- * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default -- * @param prefix the prefix of all metric names (may be null) -- * @param rateUnit the time unit of in which rates will be converted -- * @param durationUnit the time unit of in which durations will be converted -- * @param filter the filter for which metrics to report -- * @param executor the executor to use while scheduling reporting of metrics (may be null). -- * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this reporter -- * @param disabledMetricAttributes the disable metric attributes -+ * @param clock a {@link Clock} instance -+ * @return {@code this} - */ -- public InfluxDbReporter(MetricRegistry registry, InfluxDbSender sender, Clock clock, MetricName prefix, -- TimeUnit rateUnit, TimeUnit durationUnit, MetricFilter filter, ScheduledExecutorService executor, -- boolean shutdownExecutorOnStop, Set disabledMetricAttributes) { -- super(registry, "influxdb-reporter", filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, -- disabledMetricAttributes); -- this.sender = sender; -- this.clock = clock; -- this.builder = new InfluxDbLineBuilder(disabledMetricAttributes, prefix); -+ public Builder withClock(Clock clock) { -+ this.clock = clock; -+ return this; - } - -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap> gauges, -- SortedMap counters, -- SortedMap histograms, -- SortedMap meters, -- SortedMap timers) { -- -- final long timestamp = clock.getTime(); -- -- try { -- sender.connect(); -- -- for (Map.Entry> entry : gauges.entrySet()) { -- reportGauge(entry.getKey(), entry.getValue(), timestamp); -- } -- -- for (Map.Entry entry : counters.entrySet()) { -- reportCounter(entry.getKey(), entry.getValue(), timestamp); -- } -- -- for (Map.Entry entry : histograms.entrySet()) { -- reportHistogram(entry.getKey(), entry.getValue(), timestamp); -- } -- -- for (Map.Entry entry : meters.entrySet()) { -- reportMetered(entry.getKey(), entry.getValue(), timestamp); -- } -- -- for (Map.Entry entry : timers.entrySet()) { -- reportTimer(entry.getKey(), entry.getValue(), timestamp); -- } -- sender.flush(); -- } catch (IOException e) { -- LOGGER.warn("Unable to report to InfluxDb", sender, e); -- } finally { -- try { -- sender.disconnect(); -- } catch (IOException e) { -- LOGGER.warn("Error disconnecting InfluxDb", sender, e); -- } -- } -+ /** -+ * Prefix all metric names with the given name. -+ * -+ * @param prefix the prefix for all metric names -+ * @return {@code this} -+ */ -+ public Builder prefixedWith(MetricName prefix) { -+ this.prefix = prefix; -+ return this; - } - -- @Override -- public void stop() { -- try { -- super.stop(); -- } finally { -- try { -- sender.close(); -- } catch (IOException e) { -- LOGGER.debug("Error disconnecting from InfluxDb", e); -- } -- } -+ /** -+ * Convert rates to the given time unit. -+ * -+ * @param rateUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertRatesTo(TimeUnit rateUnit) { -+ this.rateUnit = rateUnit; -+ return this; - } - -- private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { -- final Snapshot snapshot = timer.getSnapshot(); -- builder.writeMeasurement(name) -- .writeFieldIfEnabled(MAX, convertDuration(snapshot.getMax())) -- .writeFieldIfEnabled(MEAN, convertDuration(snapshot.getMean())) -- .writeFieldIfEnabled(MIN, convertDuration(snapshot.getMin())) -- .writeFieldIfEnabled(STDDEV, convertDuration(snapshot.getStdDev())) -- .writeFieldIfEnabled(P50, convertDuration(snapshot.getMedian())) -- .writeFieldIfEnabled(P75, convertDuration(snapshot.get75thPercentile())) -- .writeFieldIfEnabled(P95, convertDuration(snapshot.get95thPercentile())) -- .writeFieldIfEnabled(P98, convertDuration(snapshot.get98thPercentile())) -- .writeFieldIfEnabled(P99, convertDuration(snapshot.get99thPercentile())) -- .writeFieldIfEnabled(P999, convertDuration(snapshot.get999thPercentile())); -- writeMeteredFieldsIfEnabled(timer) -- .writeTimestampMillis(timestamp); -- -- reportLine(); -+ /** -+ * Convert durations to the given time unit. -+ * -+ * @param durationUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertDurationsTo(TimeUnit durationUnit) { -+ this.durationUnit = durationUnit; -+ return this; - } - -- -- private void reportHistogram(MetricName name, Histogram histogram, long timestamp) throws IOException { -- final Snapshot snapshot = histogram.getSnapshot(); -- builder.writeMeasurement(name) -- .writeFieldIfEnabled(COUNT, histogram.getCount()) -- .writeFieldIfEnabled(SUM, histogram.getSum()) -- .writeFieldIfEnabled(MAX, snapshot.getMax()) -- .writeFieldIfEnabled(MEAN, snapshot.getMean()) -- .writeFieldIfEnabled(MIN, snapshot.getMin()) -- .writeFieldIfEnabled(STDDEV, snapshot.getStdDev()) -- .writeFieldIfEnabled(P50, snapshot.getMedian()) -- .writeFieldIfEnabled(P75, snapshot.get75thPercentile()) -- .writeFieldIfEnabled(P95, snapshot.get95thPercentile()) -- .writeFieldIfEnabled(P98, snapshot.get98thPercentile()) -- .writeFieldIfEnabled(P99, snapshot.get99thPercentile()) -- .writeFieldIfEnabled(P999, snapshot.get999thPercentile()) -- .writeTimestampMillis(timestamp); -- -- reportLine(); -+ /** -+ * Only report metrics which match the given filter. -+ * -+ * @param filter a {@link MetricFilter} -+ * @return {@code this} -+ */ -+ public Builder filter(MetricFilter filter) { -+ this.filter = filter; -+ return this; - } - -- -- private void reportMetered(MetricName name, Metered meter, long timestamp) throws IOException { -- builder.writeMeasurement(name); -- writeMeteredFieldsIfEnabled(meter) -- .writeTimestampMillis(timestamp); -- -- reportLine(); -+ /** -+ * Don't report the passed metric attributes for all metrics (e.g. "p999", "stddev" or "m15"). -+ * -+ * @param disabledMetricAttributes the disabled metric attributes -+ * @return {@code this} -+ */ -+ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -+ this.disabledMetricAttributes = disabledMetricAttributes; -+ return this; - } - -- private InfluxDbLineBuilder writeMeteredFieldsIfEnabled(Metered meter) { -- return builder.writeFieldIfEnabled(COUNT, meter.getCount()) -- .writeFieldIfEnabled(SUM, meter.getSum()) -- .writeFieldIfEnabled(M1_RATE, convertRate(meter.getOneMinuteRate())) -- .writeFieldIfEnabled(M5_RATE, convertRate(meter.getFiveMinuteRate())) -- .writeFieldIfEnabled(M15_RATE, convertRate(meter.getFifteenMinuteRate())) -- .writeFieldIfEnabled(MEAN_RATE, convertRate(meter.getMeanRate())); -+ /** -+ * Builds a InfluxDbReporter with the given properties, sending metrics using the given -+ * InfluxDbSender. -+ * -+ * @param sender the InfluxDbSender -+ * @return the InfluxDbReporter -+ */ -+ public InfluxDbReporter build(InfluxDbSender sender) { -+ return new InfluxDbReporter( -+ registry, -+ sender, -+ clock, -+ prefix, -+ rateUnit, -+ durationUnit, -+ filter, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes); - } -- -- private void reportCounter(MetricName name, Counter counter, long timestamp) throws IOException { -- builder.writeMeasurement(name) -- .writeFieldIfEnabled(COUNT, counter.getCount()) -- .writeTimestampMillis(timestamp); -- -- reportLine(); -+ } -+ -+ private static final Logger LOG = LoggerFactory.getLogger(InfluxDbReporter.class); -+ private static final String VALUE = "value"; -+ -+ private final Clock clock; -+ private final InfluxDbSender sender; -+ private final InfluxDbLineBuilder builder; -+ -+ /** -+ * Creates a new InfluxDbReporter instance. -+ * -+ * @param registry the MetricRegistry containing the metrics this reporter will report -+ * @param sender the InfluxDbSender which is responsible for sending metrics to a influxdb server -+ * via a transport protocol -+ * @param clock the instance of the time. Use {@link Clock#defaultClock()} for the default -+ * @param prefix the prefix of all metric names (may be null) -+ * @param rateUnit the time unit of in which rates will be converted -+ * @param durationUnit the time unit of in which durations will be converted -+ * @param filter the filter for which metrics to report -+ * @param executor the executor to use while scheduling reporting of metrics (may be null). -+ * @param shutdownExecutorOnStop if true, then executor will be stopped in same time with this -+ * reporter -+ * @param disabledMetricAttributes the disable metric attributes -+ */ -+ public InfluxDbReporter( -+ MetricRegistry registry, -+ InfluxDbSender sender, -+ Clock clock, -+ MetricName prefix, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ MetricFilter filter, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes) { -+ super( -+ registry, -+ "influxdb-reporter", -+ filter, -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes); -+ this.sender = sender; -+ this.clock = clock; -+ this.builder = new InfluxDbLineBuilder(disabledMetricAttributes, prefix); -+ } -+ -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap> gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ -+ final long timestamp = clock.getTime(); -+ -+ try { -+ sender.connect(); -+ -+ for (Map.Entry> entry : gauges.entrySet()) { -+ reportGauge(entry.getKey(), entry.getValue(), timestamp); -+ } -+ -+ for (Map.Entry entry : counters.entrySet()) { -+ reportCounter(entry.getKey(), entry.getValue(), timestamp); -+ } -+ -+ for (Map.Entry entry : histograms.entrySet()) { -+ reportHistogram(entry.getKey(), entry.getValue(), timestamp); -+ } -+ -+ for (Map.Entry entry : meters.entrySet()) { -+ reportMetered(entry.getKey(), entry.getValue(), timestamp); -+ } -+ -+ for (Map.Entry entry : timers.entrySet()) { -+ reportTimer(entry.getKey(), entry.getValue(), timestamp); -+ } -+ sender.flush(); -+ } catch (IOException e) { -+ LOG.warn("Unable to report to InfluxDb", sender, e); -+ } finally { -+ try { -+ sender.disconnect(); -+ } catch (IOException e) { -+ LOG.warn("Error disconnecting InfluxDb", sender, e); -+ } - } -- -- private void reportGauge(MetricName name, Gauge gauge, long timestamp) throws IOException { -- builder.writeMeasurement(name); -- final Object value = gauge.getValue(); -- if (value != null) { -- builder.writeField(VALUE); -- if (value instanceof Number) { -- final Number number = (Number) value; -- if (number instanceof Long || number instanceof Integer || number instanceof Short || -- number instanceof Byte) { -- builder.writeFieldValue(number.longValue()); -- } else { -- builder.writeFieldValue(number.doubleValue()); -- } -- } else if (value instanceof Boolean) { -- builder.writeFieldValue(((Boolean) value)); -- } else { -- builder.writeFieldValue(value.toString()); -- } -+ } -+ -+ @Override -+ public void stop() { -+ try { -+ super.stop(); -+ } finally { -+ try { -+ sender.close(); -+ } catch (IOException e) { -+ LOG.debug("Error disconnecting from InfluxDb", e); -+ } -+ } -+ } -+ -+ private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { -+ final Snapshot snapshot = timer.getSnapshot(); -+ builder -+ .writeMeasurement(name) -+ .writeFieldIfEnabled(MAX, convertDuration(snapshot.getMax())) -+ .writeFieldIfEnabled(MEAN, convertDuration(snapshot.getMean())) -+ .writeFieldIfEnabled(MIN, convertDuration(snapshot.getMin())) -+ .writeFieldIfEnabled(STDDEV, convertDuration(snapshot.getStdDev())) -+ .writeFieldIfEnabled(P50, convertDuration(snapshot.getMedian())) -+ .writeFieldIfEnabled(P75, convertDuration(snapshot.get75thPercentile())) -+ .writeFieldIfEnabled(P95, convertDuration(snapshot.get95thPercentile())) -+ .writeFieldIfEnabled(P98, convertDuration(snapshot.get98thPercentile())) -+ .writeFieldIfEnabled(P99, convertDuration(snapshot.get99thPercentile())) -+ .writeFieldIfEnabled(P999, convertDuration(snapshot.get999thPercentile())); -+ writeMeteredFieldsIfEnabled(timer).writeTimestampMillis(timestamp); -+ -+ reportLine(); -+ } -+ -+ private void reportHistogram(MetricName name, Histogram histogram, long timestamp) -+ throws IOException { -+ final Snapshot snapshot = histogram.getSnapshot(); -+ builder -+ .writeMeasurement(name) -+ .writeFieldIfEnabled(COUNT, histogram.getCount()) -+ .writeFieldIfEnabled(SUM, histogram.getSum()) -+ .writeFieldIfEnabled(MAX, snapshot.getMax()) -+ .writeFieldIfEnabled(MEAN, snapshot.getMean()) -+ .writeFieldIfEnabled(MIN, snapshot.getMin()) -+ .writeFieldIfEnabled(STDDEV, snapshot.getStdDev()) -+ .writeFieldIfEnabled(P50, snapshot.getMedian()) -+ .writeFieldIfEnabled(P75, snapshot.get75thPercentile()) -+ .writeFieldIfEnabled(P95, snapshot.get95thPercentile()) -+ .writeFieldIfEnabled(P98, snapshot.get98thPercentile()) -+ .writeFieldIfEnabled(P99, snapshot.get99thPercentile()) -+ .writeFieldIfEnabled(P999, snapshot.get999thPercentile()) -+ .writeTimestampMillis(timestamp); -+ -+ reportLine(); -+ } -+ -+ private void reportMetered(MetricName name, Metered meter, long timestamp) throws IOException { -+ builder.writeMeasurement(name); -+ writeMeteredFieldsIfEnabled(meter).writeTimestampMillis(timestamp); -+ -+ reportLine(); -+ } -+ -+ private InfluxDbLineBuilder writeMeteredFieldsIfEnabled(Metered meter) { -+ return builder -+ .writeFieldIfEnabled(COUNT, meter.getCount()) -+ .writeFieldIfEnabled(SUM, meter.getSum()) -+ .writeFieldIfEnabled(M1_RATE, convertRate(meter.getOneMinuteRate())) -+ .writeFieldIfEnabled(M5_RATE, convertRate(meter.getFiveMinuteRate())) -+ .writeFieldIfEnabled(M15_RATE, convertRate(meter.getFifteenMinuteRate())) -+ .writeFieldIfEnabled(MEAN_RATE, convertRate(meter.getMeanRate())); -+ } -+ -+ private void reportCounter(MetricName name, Counter counter, long timestamp) throws IOException { -+ builder -+ .writeMeasurement(name) -+ .writeFieldIfEnabled(COUNT, counter.getCount()) -+ .writeTimestampMillis(timestamp); -+ -+ reportLine(); -+ } -+ -+ private void reportGauge(MetricName name, Gauge gauge, long timestamp) throws IOException { -+ builder.writeMeasurement(name); -+ final Object value = gauge.getValue(); -+ if (value != null) { -+ builder.writeField(VALUE); -+ if (value instanceof Number) { -+ final Number number = (Number) value; -+ if (number instanceof Long -+ || number instanceof Integer -+ || number instanceof Short -+ || number instanceof Byte) { -+ builder.writeFieldValue(number.longValue()); -+ } else { -+ builder.writeFieldValue(number.doubleValue()); - } -- builder.writeTimestampMillis(timestamp); -- reportLine(); -+ } else if (value instanceof Boolean) { -+ builder.writeFieldValue(((Boolean) value)); -+ } else { -+ builder.writeFieldValue(value.toString()); -+ } - } -+ builder.writeTimestampMillis(timestamp); -+ reportLine(); -+ } - -- private void reportLine() throws IOException { -- if (builder.hasValues()) { -- sender.send(builder.get()); -- } -+ private void reportLine() throws IOException { -+ if (builder.hasValues()) { -+ sender.send(builder.get()); - } -+ } - } ---- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbSender.java -+++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbSender.java -@@ -5,43 +5,40 @@ import java.io.IOException; - - public interface InfluxDbSender extends Closeable { - -- /** -- * Connects to the server. -- * -- * @throws IllegalStateException if the client is already connected -- * @throws IOException if there is an error connecting -- */ -- void connect() throws IllegalStateException, IOException; -+ /** -+ * Connects to the server. -+ * -+ * @throws IllegalStateException if the client is already connected -+ * @throws IOException if there is an error connecting -+ */ -+ void connect() throws IllegalStateException, IOException; - -- /** -- * Sends the given measurement to the server. -- *

    -- * NOTE: The caller may modify the measurement buffer after this call. -- * The implementation of this method MUST NOT keep any reference to the buffer after this call. -- *

    -- * -- * @param measurement a single measurement line, -- * according to the InfluxDb line protocol including a trailing newline. -- * @throws IOException if there was an error sending the metric -- */ -- void send(StringBuilder measurement) throws IOException; -+ /** -+ * Sends the given measurement to the server. -+ * -+ *

    NOTE: The caller may modify the measurement buffer after this call. The -+ * implementation of this method MUST NOT keep any reference to the buffer after this call. -+ * -+ * @param measurement a single measurement line, according to the InfluxDb line protocol including -+ * a trailing newline. -+ * @throws IOException if there was an error sending the metric -+ */ -+ void send(StringBuilder measurement) throws IOException; - -- /** -- * Flushes buffer, if applicable -- * -- * @throws IOException if there was an error during flushing metrics to the server -- */ -- void flush() throws IOException; -+ /** -+ * Flushes buffer, if applicable -+ * -+ * @throws IOException if there was an error during flushing metrics to the server -+ */ -+ void flush() throws IOException; - -- /** -- * Disconnects from the server. -- * -- * @throws IOException if there is an error disconnecting -- */ -- void disconnect() throws IOException; -+ /** -+ * Disconnects from the server. -+ * -+ * @throws IOException if there is an error disconnecting -+ */ -+ void disconnect() throws IOException; - -- /** -- * Returns true if ready to send data -- */ -- boolean isConnected(); -+ /** Returns true if ready to send data */ -+ boolean isConnected(); - } ---- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java -+++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.influxdb; - -+import static java.util.Objects.requireNonNull; -+ - import java.io.IOException; - import java.net.InetSocketAddress; - import java.nio.ByteBuffer; -@@ -9,139 +11,137 @@ import java.nio.charset.Charset; - import java.nio.charset.CharsetEncoder; - import java.nio.charset.CoderResult; - import java.nio.charset.CodingErrorAction; --import java.util.Objects; - - public class InfluxDbUdpSender implements InfluxDbSender { - -- private final InetSocketAddress address; -- private int mtu = 1500; -- -- private DatagramChannel datagramChannel; -- private ByteBuffer byteBuf; -- private CharBuffer charBuf; -- -- private final CharsetEncoder encoder = Charset.forName("UTF-8") -- .newEncoder() -- .onMalformedInput(CodingErrorAction.REPLACE) -- .onUnmappableCharacter(CodingErrorAction.REPLACE); -- -- /** -- * Creates a new client which sends data to given address using UDP -- * -- * @param hostname The hostname of the InfluxDb server -- * @param port The port of the InfluxDb server -- */ -- public InfluxDbUdpSender(String hostname, int port) { -- this(new InetSocketAddress(hostname, port)); -+ private final InetSocketAddress address; -+ private int mtu = 1500; -+ -+ private DatagramChannel datagramChannel; -+ private ByteBuffer byteBuf; -+ private CharBuffer charBuf; -+ -+ private final CharsetEncoder encoder = -+ Charset.forName("UTF-8") -+ .newEncoder() -+ .onMalformedInput(CodingErrorAction.REPLACE) -+ .onUnmappableCharacter(CodingErrorAction.REPLACE); -+ -+ /** -+ * Creates a new client which sends data to given address using UDP -+ * -+ * @param hostname The hostname of the InfluxDb server -+ * @param port The port of the InfluxDb server -+ */ -+ public InfluxDbUdpSender(String hostname, int port) { -+ this(new InetSocketAddress(hostname, port)); -+ } -+ -+ /** -+ * Creates a new client which sends data to given address using UDP -+ * -+ * @param address the address of the InfluxDb server -+ */ -+ public InfluxDbUdpSender(InetSocketAddress address) { -+ this.address = requireNonNull(address); -+ charBuf = CharBuffer.allocate(mtu * 2); -+ byteBuf = ByteBuffer.allocate(mtu * 2); -+ } -+ -+ // for testing -+ void setMTU(int mtu) { -+ this.mtu = mtu; -+ } -+ -+ // for testing -+ void setDatagramChannel(DatagramChannel datagramChannel) { -+ this.datagramChannel = datagramChannel; -+ } -+ -+ @Override -+ public void connect() throws IllegalStateException, IOException { -+ if (datagramChannel == null) { -+ datagramChannel = DatagramChannel.open(); - } -- -- /** -- * Creates a new client which sends data to given address using UDP -- * -- * @param address the address of the InfluxDb server -- */ -- public InfluxDbUdpSender(InetSocketAddress address) { -- this.address = Objects.requireNonNull(address); -- charBuf = CharBuffer.allocate(mtu * 2); -- byteBuf = ByteBuffer.allocate(mtu * 2); -+ byteBuf.clear(); -+ } -+ -+ @Override -+ public boolean isConnected() { -+ return datagramChannel != null; -+ } -+ -+ @Override -+ public void disconnect() throws IOException { -+ // ignore, keep the datagram channel open -+ } -+ -+ @Override -+ public void close() throws IOException { -+ try { -+ datagramChannel.close(); -+ } finally { -+ datagramChannel = null; - } -- -- // for testing -- void setMTU(int mtu) { -- this.mtu = mtu; -- } -- -- // for testing -- void setDatagramChannel(DatagramChannel datagramChannel) { -- this.datagramChannel = datagramChannel; -- } -- -- @Override -- public void connect() throws IllegalStateException, IOException { -- if (datagramChannel == null) { -- datagramChannel = DatagramChannel.open(); -- } -+ } -+ -+ @Override -+ public void send(StringBuilder str) throws IOException { -+ int len = byteBuf.position(); -+ encode(str); -+ int len2 = byteBuf.position(); -+ if (len2 >= mtu) { -+ if (len == 0) { -+ // send current buffer (one single measurement exceeds the MTU) -+ sendBuffer(); - byteBuf.clear(); -+ } else { -+ // send previous buffer -+ byteBuf.position(len); -+ sendBuffer(); -+ byteBuf.limit(len2); -+ byteBuf.compact(); -+ } - } -+ } - -- @Override -- public boolean isConnected() { -- return datagramChannel != null; -+ @Override -+ public void flush() throws IOException { -+ if (byteBuf.position() > 0) { -+ sendBuffer(); -+ byteBuf.clear(); - } -- -- @Override -- public void disconnect() throws IOException { -- // ignore, keep the datagram channel open -+ } -+ -+ private void sendBuffer() throws IOException { -+ byteBuf.flip(); -+ datagramChannel.send(byteBuf, address); -+ } -+ -+ private void encode(StringBuilder str) { -+ // copy chars -+ if (charBuf.capacity() < str.length()) { -+ charBuf = CharBuffer.allocate(str.length()); -+ } else { -+ charBuf.clear(); - } -+ str.getChars(0, str.length(), charBuf.array(), charBuf.arrayOffset()); -+ charBuf.limit(str.length()); - -- @Override -- public void close() throws IOException { -- try { -- datagramChannel.close(); -- } finally { -- datagramChannel = null; -- } -- } -+ // encode chars -+ encoder.reset(); - -- @Override -- public void send(StringBuilder str) throws IOException { -- int len = byteBuf.position(); -- encode(str); -- int len2 = byteBuf.position(); -- if (len2 >= mtu) { -- if (len == 0) { -- // send current buffer (one single measurement exceeds the MTU) -- sendBuffer(); -- byteBuf.clear(); -- } else { -- // send previous buffer -- byteBuf.position(len); -- sendBuffer(); -- byteBuf.limit(len2); -- byteBuf.compact(); -- } -- } -- } -- -- @Override -- public void flush() throws IOException { -- if (byteBuf.position() > 0) { -- sendBuffer(); -- byteBuf.clear(); -- } -- } -- -- private void sendBuffer() throws IOException { -+ for (; ; ) { -+ CoderResult result = encoder.encode(charBuf, byteBuf, true); -+ if (result.isOverflow()) { -+ // grow the buffer -+ ByteBuffer byteBuf2 = ByteBuffer.allocate(byteBuf.capacity() * 2); - byteBuf.flip(); -- datagramChannel.send(byteBuf, address); -+ byteBuf2.put(byteBuf); -+ byteBuf = byteBuf2; -+ } else { // underflow, i.e. done -+ break; -+ } - } -- -- private void encode(StringBuilder str) { -- // copy chars -- if (charBuf.capacity() < str.length()) { -- charBuf = CharBuffer.allocate(str.length()); -- } else { -- charBuf.clear(); -- } -- str.getChars(0, str.length(), charBuf.array(), charBuf.arrayOffset()); -- charBuf.limit(str.length()); -- -- // encode chars -- encoder.reset(); -- -- for (; ; ) { -- CoderResult result = encoder.encode(charBuf, byteBuf, true); -- if (result.isOverflow()) { -- // grow the buffer -- ByteBuffer byteBuf2 = ByteBuffer.allocate(byteBuf.capacity() * 2); -- byteBuf.flip(); -- byteBuf2.put(byteBuf); -- byteBuf = byteBuf2; -- } else { // underflow, i.e. done -- break; -- } -- } -- } -- -- -+ } - } ---- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java -+++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java -@@ -1,17 +1,17 @@ - package io.dropwizard.metrics5.influxdb; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricAttribute; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; -- --class InfluxDbLineBuilderAssumptionsTest { -+final class InfluxDbLineBuilderAssumptionsTest { - -- @Test -- void ensureMetricAttributeCodesAreSafeFieldKeys() { -- for (MetricAttribute ma : MetricAttribute.values()) { -- String code = ma.getCode(); -- assertThat(code).doesNotContainPattern("[,= ]"); -- } -+ @Test -+ void ensureMetricAttributeCodesAreSafeFieldKeys() { -+ for (MetricAttribute ma : MetricAttribute.values()) { -+ String code = ma.getCode(); -+ assertThat(code).doesNotContainPattern("[,= ]"); - } -+ } - } ---- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java -+++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java -@@ -1,5 +1,17 @@ - package io.dropwizard.metrics5.influxdb; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.doAnswer; -+import static org.mockito.Mockito.doThrow; -+import static org.mockito.Mockito.inOrder; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.times; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.verifyNoMoreInteractions; -+import static org.mockito.Mockito.when; -+ -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -11,458 +23,397 @@ import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import org.mockito.InOrder; -- - import java.io.IOException; - import java.net.UnknownHostException; - import java.util.ArrayList; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Set; - import java.util.SortedMap; - import java.util.TreeMap; - import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; -+import org.mockito.InOrder; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.ArgumentMatchers.any; --import static org.mockito.Mockito.doAnswer; --import static org.mockito.Mockito.doThrow; --import static org.mockito.Mockito.inOrder; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.times; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.verifyNoMoreInteractions; --import static org.mockito.Mockito.when; -- --class InfluxDbReporterTest { -- private static final MetricName GAUGE = MetricName.build("gauge"); -- private static final MetricName METER = MetricName.build("meter"); -- private static final MetricName COUNTER = MetricName.build("counter"); -- -- private final long timestamp = 1000198; -- private final Clock clock = mock(Clock.class); -- private final InfluxDbSender sender = mock(InfluxDbSender.class); -- private final List send = new ArrayList<>(); -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final InfluxDbReporter reporter = InfluxDbReporter.forRegistry(registry) -+final class InfluxDbReporterTest { -+ private static final MetricName GAUGE = MetricName.build("gauge"); -+ private static final MetricName METER = MetricName.build("meter"); -+ private static final MetricName COUNTER = MetricName.build("counter"); -+ -+ private final long timestamp = 1000198; -+ private final Clock clock = mock(); -+ private final InfluxDbSender sender = mock(); -+ private final List send = new ArrayList<>(); -+ private final MetricRegistry registry = mock(); -+ private final InfluxDbReporter reporter = -+ InfluxDbReporter.forRegistry(registry) -+ .withClock(clock) -+ .prefixedWith(new MetricName("prefix", map("foo", "bar"))) -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(ImmutableSet.of()) -+ .build(sender); -+ -+ private final InfluxDbReporter minuteRateReporter = -+ InfluxDbReporter.forRegistry(registry) -+ .withClock(clock) -+ .prefixedWith(new MetricName("prefix", map("foo", "bar"))) -+ .convertRatesTo(TimeUnit.MINUTES) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(ImmutableSet.of()) -+ .build(sender); -+ -+ @BeforeEach -+ void setUp() throws IOException { -+ when(clock.getTime()).thenReturn(timestamp * 1000); -+ send.clear(); -+ doAnswer(invocation -> send.add(invocation.getArgument(0).toString())) -+ .when(sender) -+ .send(any(StringBuilder.class)); -+ } -+ -+ @Test -+ void reportsStringGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge("value")), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=\"value\" 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsByteGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge((byte) 1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsShortGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge((short) 1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsIntegerGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsLongGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(1L)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsFloatGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(1.5f)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1.5 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsDoubleGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(1.1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1.1 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsBooleanGaugeValues() throws Exception { -+ reporter.report(map(GAUGE, gauge(true)), map(), map(), map(), map()); -+ -+ reporter.report(map(GAUGE, gauge(false)), map(), map(), map(), map()); -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ -+ assertThat(send).element(0).isEqualTo("prefix.gauge,foo=bar value=t 1000198000000000\n"); -+ assertThat(send).element(1).isEqualTo("prefix.gauge,foo=bar value=f 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsCounters() throws Exception { -+ final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(100L); -+ -+ reporter.report(map(), map(COUNTER, counter), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send).first().isEqualTo("prefix.counter,foo=bar count=100i 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsHistograms() throws Exception { -+ final Histogram histogram = mock(); -+ when(histogram.getCount()).thenReturn(1L); -+ when(histogram.getSum()).thenReturn(12L); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(2L); -+ when(snapshot.getMean()).thenReturn(3.0); -+ when(snapshot.getMin()).thenReturn(4L); -+ when(snapshot.getStdDev()).thenReturn(5.0); -+ when(snapshot.getMedian()).thenReturn(6.0); -+ when(snapshot.get75thPercentile()).thenReturn(7.0); -+ when(snapshot.get95thPercentile()).thenReturn(8.0); -+ when(snapshot.get98thPercentile()).thenReturn(9.0); -+ when(snapshot.get99thPercentile()).thenReturn(10.0); -+ when(snapshot.get999thPercentile()).thenReturn(11.0); -+ -+ when(histogram.getSnapshot()).thenReturn(snapshot); -+ -+ reporter.report(map(), map(), map(MetricName.build("histogram"), histogram), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send) -+ .first() -+ .isEqualTo( -+ "prefix.histogram,foo=bar count=1i,sum=12i,max=2i,mean=3.0,min=4i,stddev=5.0,p50=6.0,p75=7.0,p95=8.0,p98=9.0,p99=10.0,p999=11.0 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsMeters() throws Exception { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(6L); -+ when(meter.getOneMinuteRate()).thenReturn(2.0); -+ when(meter.getFiveMinuteRate()).thenReturn(3.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(4.0); -+ when(meter.getMeanRate()).thenReturn(5.0); -+ -+ reporter.report(map(), map(), map(), map(METER, meter), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send) -+ .first() -+ .isEqualTo( -+ "prefix.meter,foo=bar count=1i,sum=6i,m1_rate=2.0,m5_rate=3.0,m15_rate=4.0,mean_rate=5.0 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsMetersInMinutes() throws Exception { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(6L); -+ when(meter.getOneMinuteRate()).thenReturn(2.0); -+ when(meter.getFiveMinuteRate()).thenReturn(3.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(4.0); -+ when(meter.getMeanRate()).thenReturn(5.0); -+ -+ minuteRateReporter.report( -+ this.map(), this.map(), this.map(), this.map(METER, meter), this.map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send) -+ .first() -+ .isEqualTo( -+ "prefix.meter,foo=bar count=1i,sum=6i,m1_rate=120.0,m5_rate=180.0,m15_rate=240.0,mean_rate=300.0 1000198000000000\n"); -+ } -+ -+ @Test -+ void reportsTimers() throws Exception { -+ final Timer timer = mock(); -+ when(timer.getCount()).thenReturn(1L); -+ when(timer.getSum()).thenReturn(6L); -+ when(timer.getMeanRate()).thenReturn(2.0); -+ when(timer.getOneMinuteRate()).thenReturn(3.0); -+ when(timer.getFiveMinuteRate()).thenReturn(4.0); -+ when(timer.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -+ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -+ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -+ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -+ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -+ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -+ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -+ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -+ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -+ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -+ -+ when(timer.getSnapshot()).thenReturn(snapshot); -+ -+ reporter.report(map(), map(), map(), map(), map(MetricName.build("timer"), timer)); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ assertThat(send) -+ .first() -+ .isEqualTo( -+ "prefix.timer,foo=bar max=100.0,mean=200.0,min=300.0,stddev=400.0,p50=500.0,p75=600.0,p95=700.0,p98=800.0,p99=900.0,p999=1000.0,count=1i,sum=6i,m1_rate=3.0,m5_rate=4.0,m15_rate=5.0,mean_rate=2.0 1000198000000000\n"); -+ -+ reporter.close(); -+ } -+ -+ @Test -+ void disconnectsIfSenderIsUnavailable() throws Exception { -+ doThrow(new UnknownHostException("UNKNOWN-HOST")).when(sender).connect(); -+ reporter.report(map(GAUGE, gauge(1)), map(), map(), map(), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ } -+ -+ @Test -+ void closesConnectionOnReporterStop() throws Exception { -+ reporter.stop(); -+ -+ verify(sender).close(); -+ } -+ -+ @Test -+ void disabledMetricsAttribute() throws Exception { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(6L); -+ when(meter.getOneMinuteRate()).thenReturn(2.0); -+ when(meter.getFiveMinuteRate()).thenReturn(3.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(4.0); -+ when(meter.getMeanRate()).thenReturn(5.0); -+ -+ final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(11L); -+ -+ Set disabledMetricAttributes = -+ EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE); -+ InfluxDbReporter reporterWithdisabledMetricAttributes = -+ InfluxDbReporter.forRegistry(registry) - .withClock(clock) -- .prefixedWith(new MetricName("prefix", map("foo", "bar"))) -+ .prefixedWith(MetricName.build("prefix")) - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(disabledMetricAttributes) - .build(sender); -- -- private final InfluxDbReporter minuteRateReporter = InfluxDbReporter -- .forRegistry(registry) -- .withClock(clock) -- .prefixedWith(new MetricName("prefix", map("foo", "bar"))) -- .convertRatesTo(TimeUnit.MINUTES) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -- .build(sender); -- -- @BeforeEach -- void setUp() throws IOException { -- when(clock.getTime()).thenReturn(timestamp * 1000); -- send.clear(); -- doAnswer(invocation -> send.add(invocation.getArgument(0).toString())) -- .when(sender).send(any(StringBuilder.class)); -- } -- -- @Test -- void reportsStringGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge("value")), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=\"value\" 1000198000000000\n"); -- } -- -- @Test -- void reportsByteGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge((byte) 1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); -- } -- -- @Test -- void reportsShortGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge((short) 1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); -- } -- -- @Test -- void reportsIntegerGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); -- } -- -- @Test -- void reportsLongGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(1L)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1i 1000198000000000\n"); -- } -- -- @Test -- void reportsFloatGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(1.5f)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1.5 1000198000000000\n"); -- } -- -- @Test -- void reportsDoubleGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(1.1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.gauge,foo=bar value=1.1 1000198000000000\n"); -- } -- -- @Test -- void reportsBooleanGaugeValues() throws Exception { -- reporter.report(map(GAUGE, gauge(true)), -- map(), -- map(), -- map(), -- map()); -- -- reporter.report(map(GAUGE, gauge(false)), -- map(), -- map(), -- map(), -- map()); -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- -- assertThat(send).element(0).isEqualTo("prefix.gauge,foo=bar value=t 1000198000000000\n"); -- assertThat(send).element(1).isEqualTo("prefix.gauge,foo=bar value=f 1000198000000000\n"); -- } -- -- @Test -- void reportsCounters() throws Exception { -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(100L); -- -- reporter.report(map(), -- map(COUNTER, counter), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.counter,foo=bar count=100i 1000198000000000\n"); -- } -- -- @Test -- void reportsHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -- when(histogram.getCount()).thenReturn(1L); -- when(histogram.getSum()).thenReturn(12L); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(2L); -- when(snapshot.getMean()).thenReturn(3.0); -- when(snapshot.getMin()).thenReturn(4L); -- when(snapshot.getStdDev()).thenReturn(5.0); -- when(snapshot.getMedian()).thenReturn(6.0); -- when(snapshot.get75thPercentile()).thenReturn(7.0); -- when(snapshot.get95thPercentile()).thenReturn(8.0); -- when(snapshot.get98thPercentile()).thenReturn(9.0); -- when(snapshot.get99thPercentile()).thenReturn(10.0); -- when(snapshot.get999thPercentile()).thenReturn(11.0); -- -- when(histogram.getSnapshot()).thenReturn(snapshot); -- -- reporter.report(map(), -- map(), -- map(MetricName.build("histogram"), histogram), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.histogram,foo=bar count=1i,sum=12i,max=2i,mean=3.0,min=4i,stddev=5.0,p50=6.0,p75=7.0,p95=8.0,p98=9.0,p99=10.0,p999=11.0 1000198000000000\n"); -- -- } -- -- @Test -- void reportsMeters() throws Exception { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(6L); -- when(meter.getOneMinuteRate()).thenReturn(2.0); -- when(meter.getFiveMinuteRate()).thenReturn(3.0); -- when(meter.getFifteenMinuteRate()).thenReturn(4.0); -- when(meter.getMeanRate()).thenReturn(5.0); -- -- reporter.report(map(), -- map(), -- map(), -- map(METER, meter), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.meter,foo=bar count=1i,sum=6i,m1_rate=2.0,m5_rate=3.0,m15_rate=4.0,mean_rate=5.0 1000198000000000\n"); -- } -- -- @Test -- void reportsMetersInMinutes() throws Exception { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(6L); -- when(meter.getOneMinuteRate()).thenReturn(2.0); -- when(meter.getFiveMinuteRate()).thenReturn(3.0); -- when(meter.getFifteenMinuteRate()).thenReturn(4.0); -- when(meter.getMeanRate()).thenReturn(5.0); -- -- minuteRateReporter.report(this.map(), -- this.map(), -- this.map(), -- this.map(METER, meter), -- this.map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.meter,foo=bar count=1i,sum=6i,m1_rate=120.0,m5_rate=180.0,m15_rate=240.0,mean_rate=300.0 1000198000000000\n"); -- } -- -- @Test -- void reportsTimers() throws Exception { -- final Timer timer = mock(Timer.class); -- when(timer.getCount()).thenReturn(1L); -- when(timer.getSum()).thenReturn(6L); -- when(timer.getMeanRate()).thenReturn(2.0); -- when(timer.getOneMinuteRate()).thenReturn(3.0); -- when(timer.getFiveMinuteRate()).thenReturn(4.0); -- when(timer.getFifteenMinuteRate()).thenReturn(5.0); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS -- .toNanos(1000)); -- -- when(timer.getSnapshot()).thenReturn(snapshot); -- -- reporter.report(map(), -- map(), -- map(), -- map(), -- map(MetricName.build("timer"), timer)); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- assertThat(send).first().isEqualTo("prefix.timer,foo=bar max=100.0,mean=200.0,min=300.0,stddev=400.0,p50=500.0,p75=600.0,p95=700.0,p98=800.0,p99=900.0,p999=1000.0,count=1i,sum=6i,m1_rate=3.0,m5_rate=4.0,m15_rate=5.0,mean_rate=2.0 1000198000000000\n"); -- -- reporter.close(); -- } -- -- @Test -- void disconnectsIfSenderIsUnavailable() throws Exception { -- doThrow(new UnknownHostException("UNKNOWN-HOST")).when(sender).connect(); -- reporter.report(map(GAUGE, gauge(1)), -- map(), -- map(), -- map(), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender).disconnect(); -- -- -- verifyNoMoreInteractions(sender); -- } -- -- @Test -- void closesConnectionOnReporterStop() throws Exception { -- reporter.stop(); -- -- verify(sender).close(); -- } -- -- @Test -- void disabledMetricsAttribute() throws Exception { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(6L); -- when(meter.getOneMinuteRate()).thenReturn(2.0); -- when(meter.getFiveMinuteRate()).thenReturn(3.0); -- when(meter.getFifteenMinuteRate()).thenReturn(4.0); -- when(meter.getMeanRate()).thenReturn(5.0); -- -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(11L); -- -- Set disabledMetricAttributes = EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE); -- InfluxDbReporter reporterWithdisabledMetricAttributes = InfluxDbReporter.forRegistry(registry) -- .withClock(clock) -- .prefixedWith(MetricName.build("prefix")) -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(disabledMetricAttributes) -- .build(sender); -- reporterWithdisabledMetricAttributes.report(map(), -- map(COUNTER, counter), -- map(), -- map(METER, meter), -- map()); -- -- final InOrder inOrder = inOrder(sender); -- inOrder.verify(sender).connect(); -- inOrder.verify(sender, times(2)).send(anySb()); -- inOrder.verify(sender).flush(); -- inOrder.verify(sender).disconnect(); -- -- verifyNoMoreInteractions(sender); -- -- assertThat(send).element(0).isEqualTo("prefix.counter count=11i 1000198000000000\n"); -- assertThat(send).element(1).isEqualTo("prefix.meter count=1i,sum=6i,m1_rate=2.0,mean_rate=5.0 1000198000000000\n"); -- } -- -- private SortedMap map() { -- return new TreeMap<>(); -- } -- -- private SortedMap map(K key, V value) { -- final SortedMap map = new TreeMap<>(); -- map.put(key, value); -- return map; -- } -- -- private Gauge gauge(T value) { -- return () -> value; -- } -- -- private StringBuilder anySb() { -- return any(StringBuilder.class); -- } -+ reporterWithdisabledMetricAttributes.report( -+ map(), map(COUNTER, counter), map(), map(METER, meter), map()); -+ -+ final InOrder inOrder = inOrder(sender); -+ inOrder.verify(sender).connect(); -+ inOrder.verify(sender, times(2)).send(anySb()); -+ inOrder.verify(sender).flush(); -+ inOrder.verify(sender).disconnect(); -+ -+ verifyNoMoreInteractions(sender); -+ -+ assertThat(send).element(0).isEqualTo("prefix.counter count=11i 1000198000000000\n"); -+ assertThat(send) -+ .element(1) -+ .isEqualTo("prefix.meter count=1i,sum=6i,m1_rate=2.0,mean_rate=5.0 1000198000000000\n"); -+ } -+ -+ private SortedMap map() { -+ return new TreeMap<>(); -+ } -+ -+ private SortedMap map(K key, V value) { -+ final SortedMap map = new TreeMap<>(); -+ map.put(key, value); -+ return map; -+ } -+ -+ private Gauge gauge(T value) { -+ return () -> value; -+ } -+ -+ private StringBuilder anySb() { -+ return any(StringBuilder.class); -+ } - } ---- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java -+++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java -@@ -1,83 +1,84 @@ - package io.dropwizard.metrics5.influxdb; - --import java.io.IOException; -- --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import org.mockito.Mockito; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.any; -+import static org.mockito.Mockito.doAnswer; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.times; -+import static org.mockito.Mockito.verify; - -+import java.io.IOException; - import java.net.SocketAddress; - import java.nio.ByteBuffer; - import java.nio.channels.DatagramChannel; - import java.util.ArrayList; - import java.util.List; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; -- --import static org.mockito.Mockito.doAnswer; --import static org.mockito.Mockito.any; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.times; -- --class InfluxDbUdpTest { -- -- private final String host = "example.com"; -- private final int port = 1234; -- -- private InfluxDbUdpSender influxdbUdp; -- private final DatagramChannel datagramChannel = Mockito.mock(DatagramChannel.class); -- private final List sent = new ArrayList<>(); -- -- @BeforeEach -- void setUp() throws IOException { -- sent.clear(); -- doAnswer(invocation -> { -- sent.add(toBytes(invocation.getArgument(0))); -- return 0; -- }).when(datagramChannel).send(any(ByteBuffer.class), any(SocketAddress.class)); -- influxdbUdp = new InfluxDbUdpSender(host, port); -- influxdbUdp.setDatagramChannel(datagramChannel); -- } -- -- @Test -- void writesValue() throws Exception { -- influxdbUdp.send(new StringBuilder("räksmörgås value=123 456000000000\n")); -- influxdbUdp.flush(); -- -- verify(datagramChannel).send(any(), any()); -- -- assertThat(sent).first().isEqualTo("räksmörgås value=123 456000000000\n".getBytes("UTF-8")); -- } -- -- @Test -- void batchesValues() throws Exception { -- influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); -- influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); -- influxdbUdp.flush(); -- -- verify(datagramChannel).send(any(), any()); -- -- assertThat(sent).first().isEqualTo( -- "name1 value=111 456000000000\nname2 value=222 456000000000\n".getBytes("UTF-8")); -- } -- -- @Test -- void respectsMTU() throws Exception { -- influxdbUdp.setMTU(40); -- influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); -- influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); -- influxdbUdp.flush(); -- -- verify(datagramChannel, times(2)).send(any(), any()); -- -- assertThat(sent).element(0).isEqualTo("name1 value=111 456000000000\n".getBytes("UTF-8")); -- assertThat(sent).element(1).isEqualTo("name2 value=222 456000000000\n".getBytes("UTF-8")); -- } -- -- private byte[] toBytes(ByteBuffer buf) { -- byte[] bytes = new byte[buf.remaining()]; -- buf.get(bytes); -- return bytes; -- } --} -\ No newline at end of file -+final class InfluxDbUdpTest { -+ -+ private final String host = "example.com"; -+ private final int port = 1234; -+ -+ private InfluxDbUdpSender influxdbUdp; -+ private final DatagramChannel datagramChannel = mock(); -+ private final List sent = new ArrayList<>(); -+ -+ @BeforeEach -+ void setUp() throws IOException { -+ sent.clear(); -+ doAnswer( -+ invocation -> { -+ sent.add(toBytes(invocation.getArgument(0))); -+ return 0; -+ }) -+ .when(datagramChannel) -+ .send(any(ByteBuffer.class), any(SocketAddress.class)); -+ influxdbUdp = new InfluxDbUdpSender(host, port); -+ influxdbUdp.setDatagramChannel(datagramChannel); -+ } -+ -+ @Test -+ void writesValue() throws Exception { -+ influxdbUdp.send(new StringBuilder("räksmörgås value=123 456000000000\n")); -+ influxdbUdp.flush(); -+ -+ verify(datagramChannel).send(any(), any()); -+ -+ assertThat(sent).first().isEqualTo("räksmörgås value=123 456000000000\n".getBytes("UTF-8")); -+ } -+ -+ @Test -+ void batchesValues() throws Exception { -+ influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); -+ influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); -+ influxdbUdp.flush(); -+ -+ verify(datagramChannel).send(any(), any()); -+ -+ assertThat(sent) -+ .first() -+ .isEqualTo( -+ "name1 value=111 456000000000\nname2 value=222 456000000000\n".getBytes("UTF-8")); -+ } -+ -+ @Test -+ void respectsMTU() throws Exception { -+ influxdbUdp.setMTU(40); -+ influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); -+ influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); -+ influxdbUdp.flush(); -+ -+ verify(datagramChannel, times(2)).send(any(), any()); -+ -+ assertThat(sent).element(0).isEqualTo("name1 value=111 456000000000\n".getBytes("UTF-8")); -+ assertThat(sent).element(1).isEqualTo("name2 value=222 456000000000\n".getBytes("UTF-8")); -+ } -+ -+ private byte[] toBytes(ByteBuffer buf) { -+ byte[] bytes = new byte[buf.remaining()]; -+ buf.get(bytes); -+ return bytes; -+ } -+} ---- a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -+++ b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -@@ -1,5 +1,8 @@ - package io.dropwizard.metrics5.servlet; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ -+import com.google.common.base.Strings; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -14,205 +17,197 @@ import jakarta.servlet.ServletRequest; - import jakarta.servlet.ServletResponse; - import jakarta.servlet.http.HttpServletResponse; - import jakarta.servlet.http.HttpServletResponseWrapper; -- - import java.io.IOException; - import java.util.Map; - import java.util.Map.Entry; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.ConcurrentMap; - --import static io.dropwizard.metrics5.MetricRegistry.name; -- - /** - * {@link Filter} implementation which captures request information and a breakdown of the response - * codes being returned. - */ - public abstract class AbstractInstrumentedFilter implements Filter { -- static final String METRIC_PREFIX = "name-prefix"; -- -- private final String otherMetricName; -- private final Map meterNamesByStatusCode; -- private final String registryAttribute; -- -- // initialized after call of init method -- private ConcurrentMap metersByStatusCode; -- private Meter otherMeter; -- private Meter timeoutsMeter; -- private Meter errorsMeter; -- private Counter activeRequests; -- private Timer requestTimer; -- -- -- /** -- * Creates a new instance of the filter. -- * -- * @param registryAttribute the attribute used to look up the metrics registry in the -- * servlet context -- * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are -- * interested in. -- * @param otherMetricName The name used for the catch-all meter. -- */ -- protected AbstractInstrumentedFilter(String registryAttribute, -- Map meterNamesByStatusCode, -- String otherMetricName) { -- this.registryAttribute = registryAttribute; -- this.otherMetricName = otherMetricName; -- this.meterNamesByStatusCode = meterNamesByStatusCode; -+ static final String METRIC_PREFIX = "name-prefix"; -+ -+ private final String otherMetricName; -+ private final Map meterNamesByStatusCode; -+ private final String registryAttribute; -+ -+ // initialized after call of init method -+ private ConcurrentMap metersByStatusCode; -+ private Meter otherMeter; -+ private Meter timeoutsMeter; -+ private Meter errorsMeter; -+ private Counter activeRequests; -+ private Timer requestTimer; -+ -+ /** -+ * Creates a new instance of the filter. -+ * -+ * @param registryAttribute the attribute used to look up the metrics registry in the servlet -+ * context -+ * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are -+ * interested in. -+ * @param otherMetricName The name used for the catch-all meter. -+ */ -+ protected AbstractInstrumentedFilter( -+ String registryAttribute, -+ Map meterNamesByStatusCode, -+ String otherMetricName) { -+ this.registryAttribute = registryAttribute; -+ this.otherMetricName = otherMetricName; -+ this.meterNamesByStatusCode = meterNamesByStatusCode; -+ } -+ -+ @Override -+ public void init(FilterConfig filterConfig) throws ServletException { -+ final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); -+ -+ String metricName = filterConfig.getInitParameter(METRIC_PREFIX); -+ if (Strings.isNullOrEmpty(metricName)) { -+ metricName = getClass().getName(); - } - -- @Override -- public void init(FilterConfig filterConfig) throws ServletException { -- final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); -- -- String metricName = filterConfig.getInitParameter(METRIC_PREFIX); -- if (metricName == null || metricName.isEmpty()) { -- metricName = getClass().getName(); -- } -- -- this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); -- for (Entry entry : meterNamesByStatusCode.entrySet()) { -- metersByStatusCode.put(entry.getKey(), -- metricsRegistry.meter(name(metricName, entry.getValue()))); -- } -- this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); -- this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); -- this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); -- this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); -- this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); -- -+ this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); -+ for (Entry entry : meterNamesByStatusCode.entrySet()) { -+ metersByStatusCode.put( -+ entry.getKey(), metricsRegistry.meter(name(metricName, entry.getValue()))); - } -- -- private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { -- final MetricRegistry metricsRegistry; -- -- final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); -- if (o instanceof MetricRegistry) { -- metricsRegistry = (MetricRegistry) o; -+ this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); -+ this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); -+ this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); -+ this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); -+ this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); -+ } -+ -+ private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { -+ final MetricRegistry metricsRegistry; -+ -+ final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); -+ if (o instanceof MetricRegistry) { -+ metricsRegistry = (MetricRegistry) o; -+ } else { -+ metricsRegistry = new MetricRegistry(); -+ } -+ return metricsRegistry; -+ } -+ -+ @Override -+ public void destroy() {} -+ -+ @Override -+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) -+ throws IOException, ServletException { -+ final StatusExposingServletResponse wrappedResponse = -+ new StatusExposingServletResponse((HttpServletResponse) response); -+ activeRequests.inc(); -+ final Timer.Context context = requestTimer.time(); -+ boolean error = false; -+ try { -+ chain.doFilter(request, wrappedResponse); -+ } catch (IOException | RuntimeException | ServletException e) { -+ error = true; -+ throw e; -+ } finally { -+ if (!error && request.isAsyncStarted()) { -+ request.getAsyncContext().addListener(new AsyncResultListener(context)); -+ } else { -+ context.stop(); -+ activeRequests.dec(); -+ if (error) { -+ errorsMeter.mark(); - } else { -- metricsRegistry = new MetricRegistry(); -+ markMeterForStatusCode(wrappedResponse.getStatus()); - } -- return metricsRegistry; -+ } -+ } -+ } -+ -+ private void markMeterForStatusCode(int status) { -+ final Meter metric = metersByStatusCode.get(status); -+ if (metric != null) { -+ metric.mark(); -+ } else { -+ otherMeter.mark(); - } -+ } - -- @Override -- public void destroy() { -+ private static class StatusExposingServletResponse extends HttpServletResponseWrapper { -+ // The Servlet spec says: calling setStatus is optional, if no status is set, the default is -+ // 200. -+ private int httpStatus = 200; - -+ public StatusExposingServletResponse(HttpServletResponse response) { -+ super(response); - } - - @Override -- public void doFilter(ServletRequest request, -- ServletResponse response, -- FilterChain chain) throws IOException, ServletException { -- final StatusExposingServletResponse wrappedResponse = -- new StatusExposingServletResponse((HttpServletResponse) response); -- activeRequests.inc(); -- final Timer.Context context = requestTimer.time(); -- boolean error = false; -- try { -- chain.doFilter(request, wrappedResponse); -- } catch (IOException | RuntimeException | ServletException e) { -- error = true; -- throw e; -- } finally { -- if (!error && request.isAsyncStarted()) { -- request.getAsyncContext().addListener(new AsyncResultListener(context)); -- } else { -- context.stop(); -- activeRequests.dec(); -- if (error) { -- errorsMeter.mark(); -- } else { -- markMeterForStatusCode(wrappedResponse.getStatus()); -- } -- } -- } -+ public void sendError(int sc) throws IOException { -+ httpStatus = sc; -+ super.sendError(sc); - } - -- private void markMeterForStatusCode(int status) { -- final Meter metric = metersByStatusCode.get(status); -- if (metric != null) { -- metric.mark(); -- } else { -- otherMeter.mark(); -- } -+ @Override -+ public void sendError(int sc, String msg) throws IOException { -+ httpStatus = sc; -+ super.sendError(sc, msg); - } - -- private static class StatusExposingServletResponse extends HttpServletResponseWrapper { -- // The Servlet spec says: calling setStatus is optional, if no status is set, the default is 200. -- private int httpStatus = 200; -- -- public StatusExposingServletResponse(HttpServletResponse response) { -- super(response); -- } -- -- @Override -- public void sendError(int sc) throws IOException { -- httpStatus = sc; -- super.sendError(sc); -- } -- -- @Override -- public void sendError(int sc, String msg) throws IOException { -- httpStatus = sc; -- super.sendError(sc, msg); -- } -- -- @Override -- public void setStatus(int sc) { -- httpStatus = sc; -- super.setStatus(sc); -- } -- -- @Override -- @SuppressWarnings("deprecation") -- public void setStatus(int sc, String sm) { -- httpStatus = sc; -- super.setStatus(sc, sm); -- } -+ @Override -+ public void setStatus(int sc) { -+ httpStatus = sc; -+ super.setStatus(sc); -+ } - -- @Override -- public int getStatus() { -- return httpStatus; -- } -+ @Override -+ @SuppressWarnings("deprecation") -+ public void setStatus(int sc, String sm) { -+ httpStatus = sc; -+ super.setStatus(sc, sm); - } - -- private class AsyncResultListener implements AsyncListener { -- private Timer.Context context; -- private boolean done = false; -+ @Override -+ public int getStatus() { -+ return httpStatus; -+ } -+ } - -- public AsyncResultListener(Timer.Context context) { -- this.context = context; -- } -+ private class AsyncResultListener implements AsyncListener { -+ private Timer.Context context; -+ private boolean done = false; - -- @Override -- public void onComplete(AsyncEvent event) throws IOException { -- if (!done) { -- HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); -- context.stop(); -- activeRequests.dec(); -- markMeterForStatusCode(suppliedResponse.getStatus()); -- } -- } -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException { -- context.stop(); -- activeRequests.dec(); -- timeoutsMeter.mark(); -- done = true; -- } -+ public AsyncResultListener(Timer.Context context) { -+ this.context = context; -+ } - -- @Override -- public void onError(AsyncEvent event) throws IOException { -- context.stop(); -- activeRequests.dec(); -- errorsMeter.mark(); -- done = true; -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException { -+ if (!done) { -+ HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); -+ context.stop(); -+ activeRequests.dec(); -+ markMeterForStatusCode(suppliedResponse.getStatus()); -+ } -+ } - -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException { -+ context.stop(); -+ activeRequests.dec(); -+ timeoutsMeter.mark(); -+ done = true; -+ } - -- } -+ @Override -+ public void onError(AsyncEvent event) throws IOException { -+ context.stop(); -+ activeRequests.dec(); -+ errorsMeter.mark(); -+ done = true; - } -+ -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException {} -+ } - } ---- a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilter.java -+++ b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilter.java -@@ -4,8 +4,13 @@ import java.util.HashMap; - import java.util.Map; - - /** -- * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response codes -- * to capture information about.

    Use it in your servlet.xml like this:

    -+ * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response -+ * codes to capture information about. -+ * -+ *

    Use it in your servlet.xml like this: -+ * -+ *

    -+ * - *

    {@code
    -  * 
    -  *     instrumentedFilter
    -@@ -18,31 +23,29 @@ import java.util.Map;
    -  * }
    - */ - public class InstrumentedFilter extends AbstractInstrumentedFilter { -- public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; -+ public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; - -- private static final String NAME_PREFIX = "responseCodes."; -- private static final int OK = 200; -- private static final int CREATED = 201; -- private static final int NO_CONTENT = 204; -- private static final int BAD_REQUEST = 400; -- private static final int NOT_FOUND = 404; -- private static final int SERVER_ERROR = 500; -+ private static final String NAME_PREFIX = "responseCodes."; -+ private static final int OK = 200; -+ private static final int CREATED = 201; -+ private static final int NO_CONTENT = 204; -+ private static final int BAD_REQUEST = 400; -+ private static final int NOT_FOUND = 404; -+ private static final int SERVER_ERROR = 500; - -- /** -- * Creates a new instance of the filter. -- */ -- public InstrumentedFilter() { -- super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); -- } -+ /** Creates a new instance of the filter. */ -+ public InstrumentedFilter() { -+ super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); -+ } - -- private static Map createMeterNamesByStatusCode() { -- final Map meterNamesByStatusCode = new HashMap<>(6); -- meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); -- meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); -- meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); -- meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); -- meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); -- meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); -- return meterNamesByStatusCode; -- } -+ private static Map createMeterNamesByStatusCode() { -+ final Map meterNamesByStatusCode = new HashMap<>(6); -+ meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); -+ meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); -+ meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); -+ meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); -+ meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); -+ meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); -+ return meterNamesByStatusCode; -+ } - } ---- a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListener.java -+++ b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListener.java -@@ -10,17 +10,17 @@ import jakarta.servlet.ServletContextListener; - * application. - */ - public abstract class InstrumentedFilterContextListener implements ServletContextListener { -- /** -- * @return the {@link MetricRegistry} to inject into the servlet context. -- */ -- protected abstract MetricRegistry getMetricRegistry(); -+ /** -+ * @return the {@link MetricRegistry} to inject into the servlet context. -+ */ -+ protected abstract MetricRegistry getMetricRegistry(); - -- @Override -- public void contextInitialized(ServletContextEvent sce) { -- sce.getServletContext().setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); -- } -+ @Override -+ public void contextInitialized(ServletContextEvent sce) { -+ sce.getServletContext() -+ .setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); -+ } - -- @Override -- public void contextDestroyed(ServletContextEvent sce) { -- } -+ @Override -+ public void contextDestroyed(ServletContextEvent sce) {} - } ---- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -+++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -@@ -1,32 +1,34 @@ - package io.dropwizard.metrics5.servlet; - -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.MetricRegistry; - import jakarta.servlet.ServletContext; - import jakarta.servlet.ServletContextEvent; - import org.junit.jupiter.api.Test; - --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- --class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final InstrumentedFilterContextListener listener = new InstrumentedFilterContextListener() { -+final class InstrumentedFilterContextListenerTest { -+ private final MetricRegistry registry = mock(); -+ private final InstrumentedFilterContextListener listener = -+ new InstrumentedFilterContextListener() { - @Override - protected MetricRegistry getMetricRegistry() { -- return registry; -+ return registry; - } -- }; -+ }; - -- @Test -- void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ @Test -+ void injectsTheMetricRegistryIntoTheServletContext() { -+ final ServletContext context = mock(); - -- final ServletContextEvent event = mock(ServletContextEvent.class); -- when(event.getServletContext()).thenReturn(context); -+ final ServletContextEvent event = mock(); -+ when(event.getServletContext()).thenReturn(context); - -- listener.contextInitialized(event); -+ listener.contextInitialized(event); - -- verify(context).setAttribute("io.dropwizard.metrics5.servlet.InstrumentedFilter.registry", registry); -- } -+ verify(context) -+ .setAttribute("io.dropwizard.metrics5.servlet.InstrumentedFilter.registry", registry); -+ } - } ---- a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java -+++ b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java -@@ -1,5 +1,8 @@ - package io.dropwizard.metrics5.servlet6; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ -+import com.google.common.base.Strings; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -14,198 +17,190 @@ import jakarta.servlet.ServletRequest; - import jakarta.servlet.ServletResponse; - import jakarta.servlet.http.HttpServletResponse; - import jakarta.servlet.http.HttpServletResponseWrapper; -- - import java.io.IOException; - import java.util.Map; - import java.util.Map.Entry; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.ConcurrentMap; - --import static io.dropwizard.metrics5.MetricRegistry.name; -- - /** - * {@link Filter} implementation which captures request information and a breakdown of the response - * codes being returned. - */ - public abstract class AbstractInstrumentedFilter implements Filter { -- static final String METRIC_PREFIX = "name-prefix"; -- -- private final String otherMetricName; -- private final Map meterNamesByStatusCode; -- private final String registryAttribute; -- -- // initialized after call of init method -- private ConcurrentMap metersByStatusCode; -- private Meter otherMeter; -- private Meter timeoutsMeter; -- private Meter errorsMeter; -- private Counter activeRequests; -- private Timer requestTimer; -- -- -- /** -- * Creates a new instance of the filter. -- * -- * @param registryAttribute the attribute used to look up the metrics registry in the -- * servlet context -- * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are -- * interested in. -- * @param otherMetricName The name used for the catch-all meter. -- */ -- protected AbstractInstrumentedFilter(String registryAttribute, -- Map meterNamesByStatusCode, -- String otherMetricName) { -- this.registryAttribute = registryAttribute; -- this.otherMetricName = otherMetricName; -- this.meterNamesByStatusCode = meterNamesByStatusCode; -+ static final String METRIC_PREFIX = "name-prefix"; -+ -+ private final String otherMetricName; -+ private final Map meterNamesByStatusCode; -+ private final String registryAttribute; -+ -+ // initialized after call of init method -+ private ConcurrentMap metersByStatusCode; -+ private Meter otherMeter; -+ private Meter timeoutsMeter; -+ private Meter errorsMeter; -+ private Counter activeRequests; -+ private Timer requestTimer; -+ -+ /** -+ * Creates a new instance of the filter. -+ * -+ * @param registryAttribute the attribute used to look up the metrics registry in the servlet -+ * context -+ * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are -+ * interested in. -+ * @param otherMetricName The name used for the catch-all meter. -+ */ -+ protected AbstractInstrumentedFilter( -+ String registryAttribute, -+ Map meterNamesByStatusCode, -+ String otherMetricName) { -+ this.registryAttribute = registryAttribute; -+ this.otherMetricName = otherMetricName; -+ this.meterNamesByStatusCode = meterNamesByStatusCode; -+ } -+ -+ @Override -+ public void init(FilterConfig filterConfig) throws ServletException { -+ final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); -+ -+ String metricName = filterConfig.getInitParameter(METRIC_PREFIX); -+ if (Strings.isNullOrEmpty(metricName)) { -+ metricName = getClass().getName(); - } - -- @Override -- public void init(FilterConfig filterConfig) throws ServletException { -- final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); -- -- String metricName = filterConfig.getInitParameter(METRIC_PREFIX); -- if (metricName == null || metricName.isEmpty()) { -- metricName = getClass().getName(); -- } -- -- this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); -- for (Entry entry : meterNamesByStatusCode.entrySet()) { -- metersByStatusCode.put(entry.getKey(), -- metricsRegistry.meter(name(metricName, entry.getValue()))); -- } -- this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); -- this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); -- this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); -- this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); -- this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); -- -+ this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); -+ for (Entry entry : meterNamesByStatusCode.entrySet()) { -+ metersByStatusCode.put( -+ entry.getKey(), metricsRegistry.meter(name(metricName, entry.getValue()))); - } -- -- private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { -- final MetricRegistry metricsRegistry; -- -- final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); -- if (o instanceof MetricRegistry) { -- metricsRegistry = (MetricRegistry) o; -+ this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); -+ this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); -+ this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); -+ this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); -+ this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); -+ } -+ -+ private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { -+ final MetricRegistry metricsRegistry; -+ -+ final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); -+ if (o instanceof MetricRegistry) { -+ metricsRegistry = (MetricRegistry) o; -+ } else { -+ metricsRegistry = new MetricRegistry(); -+ } -+ return metricsRegistry; -+ } -+ -+ @Override -+ public void destroy() {} -+ -+ @Override -+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) -+ throws IOException, ServletException { -+ final StatusExposingServletResponse wrappedResponse = -+ new StatusExposingServletResponse((HttpServletResponse) response); -+ activeRequests.inc(); -+ final Timer.Context context = requestTimer.time(); -+ boolean error = false; -+ try { -+ chain.doFilter(request, wrappedResponse); -+ } catch (IOException | RuntimeException | ServletException e) { -+ error = true; -+ throw e; -+ } finally { -+ if (!error && request.isAsyncStarted()) { -+ request.getAsyncContext().addListener(new AsyncResultListener(context)); -+ } else { -+ context.stop(); -+ activeRequests.dec(); -+ if (error) { -+ errorsMeter.mark(); - } else { -- metricsRegistry = new MetricRegistry(); -+ markMeterForStatusCode(wrappedResponse.getStatus()); - } -- return metricsRegistry; -+ } -+ } -+ } -+ -+ private void markMeterForStatusCode(int status) { -+ final Meter metric = metersByStatusCode.get(status); -+ if (metric != null) { -+ metric.mark(); -+ } else { -+ otherMeter.mark(); - } -+ } - -- @Override -- public void destroy() { -+ private static class StatusExposingServletResponse extends HttpServletResponseWrapper { -+ // The Servlet spec says: calling setStatus is optional, if no status is set, the default is -+ // 200. -+ private int httpStatus = 200; - -+ public StatusExposingServletResponse(HttpServletResponse response) { -+ super(response); - } - - @Override -- public void doFilter(ServletRequest request, -- ServletResponse response, -- FilterChain chain) throws IOException, ServletException { -- final StatusExposingServletResponse wrappedResponse = -- new StatusExposingServletResponse((HttpServletResponse) response); -- activeRequests.inc(); -- final Timer.Context context = requestTimer.time(); -- boolean error = false; -- try { -- chain.doFilter(request, wrappedResponse); -- } catch (IOException | RuntimeException | ServletException e) { -- error = true; -- throw e; -- } finally { -- if (!error && request.isAsyncStarted()) { -- request.getAsyncContext().addListener(new AsyncResultListener(context)); -- } else { -- context.stop(); -- activeRequests.dec(); -- if (error) { -- errorsMeter.mark(); -- } else { -- markMeterForStatusCode(wrappedResponse.getStatus()); -- } -- } -- } -+ public void sendError(int sc) throws IOException { -+ httpStatus = sc; -+ super.sendError(sc); - } - -- private void markMeterForStatusCode(int status) { -- final Meter metric = metersByStatusCode.get(status); -- if (metric != null) { -- metric.mark(); -- } else { -- otherMeter.mark(); -- } -+ @Override -+ public void sendError(int sc, String msg) throws IOException { -+ httpStatus = sc; -+ super.sendError(sc, msg); - } - -- private static class StatusExposingServletResponse extends HttpServletResponseWrapper { -- // The Servlet spec says: calling setStatus is optional, if no status is set, the default is 200. -- private int httpStatus = 200; -- -- public StatusExposingServletResponse(HttpServletResponse response) { -- super(response); -- } -- -- @Override -- public void sendError(int sc) throws IOException { -- httpStatus = sc; -- super.sendError(sc); -- } -- -- @Override -- public void sendError(int sc, String msg) throws IOException { -- httpStatus = sc; -- super.sendError(sc, msg); -- } -- -- @Override -- public void setStatus(int sc) { -- httpStatus = sc; -- super.setStatus(sc); -- } -- -- @Override -- public int getStatus() { -- return httpStatus; -- } -+ @Override -+ public void setStatus(int sc) { -+ httpStatus = sc; -+ super.setStatus(sc); - } - -- private class AsyncResultListener implements AsyncListener { -- private final Timer.Context context; -- private boolean done = false; -- -- public AsyncResultListener(Timer.Context context) { -- this.context = context; -- } -+ @Override -+ public int getStatus() { -+ return httpStatus; -+ } -+ } - -- @Override -- public void onComplete(AsyncEvent event) throws IOException { -- if (!done) { -- HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); -- context.stop(); -- activeRequests.dec(); -- markMeterForStatusCode(suppliedResponse.getStatus()); -- } -- } -+ private class AsyncResultListener implements AsyncListener { -+ private final Timer.Context context; -+ private boolean done = false; - -- @Override -- public void onTimeout(AsyncEvent event) throws IOException { -- context.stop(); -- activeRequests.dec(); -- timeoutsMeter.mark(); -- done = true; -- } -+ public AsyncResultListener(Timer.Context context) { -+ this.context = context; -+ } - -- @Override -- public void onError(AsyncEvent event) throws IOException { -- context.stop(); -- activeRequests.dec(); -- errorsMeter.mark(); -- done = true; -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException { -+ if (!done) { -+ HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); -+ context.stop(); -+ activeRequests.dec(); -+ markMeterForStatusCode(suppliedResponse.getStatus()); -+ } -+ } - -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException { -+ context.stop(); -+ activeRequests.dec(); -+ timeoutsMeter.mark(); -+ done = true; -+ } - -- } -+ @Override -+ public void onError(AsyncEvent event) throws IOException { -+ context.stop(); -+ activeRequests.dec(); -+ errorsMeter.mark(); -+ done = true; - } -+ -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException {} -+ } - } ---- a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/InstrumentedFilter.java -+++ b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/InstrumentedFilter.java -@@ -4,8 +4,13 @@ import java.util.HashMap; - import java.util.Map; - - /** -- * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response codes -- * to capture information about.

    Use it in your servlet.xml like this:

    -+ * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response -+ * codes to capture information about. -+ * -+ *

    Use it in your servlet.xml like this: -+ * -+ *

    -+ * - *

    {@code
    -  * 
    -  *     instrumentedFilter
    -@@ -18,31 +23,29 @@ import java.util.Map;
    -  * }
    - */ - public class InstrumentedFilter extends AbstractInstrumentedFilter { -- public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; -+ public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; - -- private static final String NAME_PREFIX = "responseCodes."; -- private static final int OK = 200; -- private static final int CREATED = 201; -- private static final int NO_CONTENT = 204; -- private static final int BAD_REQUEST = 400; -- private static final int NOT_FOUND = 404; -- private static final int SERVER_ERROR = 500; -+ private static final String NAME_PREFIX = "responseCodes."; -+ private static final int OK = 200; -+ private static final int CREATED = 201; -+ private static final int NO_CONTENT = 204; -+ private static final int BAD_REQUEST = 400; -+ private static final int NOT_FOUND = 404; -+ private static final int SERVER_ERROR = 500; - -- /** -- * Creates a new instance of the filter. -- */ -- public InstrumentedFilter() { -- super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); -- } -+ /** Creates a new instance of the filter. */ -+ public InstrumentedFilter() { -+ super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); -+ } - -- private static Map createMeterNamesByStatusCode() { -- final Map meterNamesByStatusCode = new HashMap<>(6); -- meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); -- meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); -- meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); -- meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); -- meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); -- meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); -- return meterNamesByStatusCode; -- } -+ private static Map createMeterNamesByStatusCode() { -+ final Map meterNamesByStatusCode = new HashMap<>(6); -+ meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); -+ meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); -+ meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); -+ meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); -+ meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); -+ meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); -+ return meterNamesByStatusCode; -+ } - } ---- a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListener.java -+++ b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListener.java -@@ -10,17 +10,17 @@ import jakarta.servlet.ServletContextListener; - * application. - */ - public abstract class InstrumentedFilterContextListener implements ServletContextListener { -- /** -- * @return the {@link MetricRegistry} to inject into the servlet context. -- */ -- protected abstract MetricRegistry getMetricRegistry(); -+ /** -+ * @return the {@link MetricRegistry} to inject into the servlet context. -+ */ -+ protected abstract MetricRegistry getMetricRegistry(); - -- @Override -- public void contextInitialized(ServletContextEvent sce) { -- sce.getServletContext().setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); -- } -+ @Override -+ public void contextInitialized(ServletContextEvent sce) { -+ sce.getServletContext() -+ .setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); -+ } - -- @Override -- public void contextDestroyed(ServletContextEvent sce) { -- } -+ @Override -+ public void contextDestroyed(ServletContextEvent sce) {} - } ---- a/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java -+++ b/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java -@@ -1,32 +1,34 @@ - package io.dropwizard.metrics5.servlet6; - -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.MetricRegistry; - import jakarta.servlet.ServletContext; - import jakarta.servlet.ServletContextEvent; - import org.junit.jupiter.api.Test; - --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- --class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final InstrumentedFilterContextListener listener = new InstrumentedFilterContextListener() { -+final class InstrumentedFilterContextListenerTest { -+ private final MetricRegistry registry = mock(); -+ private final InstrumentedFilterContextListener listener = -+ new InstrumentedFilterContextListener() { - @Override - protected MetricRegistry getMetricRegistry() { -- return registry; -+ return registry; - } -- }; -+ }; - -- @Test -- void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ @Test -+ void injectsTheMetricRegistryIntoTheServletContext() { -+ final ServletContext context = mock(); - -- final ServletContextEvent event = mock(ServletContextEvent.class); -- when(event.getServletContext()).thenReturn(context); -+ final ServletContextEvent event = mock(); -+ when(event.getServletContext()).thenReturn(context); - -- listener.contextInitialized(event); -+ listener.contextInitialized(event); - -- verify(context).setAttribute("io.dropwizard.metrics5.servlet6.InstrumentedFilter.registry", registry); -- } -+ verify(context) -+ .setAttribute("io.dropwizard.metrics5.servlet6.InstrumentedFilter.registry", registry); -+ } - } ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/AdminServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/AdminServlet.java -@@ -6,185 +6,205 @@ import jakarta.servlet.ServletException; - import jakarta.servlet.http.HttpServlet; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; -- - import java.io.IOException; - import java.io.PrintWriter; - import java.text.MessageFormat; - - public class AdminServlet extends HttpServlet { -- public static final String DEFAULT_HEALTHCHECK_URI = "/healthcheck"; -- public static final String DEFAULT_METRICS_URI = "/metrics"; -- public static final String DEFAULT_PING_URI = "/ping"; -- public static final String DEFAULT_THREADS_URI = "/threads"; -- public static final String DEFAULT_CPU_PROFILE_URI = "/pprof"; -- -- public static final String METRICS_ENABLED_PARAM_KEY = "metrics-enabled"; -- public static final String METRICS_URI_PARAM_KEY = "metrics-uri"; -- public static final String PING_ENABLED_PARAM_KEY = "ping-enabled"; -- public static final String PING_URI_PARAM_KEY = "ping-uri"; -- public static final String THREADS_ENABLED_PARAM_KEY = "threads-enabled"; -- public static final String THREADS_URI_PARAM_KEY = "threads-uri"; -- public static final String HEALTHCHECK_ENABLED_PARAM_KEY = "healthcheck-enabled"; -- public static final String HEALTHCHECK_URI_PARAM_KEY = "healthcheck-uri"; -- public static final String SERVICE_NAME_PARAM_KEY = "service-name"; -- public static final String CPU_PROFILE_ENABLED_PARAM_KEY = "cpu-profile-enabled"; -- public static final String CPU_PROFILE_URI_PARAM_KEY = "cpu-profile-uri"; -- -- private static final String BASE_TEMPLATE = -- "%n" + -- "%n" + -- "%n" + -- " Metrics{10}%n" + -- "%n" + -- "%n" + -- "

    Operational Menu{10}

    %n" + -- "
      %n" + -- "%s" + -- "
    %n" + -- "%n" + -- ""; -- private static final String METRICS_LINK = "
  • Metrics
  • %n"; -- private static final String PING_LINK = "
  • Ping
  • %n" ; -- private static final String THREADS_LINK = "
  • Threads
  • %n" ; -- private static final String HEALTHCHECK_LINK = "
  • Healthcheck
  • %n" ; -- private static final String CPU_PROFILE_LINK = "
  • CPU Profile
  • %n" + -- "
  • CPU Contention
  • %n"; -- -- -- private static final String CONTENT_TYPE = "text/html"; -- private static final long serialVersionUID = -2850794040708785318L; -- -- private transient HealthCheckServlet healthCheckServlet; -- private transient MetricsServlet metricsServlet; -- private transient PingServlet pingServlet; -- private transient ThreadDumpServlet threadDumpServlet; -- private transient CpuProfileServlet cpuProfileServlet; -- private transient boolean metricsEnabled; -- private transient String metricsUri; -- private transient boolean pingEnabled; -- private transient String pingUri; -- private transient boolean threadsEnabled; -- private transient String threadsUri; -- private transient boolean healthcheckEnabled; -- private transient String healthcheckUri; -- private transient boolean cpuProfileEnabled; -- private transient String cpuProfileUri; -- private transient String serviceName; -- private transient String pageContentTemplate; -- -- @Override -- public void init(ServletConfig config) throws ServletException { -- super.init(config); -- -- final ServletContext context = config.getServletContext(); -- final StringBuilder servletLinks = new StringBuilder(); -- -- this.metricsEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(METRICS_ENABLED_PARAM_KEY), "true")); -- if (this.metricsEnabled) { -- servletLinks.append(METRICS_LINK); -- } -- this.metricsServlet = new MetricsServlet(); -- metricsServlet.init(config); -- -- this.pingEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(PING_ENABLED_PARAM_KEY), "true")); -- if (this.pingEnabled) { -- servletLinks.append(PING_LINK); -- } -- this.pingServlet = new PingServlet(); -- pingServlet.init(config); -- -- this.threadsEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(THREADS_ENABLED_PARAM_KEY), "true")); -- if (this.threadsEnabled) { -- servletLinks.append(THREADS_LINK); -- } -- this.threadDumpServlet = new ThreadDumpServlet(); -- threadDumpServlet.init(config); -- -- this.healthcheckEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(HEALTHCHECK_ENABLED_PARAM_KEY), "true")); -- if (this.healthcheckEnabled) { -- servletLinks.append(HEALTHCHECK_LINK); -- } -- this.healthCheckServlet = new HealthCheckServlet(); -- healthCheckServlet.init(config); -- -- this.cpuProfileEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(CPU_PROFILE_ENABLED_PARAM_KEY), "true")); -- if (this.cpuProfileEnabled) { -- servletLinks.append(CPU_PROFILE_LINK); -- } -- this.cpuProfileServlet = new CpuProfileServlet(); -- cpuProfileServlet.init(config); -- -- pageContentTemplate = String.format(BASE_TEMPLATE, String.format(servletLinks.toString())); -- -- this.metricsUri = getParam(context.getInitParameter(METRICS_URI_PARAM_KEY), DEFAULT_METRICS_URI); -- this.pingUri = getParam(context.getInitParameter(PING_URI_PARAM_KEY), DEFAULT_PING_URI); -- this.threadsUri = getParam(context.getInitParameter(THREADS_URI_PARAM_KEY), DEFAULT_THREADS_URI); -- this.healthcheckUri = getParam(context.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI); -- this.cpuProfileUri = getParam(context.getInitParameter(CPU_PROFILE_URI_PARAM_KEY), DEFAULT_CPU_PROFILE_URI); -- this.serviceName = getParam(context.getInitParameter(SERVICE_NAME_PARAM_KEY), null); -+ public static final String DEFAULT_HEALTHCHECK_URI = "/healthcheck"; -+ public static final String DEFAULT_METRICS_URI = "/metrics"; -+ public static final String DEFAULT_PING_URI = "/ping"; -+ public static final String DEFAULT_THREADS_URI = "/threads"; -+ public static final String DEFAULT_CPU_PROFILE_URI = "/pprof"; -+ -+ public static final String METRICS_ENABLED_PARAM_KEY = "metrics-enabled"; -+ public static final String METRICS_URI_PARAM_KEY = "metrics-uri"; -+ public static final String PING_ENABLED_PARAM_KEY = "ping-enabled"; -+ public static final String PING_URI_PARAM_KEY = "ping-uri"; -+ public static final String THREADS_ENABLED_PARAM_KEY = "threads-enabled"; -+ public static final String THREADS_URI_PARAM_KEY = "threads-uri"; -+ public static final String HEALTHCHECK_ENABLED_PARAM_KEY = "healthcheck-enabled"; -+ public static final String HEALTHCHECK_URI_PARAM_KEY = "healthcheck-uri"; -+ public static final String SERVICE_NAME_PARAM_KEY = "service-name"; -+ public static final String CPU_PROFILE_ENABLED_PARAM_KEY = "cpu-profile-enabled"; -+ public static final String CPU_PROFILE_URI_PARAM_KEY = "cpu-profile-uri"; -+ -+ private static final String BASE_TEMPLATE = -+ "%n" -+ + "%n" -+ + "%n" -+ + " Metrics{10}%n" -+ + "%n" -+ + "%n" -+ + "

    Operational Menu{10}

    %n" -+ + "
      %n" -+ + "%s" -+ + "
    %n" -+ + "%n" -+ + ""; -+ private static final String METRICS_LINK = -+ "
  • Metrics
  • %n"; -+ private static final String PING_LINK = "
  • Ping
  • %n"; -+ private static final String THREADS_LINK = "
  • Threads
  • %n"; -+ private static final String HEALTHCHECK_LINK = -+ "
  • Healthcheck
  • %n"; -+ private static final String CPU_PROFILE_LINK = -+ "
  • CPU Profile
  • %n" -+ + "
  • CPU Contention
  • %n"; -+ -+ private static final String CONTENT_TYPE = "text/html"; -+ private static final long serialVersionUID = -2850794040708785318L; -+ -+ private transient HealthCheckServlet healthCheckServlet; -+ private transient MetricsServlet metricsServlet; -+ private transient PingServlet pingServlet; -+ private transient ThreadDumpServlet threadDumpServlet; -+ private transient CpuProfileServlet cpuProfileServlet; -+ private transient boolean metricsEnabled; -+ private transient String metricsUri; -+ private transient boolean pingEnabled; -+ private transient String pingUri; -+ private transient boolean threadsEnabled; -+ private transient String threadsUri; -+ private transient boolean healthcheckEnabled; -+ private transient String healthcheckUri; -+ private transient boolean cpuProfileEnabled; -+ private transient String cpuProfileUri; -+ private transient String serviceName; -+ private transient String pageContentTemplate; -+ -+ @Override -+ public void init(ServletConfig config) throws ServletException { -+ super.init(config); -+ -+ final ServletContext context = config.getServletContext(); -+ final StringBuilder servletLinks = new StringBuilder(); -+ -+ this.metricsEnabled = -+ Boolean.parseBoolean(getParam(context.getInitParameter(METRICS_ENABLED_PARAM_KEY), "true")); -+ if (this.metricsEnabled) { -+ servletLinks.append(METRICS_LINK); - } -+ this.metricsServlet = new MetricsServlet(); -+ metricsServlet.init(config); - -- @Override -- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { -- final String path = req.getContextPath() + req.getServletPath(); -- -- resp.setStatus(HttpServletResponse.SC_OK); -- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -- resp.setContentType(CONTENT_TYPE); -- try (PrintWriter writer = resp.getWriter()) { -- writer.println(MessageFormat.format(pageContentTemplate, path, metricsUri, path, pingUri, path, -- threadsUri, path, healthcheckUri, path, cpuProfileUri, -- serviceName == null ? "" : " (" + serviceName + ")")); -- } -+ this.pingEnabled = -+ Boolean.parseBoolean(getParam(context.getInitParameter(PING_ENABLED_PARAM_KEY), "true")); -+ if (this.pingEnabled) { -+ servletLinks.append(PING_LINK); - } -+ this.pingServlet = new PingServlet(); -+ pingServlet.init(config); - -- @Override -- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { -- final String uri = req.getPathInfo(); -- if (uri == null || uri.equals("/")) { -- super.service(req, resp); -- } else if (uri.equals(healthcheckUri)) { -- if (healthcheckEnabled) { -- healthCheckServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else if (uri.startsWith(metricsUri)) { -- if (metricsEnabled) { -- metricsServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else if (uri.equals(pingUri)) { -- if (pingEnabled) { -- pingServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else if (uri.equals(threadsUri)) { -- if (threadsEnabled) { -- threadDumpServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else if (uri.equals(cpuProfileUri)) { -- if (cpuProfileEnabled) { -- cpuProfileServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -+ this.threadsEnabled = -+ Boolean.parseBoolean(getParam(context.getInitParameter(THREADS_ENABLED_PARAM_KEY), "true")); -+ if (this.threadsEnabled) { -+ servletLinks.append(THREADS_LINK); - } -- -- private static String getParam(String initParam, String defaultValue) { -- return initParam == null ? defaultValue : initParam; -+ this.threadDumpServlet = new ThreadDumpServlet(); -+ threadDumpServlet.init(config); -+ -+ this.healthcheckEnabled = -+ Boolean.parseBoolean( -+ getParam(context.getInitParameter(HEALTHCHECK_ENABLED_PARAM_KEY), "true")); -+ if (this.healthcheckEnabled) { -+ servletLinks.append(HEALTHCHECK_LINK); -+ } -+ this.healthCheckServlet = new HealthCheckServlet(); -+ healthCheckServlet.init(config); -+ -+ this.cpuProfileEnabled = -+ Boolean.parseBoolean( -+ getParam(context.getInitParameter(CPU_PROFILE_ENABLED_PARAM_KEY), "true")); -+ if (this.cpuProfileEnabled) { -+ servletLinks.append(CPU_PROFILE_LINK); - } -+ this.cpuProfileServlet = new CpuProfileServlet(); -+ cpuProfileServlet.init(config); -+ -+ pageContentTemplate = String.format(BASE_TEMPLATE, String.format(servletLinks.toString())); -+ -+ this.metricsUri = -+ getParam(context.getInitParameter(METRICS_URI_PARAM_KEY), DEFAULT_METRICS_URI); -+ this.pingUri = getParam(context.getInitParameter(PING_URI_PARAM_KEY), DEFAULT_PING_URI); -+ this.threadsUri = -+ getParam(context.getInitParameter(THREADS_URI_PARAM_KEY), DEFAULT_THREADS_URI); -+ this.healthcheckUri = -+ getParam(context.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI); -+ this.cpuProfileUri = -+ getParam(context.getInitParameter(CPU_PROFILE_URI_PARAM_KEY), DEFAULT_CPU_PROFILE_URI); -+ this.serviceName = getParam(context.getInitParameter(SERVICE_NAME_PARAM_KEY), null); -+ } -+ -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ final String path = req.getContextPath() + req.getServletPath(); -+ -+ resp.setStatus(HttpServletResponse.SC_OK); -+ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -+ resp.setContentType(CONTENT_TYPE); -+ try (PrintWriter writer = resp.getWriter()) { -+ writer.println( -+ MessageFormat.format( -+ pageContentTemplate, -+ path, -+ metricsUri, -+ path, -+ pingUri, -+ path, -+ threadsUri, -+ path, -+ healthcheckUri, -+ path, -+ cpuProfileUri, -+ serviceName == null ? "" : " (" + serviceName + ")")); -+ } -+ } -+ -+ @Override -+ protected void service(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ final String uri = req.getPathInfo(); -+ if (uri == null || uri.equals("/")) { -+ super.service(req, resp); -+ } else if (uri.equals(healthcheckUri)) { -+ if (healthcheckEnabled) { -+ healthCheckServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else if (uri.startsWith(metricsUri)) { -+ if (metricsEnabled) { -+ metricsServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else if (uri.equals(pingUri)) { -+ if (pingEnabled) { -+ pingServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else if (uri.equals(threadsUri)) { -+ if (threadsEnabled) { -+ threadDumpServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else if (uri.equals(cpuProfileUri)) { -+ if (cpuProfileEnabled) { -+ cpuProfileServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } -+ -+ private static String getParam(String initParam, String defaultValue) { -+ return initParam == null ? defaultValue : initParam; -+ } - } ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java -@@ -5,7 +5,6 @@ import jakarta.servlet.ServletException; - import jakarta.servlet.http.HttpServlet; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; -- - import java.io.IOException; - import java.io.OutputStream; - import java.time.Duration; -@@ -13,67 +12,68 @@ import java.util.concurrent.locks.Lock; - import java.util.concurrent.locks.ReentrantLock; - - /** -- * An HTTP servlets which outputs a pprof parseable response. -+ * An HTTP servlets which outputs a pprof -+ * parseable response. - */ - public class CpuProfileServlet extends HttpServlet { -- private static final long serialVersionUID = -668666696530287501L; -- private static final String CONTENT_TYPE = "pprof/raw"; -- private static final String CACHE_CONTROL = "Cache-Control"; -- private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; -- private final Lock lock = new ReentrantLock(); -+ private static final long serialVersionUID = -668666696530287501L; -+ private static final String CONTENT_TYPE = "pprof/raw"; -+ private static final String CACHE_CONTROL = "Cache-Control"; -+ private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; -+ private final Lock lock = new ReentrantLock(); - -- @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { - -- int duration = 10; -- if (req.getParameter("duration") != null) { -- try { -- duration = Integer.parseInt(req.getParameter("duration")); -- } catch (NumberFormatException e) { -- duration = 10; -- } -- } -+ int duration = 10; -+ if (req.getParameter("duration") != null) { -+ try { -+ duration = Integer.parseInt(req.getParameter("duration")); -+ } catch (NumberFormatException e) { -+ duration = 10; -+ } -+ } - -- int frequency = 100; -- if (req.getParameter("frequency") != null) { -- try { -- frequency = Integer.parseInt(req.getParameter("frequency")); -- frequency = Math.min(Math.max(frequency, 1), 1000); -- } catch (NumberFormatException e) { -- frequency = 100; -- } -- } -+ int frequency = 100; -+ if (req.getParameter("frequency") != null) { -+ try { -+ frequency = Integer.parseInt(req.getParameter("frequency")); -+ frequency = Math.min(Math.max(frequency, 1), 1000); -+ } catch (NumberFormatException e) { -+ frequency = 100; -+ } -+ } - -- final Thread.State state; -- if ("blocked".equalsIgnoreCase(req.getParameter("state"))) { -- state = Thread.State.BLOCKED; -- } else { -- state = Thread.State.RUNNABLE; -- } -+ final Thread.State state; -+ if ("blocked".equalsIgnoreCase(req.getParameter("state"))) { -+ state = Thread.State.BLOCKED; -+ } else { -+ state = Thread.State.RUNNABLE; -+ } - -- resp.setStatus(HttpServletResponse.SC_OK); -- resp.setHeader(CACHE_CONTROL, NO_CACHE); -- resp.setContentType(CONTENT_TYPE); -- try (OutputStream output = resp.getOutputStream()) { -- doProfile(output, duration, frequency, state); -- } -+ resp.setStatus(HttpServletResponse.SC_OK); -+ resp.setHeader(CACHE_CONTROL, NO_CACHE); -+ resp.setContentType(CONTENT_TYPE); -+ try (OutputStream output = resp.getOutputStream()) { -+ doProfile(output, duration, frequency, state); - } -+ } - -- protected void doProfile(OutputStream out, int duration, int frequency, Thread.State state) throws IOException { -- if (lock.tryLock()) { -- try { -- CpuProfile profile = CpuProfile.record(Duration.ofSeconds(duration), -- frequency, state); -- if (profile == null) { -- throw new RuntimeException("could not create CpuProfile"); -- } -- profile.writeGoogleProfile(out); -- return; -- } finally { -- lock.unlock(); -- } -+ protected void doProfile(OutputStream out, int duration, int frequency, Thread.State state) -+ throws IOException { -+ if (lock.tryLock()) { -+ try { -+ CpuProfile profile = CpuProfile.record(Duration.ofSeconds(duration), frequency, state); -+ if (profile == null) { -+ throw new RuntimeException("could not create CpuProfile"); - } -- throw new RuntimeException("Only one profile request may be active at a time"); -+ profile.writeGoogleProfile(out); -+ return; -+ } finally { -+ lock.unlock(); -+ } - } -+ throw new RuntimeException("Only one profile request may be active at a time"); -+ } - } ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -@@ -1,11 +1,11 @@ - package io.dropwizard.metrics5.servlets; - -+import com.fasterxml.jackson.databind.ObjectMapper; -+import com.fasterxml.jackson.databind.ObjectWriter; - import io.dropwizard.metrics5.health.HealthCheck; - import io.dropwizard.metrics5.health.HealthCheckFilter; - import io.dropwizard.metrics5.health.HealthCheckRegistry; - import io.dropwizard.metrics5.json.HealthCheckModule; --import com.fasterxml.jackson.databind.ObjectMapper; --import com.fasterxml.jackson.databind.ObjectWriter; - import jakarta.servlet.ServletConfig; - import jakarta.servlet.ServletContext; - import jakarta.servlet.ServletContextEvent; -@@ -14,7 +14,6 @@ import jakarta.servlet.ServletException; - import jakarta.servlet.http.HttpServlet; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; -- - import java.io.IOException; - import java.io.OutputStream; - import java.util.Map; -@@ -22,175 +21,179 @@ import java.util.SortedMap; - import java.util.concurrent.ExecutorService; - - public class HealthCheckServlet extends HttpServlet { -- public static abstract class ContextListener implements ServletContextListener { -- /** -- * @return the {@link HealthCheckRegistry} to inject into the servlet context. -- */ -- protected abstract HealthCheckRegistry getHealthCheckRegistry(); -- -- /** -- * @return the {@link ExecutorService} to inject into the servlet context, or {@code null} -- * if the health checks should be run in the servlet worker thread. -- */ -- protected ExecutorService getExecutorService() { -- // don't use a thread pool by default -- return null; -- } -- -- /** -- * @return the {@link HealthCheckFilter} that shall be used to filter health checks, -- * or {@link HealthCheckFilter#ALL} if the default should be used. -- */ -- protected HealthCheckFilter getHealthCheckFilter() { -- return HealthCheckFilter.ALL; -- } -- -- /** -- * @return the {@link ObjectMapper} that shall be used to render health checks, -- * or {@code null} if the default object mapper should be used. -- */ -- protected ObjectMapper getObjectMapper() { -- // don't use an object mapper by default -- return null; -- } -- -- @Override -- public void contextInitialized(ServletContextEvent event) { -- final ServletContext context = event.getServletContext(); -- context.setAttribute(HEALTH_CHECK_REGISTRY, getHealthCheckRegistry()); -- context.setAttribute(HEALTH_CHECK_EXECUTOR, getExecutorService()); -- context.setAttribute(HEALTH_CHECK_MAPPER, getObjectMapper()); -- } -- -- @Override -- public void contextDestroyed(ServletContextEvent event) { -- // no-op -- } -- } -- -- public static final String HEALTH_CHECK_REGISTRY = HealthCheckServlet.class.getCanonicalName() + ".registry"; -- public static final String HEALTH_CHECK_EXECUTOR = HealthCheckServlet.class.getCanonicalName() + ".executor"; -- public static final String HEALTH_CHECK_FILTER = HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter"; -- public static final String HEALTH_CHECK_MAPPER = HealthCheckServlet.class.getCanonicalName() + ".mapper"; -- public static final String HEALTH_CHECK_HTTP_STATUS_INDICATOR = HealthCheckServlet.class.getCanonicalName() + ".httpStatusIndicator"; -- -- private static final long serialVersionUID = -8432996484889177321L; -- private static final String CONTENT_TYPE = "application/json"; -- private static final String HTTP_STATUS_INDICATOR_PARAM = "httpStatusIndicator"; -- -- private transient HealthCheckRegistry registry; -- private transient ExecutorService executorService; -- private transient HealthCheckFilter filter; -- private transient ObjectMapper mapper; -- private transient boolean httpStatusIndicator; -- -- public HealthCheckServlet() { -- } -- -- public HealthCheckServlet(HealthCheckRegistry registry) { -- this.registry = registry; -+ public abstract static class ContextListener implements ServletContextListener { -+ /** -+ * @return the {@link HealthCheckRegistry} to inject into the servlet context. -+ */ -+ protected abstract HealthCheckRegistry getHealthCheckRegistry(); -+ -+ /** -+ * @return the {@link ExecutorService} to inject into the servlet context, or {@code null} if -+ * the health checks should be run in the servlet worker thread. -+ */ -+ protected ExecutorService getExecutorService() { -+ // don't use a thread pool by default -+ return null; - } - -- @Override -- public void init(ServletConfig config) throws ServletException { -- super.init(config); -- -- final ServletContext context = config.getServletContext(); -- if (null == registry) { -- final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); -- if (registryAttr instanceof HealthCheckRegistry) { -- this.registry = (HealthCheckRegistry) registryAttr; -- } else { -- throw new ServletException("Couldn't find a HealthCheckRegistry instance."); -- } -- } -- -- final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR); -- if (executorAttr instanceof ExecutorService) { -- this.executorService = (ExecutorService) executorAttr; -- } -- -- -- final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER); -- if (filterAttr instanceof HealthCheckFilter) { -- filter = (HealthCheckFilter) filterAttr; -- } -- if (filter == null) { -- filter = HealthCheckFilter.ALL; -- } -- -- final Object mapperAttr = context.getAttribute(HEALTH_CHECK_MAPPER); -- if (mapperAttr instanceof ObjectMapper) { -- this.mapper = (ObjectMapper) mapperAttr; -- } else { -- this.mapper = new ObjectMapper(); -- } -- this.mapper.registerModule(new HealthCheckModule()); -- -- final Object httpStatusIndicatorAttr = context.getAttribute(HEALTH_CHECK_HTTP_STATUS_INDICATOR); -- if (httpStatusIndicatorAttr instanceof Boolean) { -- this.httpStatusIndicator = (Boolean) httpStatusIndicatorAttr; -- } else { -- this.httpStatusIndicator = true; -- } -+ /** -+ * @return the {@link HealthCheckFilter} that shall be used to filter health checks, or {@link -+ * HealthCheckFilter#ALL} if the default should be used. -+ */ -+ protected HealthCheckFilter getHealthCheckFilter() { -+ return HealthCheckFilter.ALL; -+ } -+ -+ /** -+ * @return the {@link ObjectMapper} that shall be used to render health checks, or {@code null} -+ * if the default object mapper should be used. -+ */ -+ protected ObjectMapper getObjectMapper() { -+ // don't use an object mapper by default -+ return null; - } - - @Override -- public void destroy() { -- super.destroy(); -- registry.shutdown(); -+ public void contextInitialized(ServletContextEvent event) { -+ final ServletContext context = event.getServletContext(); -+ context.setAttribute(HEALTH_CHECK_REGISTRY, getHealthCheckRegistry()); -+ context.setAttribute(HEALTH_CHECK_EXECUTOR, getExecutorService()); -+ context.setAttribute(HEALTH_CHECK_MAPPER, getObjectMapper()); - } - - @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -- final SortedMap results = runHealthChecks(); -- resp.setContentType(CONTENT_TYPE); -- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -- if (results.isEmpty()) { -- resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); -- } else { -- final String reqParameter = req.getParameter(HTTP_STATUS_INDICATOR_PARAM); -- final boolean httpStatusIndicatorParam = Boolean.parseBoolean(reqParameter); -- final boolean useHttpStatusForHealthCheck = reqParameter == null ? httpStatusIndicator : httpStatusIndicatorParam; -- if (!useHttpStatusForHealthCheck || isAllHealthy(results)) { -- resp.setStatus(HttpServletResponse.SC_OK); -- } else { -- resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); -- } -- } -- -- try (OutputStream output = resp.getOutputStream()) { -- getWriter(req).writeValue(output, results); -- } -- } -- -- private ObjectWriter getWriter(HttpServletRequest request) { -- final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); -- if (prettyPrint) { -- return mapper.writerWithDefaultPrettyPrinter(); -- } -- return mapper.writer(); -- } -- -- private SortedMap runHealthChecks() { -- if (executorService == null) { -- return registry.runHealthChecks(filter); -- } -- return registry.runHealthChecks(executorService, filter); -- } -- -- private static boolean isAllHealthy(Map results) { -- for (HealthCheck.Result result : results.values()) { -- if (!result.isHealthy()) { -- return false; -- } -- } -- return true; -- } -- -- // visible for testing -- ObjectMapper getMapper() { -- return mapper; -+ public void contextDestroyed(ServletContextEvent event) { -+ // no-op -+ } -+ } -+ -+ public static final String HEALTH_CHECK_REGISTRY = -+ HealthCheckServlet.class.getCanonicalName() + ".registry"; -+ public static final String HEALTH_CHECK_EXECUTOR = -+ HealthCheckServlet.class.getCanonicalName() + ".executor"; -+ public static final String HEALTH_CHECK_FILTER = -+ HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter"; -+ public static final String HEALTH_CHECK_MAPPER = -+ HealthCheckServlet.class.getCanonicalName() + ".mapper"; -+ public static final String HEALTH_CHECK_HTTP_STATUS_INDICATOR = -+ HealthCheckServlet.class.getCanonicalName() + ".httpStatusIndicator"; -+ -+ private static final long serialVersionUID = -8432996484889177321L; -+ private static final String CONTENT_TYPE = "application/json"; -+ private static final String HTTP_STATUS_INDICATOR_PARAM = "httpStatusIndicator"; -+ -+ private transient HealthCheckRegistry registry; -+ private transient ExecutorService executorService; -+ private transient HealthCheckFilter filter; -+ private transient ObjectMapper mapper; -+ private transient boolean httpStatusIndicator; -+ -+ public HealthCheckServlet() {} -+ -+ public HealthCheckServlet(HealthCheckRegistry registry) { -+ this.registry = registry; -+ } -+ -+ @Override -+ public void init(ServletConfig config) throws ServletException { -+ super.init(config); -+ -+ final ServletContext context = config.getServletContext(); -+ if (registry == null) { -+ final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); -+ if (registryAttr instanceof HealthCheckRegistry) { -+ this.registry = (HealthCheckRegistry) registryAttr; -+ } else { -+ throw new ServletException("Couldn't find a HealthCheckRegistry instance."); -+ } -+ } -+ -+ final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR); -+ if (executorAttr instanceof ExecutorService) { -+ this.executorService = (ExecutorService) executorAttr; -+ } -+ -+ final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER); -+ if (filterAttr instanceof HealthCheckFilter) { -+ filter = (HealthCheckFilter) filterAttr; -+ } -+ if (filter == null) { -+ filter = HealthCheckFilter.ALL; - } -+ -+ final Object mapperAttr = context.getAttribute(HEALTH_CHECK_MAPPER); -+ if (mapperAttr instanceof ObjectMapper) { -+ this.mapper = (ObjectMapper) mapperAttr; -+ } else { -+ this.mapper = new ObjectMapper(); -+ } -+ this.mapper.registerModule(new HealthCheckModule()); -+ -+ final Object httpStatusIndicatorAttr = context.getAttribute(HEALTH_CHECK_HTTP_STATUS_INDICATOR); -+ if (httpStatusIndicatorAttr instanceof Boolean) { -+ this.httpStatusIndicator = (Boolean) httpStatusIndicatorAttr; -+ } else { -+ this.httpStatusIndicator = true; -+ } -+ } -+ -+ @Override -+ public void destroy() { -+ super.destroy(); -+ registry.shutdown(); -+ } -+ -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ final SortedMap results = runHealthChecks(); -+ resp.setContentType(CONTENT_TYPE); -+ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -+ if (results.isEmpty()) { -+ resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); -+ } else { -+ final String reqParameter = req.getParameter(HTTP_STATUS_INDICATOR_PARAM); -+ final boolean httpStatusIndicatorParam = Boolean.parseBoolean(reqParameter); -+ final boolean useHttpStatusForHealthCheck = -+ reqParameter == null ? httpStatusIndicator : httpStatusIndicatorParam; -+ if (!useHttpStatusForHealthCheck || isAllHealthy(results)) { -+ resp.setStatus(HttpServletResponse.SC_OK); -+ } else { -+ resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); -+ } -+ } -+ -+ try (OutputStream output = resp.getOutputStream()) { -+ getWriter(req).writeValue(output, results); -+ } -+ } -+ -+ private ObjectWriter getWriter(HttpServletRequest request) { -+ final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); -+ if (prettyPrint) { -+ return mapper.writerWithDefaultPrettyPrinter(); -+ } -+ return mapper.writer(); -+ } -+ -+ private SortedMap runHealthChecks() { -+ if (executorService == null) { -+ return registry.runHealthChecks(filter); -+ } -+ return registry.runHealthChecks(executorService, filter); -+ } -+ -+ private static boolean isAllHealthy(Map results) { -+ for (HealthCheck.Result result : results.values()) { -+ if (!result.isHealthy()) { -+ return false; -+ } -+ } -+ return true; -+ } -+ -+ // visible for testing -+ ObjectMapper getMapper() { -+ return mapper; -+ } - } ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -@@ -1,11 +1,11 @@ - package io.dropwizard.metrics5.servlets; - --import io.dropwizard.metrics5.MetricFilter; --import io.dropwizard.metrics5.MetricRegistry; --import io.dropwizard.metrics5.json.MetricsModule; - import com.fasterxml.jackson.databind.ObjectMapper; - import com.fasterxml.jackson.databind.ObjectWriter; - import com.fasterxml.jackson.databind.util.JSONPObject; -+import io.dropwizard.metrics5.MetricFilter; -+import io.dropwizard.metrics5.MetricRegistry; -+import io.dropwizard.metrics5.json.MetricsModule; - import jakarta.servlet.ServletConfig; - import jakarta.servlet.ServletContext; - import jakarta.servlet.ServletContextEvent; -@@ -14,7 +14,6 @@ import jakarta.servlet.ServletException; - import jakarta.servlet.http.HttpServlet; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; -- - import java.io.IOException; - import java.io.OutputStream; - import java.util.Locale; -@@ -24,176 +23,177 @@ import java.util.concurrent.TimeUnit; - * A servlet which returns the metrics in a given registry as an {@code application/json} response. - */ - public class MetricsServlet extends HttpServlet { -+ /** -+ * An abstract {@link ServletContextListener} which allows you to programmatically inject the -+ * {@link MetricRegistry}, rate and duration units, and allowed origin for {@link MetricsServlet}. -+ */ -+ public abstract static class ContextListener implements ServletContextListener { - /** -- * An abstract {@link ServletContextListener} which allows you to programmatically inject the -- * {@link MetricRegistry}, rate and duration units, and allowed origin for -- * {@link MetricsServlet}. -+ * @return the {@link MetricRegistry} to inject into the servlet context. - */ -- public static abstract class ContextListener implements ServletContextListener { -- /** -- * @return the {@link MetricRegistry} to inject into the servlet context. -- */ -- protected abstract MetricRegistry getMetricRegistry(); -- -- /** -- * @return the {@link TimeUnit} to which rates should be converted, or {@code null} if the -- * default should be used. -- */ -- protected TimeUnit getRateUnit() { -- // use the default -- return null; -- } -- -- /** -- * @return the {@link TimeUnit} to which durations should be converted, or {@code null} if -- * the default should be used. -- */ -- protected TimeUnit getDurationUnit() { -- // use the default -- return null; -- } -- -- /** -- * @return the {@code Access-Control-Allow-Origin} header value, if any. -- */ -- protected String getAllowedOrigin() { -- // use the default -- return null; -- } -- -- /** -- * Returns the name of the parameter used to specify the jsonp callback, if any. -- */ -- protected String getJsonpCallbackParameter() { -- return null; -- } -- -- /** -- * Returns the {@link MetricFilter} that shall be used to filter metrics, or {@link MetricFilter#ALL} if -- * the default should be used. -- */ -- protected MetricFilter getMetricFilter() { -- // use the default -- return MetricFilter.ALL; -- } -- -- @Override -- public void contextInitialized(ServletContextEvent event) { -- final ServletContext context = event.getServletContext(); -- context.setAttribute(METRICS_REGISTRY, getMetricRegistry()); -- context.setAttribute(METRIC_FILTER, getMetricFilter()); -- if (getDurationUnit() != null) { -- context.setInitParameter(MetricsServlet.DURATION_UNIT, getDurationUnit().toString()); -- } -- if (getRateUnit() != null) { -- context.setInitParameter(MetricsServlet.RATE_UNIT, getRateUnit().toString()); -- } -- if (getAllowedOrigin() != null) { -- context.setInitParameter(MetricsServlet.ALLOWED_ORIGIN, getAllowedOrigin()); -- } -- if (getJsonpCallbackParameter() != null) { -- context.setAttribute(CALLBACK_PARAM, getJsonpCallbackParameter()); -- } -- } -- -- @Override -- public void contextDestroyed(ServletContextEvent event) { -- // no-op -- } -- } -- -- public static final String RATE_UNIT = MetricsServlet.class.getCanonicalName() + ".rateUnit"; -- public static final String DURATION_UNIT = MetricsServlet.class.getCanonicalName() + ".durationUnit"; -- public static final String SHOW_SAMPLES = MetricsServlet.class.getCanonicalName() + ".showSamples"; -- public static final String METRICS_REGISTRY = MetricsServlet.class.getCanonicalName() + ".registry"; -- public static final String ALLOWED_ORIGIN = MetricsServlet.class.getCanonicalName() + ".allowedOrigin"; -- public static final String METRIC_FILTER = MetricsServlet.class.getCanonicalName() + ".metricFilter"; -- public static final String CALLBACK_PARAM = MetricsServlet.class.getCanonicalName() + ".jsonpCallback"; -+ protected abstract MetricRegistry getMetricRegistry(); - -- private static final long serialVersionUID = 1049773947734939602L; -- private static final String CONTENT_TYPE = "application/json"; -+ /** -+ * @return the {@link TimeUnit} to which rates should be converted, or {@code null} if the -+ * default should be used. -+ */ -+ protected TimeUnit getRateUnit() { -+ // use the default -+ return null; -+ } - -- protected String allowedOrigin; -- protected String jsonpParamName; -- protected transient MetricRegistry registry; -- protected transient ObjectMapper mapper; -+ /** -+ * @return the {@link TimeUnit} to which durations should be converted, or {@code null} if the -+ * default should be used. -+ */ -+ protected TimeUnit getDurationUnit() { -+ // use the default -+ return null; -+ } - -- public MetricsServlet() { -+ /** -+ * @return the {@code Access-Control-Allow-Origin} header value, if any. -+ */ -+ protected String getAllowedOrigin() { -+ // use the default -+ return null; - } - -- public MetricsServlet(MetricRegistry registry) { -- this.registry = registry; -+ /** Returns the name of the parameter used to specify the jsonp callback, if any. */ -+ protected String getJsonpCallbackParameter() { -+ return null; - } - -- @Override -- public void init(ServletConfig config) throws ServletException { -- super.init(config); -- -- final ServletContext context = config.getServletContext(); -- if (null == registry) { -- final Object registryAttr = context.getAttribute(METRICS_REGISTRY); -- if (registryAttr instanceof MetricRegistry) { -- this.registry = (MetricRegistry) registryAttr; -- } else { -- throw new ServletException("Couldn't find a MetricRegistry instance."); -- } -- } -- this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); -- this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); -- -- setupMetricsModule(context); -+ /** -+ * Returns the {@link MetricFilter} that shall be used to filter metrics, or {@link -+ * MetricFilter#ALL} if the default should be used. -+ */ -+ protected MetricFilter getMetricFilter() { -+ // use the default -+ return MetricFilter.ALL; - } - -- protected void setupMetricsModule(ServletContext context) { -- final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), -- TimeUnit.SECONDS); -- final TimeUnit durationUnit = parseTimeUnit(context.getInitParameter(DURATION_UNIT), -- TimeUnit.SECONDS); -- final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES)); -- MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER); -- if (filter == null) { -- filter = MetricFilter.ALL; -- } -- -- this.mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit, -- durationUnit, -- showSamples, -- filter)); -+ @Override -+ public void contextInitialized(ServletContextEvent event) { -+ final ServletContext context = event.getServletContext(); -+ context.setAttribute(METRICS_REGISTRY, getMetricRegistry()); -+ context.setAttribute(METRIC_FILTER, getMetricFilter()); -+ if (getDurationUnit() != null) { -+ context.setInitParameter(MetricsServlet.DURATION_UNIT, getDurationUnit().toString()); -+ } -+ if (getRateUnit() != null) { -+ context.setInitParameter(MetricsServlet.RATE_UNIT, getRateUnit().toString()); -+ } -+ if (getAllowedOrigin() != null) { -+ context.setInitParameter(MetricsServlet.ALLOWED_ORIGIN, getAllowedOrigin()); -+ } -+ if (getJsonpCallbackParameter() != null) { -+ context.setAttribute(CALLBACK_PARAM, getJsonpCallbackParameter()); -+ } - } - - @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -- resp.setContentType(CONTENT_TYPE); -- if (allowedOrigin != null) { -- resp.setHeader("Access-Control-Allow-Origin", allowedOrigin); -- } -- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -- resp.setStatus(HttpServletResponse.SC_OK); -- -- try (OutputStream output = resp.getOutputStream()) { -- if (jsonpParamName != null && req.getParameter(jsonpParamName) != null) { -- getWriter(req).writeValue(output, new JSONPObject(req.getParameter(jsonpParamName), registry)); -- } else { -- getWriter(req).writeValue(output, registry); -- } -- } -+ public void contextDestroyed(ServletContextEvent event) { -+ // no-op -+ } -+ } -+ -+ public static final String RATE_UNIT = MetricsServlet.class.getCanonicalName() + ".rateUnit"; -+ public static final String DURATION_UNIT = -+ MetricsServlet.class.getCanonicalName() + ".durationUnit"; -+ public static final String SHOW_SAMPLES = -+ MetricsServlet.class.getCanonicalName() + ".showSamples"; -+ public static final String METRICS_REGISTRY = -+ MetricsServlet.class.getCanonicalName() + ".registry"; -+ public static final String ALLOWED_ORIGIN = -+ MetricsServlet.class.getCanonicalName() + ".allowedOrigin"; -+ public static final String METRIC_FILTER = -+ MetricsServlet.class.getCanonicalName() + ".metricFilter"; -+ public static final String CALLBACK_PARAM = -+ MetricsServlet.class.getCanonicalName() + ".jsonpCallback"; -+ -+ private static final long serialVersionUID = 1049773947734939602L; -+ private static final String CONTENT_TYPE = "application/json"; -+ -+ protected String allowedOrigin; -+ protected String jsonpParamName; -+ protected transient MetricRegistry registry; -+ protected transient ObjectMapper mapper; -+ -+ public MetricsServlet() {} -+ -+ public MetricsServlet(MetricRegistry registry) { -+ this.registry = registry; -+ } -+ -+ @Override -+ public void init(ServletConfig config) throws ServletException { -+ super.init(config); -+ -+ final ServletContext context = config.getServletContext(); -+ if (registry == null) { -+ final Object registryAttr = context.getAttribute(METRICS_REGISTRY); -+ if (registryAttr instanceof MetricRegistry) { -+ this.registry = (MetricRegistry) registryAttr; -+ } else { -+ throw new ServletException("Couldn't find a MetricRegistry instance."); -+ } -+ } -+ this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); -+ this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); -+ -+ setupMetricsModule(context); -+ } -+ -+ protected void setupMetricsModule(ServletContext context) { -+ final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), TimeUnit.SECONDS); -+ final TimeUnit durationUnit = -+ parseTimeUnit(context.getInitParameter(DURATION_UNIT), TimeUnit.SECONDS); -+ final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES)); -+ MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER); -+ if (filter == null) { -+ filter = MetricFilter.ALL; - } - -- protected ObjectWriter getWriter(HttpServletRequest request) { -- final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); -- if (prettyPrint) { -- return mapper.writerWithDefaultPrettyPrinter(); -- } -- return mapper.writer(); -+ this.mapper = -+ new ObjectMapper() -+ .registerModule(new MetricsModule(rateUnit, durationUnit, showSamples, filter)); -+ } -+ -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ resp.setContentType(CONTENT_TYPE); -+ if (allowedOrigin != null) { -+ resp.setHeader("Access-Control-Allow-Origin", allowedOrigin); -+ } -+ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -+ resp.setStatus(HttpServletResponse.SC_OK); -+ -+ try (OutputStream output = resp.getOutputStream()) { -+ if (jsonpParamName != null && req.getParameter(jsonpParamName) != null) { -+ getWriter(req) -+ .writeValue(output, new JSONPObject(req.getParameter(jsonpParamName), registry)); -+ } else { -+ getWriter(req).writeValue(output, registry); -+ } - } -+ } - -- @SuppressWarnings("IdentityConversion") -- protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { -- try { -- return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); -- } catch (IllegalArgumentException e) { -- return defaultValue; -- } -+ protected ObjectWriter getWriter(HttpServletRequest request) { -+ final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); -+ if (prettyPrint) { -+ return mapper.writerWithDefaultPrettyPrinter(); -+ } -+ return mapper.writer(); -+ } -+ -+ @SuppressWarnings("IdentityConversion") -+ protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { -+ try { -+ return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); -+ } catch (IllegalArgumentException e) { -+ return defaultValue; - } -+ } - } ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/PingServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/PingServlet.java -@@ -4,28 +4,25 @@ import jakarta.servlet.ServletException; - import jakarta.servlet.http.HttpServlet; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; -- - import java.io.IOException; - import java.io.PrintWriter; - --/** -- * An HTTP servlets which outputs a {@code text/plain} {@code "pong"} response. -- */ -+/** An HTTP servlets which outputs a {@code text/plain} {@code "pong"} response. */ - public class PingServlet extends HttpServlet { -- private static final long serialVersionUID = 3772654177231086757L; -- private static final String CONTENT_TYPE = "text/plain"; -- private static final String CONTENT = "pong"; -- private static final String CACHE_CONTROL = "Cache-Control"; -- private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; -+ private static final long serialVersionUID = 3772654177231086757L; -+ private static final String CONTENT_TYPE = "text/plain"; -+ private static final String CONTENT = "pong"; -+ private static final String CACHE_CONTROL = "Cache-Control"; -+ private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; - -- @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -- resp.setStatus(HttpServletResponse.SC_OK); -- resp.setHeader(CACHE_CONTROL, NO_CACHE); -- resp.setContentType(CONTENT_TYPE); -- try (PrintWriter writer = resp.getWriter()) { -- writer.println(CONTENT); -- } -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ resp.setStatus(HttpServletResponse.SC_OK); -+ resp.setHeader(CACHE_CONTROL, NO_CACHE); -+ resp.setContentType(CONTENT_TYPE); -+ try (PrintWriter writer = resp.getWriter()) { -+ writer.println(CONTENT); - } -+ } - } ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/ThreadDumpServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/ThreadDumpServlet.java -@@ -5,51 +5,50 @@ import jakarta.servlet.ServletException; - import jakarta.servlet.http.HttpServlet; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; -- - import java.io.IOException; - import java.io.OutputStream; - import java.lang.management.ManagementFactory; - - /** -- * An HTTP servlets which outputs a {@code text/plain} dump of all threads in -- * the VM. Only responds to {@code GET} requests. -+ * An HTTP servlets which outputs a {@code text/plain} dump of all threads in the VM. Only responds -+ * to {@code GET} requests. - */ - public class ThreadDumpServlet extends HttpServlet { - -- private static final long serialVersionUID = -2690343532336103046L; -- private static final String CONTENT_TYPE = "text/plain"; -+ private static final long serialVersionUID = -2690343532336103046L; -+ private static final String CONTENT_TYPE = "text/plain"; - -- private transient ThreadDump threadDump; -+ private transient ThreadDump threadDump; - -- @Override -- public void init() throws ServletException { -- try { -- // Some PaaS like Google App Engine blacklist java.lang.managament -- this.threadDump = new ThreadDump(ManagementFactory.getThreadMXBean()); -- } catch (NoClassDefFoundError ncdfe) { -- this.threadDump = null; // we won't be able to provide thread dump -- } -+ @Override -+ public void init() throws ServletException { -+ try { -+ // Some PaaS like Google App Engine blacklist java.lang.managament -+ this.threadDump = new ThreadDump(ManagementFactory.getThreadMXBean()); -+ } catch (NoClassDefFoundError ncdfe) { -+ this.threadDump = null; // we won't be able to provide thread dump - } -- -- @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -- final boolean includeMonitors = getParam(req.getParameter("monitors"), true); -- final boolean includeSynchronizers = getParam(req.getParameter("synchronizers"), true); -- -- resp.setStatus(HttpServletResponse.SC_OK); -- resp.setContentType(CONTENT_TYPE); -- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -- if (threadDump == null) { -- resp.getWriter().println("Sorry your runtime environment does not allow to dump threads."); -- return; -- } -- try (OutputStream output = resp.getOutputStream()) { -- threadDump.dump(includeMonitors, includeSynchronizers, output); -- } -+ } -+ -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ final boolean includeMonitors = getParam(req.getParameter("monitors"), true); -+ final boolean includeSynchronizers = getParam(req.getParameter("synchronizers"), true); -+ -+ resp.setStatus(HttpServletResponse.SC_OK); -+ resp.setContentType(CONTENT_TYPE); -+ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -+ if (threadDump == null) { -+ resp.getWriter().println("Sorry your runtime environment does not allow to dump threads."); -+ return; - } -- -- private static Boolean getParam(String initParam, boolean defaultValue) { -- return initParam == null ? defaultValue : Boolean.parseBoolean(initParam); -+ try (OutputStream output = resp.getOutputStream()) { -+ threadDump.dump(includeMonitors, includeSynchronizers, output); - } -+ } -+ -+ private static Boolean getParam(String initParam, boolean defaultValue) { -+ return initParam == null ? defaultValue : Boolean.parseBoolean(initParam); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java -@@ -6,24 +6,24 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - - public abstract class AbstractServletTest { -- private final ServletTester tester = new ServletTester(); -- protected final HttpTester.Request request = HttpTester.newRequest(); -- protected HttpTester.Response response; -+ private final ServletTester tester = new ServletTester(); -+ protected final HttpTester.Request request = HttpTester.newRequest(); -+ protected HttpTester.Response response; - -- @BeforeEach -- public void setUpTester() throws Exception { -- setUp(tester); -- tester.start(); -- } -+ @BeforeEach -+ public void setUpTester() throws Exception { -+ setUp(tester); -+ tester.start(); -+ } - -- protected abstract void setUp(ServletTester tester); -+ protected abstract void setUp(ServletTester tester); - -- @AfterEach -- public void tearDownTester() throws Exception { -- tester.stop(); -- } -+ @AfterEach -+ public void tearDownTester() throws Exception { -+ tester.stop(); -+ } - -- protected void processRequest() throws Exception { -- this.response = HttpTester.parseResponse(tester.getResponses(request.generate())); -- } -+ protected void processRequest() throws Exception { -+ this.response = HttpTester.parseResponse(tester.getResponses(request.generate())); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java -@@ -1,60 +1,60 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.health.HealthCheckRegistry; --import static org.assertj.core.api.Assertions.assertThat; - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class AdminServletExclusionTest extends AbstractServletTest { -- private final MetricRegistry registry = new MetricRegistry(); -- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -- -- @Override -- protected void setUp(ServletTester tester) { -- tester.setContextPath("/context"); -- -- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -- tester.setInitParameter("threads-enabled", "false"); -- tester.setInitParameter("cpu-profile-enabled", "false"); -- tester.addServlet(AdminServlet.class, "/admin"); -- } -- -- @BeforeEach -- void setUp() { -- request.setMethod("GET"); -- request.setURI("/context/admin"); -- request.setVersion("HTTP/1.0"); -- } -- -- @Test -- void returnsA200() throws Exception { -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.getContent()) -- .isEqualTo(String.format( -- "%n" + -- "%n" + -- "%n" + -- " Metrics%n" + -- "%n" + -- "%n" + -- "

    Operational Menu

    %n" + -- " %n" + -- "%n" + -- "%n" -- )); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("text/html;charset=UTF-8"); -- } -+final class AdminServletExclusionTest extends AbstractServletTest { -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.setContextPath("/context"); -+ -+ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -+ tester.setAttribute( -+ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -+ tester.setInitParameter("threads-enabled", "false"); -+ tester.setInitParameter("cpu-profile-enabled", "false"); -+ tester.addServlet(AdminServlet.class, "/admin"); -+ } -+ -+ @BeforeEach -+ void setUp() { -+ request.setMethod("GET"); -+ request.setURI("/context/admin"); -+ request.setVersion("HTTP/1.0"); -+ } -+ -+ @Test -+ void returnsA200() throws Exception { -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "%n" -+ + "%n" -+ + "%n" -+ + " Metrics%n" -+ + "%n" -+ + "%n" -+ + "

    Operational Menu

    %n" -+ + " %n" -+ + "%n" -+ + "%n")); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.health.HealthCheckRegistry; - import org.eclipse.jetty.http.HttpHeader; -@@ -7,56 +9,53 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; -- --class AdminServletTest extends AbstractServletTest { -- private final MetricRegistry registry = new MetricRegistry(); -- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -- -- @Override -- protected void setUp(ServletTester tester) { -- tester.setContextPath("/context"); -- -- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -- tester.addServlet(AdminServlet.class, "/admin"); -- } -- -- @BeforeEach -- void setUp() { -- request.setMethod("GET"); -- request.setURI("/context/admin"); -- request.setVersion("HTTP/1.0"); -- } -- -- @Test -- void returnsA200() throws Exception { -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.getContent()) -- .isEqualTo(String.format( -- "%n" + -- "%n" + -- "%n" + -- " Metrics%n" + -- "%n" + -- "%n" + -- "

    Operational Menu

    %n" + -- " %n" + -- "%n" + -- "%n" -- )); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("text/html;charset=UTF-8"); -- } -+final class AdminServletTest extends AbstractServletTest { -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.setContextPath("/context"); -+ -+ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -+ tester.setAttribute( -+ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -+ tester.addServlet(AdminServlet.class, "/admin"); -+ } -+ -+ @BeforeEach -+ void setUp() { -+ request.setMethod("GET"); -+ request.setURI("/context/admin"); -+ request.setVersion("HTTP/1.0"); -+ } -+ -+ @Test -+ void returnsA200() throws Exception { -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "%n" -+ + "%n" -+ + "%n" -+ + " Metrics%n" -+ + "%n" -+ + "%n" -+ + "

    Operational Menu

    %n" -+ + " %n" -+ + "%n" -+ + "%n")); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java -@@ -1,66 +1,66 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.health.HealthCheckRegistry; --import static org.assertj.core.api.Assertions.assertThat; - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class AdminServletUriTest extends AbstractServletTest { -- private final MetricRegistry registry = new MetricRegistry(); -- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -+final class AdminServletUriTest extends AbstractServletTest { -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); - -- @Override -- protected void setUp(ServletTester tester) { -- tester.setContextPath("/context"); -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.setContextPath("/context"); - -- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -- tester.setInitParameter("metrics-uri", "/metrics-test"); -- tester.setInitParameter("ping-uri", "/ping-test"); -- tester.setInitParameter("threads-uri", "/threads-test"); -- tester.setInitParameter("healthcheck-uri", "/healthcheck-test"); -- tester.setInitParameter("cpu-profile-uri", "/pprof-test"); -- tester.addServlet(AdminServlet.class, "/admin"); -- } -+ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -+ tester.setAttribute( -+ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -+ tester.setInitParameter("metrics-uri", "/metrics-test"); -+ tester.setInitParameter("ping-uri", "/ping-test"); -+ tester.setInitParameter("threads-uri", "/threads-test"); -+ tester.setInitParameter("healthcheck-uri", "/healthcheck-test"); -+ tester.setInitParameter("cpu-profile-uri", "/pprof-test"); -+ tester.addServlet(AdminServlet.class, "/admin"); -+ } - -- @BeforeEach -- void setUp() { -- request.setMethod("GET"); -- request.setURI("/context/admin"); -- request.setVersion("HTTP/1.0"); -- } -+ @BeforeEach -+ void setUp() { -+ request.setMethod("GET"); -+ request.setURI("/context/admin"); -+ request.setVersion("HTTP/1.0"); -+ } - -- @Test -- void returnsA200() throws Exception { -- processRequest(); -+ @Test -+ void returnsA200() throws Exception { -+ processRequest(); - -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.getContent()) -- .isEqualTo(String.format( -- "%n" + -- "%n" + -- "%n" + -- " Metrics%n" + -- "%n" + -- "%n" + -- "

    Operational Menu

    %n" + -- " %n" + -- "%n" + -- "%n" -- )); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("text/html;charset=UTF-8"); -- } -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "%n" -+ + "%n" -+ + "%n" -+ + " Metrics%n" -+ + "%n" -+ + "%n" -+ + "

    Operational Menu

    %n" -+ + " %n" -+ + "%n" -+ + "%n")); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java -@@ -1,44 +1,41 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; -- --class CpuProfileServletTest extends AbstractServletTest { -- -- @Override -- protected void setUp(ServletTester tester) { -- tester.addServlet(CpuProfileServlet.class, "/pprof"); -- } -- -- @BeforeEach -- void setUp() throws Exception { -- request.setMethod("GET"); -- request.setURI("/pprof?duration=1"); -- request.setVersion("HTTP/1.0"); -- -- processRequest(); -- } -- -- @Test -- void returns200OK() { -- assertThat(response.getStatus()) -- .isEqualTo(200); -- } -- -- @Test -- void returnsPprofRaw() { -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("pprof/raw"); -- } -- -- @Test -- void returnsUncacheable() { -- assertThat(response.get(HttpHeader.CACHE_CONTROL)) -- .isEqualTo("must-revalidate,no-cache,no-store"); -- -- } -+final class CpuProfileServletTest extends AbstractServletTest { -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.addServlet(CpuProfileServlet.class, "/pprof"); -+ } -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ request.setMethod("GET"); -+ request.setURI("/pprof?duration=1"); -+ request.setVersion("HTTP/1.0"); -+ -+ processRequest(); -+ } -+ -+ @Test -+ void returns200OK() { -+ assertThat(response.getStatus()).isEqualTo(200); -+ } -+ -+ @Test -+ void returnsPprofRaw() { -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("pprof/raw"); -+ } -+ -+ @Test -+ void returnsUncacheable() { -+ assertThat(response.get(HttpHeader.CACHE_CONTROL)) -+ .isEqualTo("must-revalidate,no-cache,no-store"); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -@@ -1,5 +1,12 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.never; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import com.fasterxml.jackson.databind.ObjectMapper; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.health.HealthCheck; -@@ -8,251 +15,255 @@ import io.dropwizard.metrics5.health.HealthCheckRegistry; - import jakarta.servlet.ServletConfig; - import jakarta.servlet.ServletContext; - import jakarta.servlet.ServletException; --import org.eclipse.jetty.http.HttpHeader; --import org.eclipse.jetty.servlet.ServletTester; --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- - import java.time.ZonedDateTime; - import java.time.format.DateTimeFormatter; - import java.util.concurrent.Callable; - import java.util.concurrent.ExecutorService; - import java.util.concurrent.Executors; -+import org.eclipse.jetty.http.HttpHeader; -+import org.eclipse.jetty.servlet.ServletTester; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- --class HealthCheckServletTest extends AbstractServletTest { -+final class HealthCheckServletTest extends AbstractServletTest { - -- private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); -+ private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); - -- private static final DateTimeFormatter DATE_TIME_FORMATTER = -- DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); -+ private static final DateTimeFormatter DATE_TIME_FORMATTER = -+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - -- private static final String EXPECTED_TIMESTAMP = DATE_TIME_FORMATTER.format(FIXED_TIME); -+ private static final String EXPECTED_TIMESTAMP = DATE_TIME_FORMATTER.format(FIXED_TIME); - -- private static final Clock FIXED_CLOCK = new Clock() { -+ private static final Clock FIXED_CLOCK = -+ new Clock() { - @Override - public long getTick() { -- return 0L; -+ return 0L; - } - - @Override - public long getTime() { -- return FIXED_TIME.toInstant().toEpochMilli(); -+ return FIXED_TIME.toInstant().toEpochMilli(); - } -- }; -- -- private final HealthCheckRegistry registry = new HealthCheckRegistry(); -- private final ExecutorService threadPool = Executors.newCachedThreadPool(); -- private final ObjectMapper mapper = new ObjectMapper(); -- -- @Override -- protected void setUp(ServletTester tester) { -- tester.addServlet(HealthCheckServlet.class, "/healthchecks"); -- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", registry); -- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".executor", threadPool); -- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".mapper", mapper); -- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter", -- (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); -- } -- -- @BeforeEach -- void setUp() { -- request.setMethod("GET"); -- request.setURI("/healthchecks"); -- request.setVersion("HTTP/1.0"); -- } -- -- @AfterEach -- void tearDown() { -- threadPool.shutdown(); -- } -- -- @Test -- void returns501IfNoHealthChecksAreRegistered() throws Exception { -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(501); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()).isEqualTo("{}"); -- } -- -- @Test -- void returnsA200IfAllHealthChecksAreHealthy() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()) -- .isEqualTo("{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + -- EXPECTED_TIMESTAMP + -- "\"}}"); -- } -- -- @Test -- void returnsASubsetOfHealthChecksIfFiltered() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -- registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()) -- .isEqualTo("{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + -- EXPECTED_TIMESTAMP + -- "\"}}"); -- } -- -- @Test -- void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -- registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(500); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()).contains( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", -- ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); -- } -- -- @Test -- void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -- registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -- request.setURI("/healthchecks?httpStatusIndicator=false"); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()).contains( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", -- ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); -- } -- -- @Test -- void optionallyPrettyPrintsTheJson() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); -- -- request.setURI("/healthchecks?pretty=true"); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()) -- .isEqualTo(String.format("{%n" + -- " \"fun\" : {%n" + -- " \"healthy\" : true,%n" + -- " \"message\" : \"foo bar 123\",%n" + -- " \"duration\" : 0,%n" + -- " \"timestamp\" : \"" + EXPECTED_TIMESTAMP + "\"" + -- "%n }%n}")); -- } -- -- private static HealthCheck.Result healthyResultWithMessage(String message) { -- return HealthCheck.Result.builder() -- .healthy() -- .withMessage(message) -- .usingClock(FIXED_CLOCK) -- .build(); -- } -- -- private static HealthCheck.Result unhealthyResultWithMessage(String message) { -- return HealthCheck.Result.builder() -- .unhealthy() -- .withMessage(message) -- .usingClock(FIXED_CLOCK) -- .build(); -- } -- -- @Test -- void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); -- healthCheckServlet.init(servletConfig); -- -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -- } -- -- @Test -- void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -- .thenReturn(healthCheckRegistry); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -- healthCheckServlet.init(servletConfig); -- -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -- } -- -- @Test -- void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { -- assertThrows(ServletException.class, () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -- .thenReturn("IRELLEVANT_STRING"); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -- healthCheckServlet.init(servletConfig); -- }); -+ }; -+ -+ private final HealthCheckRegistry registry = new HealthCheckRegistry(); -+ private final ExecutorService threadPool = Executors.newCachedThreadPool(); -+ private final ObjectMapper mapper = new ObjectMapper(); -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.addServlet(HealthCheckServlet.class, "/healthchecks"); -+ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", registry); -+ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".executor", threadPool); -+ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".mapper", mapper); -+ tester.setAttribute( -+ HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter", -+ (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); -+ } -+ -+ @BeforeEach -+ void setUp() { -+ request.setMethod("GET"); -+ request.setURI("/healthchecks"); -+ request.setVersion("HTTP/1.0"); -+ } -+ -+ @AfterEach -+ void tearDown() { -+ threadPool.shutdown(); -+ } -+ -+ @Test -+ void returns501IfNoHealthChecksAreRegistered() throws Exception { -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(501); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()).isEqualTo("{}"); -+ } -+ -+ @Test -+ void returnsA200IfAllHealthChecksAreHealthy() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); -+ } -+ -+ @Test -+ void returnsASubsetOfHealthChecksIfFiltered() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -+ registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); -+ } -+ -+ @Test -+ void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -+ registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(500); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .contains( -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -+ + EXPECTED_TIMESTAMP -+ + "\"}", -+ ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -+ + EXPECTED_TIMESTAMP -+ + "\"}}"); -+ } -+ -+ @Test -+ void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -+ registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -+ request.setURI("/healthchecks?httpStatusIndicator=false"); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .contains( -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -+ + EXPECTED_TIMESTAMP -+ + "\"}", -+ ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -+ + EXPECTED_TIMESTAMP -+ + "\"}}"); -+ } -+ -+ @Test -+ void optionallyPrettyPrintsTheJson() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); -+ -+ request.setURI("/healthchecks?pretty=true"); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", -+ EXPECTED_TIMESTAMP)); -+ } -+ -+ private static HealthCheck.Result healthyResultWithMessage(String message) { -+ return HealthCheck.Result.builder() -+ .healthy() -+ .withMessage(message) -+ .usingClock(FIXED_CLOCK) -+ .build(); -+ } -+ -+ private static HealthCheck.Result unhealthyResultWithMessage(String message) { -+ return HealthCheck.Result.builder() -+ .unhealthy() -+ .withMessage(message) -+ .usingClock(FIXED_CLOCK) -+ .build(); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); -+ healthCheckServlet.init(servletConfig); -+ -+ verify(servletConfig).getServletContext(); -+ verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -+ .thenReturn(healthCheckRegistry); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -+ healthCheckServlet.init(servletConfig); -+ -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() -+ throws Exception { -+ assertThatThrownBy( -+ () -> { -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -+ .thenReturn("IRELLEVANT_STRING"); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -+ healthCheckServlet.init(servletConfig); -+ }) -+ .isInstanceOf(ServletException.class); -+ } -+ -+ @Test -+ void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() -+ throws Exception { -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -+ .thenReturn(registry); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_MAPPER)) -+ .thenReturn("IRELLEVANT_STRING"); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -+ healthCheckServlet.init(servletConfig); -+ -+ assertThat(healthCheckServlet.getMapper()).isNotNull().isInstanceOf(ObjectMapper.class); -+ } -+ -+ static class TestHealthCheck implements HealthCheck { -+ private final Callable check; -+ -+ public TestHealthCheck(Callable check) { -+ this.check = check; - } - -- @Test -- void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)).thenReturn(registry); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_MAPPER)).thenReturn("IRELLEVANT_STRING"); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -- healthCheckServlet.init(servletConfig); -- -- assertThat(healthCheckServlet.getMapper()) -- .isNotNull() -- .isInstanceOf(ObjectMapper.class); -+ @Override -+ public Result check() throws Exception { -+ return check.call(); - } - -- static class TestHealthCheck implements HealthCheck { -- private final Callable check; -- -- public TestHealthCheck(Callable check) { -- this.check = check; -- } -- -- @Override -- public Result check() throws Exception { -- return check.call(); -- } -- -- @Override -- public Clock clock() { -- return FIXED_CLOCK; -- } -+ @Override -+ public Clock clock() { -+ return FIXED_CLOCK; - } -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Gauge; -@@ -7,166 +11,163 @@ import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -+import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- --class MetricsServletContextListenerTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -- private final MetricRegistry registry = new MetricRegistry(); -- private final String allowedOrigin = "some.other.origin"; -- -- @Override -- protected void setUp(ServletTester tester) { -- tester.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry); -- tester.addServlet(MetricsServlet.class, "/metrics"); -- tester.getContext().addEventListener(new MetricsServlet.ContextListener() { -- @Override -- protected MetricRegistry getMetricRegistry() { -+final class MetricsServletContextListenerTest extends AbstractServletTest { -+ private final Clock clock = mock(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final String allowedOrigin = "some.other.origin"; -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry); -+ tester.addServlet(MetricsServlet.class, "/metrics"); -+ tester -+ .getContext() -+ .addEventListener( -+ new MetricsServlet.ContextListener() { -+ @Override -+ protected MetricRegistry getMetricRegistry() { - return registry; -- } -+ } - -- @Override -- protected TimeUnit getDurationUnit() { -+ @Override -+ protected TimeUnit getDurationUnit() { - return TimeUnit.MILLISECONDS; -- } -+ } - -- @Override -- protected TimeUnit getRateUnit() { -+ @Override -+ protected TimeUnit getRateUnit() { - return TimeUnit.MINUTES; -- } -+ } - -- @Override -- protected String getAllowedOrigin() { -+ @Override -+ protected String getAllowedOrigin() { - return allowedOrigin; -- } -- }); -- } -- -- @BeforeEach -- void setUp() { -- // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves -- // will call getTick again several times and always get the same value (the last specified here) -- when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); -- -- registry.register(MetricName.build("g1"), (Gauge) () -> 100L); -- registry.counter("c").inc(); -- registry.histogram("h").update(1); -- registry.register(MetricName.build("m"), new Meter(clock)).mark(); -- registry.register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) -- .update(1, TimeUnit.SECONDS); -- -- request.setMethod("GET"); -- request.setURI("/metrics"); -- request.setVersion("HTTP/1.0"); -- } -- -- @Test -- void returnsA200() throws Exception { -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo(allowedOrigin); -- assertThat(response.getContent()) -- .isEqualTo("{" + -- "\"version\":\"5.0.0\"," + -- "\"gauges\":{" + -- "\"g1\":{\"value\":100}" + -- "}," + -- "\"counters\":{" + -- "\"c\":{\"count\":1}" + -- "}," + -- "\"histograms\":{" + -- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + -- "}," + -- "\"meters\":{" + -- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":2.0E8,\"units\":\"events/minute\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1000.0,\"mean\":1000.0,\"min\":1000.0,\"p50\":1000.0,\"p75\":1000.0,\"p95\":1000.0,\"p98\":1000.0,\"p99\":1000.0,\"p999\":1000.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":6.0E8,\"duration_units\":\"milliseconds\",\"rate_units\":\"calls/minute\"}" + -- "}" + -- "}"); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void optionallyPrettyPrintsTheJson() throws Exception { -- request.setURI("/metrics?pretty=true"); -- -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo(allowedOrigin); -- assertThat(response.getContent()) -- .isEqualTo(String.format("{%n" + -- " \"version\" : \"5.0.0\",%n" + -- " \"gauges\" : {%n" + -- " \"g1\" : {%n" + -- " \"value\" : 100%n" + -- " }%n" + -- " },%n" + -- " \"counters\" : {%n" + -- " \"c\" : {%n" + -- " \"count\" : 1%n" + -- " }%n" + -- " },%n" + -- " \"histograms\" : {%n" + -- " \"h\" : {%n" + -- " \"count\" : 1,%n" + -- " \"max\" : 1,%n" + -- " \"mean\" : 1.0,%n" + -- " \"min\" : 1,%n" + -- " \"p50\" : 1.0,%n" + -- " \"p75\" : 1.0,%n" + -- " \"p95\" : 1.0,%n" + -- " \"p98\" : 1.0,%n" + -- " \"p99\" : 1.0,%n" + -- " \"p999\" : 1.0,%n" + -- " \"stddev\" : 0.0%n" + -- " }%n" + -- " },%n" + -- " \"meters\" : {%n" + -- " \"m\" : {%n" + -- " \"count\" : 1,%n" + -- " \"m15_rate\" : 0.0,%n" + -- " \"m1_rate\" : 0.0,%n" + -- " \"m5_rate\" : 0.0,%n" + -- " \"mean_rate\" : 2.0E8,%n" + -- " \"units\" : \"events/minute\"%n" + -- " }%n" + -- " },%n" + -- " \"timers\" : {%n" + -- " \"t\" : {%n" + -- " \"count\" : 1,%n" + -- " \"max\" : 1000.0,%n" + -- " \"mean\" : 1000.0,%n" + -- " \"min\" : 1000.0,%n" + -- " \"p50\" : 1000.0,%n" + -- " \"p75\" : 1000.0,%n" + -- " \"p95\" : 1000.0,%n" + -- " \"p98\" : 1000.0,%n" + -- " \"p99\" : 1000.0,%n" + -- " \"p999\" : 1000.0,%n" + -- " \"stddev\" : 0.0,%n" + -- " \"m15_rate\" : 0.0,%n" + -- " \"m1_rate\" : 0.0,%n" + -- " \"m5_rate\" : 0.0,%n" + -- " \"mean_rate\" : 6.0E8,%n" + -- " \"duration_units\" : \"milliseconds\",%n" + -- " \"rate_units\" : \"calls/minute\"%n" + -- " }%n" + -- " }%n" + -- "}")); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -+ } -+ }); -+ } -+ -+ @BeforeEach -+ void setUp() { -+ // provide ticks for the setup (calls getTick 6 times). The serialization in the tests -+ // themselves -+ // will call getTick again several times and always get the same value (the last specified here) -+ when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); -+ -+ registry.register(MetricName.build("g1"), (Gauge) () -> 100L); -+ registry.counter("c").inc(); -+ registry.histogram("h").update(1); -+ registry.register(MetricName.build("m"), new Meter(clock)).mark(); -+ registry -+ .register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) -+ .update(1, TimeUnit.SECONDS); -+ -+ request.setMethod("GET"); -+ request.setURI("/metrics"); -+ request.setVersion("HTTP/1.0"); -+ } -+ -+ @Test -+ void returnsA200() throws Exception { -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo(allowedOrigin); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ "{" -+ + "\"version\":\"5.0.0\"," -+ + "\"gauges\":{" -+ + "\"g1\":{\"value\":100}" -+ + "}," -+ + "\"counters\":{" -+ + "\"c\":{\"count\":1}" -+ + "}," -+ + "\"histograms\":{" -+ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -+ + "}," -+ + "\"meters\":{" -+ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":2.0E8,\"units\":\"events/minute\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1000.0,\"mean\":1000.0,\"min\":1000.0,\"p50\":1000.0,\"p75\":1000.0,\"p95\":1000.0,\"p98\":1000.0,\"p99\":1000.0,\"p999\":1000.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":6.0E8,\"duration_units\":\"milliseconds\",\"rate_units\":\"calls/minute\"}" -+ + "}" -+ + "}"); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void optionallyPrettyPrintsTheJson() throws Exception { -+ request.setURI("/metrics?pretty=true"); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo(allowedOrigin); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "{%n" -+ + " \"version\" : \"5.0.0\",%n" -+ + " \"gauges\" : {%n" -+ + " \"g1\" : {%n" -+ + " \"value\" : 100%n" -+ + " }%n" -+ + " },%n" -+ + " \"counters\" : {%n" -+ + " \"c\" : {%n" -+ + " \"count\" : 1%n" -+ + " }%n" -+ + " },%n" -+ + " \"histograms\" : {%n" -+ + " \"h\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"max\" : 1,%n" -+ + " \"mean\" : 1.0,%n" -+ + " \"min\" : 1,%n" -+ + " \"p50\" : 1.0,%n" -+ + " \"p75\" : 1.0,%n" -+ + " \"p95\" : 1.0,%n" -+ + " \"p98\" : 1.0,%n" -+ + " \"p99\" : 1.0,%n" -+ + " \"p999\" : 1.0,%n" -+ + " \"stddev\" : 0.0%n" -+ + " }%n" -+ + " },%n" -+ + " \"meters\" : {%n" -+ + " \"m\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"m15_rate\" : 0.0,%n" -+ + " \"m1_rate\" : 0.0,%n" -+ + " \"m5_rate\" : 0.0,%n" -+ + " \"mean_rate\" : 2.0E8,%n" -+ + " \"units\" : \"events/minute\"%n" -+ + " }%n" -+ + " },%n" -+ + " \"timers\" : {%n" -+ + " \"t\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"max\" : 1000.0,%n" -+ + " \"mean\" : 1000.0,%n" -+ + " \"min\" : 1000.0,%n" -+ + " \"p50\" : 1000.0,%n" -+ + " \"p75\" : 1000.0,%n" -+ + " \"p95\" : 1000.0,%n" -+ + " \"p98\" : 1000.0,%n" -+ + " \"p99\" : 1000.0,%n" -+ + " \"p999\" : 1000.0,%n" -+ + " \"stddev\" : 0.0,%n" -+ + " \"m15_rate\" : 0.0,%n" -+ + " \"m1_rate\" : 0.0,%n" -+ + " \"m5_rate\" : 0.0,%n" -+ + " \"mean_rate\" : 6.0E8,%n" -+ + " \"duration_units\" : \"milliseconds\",%n" -+ + " \"rate_units\" : \"calls/minute\"%n" -+ + " }%n" -+ + " }%n" -+ + "}")); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -@@ -1,5 +1,12 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.never; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Gauge; -@@ -10,258 +17,238 @@ import io.dropwizard.metrics5.Timer; - import jakarta.servlet.ServletConfig; - import jakarta.servlet.ServletContext; - import jakarta.servlet.ServletException; -+import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.mockito.ArgumentMatchers.eq; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- --class MetricsServletTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -- private final MetricRegistry registry = new MetricRegistry(); -- private ServletTester tester; -- -- @Override -- protected void setUp(ServletTester tester) { -- this.tester = tester; -- tester.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry); -- tester.addServlet(MetricsServlet.class, "/metrics"); -- tester.getContext().setInitParameter(MetricsServlet.class.getCanonicalName() + ".allowedOrigin", "*"); -- } -- -- @BeforeEach -- void setUp() { -- // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves -- // will call getTick again several times and always get the same value (the last specified here) -- when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); -- -- registry.register(MetricName.build("g1"), (Gauge) () -> 100L); -- registry.counter("c").inc(); -- registry.histogram("h").update(1); -- registry.register(MetricName.build("m"), new Meter(clock)).mark(); -- registry.register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) -- .update(1, TimeUnit.SECONDS); -- -- request.setMethod("GET"); -- request.setURI("/metrics"); -- request.setVersion("HTTP/1.0"); -- } -- -- @Test -- void returnsA200() throws Exception { -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo("*"); -- assertThat(response.getContent()) -- .isEqualTo("{" + -- "\"version\":\"5.0.0\"," + -- "\"gauges\":{" + -- "\"g1\":{\"value\":100}" + -- "}," + -- "\"counters\":{" + -- "\"c\":{\"count\":1}" + -- "}," + -- "\"histograms\":{" + -- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + -- "}," + -- "\"meters\":{" + -- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + -- "}" + -- "}"); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void returnsJsonWhenJsonpInitParamNotSet() throws Exception { -- String callbackParamName = "callbackParam"; -- String callbackParamVal = "callbackParamVal"; -- request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo("*"); -- assertThat(response.getContent()) -- .isEqualTo("{" + -- "\"version\":\"5.0.0\"," + -- "\"gauges\":{" + -- "\"g1\":{\"value\":100}" + -- "}," + -- "\"counters\":{" + -- "\"c\":{\"count\":1}" + -- "}," + -- "\"histograms\":{" + -- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + -- "}," + -- "\"meters\":{" + -- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + -- "}" + -- "}"); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void returnsJsonpWhenInitParamSet() throws Exception { -- String callbackParamName = "callbackParam"; -- String callbackParamVal = "callbackParamVal"; -- request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); -- tester.getContext().setInitParameter(MetricsServlet.class.getCanonicalName() + ".jsonpCallback", callbackParamName); -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo("*"); -- assertThat(response.getContent()) -- .isEqualTo(callbackParamVal + "({" + -- "\"version\":\"5.0.0\"," + -- "\"gauges\":{" + -- "\"g1\":{\"value\":100}" + -- "}," + -- "\"counters\":{" + -- "\"c\":{\"count\":1}" + -- "}," + -- "\"histograms\":{" + -- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + -- "}," + -- "\"meters\":{" + -- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + -- "}" + -- "})"); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void optionallyPrettyPrintsTheJson() throws Exception { -- request.setURI("/metrics?pretty=true"); -- -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo("*"); -- assertThat(response.getContent()) -- .isEqualTo(String.format("{%n" + -- " \"version\" : \"5.0.0\",%n" + -- " \"gauges\" : {%n" + -- " \"g1\" : {%n" + -- " \"value\" : 100%n" + -- " }%n" + -- " },%n" + -- " \"counters\" : {%n" + -- " \"c\" : {%n" + -- " \"count\" : 1%n" + -- " }%n" + -- " },%n" + -- " \"histograms\" : {%n" + -- " \"h\" : {%n" + -- " \"count\" : 1,%n" + -- " \"max\" : 1,%n" + -- " \"mean\" : 1.0,%n" + -- " \"min\" : 1,%n" + -- " \"p50\" : 1.0,%n" + -- " \"p75\" : 1.0,%n" + -- " \"p95\" : 1.0,%n" + -- " \"p98\" : 1.0,%n" + -- " \"p99\" : 1.0,%n" + -- " \"p999\" : 1.0,%n" + -- " \"stddev\" : 0.0%n" + -- " }%n" + -- " },%n" + -- " \"meters\" : {%n" + -- " \"m\" : {%n" + -- " \"count\" : 1,%n" + -- " \"m15_rate\" : 0.0,%n" + -- " \"m1_rate\" : 0.0,%n" + -- " \"m5_rate\" : 0.0,%n" + -- " \"mean_rate\" : 3333333.3333333335,%n" + -- " \"units\" : \"events/second\"%n" + -- " }%n" + -- " },%n" + -- " \"timers\" : {%n" + -- " \"t\" : {%n" + -- " \"count\" : 1,%n" + -- " \"max\" : 1.0,%n" + -- " \"mean\" : 1.0,%n" + -- " \"min\" : 1.0,%n" + -- " \"p50\" : 1.0,%n" + -- " \"p75\" : 1.0,%n" + -- " \"p95\" : 1.0,%n" + -- " \"p98\" : 1.0,%n" + -- " \"p99\" : 1.0,%n" + -- " \"p999\" : 1.0,%n" + -- " \"stddev\" : 0.0,%n" + -- " \"m15_rate\" : 0.0,%n" + -- " \"m1_rate\" : 0.0,%n" + -- " \"m5_rate\" : 0.0,%n" + -- " \"mean_rate\" : 1.0E7,%n" + -- " \"duration_units\" : \"seconds\",%n" + -- " \"rate_units\" : \"calls/second\"%n" + -- " }%n" + -- " }%n" + -- "}")); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- -- final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); -- metricsServlet.init(servletConfig); -- -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -- } -- -- @Test -- void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn(metricRegistry); -- -- final MetricsServlet metricsServlet = new MetricsServlet(null); -- metricsServlet.init(servletConfig); -- -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -- } -- -- @Test -- void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { -- assertThrows(ServletException.class, () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn("IRELLEVANT_STRING"); -- -- final MetricsServlet metricsServlet = new MetricsServlet(null); -- metricsServlet.init(servletConfig); -- }); -- } -+final class MetricsServletTest extends AbstractServletTest { -+ private final Clock clock = mock(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private ServletTester tester; -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ this.tester = tester; -+ tester.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry); -+ tester.addServlet(MetricsServlet.class, "/metrics"); -+ tester -+ .getContext() -+ .setInitParameter(MetricsServlet.class.getCanonicalName() + ".allowedOrigin", "*"); -+ } -+ -+ @BeforeEach -+ void setUp() { -+ // provide ticks for the setup (calls getTick 6 times). The serialization in the tests -+ // themselves -+ // will call getTick again several times and always get the same value (the last specified here) -+ when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); -+ -+ registry.register(MetricName.build("g1"), (Gauge) () -> 100L); -+ registry.counter("c").inc(); -+ registry.histogram("h").update(1); -+ registry.register(MetricName.build("m"), new Meter(clock)).mark(); -+ registry -+ .register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) -+ .update(1, TimeUnit.SECONDS); -+ -+ request.setMethod("GET"); -+ request.setURI("/metrics"); -+ request.setVersion("HTTP/1.0"); -+ } -+ -+ @Test -+ void returnsA200() throws Exception { -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ "{" -+ + "\"version\":\"5.0.0\"," -+ + "\"gauges\":{" -+ + "\"g1\":{\"value\":100}" -+ + "}," -+ + "\"counters\":{" -+ + "\"c\":{\"count\":1}" -+ + "}," -+ + "\"histograms\":{" -+ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -+ + "}," -+ + "\"meters\":{" -+ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -+ + "}" -+ + "}"); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void returnsJsonWhenJsonpInitParamNotSet() throws Exception { -+ String callbackParamName = "callbackParam"; -+ String callbackParamVal = "callbackParamVal"; -+ request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ "{" -+ + "\"version\":\"5.0.0\"," -+ + "\"gauges\":{" -+ + "\"g1\":{\"value\":100}" -+ + "}," -+ + "\"counters\":{" -+ + "\"c\":{\"count\":1}" -+ + "}," -+ + "\"histograms\":{" -+ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -+ + "}," -+ + "\"meters\":{" -+ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -+ + "}" -+ + "}"); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void returnsJsonpWhenInitParamSet() throws Exception { -+ String callbackParamName = "callbackParam"; -+ String callbackParamVal = "callbackParamVal"; -+ request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); -+ tester -+ .getContext() -+ .setInitParameter( -+ MetricsServlet.class.getCanonicalName() + ".jsonpCallback", callbackParamName); -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ "%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", -+ callbackParamVal); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void optionallyPrettyPrintsTheJson() throws Exception { -+ request.setURI("/metrics?pretty=true"); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "{%n" -+ + " \"version\" : \"5.0.0\",%n" -+ + " \"gauges\" : {%n" -+ + " \"g1\" : {%n" -+ + " \"value\" : 100%n" -+ + " }%n" -+ + " },%n" -+ + " \"counters\" : {%n" -+ + " \"c\" : {%n" -+ + " \"count\" : 1%n" -+ + " }%n" -+ + " },%n" -+ + " \"histograms\" : {%n" -+ + " \"h\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"max\" : 1,%n" -+ + " \"mean\" : 1.0,%n" -+ + " \"min\" : 1,%n" -+ + " \"p50\" : 1.0,%n" -+ + " \"p75\" : 1.0,%n" -+ + " \"p95\" : 1.0,%n" -+ + " \"p98\" : 1.0,%n" -+ + " \"p99\" : 1.0,%n" -+ + " \"p999\" : 1.0,%n" -+ + " \"stddev\" : 0.0%n" -+ + " }%n" -+ + " },%n" -+ + " \"meters\" : {%n" -+ + " \"m\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"m15_rate\" : 0.0,%n" -+ + " \"m1_rate\" : 0.0,%n" -+ + " \"m5_rate\" : 0.0,%n" -+ + " \"mean_rate\" : 3333333.3333333335,%n" -+ + " \"units\" : \"events/second\"%n" -+ + " }%n" -+ + " },%n" -+ + " \"timers\" : {%n" -+ + " \"t\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"max\" : 1.0,%n" -+ + " \"mean\" : 1.0,%n" -+ + " \"min\" : 1.0,%n" -+ + " \"p50\" : 1.0,%n" -+ + " \"p75\" : 1.0,%n" -+ + " \"p95\" : 1.0,%n" -+ + " \"p98\" : 1.0,%n" -+ + " \"p99\" : 1.0,%n" -+ + " \"p999\" : 1.0,%n" -+ + " \"stddev\" : 0.0,%n" -+ + " \"m15_rate\" : 0.0,%n" -+ + " \"m1_rate\" : 0.0,%n" -+ + " \"m5_rate\" : 0.0,%n" -+ + " \"mean_rate\" : 1.0E7,%n" -+ + " \"duration_units\" : \"seconds\",%n" -+ + " \"rate_units\" : \"calls/second\"%n" -+ + " }%n" -+ + " }%n" -+ + "}")); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ -+ final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); -+ metricsServlet.init(servletConfig); -+ -+ verify(servletConfig).getServletContext(); -+ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); -+ -+ final MetricsServlet metricsServlet = new MetricsServlet(null); -+ metricsServlet.init(servletConfig); -+ -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() -+ throws Exception { -+ assertThatThrownBy( -+ () -> { -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) -+ .thenReturn("IRELLEVANT_STRING"); -+ -+ final MetricsServlet metricsServlet = new MetricsServlet(null); -+ metricsServlet.init(servletConfig); -+ }) -+ .isInstanceOf(ServletException.class); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java -@@ -1,49 +1,45 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; -- --class PingServletTest extends AbstractServletTest { -- @Override -- protected void setUp(ServletTester tester) { -- tester.addServlet(PingServlet.class, "/ping"); -- } -- -- @BeforeEach -- void setUp() throws Exception { -- request.setMethod("GET"); -- request.setURI("/ping"); -- request.setVersion("HTTP/1.0"); -- -- processRequest(); -- } -- -- @Test -- void returns200OK() { -- assertThat(response.getStatus()) -- .isEqualTo(200); -- } -- -- @Test -- void returnsPong() { -- assertThat(response.getContent()) -- .isEqualTo(String.format("pong%n")); -- } -- -- @Test -- void returnsTextPlain() { -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("text/plain;charset=ISO-8859-1"); -- } -- -- @Test -- void returnsUncacheable() { -- assertThat(response.get(HttpHeader.CACHE_CONTROL)) -- .isEqualTo("must-revalidate,no-cache,no-store"); -- -- } -+final class PingServletTest extends AbstractServletTest { -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.addServlet(PingServlet.class, "/ping"); -+ } -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ request.setMethod("GET"); -+ request.setURI("/ping"); -+ request.setVersion("HTTP/1.0"); -+ -+ processRequest(); -+ } -+ -+ @Test -+ void returns200OK() { -+ assertThat(response.getStatus()).isEqualTo(200); -+ } -+ -+ @Test -+ void returnsPong() { -+ assertThat(response.getContent()).isEqualTo(String.format("pong%n")); -+ } -+ -+ @Test -+ void returnsTextPlain() { -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/plain;charset=ISO-8859-1"); -+ } -+ -+ @Test -+ void returnsUncacheable() { -+ assertThat(response.get(HttpHeader.CACHE_CONTROL)) -+ .isEqualTo("must-revalidate,no-cache,no-store"); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java -@@ -1,49 +1,45 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; -- --class ThreadDumpServletTest extends AbstractServletTest { -- @Override -- protected void setUp(ServletTester tester) { -- tester.addServlet(ThreadDumpServlet.class, "/threads"); -- } -- -- @BeforeEach -- void setUp() throws Exception { -- request.setMethod("GET"); -- request.setURI("/threads"); -- request.setVersion("HTTP/1.0"); -- -- processRequest(); -- } -- -- @Test -- void returns200OK() { -- assertThat(response.getStatus()) -- .isEqualTo(200); -- } -- -- @Test -- void returnsAThreadDump() { -- assertThat(response.getContent()) -- .contains("Finalizer"); -- } -- -- @Test -- void returnsTextPlain() { -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("text/plain"); -- } -- -- @Test -- void returnsUncacheable() { -- assertThat(response.get(HttpHeader.CACHE_CONTROL)) -- .isEqualTo("must-revalidate,no-cache,no-store"); -- -- } -+final class ThreadDumpServletTest extends AbstractServletTest { -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.addServlet(ThreadDumpServlet.class, "/threads"); -+ } -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ request.setMethod("GET"); -+ request.setURI("/threads"); -+ request.setVersion("HTTP/1.0"); -+ -+ processRequest(); -+ } -+ -+ @Test -+ void returns200OK() { -+ assertThat(response.getStatus()).isEqualTo(200); -+ } -+ -+ @Test -+ void returnsAThreadDump() { -+ assertThat(response.getContent()).contains("Finalizer"); -+ } -+ -+ @Test -+ void returnsTextPlain() { -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/plain"); -+ } -+ -+ @Test -+ void returnsUncacheable() { -+ assertThat(response.get(HttpHeader.CACHE_CONTROL)) -+ .isEqualTo("must-revalidate,no-cache,no-store"); -+ } - } ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/experiments/ExampleServer.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/experiments/ExampleServer.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.servlets.experiments; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.MetricRegistry; -@@ -18,43 +20,48 @@ import org.eclipse.jetty.servlet.ServletContextHandler; - import org.eclipse.jetty.servlet.ServletHolder; - import org.eclipse.jetty.util.thread.ThreadPool; - --import static io.dropwizard.metrics5.MetricRegistry.name; -- - public class ExampleServer { -- private static final MetricRegistry REGISTRY = new MetricRegistry(); -- private static final Counter COUNTER_1 = REGISTRY.counter(name(ExampleServer.class, "wah", "doody")); -- private static final Counter COUNTER_2 = REGISTRY.counter(name(ExampleServer.class, "woo")); -+ private static final MetricRegistry REGISTRY = new MetricRegistry(); -+ private static final Counter COUNTER_1 = -+ REGISTRY.counter(name(ExampleServer.class, "wah", "doody")); -+ private static final Counter COUNTER_2 = REGISTRY.counter(name(ExampleServer.class, "woo")); - -- static { -- REGISTRY.register(name(ExampleServer.class, "boo"), (Gauge) () -> { -- throw new RuntimeException("asplode!"); -- }); -- } -+ static { -+ REGISTRY.register( -+ name(ExampleServer.class, "boo"), -+ (Gauge) -+ () -> { -+ throw new RuntimeException("asplode!"); -+ }); -+ } - -- public static void main(String[] args) throws Exception { -- COUNTER_1.inc(); -- COUNTER_2.inc(); -+ public static void main(String[] args) throws Exception { -+ COUNTER_1.inc(); -+ COUNTER_2.inc(); - -- final ThreadPool threadPool = new InstrumentedQueuedThreadPool(REGISTRY); -- final Server server = new Server(threadPool); -+ final ThreadPool threadPool = new InstrumentedQueuedThreadPool(REGISTRY); -+ final Server server = new Server(threadPool); - -- final Connector connector = new ServerConnector(server, new InstrumentedConnectionFactory( -+ final Connector connector = -+ new ServerConnector( -+ server, -+ new InstrumentedConnectionFactory( - new HttpConnectionFactory(), REGISTRY.timer("http.connection"))); -- server.addConnector(connector); -+ server.addConnector(connector); - -- final ServletContextHandler context = new ServletContextHandler(); -- context.setContextPath("/initial"); -- context.setAttribute(MetricsServlet.METRICS_REGISTRY, REGISTRY); -- context.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, new HealthCheckRegistry()); -+ final ServletContextHandler context = new ServletContextHandler(); -+ context.setContextPath("/initial"); -+ context.setAttribute(MetricsServlet.METRICS_REGISTRY, REGISTRY); -+ context.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, new HealthCheckRegistry()); - -- final ServletHolder holder = new ServletHolder(new AdminServlet()); -- context.addServlet(holder, "/dingo/*"); -+ final ServletHolder holder = new ServletHolder(new AdminServlet()); -+ context.addServlet(holder, "/dingo/*"); - -- final InstrumentedHandler handler = new InstrumentedHandler(REGISTRY); -- handler.setHandler(context); -- server.setHandler(handler); -+ final InstrumentedHandler handler = new InstrumentedHandler(REGISTRY); -+ handler.setHandler(context); -+ server.setHandler(handler); - -- server.start(); -- server.join(); -- } -+ server.start(); -+ server.join(); -+ } - } ---- a/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java -+++ b/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java -@@ -1,27 +1,26 @@ - package io.dropwizard.metrics5.jcache; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricSet; - import io.dropwizard.metrics5.jvm.JmxAttributeGauge; --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -- --import javax.cache.management.CacheStatisticsMXBean; --import javax.management.MalformedObjectNameException; --import javax.management.ObjectInstance; --import javax.management.ObjectName; - import java.lang.management.ManagementFactory; - import java.lang.reflect.Method; - import java.util.ArrayList; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Locale; - import java.util.Map; - import java.util.Set; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -+import javax.cache.management.CacheStatisticsMXBean; -+import javax.management.MalformedObjectNameException; -+import javax.management.ObjectInstance; -+import javax.management.ObjectName; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; - - /** - * Gauge set retrieving JCache JMX attributes -@@ -31,54 +30,55 @@ import static io.dropwizard.metrics5.MetricRegistry.name; - */ - public class JCacheGaugeSet implements MetricSet { - -- private static final String M_BEAN_COORDINATES = "javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"; -- -- private static final Logger LOGGER = LoggerFactory.getLogger(JCacheGaugeSet.class); -+ private static final String M_BEAN_COORDINATES = -+ "javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"; - -- @Override -- public Map getMetrics() { -- Set cacheBeans = getCacheBeans(); -- List availableStatsNames = retrieveStatsNames(); -+ private static final Logger LOG = LoggerFactory.getLogger(JCacheGaugeSet.class); - -- Map gauges = new HashMap<>(cacheBeans.size() * availableStatsNames.size()); -+ @Override -+ public Map getMetrics() { -+ Set cacheBeans = getCacheBeans(); -+ List availableStatsNames = retrieveStatsNames(); - -- for (ObjectInstance cacheBean : cacheBeans) { -- ObjectName objectName = cacheBean.getObjectName(); -- String cacheName = objectName.getKeyProperty("Cache"); -+ Map gauges = new HashMap<>(cacheBeans.size() * availableStatsNames.size()); - -- for (String statsName : availableStatsNames) { -- JmxAttributeGauge jmxAttributeGauge = new JmxAttributeGauge(objectName, statsName); -- gauges.put(name(cacheName, toSpinalCase(statsName)), jmxAttributeGauge); -- } -- } -+ for (ObjectInstance cacheBean : cacheBeans) { -+ ObjectName objectName = cacheBean.getObjectName(); -+ String cacheName = objectName.getKeyProperty("Cache"); - -- return Collections.unmodifiableMap(gauges); -+ for (String statsName : availableStatsNames) { -+ JmxAttributeGauge jmxAttributeGauge = new JmxAttributeGauge(objectName, statsName); -+ gauges.put(name(cacheName, toSpinalCase(statsName)), jmxAttributeGauge); -+ } - } - -- private Set getCacheBeans() { -- try { -- return ManagementFactory.getPlatformMBeanServer().queryMBeans(ObjectName.getInstance(M_BEAN_COORDINATES), null); -- } catch (MalformedObjectNameException e) { -- LOGGER.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); -- throw new RuntimeException(e); -- } -- } -+ return unmodifiableMap(gauges); -+ } - -- private List retrieveStatsNames() { -- Method[] methods = CacheStatisticsMXBean.class.getDeclaredMethods(); -- List availableStatsNames = new ArrayList<>(methods.length); -- -- for (Method method : methods) { -- String methodName = method.getName(); -- if (methodName.startsWith("get")) { -- availableStatsNames.add(methodName.substring(3)); -- } -- } -- return availableStatsNames; -+ private Set getCacheBeans() { -+ try { -+ return ManagementFactory.getPlatformMBeanServer() -+ .queryMBeans(ObjectName.getInstance(M_BEAN_COORDINATES), null); -+ } catch (MalformedObjectNameException e) { -+ LOG.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); -+ throw new RuntimeException(e); - } -+ } -+ -+ private List retrieveStatsNames() { -+ Method[] methods = CacheStatisticsMXBean.class.getDeclaredMethods(); -+ List availableStatsNames = new ArrayList<>(methods.length); - -- private static String toSpinalCase(String camelCase) { -- return camelCase.replaceAll("(.)(\\p{Upper})", "$1-$2").toLowerCase(Locale.US); -+ for (Method method : methods) { -+ String methodName = method.getName(); -+ if (methodName.startsWith("get")) { -+ availableStatsNames.add(methodName.substring(3)); -+ } - } -+ return availableStatsNames; -+ } - -+ private static String toSpinalCase(String camelCase) { -+ return camelCase.replaceAll("(.)(\\p{Upper})", "$1-$2").toLowerCase(Locale.US); -+ } - } ---- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java -+++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java -@@ -1,88 +1,83 @@ -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jcache.JCacheGaugeSet; --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- - import javax.cache.Cache; - import javax.cache.CacheManager; - import javax.cache.Caching; - import javax.cache.spi.CachingProvider; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; -- --class JCacheGaugeSetTest { -+final class JCacheGaugeSetTest { - -- private MetricRegistry registry; -- private Cache myCache; -- private Cache myOtherCache; -- private CacheManager cacheManager; -+ private MetricRegistry registry; -+ private Cache myCache; -+ private Cache myOtherCache; -+ private CacheManager cacheManager; - -- @BeforeEach -- void setUp() throws Exception { -+ @BeforeEach -+ void setUp() throws Exception { - -- CachingProvider provider = Caching.getCachingProvider(); -- cacheManager = provider.getCacheManager( -- getClass().getResource("ehcache.xml").toURI(), -- getClass().getClassLoader()); -+ CachingProvider provider = Caching.getCachingProvider(); -+ cacheManager = -+ provider.getCacheManager( -+ getClass().getResource("ehcache.xml").toURI(), getClass().getClassLoader()); - -- myCache = cacheManager.getCache("myCache"); -- myOtherCache = cacheManager.getCache("myOtherCache"); -+ myCache = cacheManager.getCache("myCache"); -+ myOtherCache = cacheManager.getCache("myOtherCache"); - -- registry = new MetricRegistry(); -- registry.register(MetricName.build("jcache.statistics"), new JCacheGaugeSet()); -- } -+ registry = new MetricRegistry(); -+ registry.register(MetricName.build("jcache.statistics"), new JCacheGaugeSet()); -+ } - -- @Test -- void measuresGauges() throws Exception { -+ @Test -+ void measuresGauges() throws Exception { - -- myOtherCache.get("woo"); -- assertThat(registry.getGauges().get(MetricName.build("jcache.statistics.myOtherCache.cache-misses")) -+ myOtherCache.get("woo"); -+ assertThat( -+ registry -+ .getGauges() -+ .get(MetricName.build("jcache.statistics.myOtherCache.cache-misses")) - .getValue()) -- .isEqualTo(1L); -- -- myCache.get("woo"); -- MetricName myCache = MetricName.build("jcache.statistics.myCache"); -- assertThat(registry.getGauges().get(myCache.resolve("cache-misses")).getValue()) -- .isEqualTo(1L); -- assertThat(registry.getGauges().get(myCache.resolve("cache-hits")).getValue()) -- .isEqualTo(0L); -- assertThat(registry.getGauges().get(myCache.resolve("cache-gets")).getValue()) -- .isEqualTo(1L); -- -- this.myCache.put("woo", "whee"); -- this.myCache.get("woo"); -- assertThat(registry.getGauges().get(myCache.resolve("cache-puts")).getValue()) -- .isEqualTo(1L); -- assertThat(registry.getGauges().get(myCache.resolve("cache-hits")).getValue()) -- .isEqualTo(1L); -- assertThat(registry.getGauges().get(myCache.resolve("cache-hit-percentage")).getValue()) -- .isEqualTo(50.0f); -- assertThat(registry.getGauges().get(myCache.resolve("cache-miss-percentage")).getValue()) -- .isEqualTo(50.0f); -- assertThat(registry.getGauges().get(myCache.resolve("cache-gets")).getValue()) -- .isEqualTo(2L); -- -- // cache size being 1, eviction occurs after this line -- this.myCache.put("woo2", "whoza"); -- assertThat(registry.getGauges().get(myCache.resolve("cache-evictions")).getValue()) -- .isEqualTo(1L); -- -- this.myCache.remove("woo2"); -- assertThat((Float) registry.getGauges().get(myCache.resolve("average-get-time")).getValue()) -- .isGreaterThan(0.0f); -- assertThat((Float) registry.getGauges().get(myCache.resolve("average-put-time")).getValue()) -- .isGreaterThan(0.0f); -- assertThat((Float) registry.getGauges().get(myCache.resolve("average-remove-time")).getValue()) -- .isGreaterThan(0.0f); -- -- } -- -- @AfterEach -- void tearDown() throws Exception { -- cacheManager.destroyCache("myCache"); -- cacheManager.destroyCache("myOtherCache"); -- cacheManager.close(); -- } -+ .isEqualTo(1L); -+ -+ myCache.get("woo"); -+ MetricName myCache = MetricName.build("jcache.statistics.myCache"); -+ assertThat(registry.getGauges().get(myCache.resolve("cache-misses")).getValue()).isEqualTo(1L); -+ assertThat(registry.getGauges().get(myCache.resolve("cache-hits")).getValue()).isEqualTo(0L); -+ assertThat(registry.getGauges().get(myCache.resolve("cache-gets")).getValue()).isEqualTo(1L); -+ -+ this.myCache.put("woo", "whee"); -+ this.myCache.get("woo"); -+ assertThat(registry.getGauges().get(myCache.resolve("cache-puts")).getValue()).isEqualTo(1L); -+ assertThat(registry.getGauges().get(myCache.resolve("cache-hits")).getValue()).isEqualTo(1L); -+ assertThat(registry.getGauges().get(myCache.resolve("cache-hit-percentage")).getValue()) -+ .isEqualTo(50.0f); -+ assertThat(registry.getGauges().get(myCache.resolve("cache-miss-percentage")).getValue()) -+ .isEqualTo(50.0f); -+ assertThat(registry.getGauges().get(myCache.resolve("cache-gets")).getValue()).isEqualTo(2L); -+ -+ // cache size being 1, eviction occurs after this line -+ this.myCache.put("woo2", "whoza"); -+ assertThat(registry.getGauges().get(myCache.resolve("cache-evictions")).getValue()) -+ .isEqualTo(1L); -+ -+ this.myCache.remove("woo2"); -+ assertThat((Float) registry.getGauges().get(myCache.resolve("average-get-time")).getValue()) -+ .isPositive(); -+ assertThat((Float) registry.getGauges().get(myCache.resolve("average-put-time")).getValue()) -+ .isPositive(); -+ assertThat((Float) registry.getGauges().get(myCache.resolve("average-remove-time")).getValue()) -+ .isPositive(); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ cacheManager.destroyCache("myCache"); -+ cacheManager.destroyCache("myOtherCache"); -+ cacheManager.close(); -+ } - } ---- a/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTrimReadTest.java -+++ b/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTrimReadTest.java -@@ -1,5 +1,8 @@ - package io.dropwizard.metrics5; - -+import java.util.Arrays; -+import java.util.concurrent.TimeUnit; -+import java.util.concurrent.atomic.AtomicLong; - import org.openjdk.jcstress.annotations.Actor; - import org.openjdk.jcstress.annotations.Expect; - import org.openjdk.jcstress.annotations.JCStressTest; -@@ -7,61 +10,59 @@ import org.openjdk.jcstress.annotations.Outcome; - import org.openjdk.jcstress.annotations.State; - import org.openjdk.jcstress.infra.results.L_Result; - --import java.util.Arrays; --import java.util.concurrent.TimeUnit; --import java.util.concurrent.atomic.AtomicLong; -- - @JCStressTest - @Outcome( - id = "\\[240, 241, 242, 243, 244, 245, 246, 247, 248, 249\\]", - expect = Expect.ACCEPTABLE, -- desc = "Actor1 made read before Actor2 even started" -- ) -+ desc = "Actor1 made read before Actor2 even started") - @Outcome( - id = "\\[243, 244, 245, 246, 247, 248, 249\\]", - expect = Expect.ACCEPTABLE, -- desc = "Actor2 made trim before Actor1 even started" -- ) -+ desc = "Actor2 made trim before Actor1 even started") - @Outcome( - id = "\\[244, 245, 246, 247, 248, 249\\]", - expect = Expect.ACCEPTABLE, -- desc = "Actor1 made trim, then Actor2 started trim and made startIndex change, " + -- "before Actor1 concurrent read." -- ) -+ desc = -+ "Actor1 made trim, then Actor2 started trim and made startIndex change, " -+ + "before Actor1 concurrent read.") - @Outcome( - id = "\\[243, 244, 245, 246, 247, 248\\]", - expect = Expect.ACCEPTABLE, -- desc = "Actor1 made trim, then Actor2 started trim, but not finished startIndex change, before Actor1 concurrent read." -- ) -+ desc = -+ "Actor1 made trim, then Actor2 started trim, but not finished startIndex change, before Actor1 concurrent read.") - @State - public class SlidingTimeWindowArrayReservoirTrimReadTest { -- private final AtomicLong ticks = new AtomicLong(0); -- private final SlidingTimeWindowArrayReservoir reservoir; -+ private final AtomicLong ticks = new AtomicLong(0); -+ private final SlidingTimeWindowArrayReservoir reservoir; - -- public SlidingTimeWindowArrayReservoirTrimReadTest() { -- reservoir = new SlidingTimeWindowArrayReservoir(10, TimeUnit.NANOSECONDS, new Clock() { -- @Override -- public long getTick() { -+ public SlidingTimeWindowArrayReservoirTrimReadTest() { -+ reservoir = -+ new SlidingTimeWindowArrayReservoir( -+ 10, -+ TimeUnit.NANOSECONDS, -+ new Clock() { -+ @Override -+ public long getTick() { - return ticks.get(); -- } -- }); -+ } -+ }); - -- for (int i = 0; i < 250; i++) { -- ticks.set(i); -- reservoir.update(i); -- } -+ for (int i = 0; i < 250; i++) { -+ ticks.set(i); -+ reservoir.update(i); - } -+ } - -- @Actor -- public void actor1(L_Result r) { -- Snapshot snapshot = reservoir.getSnapshot(); -- String stringValues = Arrays.toString(snapshot.getValues()); -- r.r1 = stringValues; -- } -+ @Actor -+ public void actor1(L_Result r) { -+ Snapshot snapshot = reservoir.getSnapshot(); -+ String stringValues = Arrays.toString(snapshot.getValues()); -+ r.r1 = stringValues; -+ } - -- @Actor -- public void actor2() { -- ticks.set(253); -- reservoir.trim(); -- } --} -\ No newline at end of file -+ @Actor -+ public void actor2() { -+ ticks.set(253); -+ reservoir.trim(); -+ } -+} ---- a/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirWriteReadAllocate.java -+++ b/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirWriteReadAllocate.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5; - -+import java.util.Arrays; -+import java.util.concurrent.TimeUnit; - import org.openjdk.jcstress.annotations.Actor; - import org.openjdk.jcstress.annotations.Arbiter; - import org.openjdk.jcstress.annotations.Expect; -@@ -8,38 +10,36 @@ import org.openjdk.jcstress.annotations.Outcome; - import org.openjdk.jcstress.annotations.State; - import org.openjdk.jcstress.infra.results.L_Result; - --import java.util.Arrays; --import java.util.concurrent.TimeUnit; -- - @JCStressTest - @Outcome(id = "\\[1023, 1029, 1034\\]", expect = Expect.ACCEPTABLE) - @State - public class SlidingTimeWindowArrayReservoirWriteReadAllocate { - -- private final SlidingTimeWindowArrayReservoir reservoir; -- -- public SlidingTimeWindowArrayReservoirWriteReadAllocate() { -- reservoir = new SlidingTimeWindowArrayReservoir(500, TimeUnit.SECONDS); -- for (int i = 0; i < 1024; i++) { -- reservoir.update(i); -- } -- } -- -- @Actor -- public void actor1() { -- reservoir.update(1029L); -- } -- -- @Actor -- public void actor2() { -- reservoir.update(1034L); -- } -+ private final SlidingTimeWindowArrayReservoir reservoir; - -- @Arbiter -- public void arbiter(L_Result r) { -- Snapshot snapshot = reservoir.getSnapshot(); -- long[] values = snapshot.getValues(); -- String stringValues = Arrays.toString(Arrays.copyOfRange(values, values.length - 3, values.length)); -- r.r1 = stringValues; -+ public SlidingTimeWindowArrayReservoirWriteReadAllocate() { -+ reservoir = new SlidingTimeWindowArrayReservoir(500, TimeUnit.SECONDS); -+ for (int i = 0; i < 1024; i++) { -+ reservoir.update(i); - } --} -\ No newline at end of file -+ } -+ -+ @Actor -+ public void actor1() { -+ reservoir.update(1029L); -+ } -+ -+ @Actor -+ public void actor2() { -+ reservoir.update(1034L); -+ } -+ -+ @Arbiter -+ public void arbiter(L_Result r) { -+ Snapshot snapshot = reservoir.getSnapshot(); -+ long[] values = snapshot.getValues(); -+ String stringValues = -+ Arrays.toString(Arrays.copyOfRange(values, values.length - 3, values.length)); -+ r.r1 = stringValues; -+ } -+} ---- a/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirWriteReadTest.java -+++ b/metrics-jcstress/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirWriteReadTest.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5; - -+import java.util.Arrays; -+import java.util.concurrent.TimeUnit; - import org.openjdk.jcstress.annotations.Actor; - import org.openjdk.jcstress.annotations.Expect; - import org.openjdk.jcstress.annotations.JCStressTest; -@@ -7,9 +9,6 @@ import org.openjdk.jcstress.annotations.Outcome; - import org.openjdk.jcstress.annotations.State; - import org.openjdk.jcstress.infra.results.L_Result; - --import java.util.Arrays; --import java.util.concurrent.TimeUnit; -- - @JCStressTest - @Outcome(id = "\\[\\]", expect = Expect.ACCEPTABLE) - @Outcome(id = "\\[31\\]", expect = Expect.ACCEPTABLE) -@@ -19,27 +18,26 @@ import java.util.concurrent.TimeUnit; - @State - public class SlidingTimeWindowArrayReservoirWriteReadTest { - -- private final SlidingTimeWindowArrayReservoir reservoir; -- -- public SlidingTimeWindowArrayReservoirWriteReadTest() { -- reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.SECONDS); -- } -- -- @Actor -- public void actor1() { -- reservoir.update(31L); -- } -- -- @Actor -- public void actor2() { -- reservoir.update(15L); -- } -- -- @Actor -- public void actor3(L_Result r) { -- Snapshot snapshot = reservoir.getSnapshot(); -- String stringValues = Arrays.toString(snapshot.getValues()); -- r.r1 = stringValues; -- } -- --} -\ No newline at end of file -+ private final SlidingTimeWindowArrayReservoir reservoir; -+ -+ public SlidingTimeWindowArrayReservoirWriteReadTest() { -+ reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.SECONDS); -+ } -+ -+ @Actor -+ public void actor1() { -+ reservoir.update(31L); -+ } -+ -+ @Actor -+ public void actor2() { -+ reservoir.update(15L); -+ } -+ -+ @Actor -+ public void actor3(L_Result r) { -+ Snapshot snapshot = reservoir.getSnapshot(); -+ String stringValues = Arrays.toString(snapshot.getValues()); -+ r.r1 = stringValues; -+ } -+} ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedSqlLogger.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedSqlLogger.java -@@ -4,45 +4,45 @@ import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jdbi3.strategies.SmartNameStrategy; - import io.dropwizard.metrics5.jdbi3.strategies.StatementNameStrategy; --import org.jdbi.v3.core.statement.SqlLogger; --import org.jdbi.v3.core.statement.StatementContext; -- - import java.sql.SQLException; - import java.time.temporal.ChronoUnit; - import java.util.concurrent.TimeUnit; -+import org.jdbi.v3.core.statement.SqlLogger; -+import org.jdbi.v3.core.statement.StatementContext; - - /** -- * A {@link SqlLogger} implementation for JDBI which uses the SQL objects' class names and -- * method names for nanosecond-precision timers. -+ * A {@link SqlLogger} implementation for JDBI which uses the SQL objects' class names and method -+ * names for nanosecond-precision timers. - */ - public class InstrumentedSqlLogger implements SqlLogger { -- private final MetricRegistry registry; -- private final StatementNameStrategy statementNameStrategy; -- -- public InstrumentedSqlLogger(MetricRegistry registry) { -- this(registry, new SmartNameStrategy()); -- } -- -- public InstrumentedSqlLogger(MetricRegistry registry, StatementNameStrategy statementNameStrategy) { -- this.registry = registry; -- this.statementNameStrategy = statementNameStrategy; -- } -- -- @Override -- public void logAfterExecution(StatementContext context) { -- log(context); -- } -- -- @Override -- public void logException(StatementContext context, SQLException ex) { -- log(context); -- } -- -- private void log(StatementContext context) { -- MetricName statementName = statementNameStrategy.getStatementName(context); -- if (statementName != null) { -- final long elapsed = context.getElapsedTime(ChronoUnit.NANOS); -- registry.timer(statementName).update(elapsed, TimeUnit.NANOSECONDS); -- } -+ private final MetricRegistry registry; -+ private final StatementNameStrategy statementNameStrategy; -+ -+ public InstrumentedSqlLogger(MetricRegistry registry) { -+ this(registry, new SmartNameStrategy()); -+ } -+ -+ public InstrumentedSqlLogger( -+ MetricRegistry registry, StatementNameStrategy statementNameStrategy) { -+ this.registry = registry; -+ this.statementNameStrategy = statementNameStrategy; -+ } -+ -+ @Override -+ public void logAfterExecution(StatementContext context) { -+ log(context); -+ } -+ -+ @Override -+ public void logException(StatementContext context, SQLException ex) { -+ log(context); -+ } -+ -+ private void log(StatementContext context) { -+ MetricName statementName = statementNameStrategy.getStatementName(context); -+ if (statementName != null) { -+ final long elapsed = context.getElapsedTime(ChronoUnit.NANOS); -+ registry.timer(statementName).update(elapsed, TimeUnit.NANOSECONDS); - } -+ } - } ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java -@@ -4,39 +4,39 @@ import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jdbi3.strategies.SmartNameStrategy; - import io.dropwizard.metrics5.jdbi3.strategies.StatementNameStrategy; -+import java.util.concurrent.TimeUnit; - import org.jdbi.v3.core.statement.SqlLogger; - import org.jdbi.v3.core.statement.StatementContext; - import org.jdbi.v3.core.statement.TimingCollector; - --import java.util.concurrent.TimeUnit; -- - /** - * A {@link TimingCollector} implementation for JDBI which uses the SQL objects' class names and - * method names for millisecond-precision timers. - * -- * @deprecated Use {@link InstrumentedSqlLogger} and {@link org.jdbi.v3.core.Jdbi#setSqlLogger(SqlLogger)} instead. -+ * @deprecated Use {@link InstrumentedSqlLogger} and {@link -+ * org.jdbi.v3.core.Jdbi#setSqlLogger(SqlLogger)} instead. - */ - @Deprecated - public class InstrumentedTimingCollector implements TimingCollector { - -- private final MetricRegistry registry; -- private final StatementNameStrategy statementNameStrategy; -+ private final MetricRegistry registry; -+ private final StatementNameStrategy statementNameStrategy; - -- public InstrumentedTimingCollector(MetricRegistry registry) { -- this(registry, new SmartNameStrategy()); -- } -+ public InstrumentedTimingCollector(MetricRegistry registry) { -+ this(registry, new SmartNameStrategy()); -+ } - -- public InstrumentedTimingCollector(MetricRegistry registry, -- StatementNameStrategy statementNameStrategy) { -- this.registry = registry; -- this.statementNameStrategy = statementNameStrategy; -- } -+ public InstrumentedTimingCollector( -+ MetricRegistry registry, StatementNameStrategy statementNameStrategy) { -+ this.registry = registry; -+ this.statementNameStrategy = statementNameStrategy; -+ } - -- @Override -- public void collect(long elapsedTime, StatementContext ctx) { -- MetricName statementName = statementNameStrategy.getStatementName(ctx); -- if (statementName != null) { -- registry.timer(statementName).update(elapsedTime, TimeUnit.NANOSECONDS); -- } -+ @Override -+ public void collect(long elapsedTime, StatementContext ctx) { -+ MetricName statementName = statementNameStrategy.getStatementName(ctx); -+ if (statementName != null) { -+ registry.timer(statementName).update(elapsedTime, TimeUnit.NANOSECONDS); - } -+ } - } ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategy.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategy.java -@@ -1,12 +1,9 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - --/** -- * Collects metrics by respective SQLObject methods. -- */ -+/** Collects metrics by respective SQLObject methods. */ - public class BasicSqlNameStrategy extends DelegatingStatementNameStrategy { - -- public BasicSqlNameStrategy() { -- super(DefaultNameStrategy.CHECK_EMPTY, -- DefaultNameStrategy.SQL_OBJECT); -- } -+ public BasicSqlNameStrategy() { -+ super(DefaultNameStrategy.CHECK_EMPTY, DefaultNameStrategy.SQL_OBJECT); -+ } - } ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java -@@ -1,60 +1,52 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - -+import com.google.common.base.Strings; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import org.jdbi.v3.core.extension.ExtensionMethod; - import org.jdbi.v3.core.statement.StatementContext; - --/** -- * Default strategies which build a basis of more complex strategies -- */ -+/** Default strategies which build a basis of more complex strategies */ - public enum DefaultNameStrategy implements StatementNameStrategy { - -- /** -- * If no SQL in the context, returns `sql.empty`, otherwise falls through -- */ -- CHECK_EMPTY { -- @Override -- public MetricName getStatementName(StatementContext statementContext) { -- final String rawSql = statementContext.getRawSql(); -- return rawSql == null || rawSql.isEmpty() ? MetricName.build("sql.empty") : null; -- } -- }, -- -- /** -- * If there is an SQL object attached to the context, returns the name package, -- * the class and the method on which SQL is declared. If not SQL object is attached, -- * falls through -- */ -- SQL_OBJECT { -- @Override -- public MetricName getStatementName(StatementContext statementContext) { -- ExtensionMethod extensionMethod = statementContext.getExtensionMethod(); -- if (extensionMethod != null) { -- return MetricRegistry.name(extensionMethod.getType(), extensionMethod.getMethod().getName()); -- } -- return null; -- } -- }, -+ /** If no SQL in the context, returns `sql.empty`, otherwise falls through */ -+ CHECK_EMPTY { -+ @Override -+ public MetricName getStatementName(StatementContext statementContext) { -+ final String rawSql = statementContext.getRawSql(); -+ return Strings.isNullOrEmpty(rawSql) ? MetricName.build("sql.empty") : null; -+ } -+ }, - -- /** -- * Returns a raw SQL in the context (even if it's not exist) -- */ -- NAIVE_NAME { -- @Override -- public MetricName getStatementName(StatementContext statementContext) { -- return MetricName.build(statementContext.getRawSql()); -- } -- }, -+ /** -+ * If there is an SQL object attached to the context, returns the name package, the class and the -+ * method on which SQL is declared. If not SQL object is attached, falls through -+ */ -+ SQL_OBJECT { -+ @Override -+ public MetricName getStatementName(StatementContext statementContext) { -+ ExtensionMethod extensionMethod = statementContext.getExtensionMethod(); -+ if (extensionMethod != null) { -+ return MetricRegistry.name( -+ extensionMethod.getType(), extensionMethod.getMethod().getName()); -+ } -+ return null; -+ } -+ }, - -- /** -- * Returns the `sql.raw` constant -- */ -- CONSTANT_SQL_RAW { -- @Override -- public MetricName getStatementName(StatementContext statementContext) { -- return MetricName.build("sql.raw"); -- } -+ /** Returns a raw SQL in the context (even if it's not exist) */ -+ NAIVE_NAME { -+ @Override -+ public MetricName getStatementName(StatementContext statementContext) { -+ return MetricName.build(statementContext.getRawSql()); - } -+ }, - -+ /** Returns the `sql.raw` constant */ -+ CONSTANT_SQL_RAW { -+ @Override -+ public MetricName getStatementName(StatementContext statementContext) { -+ return MetricName.build("sql.raw"); -+ } -+ } - } ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DelegatingStatementNameStrategy.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DelegatingStatementNameStrategy.java -@@ -1,33 +1,30 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - - import io.dropwizard.metrics5.MetricName; --import org.jdbi.v3.core.statement.StatementContext; -- - import java.util.Arrays; - import java.util.List; -+import org.jdbi.v3.core.statement.StatementContext; - - public abstract class DelegatingStatementNameStrategy implements StatementNameStrategy { - -- /** -- * Unknown SQL. -- */ -- private static final MetricName UNKNOWN_SQL = MetricName.build("sql.unknown"); -+ /** Unknown SQL. */ -+ private static final MetricName UNKNOWN_SQL = MetricName.build("sql.unknown"); - -- private final List strategies; -+ private final List strategies; - -- protected DelegatingStatementNameStrategy(StatementNameStrategy... strategies) { -- this.strategies = Arrays.asList(strategies); -- } -- -- @Override -- public MetricName getStatementName(StatementContext statementContext) { -- for (StatementNameStrategy strategy : strategies) { -- final MetricName statementName = strategy.getStatementName(statementContext); -- if (statementName != null) { -- return statementName; -- } -- } -+ protected DelegatingStatementNameStrategy(StatementNameStrategy... strategies) { -+ this.strategies = Arrays.asList(strategies); -+ } - -- return UNKNOWN_SQL; -+ @Override -+ public MetricName getStatementName(StatementContext statementContext) { -+ for (StatementNameStrategy strategy : strategies) { -+ final MetricName statementName = strategy.getStatementName(statementContext); -+ if (statementName != null) { -+ return statementName; -+ } - } -+ -+ return UNKNOWN_SQL; -+ } - } ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategy.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategy.java -@@ -1,12 +1,9 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - --/** -- * Very simple strategy, can be used with any JDBI loader to build basic statistics. -- */ -+/** Very simple strategy, can be used with any JDBI loader to build basic statistics. */ - public class NaiveNameStrategy extends DelegatingStatementNameStrategy { - -- public NaiveNameStrategy() { -- super(DefaultNameStrategy.CHECK_EMPTY, -- DefaultNameStrategy.NAIVE_NAME); -- } -+ public NaiveNameStrategy() { -+ super(DefaultNameStrategy.CHECK_EMPTY, DefaultNameStrategy.NAIVE_NAME); -+ } - } ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategy.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategy.java -@@ -5,9 +5,10 @@ package io.dropwizard.metrics5.jdbi3.strategies; - */ - public class SmartNameStrategy extends DelegatingStatementNameStrategy { - -- public SmartNameStrategy() { -- super(DefaultNameStrategy.CHECK_EMPTY, -- DefaultNameStrategy.SQL_OBJECT, -- DefaultNameStrategy.CONSTANT_SQL_RAW); -- } -+ public SmartNameStrategy() { -+ super( -+ DefaultNameStrategy.CHECK_EMPTY, -+ DefaultNameStrategy.SQL_OBJECT, -+ DefaultNameStrategy.CONSTANT_SQL_RAW); -+ } - } ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/StatementNameStrategy.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/StatementNameStrategy.java -@@ -3,11 +3,9 @@ package io.dropwizard.metrics5.jdbi3.strategies; - import io.dropwizard.metrics5.MetricName; - import org.jdbi.v3.core.statement.StatementContext; - --/** -- * Interface for strategies to statement contexts to metric names. -- */ -+/** Interface for strategies to statement contexts to metric names. */ - @FunctionalInterface - public interface StatementNameStrategy { - -- MetricName getStatementName(StatementContext statementContext); -+ MetricName getStatementName(StatementContext statementContext); - } ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategy.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategy.java -@@ -3,46 +3,44 @@ package io.dropwizard.metrics5.jdbi3.strategies; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.annotation.Timed; -+import java.lang.reflect.Method; - import org.jdbi.v3.core.extension.ExtensionMethod; - import org.jdbi.v3.core.statement.StatementContext; - --import java.lang.reflect.Method; -- --/** -- * Takes into account the {@link Timed} annotation on extension methods -- */ -+/** Takes into account the {@link Timed} annotation on extension methods */ - public class TimedAnnotationNameStrategy implements StatementNameStrategy { - -- @Override -- public MetricName getStatementName(StatementContext statementContext) { -- final ExtensionMethod extensionMethod = statementContext.getExtensionMethod(); -- if (extensionMethod == null) { -- return null; -- } -+ @Override -+ public MetricName getStatementName(StatementContext statementContext) { -+ final ExtensionMethod extensionMethod = statementContext.getExtensionMethod(); -+ if (extensionMethod == null) { -+ return null; -+ } - -- final Class clazz = extensionMethod.getType(); -- final Timed classTimed = clazz.getAnnotation(Timed.class); -- final Method method = extensionMethod.getMethod(); -- final Timed methodTimed = method.getAnnotation(Timed.class); -+ final Class clazz = extensionMethod.getType(); -+ final Timed classTimed = clazz.getAnnotation(Timed.class); -+ final Method method = extensionMethod.getMethod(); -+ final Timed methodTimed = method.getAnnotation(Timed.class); - -- // If the method is timed, figure out the name -- if (methodTimed != null) { -- String methodName = methodTimed.name().isEmpty() ? method.getName() : methodTimed.name(); -- if (methodTimed.absolute()) { -- return MetricName.build(methodName); -- } else { -- // We need to check if the class has a custom timer name -- return classTimed == null || classTimed.name().isEmpty() ? -- MetricRegistry.name(clazz, methodName) : -- MetricRegistry.name(classTimed.name(), methodName); -- } -- } else if (classTimed != null) { -- // Maybe the class is timed? -- return classTimed.name().isEmpty() ? MetricRegistry.name(clazz, method.getName()) : -- MetricRegistry.name(classTimed.name(), method.getName()); -- } else { -- // No timers neither on the method or the class -- return null; -- } -+ // If the method is timed, figure out the name -+ if (methodTimed != null) { -+ String methodName = methodTimed.name().isEmpty() ? method.getName() : methodTimed.name(); -+ if (methodTimed.absolute()) { -+ return MetricName.build(methodName); -+ } else { -+ // We need to check if the class has a custom timer name -+ return classTimed == null || classTimed.name().isEmpty() -+ ? MetricRegistry.name(clazz, methodName) -+ : MetricRegistry.name(classTimed.name(), methodName); -+ } -+ } else if (classTimed != null) { -+ // Maybe the class is timed? -+ return classTimed.name().isEmpty() -+ ? MetricRegistry.name(clazz, method.getName()) -+ : MetricRegistry.name(classTimed.name(), method.getName()); -+ } else { -+ // No timers neither on the method or the class -+ return null; - } -+ } - } ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/AbstractStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/AbstractStrategyTest.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import org.jdbi.v3.core.statement.StatementContext; -@@ -10,22 +12,19 @@ import org.mockito.junit.jupiter.MockitoExtension; - import org.mockito.junit.jupiter.MockitoSettings; - import org.mockito.quality.Strictness; - --import static org.mockito.Mockito.when; -- - @ExtendWith(MockitoExtension.class) - @MockitoSettings(strictness = Strictness.LENIENT) - class AbstractStrategyTest { - -- MetricRegistry registry = new MetricRegistry(); -- @Mock -- StatementContext ctx; -+ MetricRegistry registry = new MetricRegistry(); -+ @Mock StatementContext ctx; - -- @BeforeEach -- void setUp() throws Exception { -- when(ctx.getRawSql()).thenReturn("SELECT 1"); -- } -+ @BeforeEach -+ void setUp() throws Exception { -+ when(ctx.getRawSql()).thenReturn("SELECT 1"); -+ } - -- long getTimerMaxValue(MetricName name) { -- return registry.timer(name).getSnapshot().getMax(); -- } -+ long getTimerMaxValue(MetricName name) { -+ return registry.timer(name).getSnapshot().getMax(); -+ } - } ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java -@@ -1,24 +1,24 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - --import io.dropwizard.metrics5.MetricName; --import org.jdbi.v3.core.extension.ExtensionMethod; --import org.junit.jupiter.api.Test; -- - import static io.dropwizard.metrics5.MetricRegistry.name; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.when; - --class BasicSqlNameStrategyTest extends AbstractStrategyTest { -+import io.dropwizard.metrics5.MetricName; -+import org.jdbi.v3.core.extension.ExtensionMethod; -+import org.junit.jupiter.api.Test; -+ -+final class BasicSqlNameStrategyTest extends AbstractStrategyTest { - -- private final BasicSqlNameStrategy basicSqlNameStrategy = new BasicSqlNameStrategy(); -+ private final BasicSqlNameStrategy basicSqlNameStrategy = new BasicSqlNameStrategy(); - -- @Test -- void producesMethodNameAsMetric() throws Exception { -- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); -- MetricName name = basicSqlNameStrategy.getStatementName(ctx); -- assertThat(name).isEqualTo(name(getClass(), "someMethod")); -- } -+ @Test -+ void producesMethodNameAsMetric() throws Exception { -+ when(ctx.getExtensionMethod()) -+ .thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); -+ MetricName name = basicSqlNameStrategy.getStatementName(ctx); -+ assertThat(name).isEqualTo(name(getClass(), "someMethod")); -+ } - -- public void someMethod() { -- } -+ public void someMethod() {} - } ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java -@@ -1,61 +1,59 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - -+import static org.mockito.Mockito.*; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.jdbi3.InstrumentedSqlLogger; --import io.dropwizard.metrics5.jdbi3.strategies.StatementNameStrategy; --import org.jdbi.v3.core.statement.StatementContext; --import org.junit.jupiter.api.Test; -- - import java.sql.SQLException; - import java.time.temporal.ChronoUnit; - import java.util.concurrent.TimeUnit; -+import org.jdbi.v3.core.statement.StatementContext; -+import org.junit.jupiter.api.Test; - --import static org.mockito.Mockito.*; -- --class InstrumentedSqlLoggerTest { -- @Test -- void logsExecutionTime() { -- final MetricRegistry mockRegistry = mock(MetricRegistry.class); -- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); -- final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); -+final class InstrumentedSqlLoggerTest { -+ @Test -+ void logsExecutionTime() { -+ final MetricRegistry mockRegistry = mock(); -+ final StatementNameStrategy mockNameStrategy = mock(); -+ final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); - -- final StatementContext mockContext = mock(StatementContext.class); -- final Timer mockTimer = mock(Timer.class); -+ final StatementContext mockContext = mock(); -+ final Timer mockTimer = mock(); - -- final MetricName statementName = MetricName.build("my-fake-name"); -- final long fakeElapsed = 1234L; -+ final MetricName statementName = MetricName.build("my-fake-name"); -+ final long fakeElapsed = 1234L; - -- when(mockNameStrategy.getStatementName(mockContext)).thenReturn(statementName); -- when(mockRegistry.timer(statementName)).thenReturn(mockTimer); -+ when(mockNameStrategy.getStatementName(mockContext)).thenReturn(statementName); -+ when(mockRegistry.timer(statementName)).thenReturn(mockTimer); - -- when(mockContext.getElapsedTime(ChronoUnit.NANOS)).thenReturn(fakeElapsed); -+ when(mockContext.getElapsedTime(ChronoUnit.NANOS)).thenReturn(fakeElapsed); - -- logger.logAfterExecution(mockContext); -+ logger.logAfterExecution(mockContext); - -- verify(mockTimer).update(fakeElapsed, TimeUnit.NANOSECONDS); -- } -+ verify(mockTimer).update(fakeElapsed, TimeUnit.NANOSECONDS); -+ } - -- @Test -- void logsExceptionTime() { -- final MetricRegistry mockRegistry = mock(MetricRegistry.class); -- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); -- final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); -+ @Test -+ void logsExceptionTime() { -+ final MetricRegistry mockRegistry = mock(); -+ final StatementNameStrategy mockNameStrategy = mock(); -+ final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); - -- final StatementContext mockContext = mock(StatementContext.class); -- final Timer mockTimer = mock(Timer.class); -+ final StatementContext mockContext = mock(); -+ final Timer mockTimer = mock(); - -- final MetricName statementName = MetricName.build("my-fake-name"); -- final long fakeElapsed = 1234L; -+ final MetricName statementName = MetricName.build("my-fake-name"); -+ final long fakeElapsed = 1234L; - -- when(mockNameStrategy.getStatementName(mockContext)).thenReturn(statementName); -- when(mockRegistry.timer(statementName)).thenReturn(mockTimer); -+ when(mockNameStrategy.getStatementName(mockContext)).thenReturn(statementName); -+ when(mockRegistry.timer(statementName)).thenReturn(mockTimer); - -- when(mockContext.getElapsedTime(ChronoUnit.NANOS)).thenReturn(fakeElapsed); -+ when(mockContext.getElapsedTime(ChronoUnit.NANOS)).thenReturn(fakeElapsed); - -- logger.logException(mockContext, new SQLException()); -+ logger.logException(mockContext, new SQLException()); - -- verify(mockTimer).update(fakeElapsed, TimeUnit.NANOSECONDS); -- } -+ verify(mockTimer).update(fakeElapsed, TimeUnit.NANOSECONDS); -+ } - } ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java -@@ -1,18 +1,17 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - --import io.dropwizard.metrics5.MetricName; --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; - --class NaiveNameStrategyTest extends AbstractStrategyTest { -+import io.dropwizard.metrics5.MetricName; -+import org.junit.jupiter.api.Test; - -- private final NaiveNameStrategy naiveNameStrategy = new NaiveNameStrategy(); -+final class NaiveNameStrategyTest extends AbstractStrategyTest { - -- @Test -- void producesSqlRawMetrics() throws Exception { -- MetricName name = naiveNameStrategy.getStatementName(ctx); -- assertThat(name.getKey()).isEqualToIgnoringCase("SELECT 1"); -- } -+ private final NaiveNameStrategy naiveNameStrategy = new NaiveNameStrategy(); - -+ @Test -+ void producesSqlRawMetrics() throws Exception { -+ MetricName name = naiveNameStrategy.getStatementName(ctx); -+ assertThat(name.getKey()).isEqualToIgnoringCase("SELECT 1"); -+ } - } ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java -@@ -1,73 +1,71 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.reset; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.jdbi3.InstrumentedTimingCollector; -+import java.util.concurrent.TimeUnit; - import org.jdbi.v3.core.extension.ExtensionMethod; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.reset; --import static org.mockito.Mockito.when; -- --class SmartNameStrategyTest extends AbstractStrategyTest { -+final class SmartNameStrategyTest extends AbstractStrategyTest { - -- private final StatementNameStrategy smartNameStrategy = new SmartNameStrategy(); -- private InstrumentedTimingCollector collector; -+ private final StatementNameStrategy smartNameStrategy = new SmartNameStrategy(); -+ private InstrumentedTimingCollector collector; - -- @BeforeEach -- @Override -- public void setUp() throws Exception { -- super.setUp(); -- collector = new InstrumentedTimingCollector(registry, smartNameStrategy); -- } -+ @BeforeEach -+ @Override -+ public void setUp() throws Exception { -+ super.setUp(); -+ collector = new InstrumentedTimingCollector(registry, smartNameStrategy); -+ } - -- @Test -- void updatesTimerForSqlObjects() throws Exception { -- when(ctx.getExtensionMethod()).thenReturn( -- new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); -+ @Test -+ void updatesTimerForSqlObjects() throws Exception { -+ when(ctx.getExtensionMethod()) -+ .thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); - -- collector.collect(TimeUnit.SECONDS.toNanos(1), ctx); -+ collector.collect(TimeUnit.SECONDS.toNanos(1), ctx); - -- MetricName name = smartNameStrategy.getStatementName(ctx); -- assertThat(name).isEqualTo(name(getClass(), "someMethod")); -- assertThat(getTimerMaxValue(name)).isEqualTo(1000000000); -- } -+ MetricName name = smartNameStrategy.getStatementName(ctx); -+ assertThat(name).isEqualTo(name(getClass(), "someMethod")); -+ assertThat(getTimerMaxValue(name)).isEqualTo(1000000000); -+ } - -- @Test -- void updatesTimerForRawSql() throws Exception { -- collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); -+ @Test -+ void updatesTimerForRawSql() throws Exception { -+ collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); - -- MetricName name = smartNameStrategy.getStatementName(ctx); -- assertThat(name).isEqualTo(name("sql", "raw")); -- assertThat(getTimerMaxValue(name)).isEqualTo(2000000000); -- } -+ MetricName name = smartNameStrategy.getStatementName(ctx); -+ assertThat(name).isEqualTo(name("sql", "raw")); -+ assertThat(getTimerMaxValue(name)).isEqualTo(2000000000); -+ } - -- @Test -- void updatesTimerForNoRawSql() throws Exception { -- reset(ctx); -+ @Test -+ void updatesTimerForNoRawSql() throws Exception { -+ reset(ctx); - -- collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); -+ collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); - -- MetricName name = smartNameStrategy.getStatementName(ctx); -- assertThat(name).isEqualTo(name("sql", "empty")); -- assertThat(getTimerMaxValue(name)).isEqualTo(2000000000); -- } -+ MetricName name = smartNameStrategy.getStatementName(ctx); -+ assertThat(name).isEqualTo(name("sql", "empty")); -+ assertThat(getTimerMaxValue(name)).isEqualTo(2000000000); -+ } - -- @Test -- void updatesTimerForContextClass() throws Exception { -- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(getClass(), -- getClass().getMethod("someMethod"))); -- collector.collect(TimeUnit.SECONDS.toNanos(3), ctx); -+ @Test -+ void updatesTimerForContextClass() throws Exception { -+ when(ctx.getExtensionMethod()) -+ .thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); -+ collector.collect(TimeUnit.SECONDS.toNanos(3), ctx); - -- MetricName name = smartNameStrategy.getStatementName(ctx); -- assertThat(name).isEqualTo(name(getClass(), "someMethod")); -- assertThat(getTimerMaxValue(name)).isEqualTo(3000000000L); -- } -+ MetricName name = smartNameStrategy.getStatementName(ctx); -+ assertThat(name).isEqualTo(name(getClass(), "someMethod")); -+ assertThat(getTimerMaxValue(name)).isEqualTo(3000000000L); -+ } - -- public void someMethod() { -- } -+ public void someMethod() {} - } ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java -@@ -1,89 +1,104 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.annotation.Timed; - import org.jdbi.v3.core.extension.ExtensionMethod; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.when; -- --class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { -- -- private final TimedAnnotationNameStrategy timedAnnotationNameStrategy = new TimedAnnotationNameStrategy(); -- -- public interface Foo { -- -- @Timed -- void update(); -- -- @Timed(name = "custom-update") -- void customUpdate(); -+final class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { - -- @Timed(name = "absolute-update", absolute = true) -- void absoluteUpdate(); -- } -+ private final TimedAnnotationNameStrategy timedAnnotationNameStrategy = -+ new TimedAnnotationNameStrategy(); - -+ public interface Foo { - - @Timed -- public interface Bar { -- -- void update(); -- } -- -- @Timed(name = "custom-bar") -- public interface CustomBar { -- -- @Timed(name = "find-by-id") -- int find(String name); -- } -- -- public interface Dummy { -- -- void show(); -- } -- -- @Test -- void testAnnotationOnMethod() throws Exception { -- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("update"))); -- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -- .isEqualTo(MetricName.build("io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.update")); -- } -- -- @Test -- void testAnnotationOnMethodWithCustomName() throws Exception { -- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("customUpdate"))); -- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -- .isEqualTo(MetricName.build("io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.custom-update")); -- } -- -- @Test -- void testAnnotationOnMethodWithCustomAbsoluteName() throws Exception { -- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("absoluteUpdate"))); -- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isEqualTo(MetricName.build("absolute-update")); -- } -- -- @Test -- void testAnnotationOnClass() throws Exception { -- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Bar.class, Bar.class.getMethod("update"))); -- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -- .isEqualTo(MetricName.build("io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Bar.update")); -- } -- -- @Test -- void testAnnotationOnMethodAndClassWithCustomNames() throws Exception { -- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(CustomBar.class, CustomBar.class.getMethod("find", String.class))); -- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isEqualTo(MetricName.build("custom-bar.find-by-id")); -- } -- -- @Test -- void testNoAnnotations() throws Exception { -- when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Dummy.class, Dummy.class.getMethod("show"))); -- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); -- } -- -- @Test -- void testNoMethod() { -- assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); -- } --} -\ No newline at end of file -+ void update(); -+ -+ @Timed(name = "custom-update") -+ void customUpdate(); -+ -+ @Timed(name = "absolute-update", absolute = true) -+ void absoluteUpdate(); -+ } -+ -+ @Timed -+ public interface Bar { -+ -+ void update(); -+ } -+ -+ @Timed(name = "custom-bar") -+ public interface CustomBar { -+ -+ @Timed(name = "find-by-id") -+ int find(String name); -+ } -+ -+ public interface Dummy { -+ -+ void show(); -+ } -+ -+ @Test -+ void annotationOnMethod() throws Exception { -+ when(ctx.getExtensionMethod()) -+ .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("update"))); -+ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -+ .isEqualTo( -+ MetricName.build( -+ "io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.update")); -+ } -+ -+ @Test -+ void annotationOnMethodWithCustomName() throws Exception { -+ when(ctx.getExtensionMethod()) -+ .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("customUpdate"))); -+ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -+ .isEqualTo( -+ MetricName.build( -+ "io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.custom-update")); -+ } -+ -+ @Test -+ void annotationOnMethodWithCustomAbsoluteName() throws Exception { -+ when(ctx.getExtensionMethod()) -+ .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("absoluteUpdate"))); -+ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -+ .isEqualTo(MetricName.build("absolute-update")); -+ } -+ -+ @Test -+ void annotationOnClass() throws Exception { -+ when(ctx.getExtensionMethod()) -+ .thenReturn(new ExtensionMethod(Bar.class, Bar.class.getMethod("update"))); -+ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -+ .isEqualTo( -+ MetricName.build( -+ "io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Bar.update")); -+ } -+ -+ @Test -+ void annotationOnMethodAndClassWithCustomNames() throws Exception { -+ when(ctx.getExtensionMethod()) -+ .thenReturn( -+ new ExtensionMethod(CustomBar.class, CustomBar.class.getMethod("find", String.class))); -+ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -+ .isEqualTo(MetricName.build("custom-bar.find-by-id")); -+ } -+ -+ @Test -+ void noAnnotations() throws Exception { -+ when(ctx.getExtensionMethod()) -+ .thenReturn(new ExtensionMethod(Dummy.class, Dummy.class.getMethod("show"))); -+ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); -+ } -+ -+ @Test -+ void noMethod() { -+ assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); -+ } -+} ---- a/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java -@@ -1,5 +1,13 @@ - package io.dropwizard.metrics5.jersey2; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; -+ -+import com.google.common.base.Strings; -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Meter; -@@ -12,541 +20,589 @@ import io.dropwizard.metrics5.annotation.Metered; - import io.dropwizard.metrics5.annotation.ResponseMetered; - import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; - import io.dropwizard.metrics5.annotation.Timed; --import org.glassfish.jersey.server.ContainerResponse; --import org.glassfish.jersey.server.model.ModelProcessor; --import org.glassfish.jersey.server.model.Resource; --import org.glassfish.jersey.server.model.ResourceMethod; --import org.glassfish.jersey.server.model.ResourceModel; --import org.glassfish.jersey.server.monitoring.ApplicationEvent; --import org.glassfish.jersey.server.monitoring.ApplicationEventListener; --import org.glassfish.jersey.server.monitoring.RequestEvent; --import org.glassfish.jersey.server.monitoring.RequestEventListener; -- --import javax.ws.rs.core.Configuration; --import javax.ws.rs.ext.Provider; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; -+import java.util.EnumSet; - import java.util.List; - import java.util.Map; - import java.util.Set; --import java.util.EnumSet; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.ConcurrentMap; - import java.util.concurrent.TimeUnit; - import java.util.function.Supplier; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import javax.ws.rs.core.Configuration; -+import javax.ws.rs.ext.Provider; -+import org.glassfish.jersey.server.ContainerResponse; -+import org.glassfish.jersey.server.model.ModelProcessor; -+import org.glassfish.jersey.server.model.Resource; -+import org.glassfish.jersey.server.model.ResourceMethod; -+import org.glassfish.jersey.server.model.ResourceModel; -+import org.glassfish.jersey.server.monitoring.ApplicationEvent; -+import org.glassfish.jersey.server.monitoring.ApplicationEventListener; -+import org.glassfish.jersey.server.monitoring.RequestEvent; -+import org.glassfish.jersey.server.monitoring.RequestEventListener; - - /** -- * An application event listener that listens for Jersey application initialization to -- * be finished, then creates a map of resource method that have metrics annotations. -- *

    -- * Finally, it listens for method start events, and returns a {@link RequestEventListener} -- * that updates the relevant metric for suitably annotated methods when it gets the -- * request events indicating that the method is about to be invoked, or just got done -- * being invoked. -+ * An application event listener that listens for Jersey application initialization to be finished, -+ * then creates a map of resource method that have metrics annotations. -+ * -+ *

    Finally, it listens for method start events, and returns a {@link RequestEventListener} that -+ * updates the relevant metric for suitably annotated methods when it gets the request events -+ * indicating that the method is about to be invoked, or just got done being invoked. - */ - @Provider --public class InstrumentedResourceMethodApplicationListener implements ApplicationEventListener, ModelProcessor { -- -- private static final String[] REQUEST_FILTERING = {"request", "filtering"}; -- private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; -- private static final String TOTAL = "total"; -- -- private final MetricRegistry metrics; -- private final ConcurrentMap timers = new ConcurrentHashMap<>(); -- private final ConcurrentMap meters = new ConcurrentHashMap<>(); -- private final ConcurrentMap exceptionMeters = new ConcurrentHashMap<>(); -- private final ConcurrentMap responseMeters = new ConcurrentHashMap<>(); -- -- private final Clock clock; -- private final boolean trackFilters; -- private final Supplier reservoirSupplier; -- -- /** -- * Construct an application event listener using the given metrics registry. -- *

    -- * When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} -- * should be added to a Jersey {@code ResourceConfig} as a singleton. -- * -- * @param metrics a {@link MetricRegistry} -- */ -- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { -- this(metrics, Clock.defaultClock(), false); -- } -- -- /** -- * Constructs a custom application listener. -- * -- * @param metrics the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- */ -- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, -- final boolean trackFilters) { -- this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); -- } -- -- /** -- * Constructs a custom application listener. -- * -- * @param metrics the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -- */ -- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, -- final boolean trackFilters, -- final Supplier reservoirSupplier) { -- this.metrics = metrics; -- this.clock = clock; -- this.trackFilters = trackFilters; -- this.reservoirSupplier = reservoirSupplier; -- } -- -- /** -- * A private class to maintain the metric for a method annotated with the -- * {@link ExceptionMetered} annotation, which needs to maintain both a meter -- * and a cause for which the meter should be updated. -- */ -- private static class ExceptionMeterMetric { -- public final Meter meter; -- public final Class cause; -- -- public ExceptionMeterMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final ExceptionMetered exceptionMetered) { -- final MetricName name = chooseName(exceptionMetered.name(), -- exceptionMetered.absolute(), method, ExceptionMetered.DEFAULT_NAME_SUFFIX); -- this.meter = registry.meter(name); -- this.cause = exceptionMetered.cause(); -- } -+public class InstrumentedResourceMethodApplicationListener -+ implements ApplicationEventListener, ModelProcessor { -+ -+ private static final String[] REQUEST_FILTERING = {"request", "filtering"}; -+ private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; -+ private static final String TOTAL = "total"; -+ -+ private final MetricRegistry metrics; -+ private final ConcurrentMap timers = new ConcurrentHashMap<>(); -+ private final ConcurrentMap meters = new ConcurrentHashMap<>(); -+ private final ConcurrentMap exceptionMeters = -+ new ConcurrentHashMap<>(); -+ private final ConcurrentMap responseMeters = -+ new ConcurrentHashMap<>(); -+ -+ private final Clock clock; -+ private final boolean trackFilters; -+ private final Supplier reservoirSupplier; -+ -+ /** -+ * Construct an application event listener using the given metrics registry. -+ * -+ *

    When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} -+ * should be added to a Jersey {@code ResourceConfig} as a singleton. -+ * -+ * @param metrics a {@link MetricRegistry} -+ */ -+ public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { -+ this(metrics, Clock.defaultClock(), false); -+ } -+ -+ /** -+ * Constructs a custom application listener. -+ * -+ * @param metrics the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be -+ * tracked -+ */ -+ public InstrumentedResourceMethodApplicationListener( -+ final MetricRegistry metrics, final Clock clock, final boolean trackFilters) { -+ this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); -+ } -+ -+ /** -+ * Constructs a custom application listener. -+ * -+ * @param metrics the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be -+ * tracked -+ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -+ */ -+ public InstrumentedResourceMethodApplicationListener( -+ final MetricRegistry metrics, -+ final Clock clock, -+ final boolean trackFilters, -+ final Supplier reservoirSupplier) { -+ this.metrics = metrics; -+ this.clock = clock; -+ this.trackFilters = trackFilters; -+ this.reservoirSupplier = reservoirSupplier; -+ } -+ -+ /** -+ * A private class to maintain the metric for a method annotated with the {@link ExceptionMetered} -+ * annotation, which needs to maintain both a meter and a cause for which the meter should be -+ * updated. -+ */ -+ private static class ExceptionMeterMetric { -+ public final Meter meter; -+ public final Class cause; -+ -+ public ExceptionMeterMetric( -+ final MetricRegistry registry, -+ final ResourceMethod method, -+ final ExceptionMetered exceptionMetered) { -+ final MetricName name = -+ chooseName( -+ exceptionMetered.name(), -+ exceptionMetered.absolute(), -+ method, -+ ExceptionMetered.DEFAULT_NAME_SUFFIX); -+ this.meter = registry.meter(name); -+ this.cause = exceptionMetered.cause(); - } -- -- /** -- * A private class to maintain the metrics for a method annotated with the -- * {@link ResponseMetered} annotation, which needs to maintain meters for -- * different response codes -- */ -- private static class ResponseMeterMetric { -- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -- private final MetricName metricName; -- private final List meters; -- private final Map responseCodeMeters; -- private final MetricRegistry metricRegistry; -- private final ResponseMeteredLevel level; -- -- public ResponseMeterMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final ResponseMetered responseMetered) { -- this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); -- this.level = responseMetered.level(); -- this.meters = COARSE_METER_LEVELS.contains(level) ? -- Collections.unmodifiableList(Arrays.asList( -- registry.meter(metricName.resolve("1xx-responses")), // 1xx -- registry.meter(metricName.resolve("2xx-responses")), // 2xx -- registry.meter(metricName.resolve("3xx-responses")), // 3xx -- registry.meter(metricName.resolve("4xx-responses")), // 4xx -- registry.meter(metricName.resolve("5xx-responses")) // 5xx -- )) : Collections.emptyList(); -- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : Collections.emptyMap(); -- this.metricRegistry = registry; -- } -- -- public void mark(int statusCode) { -- if (DETAILED_METER_LEVELS.contains(level)) { -- getResponseCodeMeter(statusCode).mark(); -- } -- -- if (COARSE_METER_LEVELS.contains(level)) { -- final int responseStatus = statusCode / 100; -- if (responseStatus >= 1 && responseStatus <= 5) { -- meters.get(responseStatus - 1).mark(); -- } -- } -- } -- -- private Meter getResponseCodeMeter(int statusCode) { -- return responseCodeMeters -- .computeIfAbsent(statusCode, sc -> metricRegistry -- .meter(metricName.resolve(String.format("%d-responses", sc)))); -- } -+ } -+ -+ /** -+ * A private class to maintain the metrics for a method annotated with the {@link ResponseMetered} -+ * annotation, which needs to maintain meters for different response codes -+ */ -+ private static class ResponseMeterMetric { -+ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -+ private static final Set DETAILED_METER_LEVELS = -+ EnumSet.of(DETAILED, ALL); -+ private final MetricName metricName; -+ private final List meters; -+ private final Map responseCodeMeters; -+ private final MetricRegistry metricRegistry; -+ private final ResponseMeteredLevel level; -+ -+ public ResponseMeterMetric( -+ final MetricRegistry registry, -+ final ResourceMethod method, -+ final ResponseMetered responseMetered) { -+ this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); -+ this.level = responseMetered.level(); -+ this.meters = -+ COARSE_METER_LEVELS.contains(level) -+ ? unmodifiableList( -+ Arrays.asList( -+ registry.meter(metricName.resolve("1xx-responses")), // 1xx -+ registry.meter(metricName.resolve("2xx-responses")), // 2xx -+ registry.meter(metricName.resolve("3xx-responses")), // 3xx -+ registry.meter(metricName.resolve("4xx-responses")), // 4xx -+ registry.meter(metricName.resolve("5xx-responses")) // 5xx -+ )) -+ : ImmutableList.of(); -+ this.responseCodeMeters = -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); -+ this.metricRegistry = registry; - } - -- private static class TimerRequestEventListener implements RequestEventListener { -+ public void mark(int statusCode) { -+ if (DETAILED_METER_LEVELS.contains(level)) { -+ getResponseCodeMeter(statusCode).mark(); -+ } - -- private final ConcurrentMap timers; -- private final Clock clock; -- private final long start; -- private Timer.Context resourceMethodStartContext; -- private Timer.Context requestMatchedContext; -- private Timer.Context responseFiltersStartContext; -- -- public TimerRequestEventListener(final ConcurrentMap timers, final Clock clock) { -- this.timers = timers; -- this.clock = clock; -- start = clock.getTick(); -- } -- -- @Override -- public void onEvent(RequestEvent event) { -- switch (event.getType()) { -- case RESOURCE_METHOD_START: -- resourceMethodStartContext = context(event); -- break; -- case REQUEST_MATCHED: -- requestMatchedContext = context(event); -- break; -- case RESP_FILTERS_START: -- responseFiltersStartContext = context(event); -- break; -- case RESOURCE_METHOD_FINISHED: -- if (resourceMethodStartContext != null) { -- resourceMethodStartContext.close(); -- } -- break; -- case REQUEST_FILTERED: -- if (requestMatchedContext != null) { -- requestMatchedContext.close(); -- } -- break; -- case RESP_FILTERS_FINISHED: -- if (responseFiltersStartContext != null) { -- responseFiltersStartContext.close(); -- } -- break; -- case FINISHED: -- if (requestMatchedContext != null && responseFiltersStartContext != null) { -- final Timer timer = timer(event); -- if (timer != null) { -- timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); -- } -- } -- break; -- default: -- break; -- } -- } -- -- private Timer timer(RequestEvent event) { -- final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); -- if (resourceMethod == null) { -- return null; -- } -- return timers.get(new EventTypeAndMethod(event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); -- } -- -- private Timer.Context context(RequestEvent event) { -- final Timer timer = timer(event); -- return timer != null ? timer.time() : null; -+ if (COARSE_METER_LEVELS.contains(level)) { -+ final int responseStatus = statusCode / 100; -+ if (responseStatus >= 1 && responseStatus <= 5) { -+ meters.get(responseStatus - 1).mark(); - } -+ } - } - -- private static class MeterRequestEventListener implements RequestEventListener { -- private final ConcurrentMap meters; -- -- public MeterRequestEventListener(final ConcurrentMap meters) { -- this.meters = meters; -- } -- -- @Override -- public void onEvent(RequestEvent event) { -- if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { -- final Meter meter = this.meters.get(event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); -- if (meter != null) { -- meter.mark(); -- } -- } -- } -+ private Meter getResponseCodeMeter(int statusCode) { -+ return responseCodeMeters.computeIfAbsent( -+ statusCode, -+ sc -> metricRegistry.meter(metricName.resolve(String.format("%d-responses", sc)))); - } -+ } - -- private static class ExceptionMeterRequestEventListener implements RequestEventListener { -- private final ConcurrentMap exceptionMeters; -+ private static class TimerRequestEventListener implements RequestEventListener { - -- public ExceptionMeterRequestEventListener(final ConcurrentMap exceptionMeters) { -- this.exceptionMeters = exceptionMeters; -- } -+ private final ConcurrentMap timers; -+ private final Clock clock; -+ private final long start; -+ private Timer.Context resourceMethodStartContext; -+ private Timer.Context requestMatchedContext; -+ private Timer.Context responseFiltersStartContext; -+ -+ public TimerRequestEventListener( -+ final ConcurrentMap timers, final Clock clock) { -+ this.timers = timers; -+ this.clock = clock; -+ start = clock.getTick(); -+ } - -- @Override -- public void onEvent(RequestEvent event) { -- if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { -- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -- final ExceptionMeterMetric metric = (method != null) ? -- this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) : null; -- -- if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) || -- (event.getException().getCause() != null && -- metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -- metric.meter.mark(); -- } -- } -+ @Override -+ public void onEvent(RequestEvent event) { -+ switch (event.getType()) { -+ case RESOURCE_METHOD_START: -+ resourceMethodStartContext = context(event); -+ break; -+ case REQUEST_MATCHED: -+ requestMatchedContext = context(event); -+ break; -+ case RESP_FILTERS_START: -+ responseFiltersStartContext = context(event); -+ break; -+ case RESOURCE_METHOD_FINISHED: -+ if (resourceMethodStartContext != null) { -+ resourceMethodStartContext.close(); -+ } -+ break; -+ case REQUEST_FILTERED: -+ if (requestMatchedContext != null) { -+ requestMatchedContext.close(); -+ } -+ break; -+ case RESP_FILTERS_FINISHED: -+ if (responseFiltersStartContext != null) { -+ responseFiltersStartContext.close(); -+ } -+ break; -+ case FINISHED: -+ if (requestMatchedContext != null && responseFiltersStartContext != null) { -+ final Timer timer = timer(event); -+ if (timer != null) { -+ timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); - } -- } -+ } -+ break; -+ default: -+ break; -+ } - } - -- private static class ResponseMeterRequestEventListener implements RequestEventListener { -- private final ConcurrentMap responseMeters; -- -- public ResponseMeterRequestEventListener(final ConcurrentMap responseMeters) { -- this.responseMeters = responseMeters; -- } -- -- @Override -- public void onEvent(RequestEvent event) { -- if (event.getType() == RequestEvent.Type.FINISHED) { -- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -- final ResponseMeterMetric metric = (method != null) ? -- this.responseMeters.get(method.getInvocable().getDefinitionMethod()) : null; -- -- if (metric != null) { -- ContainerResponse containerResponse = event.getContainerResponse(); -- if (containerResponse == null && event.getException() != null) { -- metric.mark(500); -- } else if (containerResponse != null) { -- metric.mark(containerResponse.getStatus()); -- } -- } -- } -- } -+ private Timer timer(RequestEvent event) { -+ final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); -+ if (resourceMethod == null) { -+ return null; -+ } -+ return timers.get( -+ new EventTypeAndMethod( -+ event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); - } - -- private static class ChainedRequestEventListener implements RequestEventListener { -- private final RequestEventListener[] listeners; -+ private Timer.Context context(RequestEvent event) { -+ final Timer timer = timer(event); -+ return timer != null ? timer.time() : null; -+ } -+ } - -- private ChainedRequestEventListener(final RequestEventListener... listeners) { -- this.listeners = listeners; -- } -+ private static class MeterRequestEventListener implements RequestEventListener { -+ private final ConcurrentMap meters; - -- @Override -- public void onEvent(final RequestEvent event) { -- for (RequestEventListener listener : listeners) { -- listener.onEvent(event); -- } -- } -+ public MeterRequestEventListener(final ConcurrentMap meters) { -+ this.meters = meters; - } - - @Override -- public void onEvent(ApplicationEvent event) { -- if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { -- registerMetricsForModel(event.getResourceModel()); -- } -+ public void onEvent(RequestEvent event) { -+ if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { -+ final Meter meter = -+ this.meters.get( -+ event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); -+ if (meter != null) { -+ meter.mark(); -+ } -+ } - } -+ } - -- @Override -- public ResourceModel processResourceModel(ResourceModel resourceModel, Configuration configuration) { -- return resourceModel; -+ private static class ExceptionMeterRequestEventListener implements RequestEventListener { -+ private final ConcurrentMap exceptionMeters; -+ -+ public ExceptionMeterRequestEventListener( -+ final ConcurrentMap exceptionMeters) { -+ this.exceptionMeters = exceptionMeters; - } - - @Override -- public ResourceModel processSubResource(ResourceModel subResourceModel, Configuration configuration) { -- registerMetricsForModel(subResourceModel); -- return subResourceModel; -+ public void onEvent(RequestEvent event) { -+ if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { -+ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -+ final ExceptionMeterMetric metric = -+ (method != null) -+ ? this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) -+ : null; -+ -+ if (metric != null) { -+ if (metric.cause.isInstance(event.getException()) -+ || (event.getException().getCause() != null -+ && metric.cause.isInstance(event.getException().getCause()))) { -+ metric.meter.mark(); -+ } -+ } -+ } - } -+ } - -- private void registerMetricsForModel(ResourceModel resourceModel) { -- for (final Resource resource : resourceModel.getResources()) { -- -- final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); -- final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); -- final ExceptionMetered classLevelExceptionMetered = getClassLevelAnnotation(resource, ExceptionMetered.class); -- final ResponseMetered classLevelResponseMetered = getClassLevelAnnotation(resource, ResponseMetered.class); -- -- for (final ResourceMethod method : resource.getAllMethods()) { -- registerTimedAnnotations(method, classLevelTimed); -- registerMeteredAnnotations(method, classLevelMetered); -- registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); -- registerResponseMeteredAnnotations(method, classLevelResponseMetered); -- } -- -- for (final Resource childResource : resource.getChildResources()) { -+ private static class ResponseMeterRequestEventListener implements RequestEventListener { -+ private final ConcurrentMap responseMeters; - -- final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); -- final Metered classLevelMeteredChild = getClassLevelAnnotation(childResource, Metered.class); -- final ExceptionMetered classLevelExceptionMeteredChild = getClassLevelAnnotation(childResource, ExceptionMetered.class); -- final ResponseMetered classLevelResponseMeteredChild = getClassLevelAnnotation(childResource, ResponseMetered.class); -- -- for (final ResourceMethod method : childResource.getAllMethods()) { -- registerTimedAnnotations(method, classLevelTimedChild); -- registerMeteredAnnotations(method, classLevelMeteredChild); -- registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); -- registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); -- } -- } -- } -+ public ResponseMeterRequestEventListener( -+ final ConcurrentMap responseMeters) { -+ this.responseMeters = responseMeters; - } - - @Override -- public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ public void onEvent(RequestEvent event) { -+ if (event.getType() == RequestEvent.Type.FINISHED) { -+ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -+ final ResponseMeterMetric metric = -+ (method != null) -+ ? this.responseMeters.get(method.getInvocable().getDefinitionMethod()) -+ : null; -+ -+ if (metric != null) { -+ ContainerResponse containerResponse = event.getContainerResponse(); -+ if (containerResponse == null && event.getException() != null) { -+ metric.mark(500); -+ } else if (containerResponse != null) { -+ metric.mark(containerResponse.getStatus()); -+ } -+ } -+ } - } -+ } - -- private T getClassLevelAnnotation(final Resource resource, final Class annotationClazz) { -- T annotation = null; -+ private static class ChainedRequestEventListener implements RequestEventListener { -+ private final RequestEventListener[] listeners; - -- for (final Class clazz : resource.getHandlerClasses()) { -- annotation = clazz.getAnnotation(annotationClazz); -- -- if (annotation != null) { -- break; -- } -- } -- return annotation; -+ private ChainedRequestEventListener(final RequestEventListener... listeners) { -+ this.listeners = listeners; - } - -- private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -- if (classLevelTimed != null) { -- registerTimers(method, definitionMethod, classLevelTimed); -- return; -- } -- -- final Timed annotation = definitionMethod.getAnnotation(Timed.class); -- if (annotation != null) { -- registerTimers(method, definitionMethod, annotation); -- } -+ @Override -+ public void onEvent(final RequestEvent event) { -+ for (RequestEventListener listener : listeners) { -+ listener.onEvent(event); -+ } - } -+ } - -- private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { -- timers.putIfAbsent(EventTypeAndMethod.requestMethodStart(definitionMethod), timerMetric(metrics, method, annotation)); -- if (trackFilters) { -- timers.putIfAbsent(EventTypeAndMethod.requestMatched(definitionMethod), timerMetric(metrics, method, annotation, REQUEST_FILTERING)); -- timers.putIfAbsent(EventTypeAndMethod.respFiltersStart(definitionMethod), timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); -- timers.putIfAbsent(EventTypeAndMethod.finished(definitionMethod), timerMetric(metrics, method, annotation, TOTAL)); -- } -+ @Override -+ public void onEvent(ApplicationEvent event) { -+ if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { -+ registerMetricsForModel(event.getResourceModel()); -+ } -+ } -+ -+ @Override -+ public ResourceModel processResourceModel( -+ ResourceModel resourceModel, Configuration configuration) { -+ return resourceModel; -+ } -+ -+ @Override -+ public ResourceModel processSubResource( -+ ResourceModel subResourceModel, Configuration configuration) { -+ registerMetricsForModel(subResourceModel); -+ return subResourceModel; -+ } -+ -+ private void registerMetricsForModel(ResourceModel resourceModel) { -+ for (final Resource resource : resourceModel.getResources()) { -+ -+ final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); -+ final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); -+ final ExceptionMetered classLevelExceptionMetered = -+ getClassLevelAnnotation(resource, ExceptionMetered.class); -+ final ResponseMetered classLevelResponseMetered = -+ getClassLevelAnnotation(resource, ResponseMetered.class); -+ -+ for (final ResourceMethod method : resource.getAllMethods()) { -+ registerTimedAnnotations(method, classLevelTimed); -+ registerMeteredAnnotations(method, classLevelMetered); -+ registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); -+ registerResponseMeteredAnnotations(method, classLevelResponseMetered); -+ } -+ -+ for (final Resource childResource : resource.getChildResources()) { -+ -+ final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); -+ final Metered classLevelMeteredChild = -+ getClassLevelAnnotation(childResource, Metered.class); -+ final ExceptionMetered classLevelExceptionMeteredChild = -+ getClassLevelAnnotation(childResource, ExceptionMetered.class); -+ final ResponseMetered classLevelResponseMeteredChild = -+ getClassLevelAnnotation(childResource, ResponseMetered.class); -+ -+ for (final ResourceMethod method : childResource.getAllMethods()) { -+ registerTimedAnnotations(method, classLevelTimedChild); -+ registerMeteredAnnotations(method, classLevelMeteredChild); -+ registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); -+ registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); -+ } -+ } -+ } -+ } -+ -+ @Override -+ public RequestEventListener onRequest(final RequestEvent event) { -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); -+ } -+ -+ private T getClassLevelAnnotation( -+ final Resource resource, final Class annotationClazz) { -+ T annotation = null; -+ -+ for (final Class clazz : resource.getHandlerClasses()) { -+ annotation = clazz.getAnnotation(annotationClazz); -+ -+ if (annotation != null) { -+ break; -+ } -+ } -+ return annotation; -+ } -+ -+ private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ if (classLevelTimed != null) { -+ registerTimers(method, definitionMethod, classLevelTimed); -+ return; - } - -- private void registerMeteredAnnotations(final ResourceMethod method, final Metered classLevelMetered) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ final Timed annotation = definitionMethod.getAnnotation(Timed.class); -+ if (annotation != null) { -+ registerTimers(method, definitionMethod, annotation); -+ } -+ } -+ -+ private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { -+ timers.putIfAbsent( -+ EventTypeAndMethod.requestMethodStart(definitionMethod), -+ timerMetric(metrics, method, annotation)); -+ if (trackFilters) { -+ timers.putIfAbsent( -+ EventTypeAndMethod.requestMatched(definitionMethod), -+ timerMetric(metrics, method, annotation, REQUEST_FILTERING)); -+ timers.putIfAbsent( -+ EventTypeAndMethod.respFiltersStart(definitionMethod), -+ timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); -+ timers.putIfAbsent( -+ EventTypeAndMethod.finished(definitionMethod), -+ timerMetric(metrics, method, annotation, TOTAL)); -+ } -+ } - -- if (classLevelMetered != null) { -- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); -- return; -- } -- final Metered annotation = definitionMethod.getAnnotation(Metered.class); -+ private void registerMeteredAnnotations( -+ final ResourceMethod method, final Metered classLevelMetered) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - -- if (annotation != null) { -- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); -- } -+ if (classLevelMetered != null) { -+ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); -+ return; - } -+ final Metered annotation = definitionMethod.getAnnotation(Metered.class); - -- private void registerExceptionMeteredAnnotations(final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ if (annotation != null) { -+ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); -+ } -+ } - -- if (classLevelExceptionMetered != null) { -- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); -- return; -- } -- final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); -+ private void registerExceptionMeteredAnnotations( -+ final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - -- if (annotation != null) { -- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); -- } -+ if (classLevelExceptionMetered != null) { -+ exceptionMeters.putIfAbsent( -+ definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); -+ return; - } -+ final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); - -- private void registerResponseMeteredAnnotations(final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ if (annotation != null) { -+ exceptionMeters.putIfAbsent( -+ definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); -+ } -+ } - -- if (classLevelResponseMetered != null) { -- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); -- return; -- } -- final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); -+ private void registerResponseMeteredAnnotations( -+ final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - -- if (annotation != null) { -- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); -- } -+ if (classLevelResponseMetered != null) { -+ responseMeters.putIfAbsent( -+ definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); -+ return; - } -+ final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); - -- private Timer timerMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final Timed timed, -- final String... suffixes) { -- final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); -- return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); -+ if (annotation != null) { -+ responseMeters.putIfAbsent( -+ definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); - } -- -- private Meter meterMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final Metered metered) { -- final MetricName name = chooseName(metered.name(), metered.absolute(), method); -- return registry.meter(name, () -> new Meter(clock)); -+ } -+ -+ private Timer timerMetric( -+ final MetricRegistry registry, -+ final ResourceMethod method, -+ final Timed timed, -+ final String... suffixes) { -+ final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); -+ return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); -+ } -+ -+ private Meter meterMetric( -+ final MetricRegistry registry, final ResourceMethod method, final Metered metered) { -+ final MetricName name = chooseName(metered.name(), metered.absolute(), method); -+ return registry.meter(name, () -> new Meter(clock)); -+ } -+ -+ protected static MetricName chooseName( -+ final String explicitName, -+ final boolean absolute, -+ final ResourceMethod method, -+ final String... suffixes) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ MetricName metricName; -+ if (!Strings.isNullOrEmpty(explicitName)) { -+ metricName = -+ absolute -+ ? MetricRegistry.name(explicitName) -+ : MetricRegistry.name(definitionMethod.getDeclaringClass(), explicitName); -+ } else { -+ metricName = -+ MetricRegistry.name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); - } -- -- protected static MetricName chooseName(final String explicitName, final boolean absolute, final ResourceMethod method, -- final String... suffixes) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -- MetricName metricName; -- if (explicitName != null && !explicitName.isEmpty()) { -- metricName = absolute ? MetricRegistry.name(explicitName) : MetricRegistry.name(definitionMethod.getDeclaringClass(), explicitName); -- } else { -- metricName = MetricRegistry.name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); -- } -- for (String suffix : suffixes) { -- metricName = metricName.resolve(suffix); -- } -- return metricName; -+ for (String suffix : suffixes) { -+ metricName = metricName.resolve(suffix); - } -+ return metricName; -+ } - -- private static class EventTypeAndMethod { -+ private static class EventTypeAndMethod { - -- private final RequestEvent.Type type; -- private final Method method; -- -- private EventTypeAndMethod(RequestEvent.Type type, Method method) { -- this.type = type; -- this.method = method; -- } -- -- static EventTypeAndMethod requestMethodStart(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); -- } -+ private final RequestEvent.Type type; -+ private final Method method; - -- static EventTypeAndMethod requestMatched(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); -- } -+ private EventTypeAndMethod(RequestEvent.Type type, Method method) { -+ this.type = type; -+ this.method = method; -+ } - -- static EventTypeAndMethod respFiltersStart(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); -- } -+ static EventTypeAndMethod requestMethodStart(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); -+ } - -- static EventTypeAndMethod finished(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); -- } -+ static EventTypeAndMethod requestMatched(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); -+ } - -- @Override -- public boolean equals(Object o) { -- if (this == o) { -- return true; -- } -- if (o == null || getClass() != o.getClass()) { -- return false; -- } -+ static EventTypeAndMethod respFiltersStart(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); -+ } - -- EventTypeAndMethod that = (EventTypeAndMethod) o; -+ static EventTypeAndMethod finished(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); -+ } - -- if (type != that.type) { -- return false; -- } -- return method.equals(that.method); -- } -+ @Override -+ public boolean equals(Object o) { -+ if (this == o) { -+ return true; -+ } -+ if (o == null || getClass() != o.getClass()) { -+ return false; -+ } -+ -+ EventTypeAndMethod that = (EventTypeAndMethod) o; -+ -+ if (type != that.type) { -+ return false; -+ } -+ return method.equals(that.method); -+ } - -- @Override -- public int hashCode() { -- int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -- } -+ @Override -+ public int hashCode() { -+ int result = type.hashCode(); -+ return 31 * result + method.hashCode(); - } -+ } - } ---- a/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/MetricsFeature.java -+++ b/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/MetricsFeature.java -@@ -5,93 +5,98 @@ import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Reservoir; - import io.dropwizard.metrics5.SharedMetricRegistries; -- -+import java.util.function.Supplier; - import javax.ws.rs.core.Feature; - import javax.ws.rs.core.FeatureContext; --import java.util.function.Supplier; - - /** -- * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} -- * for recording request events. -+ * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} for -+ * recording request events. - */ - public class MetricsFeature implements Feature { - -- private final MetricRegistry registry; -- private final Clock clock; -- private final boolean trackFilters; -- private final Supplier reservoirSupplier; -+ private final MetricRegistry registry; -+ private final Clock clock; -+ private final boolean trackFilters; -+ private final Supplier reservoirSupplier; - -- /* -- * @param registry the metrics registry where the metrics will be stored -- */ -- public MetricsFeature(MetricRegistry registry) { -- this(registry, Clock.defaultClock()); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ */ -+ public MetricsFeature(MetricRegistry registry) { -+ this(registry, Clock.defaultClock()); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -- */ -- public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { -- this(registry, Clock.defaultClock(), false, reservoirSupplier); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -+ */ -+ public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { -+ this(registry, Clock.defaultClock(), false, reservoirSupplier); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- */ -- public MetricsFeature(MetricRegistry registry, Clock clock) { -- this(registry, clock, false); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ */ -+ public MetricsFeature(MetricRegistry registry, Clock clock) { -+ this(registry, clock, false); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- */ -- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { -- this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be tracked -+ */ -+ public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { -+ this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -- */ -- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters, Supplier reservoirSupplier) { -- this.registry = registry; -- this.clock = clock; -- this.trackFilters = trackFilters; -- this.reservoirSupplier = reservoirSupplier; -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be tracked -+ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -+ */ -+ public MetricsFeature( -+ MetricRegistry registry, -+ Clock clock, -+ boolean trackFilters, -+ Supplier reservoirSupplier) { -+ this.registry = registry; -+ this.clock = clock; -+ this.trackFilters = trackFilters; -+ this.reservoirSupplier = reservoirSupplier; -+ } - -- public MetricsFeature(String registryName) { -- this(SharedMetricRegistries.getOrCreate(registryName)); -- } -+ public MetricsFeature(String registryName) { -+ this(SharedMetricRegistries.getOrCreate(registryName)); -+ } - -- /** -- * A call-back method called when the feature is to be enabled in a given -- * runtime configuration scope. -- *

    -- * The responsibility of the feature is to properly update the supplied runtime configuration context -- * and return {@code true} if the feature was successfully enabled or {@code false} otherwise. -- *

    -- * Note that under some circumstances the feature may decide not to enable itself, which -- * is indicated by returning {@code false}. In such case the configuration context does -- * not add the feature to the collection of enabled features and a subsequent call to -- * {@link javax.ws.rs.core.Configuration#isEnabled(javax.ws.rs.core.Feature)} or -- * {@link javax.ws.rs.core.Configuration#isEnabled(Class)} method -- * would return {@code false}. -- *

    -- * -- * @param context configurable context in which the feature should be enabled. -- * @return {@code true} if the feature was successfully enabled, {@code false} -- * otherwise. -- */ -- @Override -- public boolean configure(FeatureContext context) { -- context.register(new InstrumentedResourceMethodApplicationListener(registry, clock, trackFilters, reservoirSupplier)); -- return true; -- } -+ /** -+ * A call-back method called when the feature is to be enabled in a given runtime configuration -+ * scope. -+ * -+ *

    The responsibility of the feature is to properly update the supplied runtime configuration -+ * context and return {@code true} if the feature was successfully enabled or {@code false} -+ * otherwise. -+ * -+ *

    Note that under some circumstances the feature may decide not to enable itself, which is -+ * indicated by returning {@code false}. In such case the configuration context does not add the -+ * feature to the collection of enabled features and a subsequent call to {@link -+ * javax.ws.rs.core.Configuration#isEnabled(javax.ws.rs.core.Feature)} or {@link -+ * javax.ws.rs.core.Configuration#isEnabled(Class)} method would return {@code false}. -+ * -+ *

    -+ * -+ * @param context configurable context in which the feature should be enabled. -+ * @return {@code true} if the feature was successfully enabled, {@code false} otherwise. -+ */ -+ @Override -+ public boolean configure(FeatureContext context) { -+ context.register( -+ new InstrumentedResourceMethodApplicationListener( -+ registry, clock, trackFilters, reservoirSupplier)); -+ return true; -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java -@@ -1,45 +1,44 @@ - package io.dropwizard.metrics5.jersey2; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.UniformReservoir; --import io.dropwizard.metrics5.jersey2.MetricsFeature; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceTimedPerClass; -+import java.util.logging.Level; -+import java.util.logging.Logger; -+import javax.ws.rs.core.Application; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import javax.ws.rs.core.Application; --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; -- --class CustomReservoirImplementationTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -+final class CustomReservoirImplementationTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- private MetricRegistry registry; -+ private MetricRegistry registry; - -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- return new ResourceConfig() -+ return new ResourceConfig() - .register(new MetricsFeature(this.registry, UniformReservoir::new)) - .register(InstrumentedResourceTimedPerClass.class); -- } -+ } - -- @Test -- void timerHistogramIsUsingCustomReservoirImplementation() { -- assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); -+ @Test -+ void timerHistogramIsUsingCustomReservoirImplementation() { -+ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); - -- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); -- assertThat(timer) -+ final Timer timer = -+ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); -+ assertThat(timer) - .extracting("histogram") - .extracting("reservoir") - .isInstanceOf(UniformReservoir.class); -- } -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java -@@ -1,161 +1,146 @@ - package io.dropwizard.metrics5.jersey2; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedFilteredResource; - import io.dropwizard.metrics5.jersey2.resources.TestRequestFilter; -+import java.util.logging.Level; -+import java.util.logging.Logger; -+import javax.ws.rs.core.Application; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import javax.ws.rs.core.Application; --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static org.assertj.core.api.Assertions.assertThat; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} with filter tracking -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} with filter tracking - */ --class SingletonFilterMetricsJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- private TestClock testClock; -- -- @Override -- protected Application configure() { -- registry = new MetricRegistry(); -- testClock = new TestClock(); -- ResourceConfig config = new ResourceConfig(); -- config = config.register(new MetricsFeature(this.registry, testClock, true)); -- config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -- } -- -- @BeforeEach -- void resetClock() { -- testClock.tick = 0; -- } -- -- @Test -- void timedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -- } -- -- @Test -- void explicitNamesAreTimed() { -- assertThat(target("named") -- .request() -- .get(String.class)) -- .isEqualTo("fancy"); -- -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "fancyName")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -- } -- -- @Test -- void absoluteNamesAreTimed() { -- assertThat(target("absolute") -- .request() -- .get(String.class)) -- .isEqualTo("absolute"); -- -- final Timer timer = registry.timer("absolutelyFancy"); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -- } -- -- @Test -- void requestFiltersOfTimedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -- } -- -- @Test -- void responseFiltersOfTimedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- } -- -- @Test -- void totalTimeOfTimedMethodsIsTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "total")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); -- } -- -- @Test -- void requestFiltersOfNamedMethodsAreTimed() { -- assertThat(target("named") -- .request() -- .get(String.class)) -- .isEqualTo("fancy"); -- -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -- } -- -- @Test -- void requestFiltersOfAbsoluteMethodsAreTimed() { -- assertThat(target("absolute") -- .request() -- .get(String.class)) -- .isEqualTo("absolute"); -- -- final Timer timer = registry.timer(MetricRegistry.name("absolutelyFancy", "request", "filtering")); -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -- } -- -- @Test -- void subResourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, -- "timed")); -- assertThat(timer.getCount()).isEqualTo(1); -- -- } -+final class SingletonFilterMetricsJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } -+ -+ private MetricRegistry registry; -+ -+ private TestClock testClock; -+ -+ @Override -+ protected Application configure() { -+ registry = new MetricRegistry(); -+ testClock = new TestClock(); -+ ResourceConfig config = new ResourceConfig(); -+ config = config.register(new MetricsFeature(this.registry, testClock, true)); -+ config = config.register(new TestRequestFilter(testClock)); -+ return config.register(new InstrumentedFilteredResource(testClock)); -+ } -+ -+ @BeforeEach -+ void resetClock() { -+ testClock.tick = 0; -+ } -+ -+ @Test -+ void timedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -+ } -+ -+ @Test -+ void explicitNamesAreTimed() { -+ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); -+ -+ final Timer timer = -+ registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "fancyName")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -+ } -+ -+ @Test -+ void absoluteNamesAreTimed() { -+ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); -+ -+ final Timer timer = registry.timer("absolutelyFancy"); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -+ } -+ -+ @Test -+ void requestFiltersOfTimedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer( -+ MetricRegistry.name( -+ InstrumentedFilteredResource.class, "timed", "request", "filtering")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -+ } -+ -+ @Test -+ void responseFiltersOfTimedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer( -+ MetricRegistry.name( -+ InstrumentedFilteredResource.class, "timed", "response", "filtering")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void totalTimeOfTimedMethodsIsTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "total")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); -+ } -+ -+ @Test -+ void requestFiltersOfNamedMethodsAreTimed() { -+ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); -+ -+ final Timer timer = -+ registry.timer( -+ MetricRegistry.name( -+ InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -+ } -+ -+ @Test -+ void requestFiltersOfAbsoluteMethodsAreTimed() { -+ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); -+ -+ final Timer timer = -+ registry.timer(MetricRegistry.name("absolutelyFancy", "request", "filtering")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -+ } -+ -+ @Test -+ void subResourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer( -+ MetricRegistry.name( -+ InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, "timed")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -1,97 +1,91 @@ - package io.dropwizard.metrics5.jersey2; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceExceptionMeteredPerClass; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceExceptionMeteredPerClass; --import org.glassfish.jersey.server.ResourceConfig; --import org.glassfish.jersey.test.JerseyTest; --import org.junit.jupiter.api.Test; -- --import javax.ws.rs.ProcessingException; --import javax.ws.rs.core.Application; - import java.io.IOException; - import java.util.logging.Level; - import java.util.logging.Logger; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+import javax.ws.rs.ProcessingException; -+import javax.ws.rs.core.Application; -+import org.glassfish.jersey.server.ResourceConfig; -+import org.glassfish.jersey.test.JerseyTest; -+import org.junit.jupiter.api.Test; - - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -+final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- private MetricRegistry registry; -+ private MetricRegistry registry; - -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- ResourceConfig config = new ResourceConfig(); -+ ResourceConfig config = new ResourceConfig(); - -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); -+ } - -- return config; -- } -- -- @Test -- void exceptionMeteredMethodsAreExceptionMetered() { -- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResourceExceptionMeteredPerClass.class, -- "exceptionMetered", -- "exceptions")); -- -- assertThat(target("exception-metered") -- .request() -- .get(String.class)) -- .isEqualTo("fuh"); -+ @Test -+ void exceptionMeteredMethodsAreExceptionMetered() { -+ final Meter meter = -+ registry.meter( -+ MetricRegistry.name( -+ InstrumentedResourceExceptionMeteredPerClass.class, -+ "exceptionMetered", -+ "exceptions")); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- try { -- target("exception-metered") -- .queryParam("splode", true) -- .request() -- .get(String.class); -+ assertThat(meter.getCount()).isEqualTo(0); - -- failBecauseExceptionWasNotThrown(ProcessingException.class); -- } catch (ProcessingException e) { -- assertThat(e.getCause()).isInstanceOf(IOException.class); -- } -+ try { -+ target("exception-metered").queryParam("splode", true).request().get(String.class); - -- assertThat(meter.getCount()).isEqualTo(1); -+ failBecauseExceptionWasNotThrown(ProcessingException.class); -+ } catch (ProcessingException e) { -+ assertThat(e.getCause()).isInstanceOf(IOException.class); - } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedSubResourceExceptionMeteredPerClass.class, -- "exceptionMetered", -- "exceptions")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - -- assertThat(target("subresource/exception-metered") -- .request() -- .get(String.class)) -- .isEqualTo("fuh"); -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ final Meter meter = -+ registry.meter( -+ MetricRegistry.name( -+ InstrumentedSubResourceExceptionMeteredPerClass.class, -+ "exceptionMetered", -+ "exceptions")); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(target("subresource/exception-metered").request().get(String.class)) -+ .isEqualTo("fuh"); - -- try { -- target("subresource/exception-metered") -- .queryParam("splode", true) -- .request() -- .get(String.class); -+ assertThat(meter.getCount()).isEqualTo(0); - -- failBecauseExceptionWasNotThrown(ProcessingException.class); -- } catch (ProcessingException e) { -- assertThat(e.getCause()).isInstanceOf(IOException.class); -- } -+ try { -+ target("subresource/exception-metered") -+ .queryParam("splode", true) -+ .request() -+ .get(String.class); - -- assertThat(meter.getCount()).isEqualTo(1); -+ failBecauseExceptionWasNotThrown(ProcessingException.class); -+ } catch (ProcessingException e) { -+ assertThat(e.getCause()).isInstanceOf(IOException.class); - } - -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java -@@ -1,155 +1,127 @@ - package io.dropwizard.metrics5.jersey2; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedResource; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResource; --import org.glassfish.jersey.client.ClientResponse; --import org.glassfish.jersey.server.ResourceConfig; --import org.glassfish.jersey.test.JerseyTest; --import org.junit.jupiter.api.Test; -- -+import java.io.IOException; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import javax.ws.rs.NotFoundException; - import javax.ws.rs.ProcessingException; - import javax.ws.rs.core.Application; - import javax.ws.rs.core.Response; --import java.io.IOException; --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+import org.glassfish.jersey.client.ClientResponse; -+import org.glassfish.jersey.server.ResourceConfig; -+import org.glassfish.jersey.test.JerseyTest; -+import org.junit.jupiter.api.Test; - - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link org.glassfish.jersey.server.ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link org.glassfish.jersey.server.ResourceConfig} - */ --class SingletonMetricsJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -+final class SingletonMetricsJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- private MetricRegistry registry; -+ private MetricRegistry registry; - -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- ResourceConfig config = new ResourceConfig(); -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -+ ResourceConfig config = new ResourceConfig(); -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResource.class); -+ } - -- return config; -- } -+ @Test -+ void timedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); - -- @Test -- void timedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ final Timer timer = registry.timer(MetricRegistry.name(InstrumentedResource.class, "timed")); - -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedResource.class, "timed")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - -- assertThat(timer.getCount()).isEqualTo(1); -- } -+ @Test -+ void meteredMethodsAreMetered() { -+ assertThat(target("metered").request().get(String.class)).isEqualTo("woo"); - -- @Test -- void meteredMethodsAreMetered() { -- assertThat(target("metered") -- .request() -- .get(String.class)) -- .isEqualTo("woo"); -+ final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResource.class, "metered")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - -- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResource.class, "metered")); -- assertThat(meter.getCount()).isEqualTo(1); -- } -- -- @Test -- void exceptionMeteredMethodsAreExceptionMetered() { -- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResource.class, -- "exceptionMetered", -- "exceptions")); -+ @Test -+ void exceptionMeteredMethodsAreExceptionMetered() { -+ final Meter meter = -+ registry.meter( -+ MetricRegistry.name(InstrumentedResource.class, "exceptionMetered", "exceptions")); - -- assertThat(target("exception-metered") -- .request() -- .get(String.class)) -- .isEqualTo("fuh"); -+ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - -- try { -- target("exception-metered") -- .queryParam("splode", true) -- .request() -- .get(String.class); -+ try { -+ target("exception-metered").queryParam("splode", true).request().get(String.class); - -- failBecauseExceptionWasNotThrown(ProcessingException.class); -- } catch (ProcessingException e) { -- assertThat(e.getCause()).isInstanceOf(IOException.class); -- } -- -- assertThat(meter.getCount()).isEqualTo(1); -+ failBecauseExceptionWasNotThrown(ProcessingException.class); -+ } catch (ProcessingException e) { -+ assertThat(e.getCause()).isInstanceOf(IOException.class); - } - -- @Test -- void responseMeteredMethodsAreMetered() { -- final Meter meter2xx = registry.meter(MetricRegistry.name(InstrumentedResource.class, -- "response2xxMetered", -- "2xx-responses")); -- final Meter meter4xx = registry.meter(MetricRegistry.name(InstrumentedResource.class, -- "response4xxMetered", -- "4xx-responses")); -- final Meter meter5xx = registry.meter(MetricRegistry.name(InstrumentedResource.class, -- "response5xxMetered", -- "5xx-responses")); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(target("response-2xx-metered") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -- -- assertThat(meter4xx.getCount()).isZero(); -- assertThat(target("response-4xx-metered") -- .request() -- .get().getStatus()) -- .isEqualTo(400); -- -- assertThat(meter5xx.getCount()).isZero(); -- assertThat(target("response-5xx-metered") -- .request() -- .get().getStatus()) -- .isEqualTo(500); -- -- assertThat(meter2xx.getCount()).isEqualTo(1); -- assertThat(meter4xx.getCount()).isEqualTo(1); -- assertThat(meter5xx.getCount()).isEqualTo(1); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredMethodsAreMetered() { -+ final Meter meter2xx = -+ registry.meter( -+ MetricRegistry.name(InstrumentedResource.class, "response2xxMetered", "2xx-responses")); -+ final Meter meter4xx = -+ registry.meter( -+ MetricRegistry.name(InstrumentedResource.class, "response4xxMetered", "4xx-responses")); -+ final Meter meter5xx = -+ registry.meter( -+ MetricRegistry.name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); -+ -+ assertThat(meter4xx.getCount()).isEqualTo(0); -+ assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); -+ -+ assertThat(meter5xx.getCount()).isEqualTo(0); -+ assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter4xx.getCount()).isEqualTo(1); -+ assertThat(meter5xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void resourceNotFound() { -+ final Response response = target().path("not-found").request().get(); -+ assertThat(response.getStatus()).isEqualTo(404); -+ -+ try { -+ target().path("not-found").request().get(ClientResponse.class); -+ failBecauseExceptionWasNotThrown(NotFoundException.class); -+ } catch (NotFoundException e) { -+ assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); - } -+ } - -- @Test -- void testResourceNotFound() { -- final Response response = target().path("not-found").request().get(); -- assertThat(response.getStatus()).isEqualTo(404); -- -- try { -- target().path("not-found").request().get(ClientResponse.class); -- failBecauseExceptionWasNotThrown(NotFoundException.class); -- } catch (NotFoundException e) { -- assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); -- } -- } -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedSubResource.class, "timed")); -- assertThat(timer.getCount()).isEqualTo(1); -- -- } -+ final Timer timer = registry.timer(MetricRegistry.name(InstrumentedSubResource.class, "timed")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -1,65 +1,57 @@ - package io.dropwizard.metrics5.jersey2; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceMeteredPerClass; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceMeteredPerClass; -+import java.util.logging.Level; -+import java.util.logging.Logger; -+import javax.ws.rs.core.Application; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import javax.ws.rs.core.Application; --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static org.assertj.core.api.Assertions.assertThat; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -- -- ResourceConfig config = new ResourceConfig(); -- -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -+final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- return config; -- } -+ private MetricRegistry registry; - -- @Test -- void meteredPerClassMethodsAreMetered() { -- assertThat(target("meteredPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); -+ ResourceConfig config = new ResourceConfig(); - -- assertThat(meter.getCount()).isEqualTo(1); -- } -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResourceMeteredPerClass.class); -+ } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/meteredPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Test -+ void meteredPerClassMethodsAreMetered() { -+ assertThat(target("meteredPerClass").request().get(String.class)).isEqualTo("yay"); - -- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); -- assertThat(meter.getCount()).isEqualTo(1); -+ final Meter meter = -+ registry.meter( -+ MetricRegistry.name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); - -- } -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/meteredPerClass").request().get(String.class)).isEqualTo("yay"); - -+ final Meter meter = -+ registry.meter( -+ MetricRegistry.name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -1,138 +1,138 @@ - package io.dropwizard.metrics5.jersey2; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jersey2.exception.mapper.TestExceptionMapper; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceResponseMeteredPerClass; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceResponseMeteredPerClass; -+import java.util.logging.Level; -+import java.util.logging.Logger; -+import javax.ws.rs.core.Application; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import javax.ws.rs.core.Application; --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -- -- -- ResourceConfig config = new ResourceConfig(); -- -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -- } -- -- @Test -- void responseMetered2xxPerClassMethodsAreMetered() { -- assertThat(target("responseMetered2xxPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -- -- final Meter meter2xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMetered2xxPerClass", -- "2xx-responses")); -- -- assertThat(meter2xx.getCount()).isEqualTo(1); -- } -- -- @Test -- void responseMetered4xxPerClassMethodsAreMetered() { -- assertThat(target("responseMetered4xxPerClass") -- .request() -- .get().getStatus()) -+final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } -+ -+ private MetricRegistry registry; -+ -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); -+ -+ ResourceConfig config = new ResourceConfig(); -+ -+ config = config.register(new MetricsFeature(this.registry)); -+ config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -+ return config.register(new TestExceptionMapper()); -+ } -+ -+ @Test -+ void responseMetered2xxPerClassMethodsAreMetered() { -+ assertThat(target("responseMetered2xxPerClass").request().get().getStatus()).isEqualTo(200); -+ -+ final Meter meter2xx = -+ registry.meter( -+ MetricRegistry.name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMetered2xxPerClass", -+ "2xx-responses")); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMetered4xxPerClassMethodsAreMetered() { -+ assertThat(target("responseMetered4xxPerClass").request().get().getStatus()).isEqualTo(400); -+ assertThat(target("responseMeteredBadRequestPerClass").request().get().getStatus()) - .isEqualTo(400); -- assertThat(target("responseMeteredBadRequestPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(400); -- -- final Meter meter4xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMetered4xxPerClass", -- "4xx-responses")); -- final Meter meterException4xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMeteredBadRequestPerClass", -- "4xx-responses")); - -- assertThat(meter4xx.getCount()).isEqualTo(1); -- assertThat(meterException4xx.getCount()).isEqualTo(1); -- } -- -- @Test -- void responseMetered5xxPerClassMethodsAreMetered() { -- assertThat(target("responseMetered5xxPerClass") -- .request() -- .get().getStatus()) -+ final Meter meter4xx = -+ registry.meter( -+ MetricRegistry.name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMetered4xxPerClass", -+ "4xx-responses")); -+ final Meter meterException4xx = -+ registry.meter( -+ MetricRegistry.name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMeteredBadRequestPerClass", -+ "4xx-responses")); -+ -+ assertThat(meter4xx.getCount()).isEqualTo(1); -+ assertThat(meterException4xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMetered5xxPerClassMethodsAreMetered() { -+ assertThat(target("responseMetered5xxPerClass").request().get().getStatus()).isEqualTo(500); -+ -+ final Meter meter5xx = -+ registry.meter( -+ MetricRegistry.name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMetered5xxPerClass", -+ "5xx-responses")); -+ -+ assertThat(meter5xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredMappedExceptionPerClassMethodsAreMetered() { -+ assertThat(target("responseMeteredTestExceptionPerClass").request().get().getStatus()) - .isEqualTo(500); - -- final Meter meter5xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMetered5xxPerClass", -- "5xx-responses")); -- -- assertThat(meter5xx.getCount()).isEqualTo(1); -+ final Meter meterTestException = -+ registry.meter( -+ MetricRegistry.name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMeteredTestExceptionPerClass", -+ "5xx-responses")); -+ -+ assertThat(meterTestException.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { -+ try { -+ target("responseMeteredRuntimeExceptionPerClass").request().get(); -+ fail("expected RuntimeException"); -+ } catch (Exception e) { -+ assertThat(e.getCause()).isInstanceOf(RuntimeException.class); - } - -- @Test -- void responseMeteredMappedExceptionPerClassMethodsAreMetered() { -- assertThat(target("responseMeteredTestExceptionPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(500); -+ final Meter meterException5xx = -+ registry.meter( -+ MetricRegistry.name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMeteredRuntimeExceptionPerClass", -+ "5xx-responses")); - -- final Meter meterTestException = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMeteredTestExceptionPerClass", -- "5xx-responses")); -+ assertThat(meterException5xx.getCount()).isEqualTo(1); -+ } - -- assertThat(meterTestException.getCount()).isEqualTo(1); -- } -- -- @Test -- void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { -- try { -- target("responseMeteredRuntimeExceptionPerClass") -- .request() -- .get(); -- fail("expected RuntimeException"); -- } catch (Exception e) { -- assertThat(e.getCause()).isInstanceOf(RuntimeException.class); -- } -- -- final Meter meterException5xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMeteredRuntimeExceptionPerClass", -- "5xx-responses")); -- -- assertThat(meterException5xx.getCount()).isEqualTo(1); -- } -- -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/responseMeteredPerClass") -- .request() -- .get().getStatus()) -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); - -- final Meter meter = registry.meter(MetricRegistry.name(InstrumentedSubResourceResponseMeteredPerClass.class, -- "responseMeteredPerClass", -- "2xx-responses")); -- assertThat(meter.getCount()).isEqualTo(1); -- } -+ final Meter meter = -+ registry.meter( -+ MetricRegistry.name( -+ InstrumentedSubResourceResponseMeteredPerClass.class, -+ "responseMeteredPerClass", -+ "2xx-responses")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java -@@ -1,65 +1,57 @@ - package io.dropwizard.metrics5.jersey2; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceTimedPerClass; - import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceTimedPerClass; -+import java.util.logging.Level; -+import java.util.logging.Logger; -+import javax.ws.rs.core.Application; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import javax.ws.rs.core.Application; --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static org.assertj.core.api.Assertions.assertThat; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -- -- ResourceConfig config = new ResourceConfig(); -- -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -+final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- return config; -- } -+ private MetricRegistry registry; - -- @Test -- void timedPerClassMethodsAreTimed() { -- assertThat(target("timedPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); -+ ResourceConfig config = new ResourceConfig(); - -- assertThat(timer.getCount()).isEqualTo(1); -- } -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResourceTimedPerClass.class); -+ } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/timedPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Test -+ void timedPerClassMethodsAreTimed() { -+ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); - -- final Timer timer = registry.timer(MetricRegistry.name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); -- assertThat(timer.getCount()).isEqualTo(1); -+ final Timer timer = -+ registry.timer( -+ MetricRegistry.name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); - -- } -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/timedPerClass").request().get(String.class)).isEqualTo("yay"); - -+ final Timer timer = -+ registry.timer( -+ MetricRegistry.name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/TestClock.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/TestClock.java -@@ -4,10 +4,10 @@ import io.dropwizard.metrics5.Clock; - - public class TestClock extends Clock { - -- public long tick; -+ public long tick; - -- @Override -- public long getTick() { -- return tick; -- } -+ @Override -+ public long getTick() { -+ return tick; -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/exception/TestException.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/exception/TestException.java -@@ -1,9 +1,9 @@ - package io.dropwizard.metrics5.jersey2.exception; - - public class TestException extends RuntimeException { -- private static final long serialVersionUID = 1L; -+ private static final long serialVersionUID = 1L; - -- public TestException(String message) { -- super(message); -- } -+ public TestException(String message) { -+ super(message); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/exception/mapper/TestExceptionMapper.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/exception/mapper/TestExceptionMapper.java -@@ -1,15 +1,14 @@ - package io.dropwizard.metrics5.jersey2.exception.mapper; - - import io.dropwizard.metrics5.jersey2.exception.TestException; -- - import javax.ws.rs.core.Response; - import javax.ws.rs.ext.ExceptionMapper; - import javax.ws.rs.ext.Provider; - - @Provider - public class TestExceptionMapper implements ExceptionMapper { -- @Override -- public Response toResponse(TestException exception) { -- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -- } -+ @Override -+ public Response toResponse(TestException exception) { -+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java -@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.annotation.Timed; - import io.dropwizard.metrics5.jersey2.TestClock; -- - import javax.ws.rs.GET; - import javax.ws.rs.Path; - import javax.ws.rs.Produces; -@@ -12,51 +11,50 @@ import javax.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedFilteredResource { - -- private final TestClock testClock; -- -- public InstrumentedFilteredResource(TestClock testClock) { -- this.testClock = testClock; -- } -+ private final TestClock testClock; -+ -+ public InstrumentedFilteredResource(TestClock testClock) { -+ this.testClock = testClock; -+ } -+ -+ @GET -+ @Path("/timed") -+ @Timed -+ public String timed() { -+ testClock.tick++; -+ return "yay"; -+ } -+ -+ @GET -+ @Path("/named") -+ @Timed(name = "fancyName") -+ public String named() { -+ testClock.tick++; -+ return "fancy"; -+ } -+ -+ @GET -+ @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) -+ public String absolute() { -+ testClock.tick++; -+ return "absolute"; -+ } -+ -+ @Path("/subresource") -+ public InstrumentedFilteredSubResource locateSubResource() { -+ return new InstrumentedFilteredSubResource(); -+ } -+ -+ @Produces(MediaType.TEXT_PLAIN) -+ public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { -- testClock.tick++; -- return "yay"; -- } -- -- @GET -- @Timed(name = "fancyName") -- @Path("/named") -- public String named() { -- testClock.tick++; -- return "fancy"; -- } -- -- @GET -- @Timed(name = "absolutelyFancy", absolute = true) -- @Path("/absolute") -- public String absolute() { -- testClock.tick++; -- return "absolute"; -- } -- -- @Path("/subresource") -- public InstrumentedFilteredSubResource locateSubResource() { -- return new InstrumentedFilteredSubResource(); -- } -- -- @Produces(MediaType.TEXT_PLAIN) -- public class InstrumentedFilteredSubResource { -- -- @GET -- @Timed -- @Path("/timed") -- public String timed() { -- testClock.tick += 2; -- return "yay"; -- } -- -+ testClock.tick += 2; -+ return "yay"; - } -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java -@@ -1,10 +1,14 @@ - package io.dropwizard.metrics5.jersey2.resources; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+ - import io.dropwizard.metrics5.annotation.ExceptionMetered; - import io.dropwizard.metrics5.annotation.Metered; - import io.dropwizard.metrics5.annotation.ResponseMetered; - import io.dropwizard.metrics5.annotation.Timed; -- -+import java.io.IOException; - import javax.ws.rs.DefaultValue; - import javax.ws.rs.GET; - import javax.ws.rs.Path; -@@ -12,83 +16,82 @@ import javax.ws.rs.Produces; - import javax.ws.rs.QueryParam; - import javax.ws.rs.core.MediaType; - import javax.ws.rs.core.Response; --import java.io.IOException; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; - - @Path("/") - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { -- @GET -- @Timed -- @Path("/timed") -- public String timed() { -- return "yay"; -- } -+ @GET -+ @Path("/timed") -+ @Timed -+ public String timed() { -+ return "yay"; -+ } - -- @GET -- @Metered -- @Path("/metered") -- public String metered() { -- return "woo"; -- } -+ @GET -+ @Metered -+ @Path("/metered") -+ public String metered() { -+ return "woo"; -+ } - -- @GET -- @ExceptionMetered(cause = IOException.class) -- @Path("/exception-metered") -- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { -- if (splode) { -- throw new IOException("AUGH"); -- } -- return "fuh"; -+ @ExceptionMetered(cause = IOException.class) -+ @GET -+ @Path("/exception-metered") -+ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) -+ throws IOException { -+ if (splode) { -+ throw new IOException("AUGH"); - } -+ return "fuh"; -+ } - -- @GET -- @ResponseMetered(level = DETAILED) -- @Path("/response-metered-detailed") -- public Response responseMeteredDetailed(@QueryParam("status_code") @DefaultValue("200") int statusCode) { -- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -- } -+ @GET -+ @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) -+ public Response responseMeteredDetailed( -+ @QueryParam("status_code") @DefaultValue("200") int statusCode) { -+ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -+ } - -- @GET -- @ResponseMetered(level = COARSE) -- @Path("/response-metered-coarse") -- public Response responseMeteredCoarse(@QueryParam("status_code") @DefaultValue("200") int statusCode) { -- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -- } -+ @GET -+ @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) -+ public Response responseMeteredCoarse( -+ @QueryParam("status_code") @DefaultValue("200") int statusCode) { -+ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -+ } - -- @GET -- @ResponseMetered(level = ALL) -- @Path("/response-metered-all") -- public Response responseMeteredAll(@QueryParam("status_code") @DefaultValue("200") int statusCode) { -- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -- } -+ @GET -+ @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) -+ public Response responseMeteredAll( -+ @QueryParam("status_code") @DefaultValue("200") int statusCode) { -+ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -+ } - -- @GET -- @ResponseMetered -- @Path("/response-2xx-metered") -- public Response response2xxMetered() { -- return Response.ok().build(); -- } -+ @GET -+ @Path("/response-2xx-metered") -+ @ResponseMetered -+ public Response response2xxMetered() { -+ return Response.ok().build(); -+ } - -- @GET -- @ResponseMetered -- @Path("/response-4xx-metered") -- public Response response4xxMetered() { -- return Response.status(Response.Status.BAD_REQUEST).build(); -- } -+ @GET -+ @Path("/response-4xx-metered") -+ @ResponseMetered -+ public Response response4xxMetered() { -+ return Response.status(Response.Status.BAD_REQUEST).build(); -+ } - -- @GET -- @ResponseMetered -- @Path("/response-5xx-metered") -- public Response response5xxMetered() { -- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -- } -+ @GET -+ @Path("/response-5xx-metered") -+ @ResponseMetered -+ public Response response5xxMetered() { -+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -+ } - -- @Path("/subresource") -- public InstrumentedSubResource locateSubResource() { -- return new InstrumentedSubResource(); -- } -+ @Path("/subresource") -+ public InstrumentedSubResource locateSubResource() { -+ return new InstrumentedSubResource(); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceExceptionMeteredPerClass.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceExceptionMeteredPerClass.java -@@ -1,32 +1,31 @@ - package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.annotation.ExceptionMetered; -- -+import java.io.IOException; - import javax.ws.rs.DefaultValue; - import javax.ws.rs.GET; - import javax.ws.rs.Path; - import javax.ws.rs.Produces; - import javax.ws.rs.QueryParam; - import javax.ws.rs.core.MediaType; --import java.io.IOException; - - @ExceptionMetered(cause = IOException.class) - @Path("/") - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceExceptionMeteredPerClass { - -- @GET -- @Path("/exception-metered") -- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { -- if (splode) { -- throw new IOException("AUGH"); -- } -- return "fuh"; -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { -- return new InstrumentedSubResourceExceptionMeteredPerClass(); -+ @GET -+ @Path("/exception-metered") -+ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) -+ throws IOException { -+ if (splode) { -+ throw new IOException("AUGH"); - } -+ return "fuh"; -+ } - -+ @Path("/subresource") -+ public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { -+ return new InstrumentedSubResourceExceptionMeteredPerClass(); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceMeteredPerClass.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceMeteredPerClass.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.annotation.Metered; -- - import javax.ws.rs.GET; - import javax.ws.rs.Path; - import javax.ws.rs.Produces; -@@ -12,15 +11,14 @@ import javax.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceMeteredPerClass { - -- @GET -- @Path("/meteredPerClass") -- public String meteredPerClass() { -- return "yay"; -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceMeteredPerClass locateSubResource() { -- return new InstrumentedSubResourceMeteredPerClass(); -- } -+ @GET -+ @Path("/meteredPerClass") -+ public String meteredPerClass() { -+ return "yay"; -+ } - -+ @Path("/subresource") -+ public InstrumentedSubResourceMeteredPerClass locateSubResource() { -+ return new InstrumentedSubResourceMeteredPerClass(); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceResponseMeteredPerClass.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceResponseMeteredPerClass.java -@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.annotation.ResponseMetered; - import io.dropwizard.metrics5.jersey2.exception.TestException; -- - import javax.ws.rs.BadRequestException; - import javax.ws.rs.GET; - import javax.ws.rs.Path; -@@ -15,45 +14,44 @@ import javax.ws.rs.core.Response; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceResponseMeteredPerClass { - -- @GET -- @Path("/responseMetered2xxPerClass") -- public Response responseMetered2xxPerClass() { -- return Response.ok().build(); -- } -- -- @GET -- @Path("/responseMetered4xxPerClass") -- public Response responseMetered4xxPerClass() { -- return Response.status(Response.Status.BAD_REQUEST).build(); -- } -- -- @GET -- @Path("/responseMetered5xxPerClass") -- public Response responseMetered5xxPerClass() { -- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -- } -- -- @GET -- @Path("/responseMeteredBadRequestPerClass") -- public String responseMeteredBadRequestPerClass() { -- throw new BadRequestException(); -- } -- -- @GET -- @Path("/responseMeteredRuntimeExceptionPerClass") -- public String responseMeteredRuntimeExceptionPerClass() { -- throw new RuntimeException(); -- } -- -- @GET -- @Path("/responseMeteredTestExceptionPerClass") -- public String responseMeteredTestExceptionPerClass() { -- throw new TestException("test"); -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { -- return new InstrumentedSubResourceResponseMeteredPerClass(); -- } -- -+ @GET -+ @Path("/responseMetered2xxPerClass") -+ public Response responseMetered2xxPerClass() { -+ return Response.ok().build(); -+ } -+ -+ @GET -+ @Path("/responseMetered4xxPerClass") -+ public Response responseMetered4xxPerClass() { -+ return Response.status(Response.Status.BAD_REQUEST).build(); -+ } -+ -+ @GET -+ @Path("/responseMetered5xxPerClass") -+ public Response responseMetered5xxPerClass() { -+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -+ } -+ -+ @GET -+ @Path("/responseMeteredBadRequestPerClass") -+ public String responseMeteredBadRequestPerClass() { -+ throw new BadRequestException(); -+ } -+ -+ @GET -+ @Path("/responseMeteredRuntimeExceptionPerClass") -+ public String responseMeteredRuntimeExceptionPerClass() { -+ throw new RuntimeException(); -+ } -+ -+ @GET -+ @Path("/responseMeteredTestExceptionPerClass") -+ public String responseMeteredTestExceptionPerClass() { -+ throw new TestException("test"); -+ } -+ -+ @Path("/subresource") -+ public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { -+ return new InstrumentedSubResourceResponseMeteredPerClass(); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceTimedPerClass.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResourceTimedPerClass.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.annotation.Timed; -- - import javax.ws.rs.GET; - import javax.ws.rs.Path; - import javax.ws.rs.Produces; -@@ -12,15 +11,14 @@ import javax.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceTimedPerClass { - -- @GET -- @Path("/timedPerClass") -- public String timedPerClass() { -- return "yay"; -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceTimedPerClass locateSubResource() { -- return new InstrumentedSubResourceTimedPerClass(); -- } -+ @GET -+ @Path("/timedPerClass") -+ public String timedPerClass() { -+ return "yay"; -+ } - -+ @Path("/subresource") -+ public InstrumentedSubResourceTimedPerClass locateSubResource() { -+ return new InstrumentedSubResourceTimedPerClass(); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.annotation.Timed; -- - import javax.ws.rs.GET; - import javax.ws.rs.Path; - import javax.ws.rs.Produces; -@@ -10,11 +9,10 @@ import javax.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResource { - -- @GET -- @Timed -- @Path("/timed") -- public String timed() { -- return "yay"; -- } -- -+ @GET -+ @Path("/timed") -+ @Timed -+ public String timed() { -+ return "yay"; -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceExceptionMeteredPerClass.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceExceptionMeteredPerClass.java -@@ -1,24 +1,24 @@ - package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.annotation.ExceptionMetered; -- -+import java.io.IOException; - import javax.ws.rs.DefaultValue; - import javax.ws.rs.GET; - import javax.ws.rs.Path; - import javax.ws.rs.Produces; - import javax.ws.rs.QueryParam; - import javax.ws.rs.core.MediaType; --import java.io.IOException; - - @ExceptionMetered(cause = IOException.class) - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceExceptionMeteredPerClass { -- @GET -- @Path("/exception-metered") -- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { -- if (splode) { -- throw new IOException("AUGH"); -- } -- return "fuh"; -+ @GET -+ @Path("/exception-metered") -+ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) -+ throws IOException { -+ if (splode) { -+ throw new IOException("AUGH"); - } -+ return "fuh"; -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceMeteredPerClass.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceMeteredPerClass.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.annotation.Metered; -- - import javax.ws.rs.GET; - import javax.ws.rs.Path; - import javax.ws.rs.Produces; -@@ -10,9 +9,9 @@ import javax.ws.rs.core.MediaType; - @Metered - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceMeteredPerClass { -- @GET -- @Path("/meteredPerClass") -- public String meteredPerClass() { -- return "yay"; -- } -+ @GET -+ @Path("/meteredPerClass") -+ public String meteredPerClass() { -+ return "yay"; -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceResponseMeteredPerClass.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceResponseMeteredPerClass.java -@@ -1,21 +1,20 @@ - package io.dropwizard.metrics5.jersey2.resources; - --import io.dropwizard.metrics5.annotation.ResponseMetered; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - -+import io.dropwizard.metrics5.annotation.ResponseMetered; - import javax.ws.rs.GET; - import javax.ws.rs.Path; - import javax.ws.rs.Produces; - import javax.ws.rs.core.MediaType; - import javax.ws.rs.core.Response; - --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -- - @ResponseMetered(level = ALL) - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceResponseMeteredPerClass { -- @GET -- @Path("/responseMeteredPerClass") -- public Response responseMeteredPerClass() { -- return Response.status(Response.Status.OK).build(); -- } -+ @GET -+ @Path("/responseMeteredPerClass") -+ public Response responseMeteredPerClass() { -+ return Response.status(Response.Status.OK).build(); -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceTimedPerClass.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResourceTimedPerClass.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.annotation.Timed; -- - import javax.ws.rs.GET; - import javax.ws.rs.Path; - import javax.ws.rs.Produces; -@@ -10,9 +9,9 @@ import javax.ws.rs.core.MediaType; - @Timed - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceTimedPerClass { -- @GET -- @Path("/timedPerClass") -- public String timedPerClass() { -- return "yay"; -- } -+ @GET -+ @Path("/timedPerClass") -+ public String timedPerClass() { -+ return "yay"; -+ } - } ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/TestRequestFilter.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/TestRequestFilter.java -@@ -1,21 +1,20 @@ - package io.dropwizard.metrics5.jersey2.resources; - - import io.dropwizard.metrics5.jersey2.TestClock; -- -+import java.io.IOException; - import javax.ws.rs.container.ContainerRequestContext; - import javax.ws.rs.container.ContainerRequestFilter; --import java.io.IOException; - - public class TestRequestFilter implements ContainerRequestFilter { - -- private final TestClock testClock; -+ private final TestClock testClock; - -- public TestRequestFilter(TestClock testClock) { -- this.testClock = testClock; -- } -+ public TestRequestFilter(TestClock testClock) { -+ this.testClock = testClock; -+ } - -- @Override -- public void filter(ContainerRequestContext containerRequestContext) throws IOException { -- testClock.tick += 4; -- } -+ @Override -+ public void filter(ContainerRequestContext containerRequestContext) throws IOException { -+ testClock.tick += 4; -+ } - } ---- a/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java -@@ -1,5 +1,14 @@ - package io.dropwizard.metrics5.jersey3; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; -+ -+import com.google.common.base.Strings; -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Meter; -@@ -14,20 +23,9 @@ import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; - import io.dropwizard.metrics5.annotation.Timed; - import jakarta.ws.rs.core.Configuration; - import jakarta.ws.rs.ext.Provider; --import org.glassfish.jersey.server.ContainerResponse; --import org.glassfish.jersey.server.model.ModelProcessor; --import org.glassfish.jersey.server.model.Resource; --import org.glassfish.jersey.server.model.ResourceMethod; --import org.glassfish.jersey.server.model.ResourceModel; --import org.glassfish.jersey.server.monitoring.ApplicationEvent; --import org.glassfish.jersey.server.monitoring.ApplicationEventListener; --import org.glassfish.jersey.server.monitoring.RequestEvent; --import org.glassfish.jersey.server.monitoring.RequestEventListener; -- - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -36,518 +34,573 @@ import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.ConcurrentMap; - import java.util.concurrent.TimeUnit; - import java.util.function.Supplier; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import org.glassfish.jersey.server.ContainerResponse; -+import org.glassfish.jersey.server.model.ModelProcessor; -+import org.glassfish.jersey.server.model.Resource; -+import org.glassfish.jersey.server.model.ResourceMethod; -+import org.glassfish.jersey.server.model.ResourceModel; -+import org.glassfish.jersey.server.monitoring.ApplicationEvent; -+import org.glassfish.jersey.server.monitoring.ApplicationEventListener; -+import org.glassfish.jersey.server.monitoring.RequestEvent; -+import org.glassfish.jersey.server.monitoring.RequestEventListener; - - /** -- * An application event listener that listens for Jersey application initialization to -- * be finished, then creates a map of resource method that have metrics annotations. -- *

    -- * Finally, it listens for method start events, and returns a {@link RequestEventListener} -- * that updates the relevant metric for suitably annotated methods when it gets the -- * request events indicating that the method is about to be invoked, or just got done -- * being invoked. -+ * An application event listener that listens for Jersey application initialization to be finished, -+ * then creates a map of resource method that have metrics annotations. -+ * -+ *

    Finally, it listens for method start events, and returns a {@link RequestEventListener} that -+ * updates the relevant metric for suitably annotated methods when it gets the request events -+ * indicating that the method is about to be invoked, or just got done being invoked. - */ - @Provider --public class InstrumentedResourceMethodApplicationListener implements ApplicationEventListener, ModelProcessor { -- -- private static final String[] REQUEST_FILTERING = {"request", "filtering"}; -- private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; -- private static final String TOTAL = "total"; -- -- private final MetricRegistry metrics; -- private final ConcurrentMap timers = new ConcurrentHashMap<>(); -- private final ConcurrentMap meters = new ConcurrentHashMap<>(); -- private final ConcurrentMap exceptionMeters = new ConcurrentHashMap<>(); -- private final ConcurrentMap responseMeters = new ConcurrentHashMap<>(); -- -- private final Clock clock; -- private final boolean trackFilters; -- private final Supplier reservoirSupplier; -- -- /** -- * Construct an application event listener using the given metrics registry. -- *

    -- * When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} -- * should be added to a Jersey {@code ResourceConfig} as a singleton. -- * -- * @param metrics a {@link MetricRegistry} -- */ -- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { -- this(metrics, Clock.defaultClock(), false); -- } -- -- /** -- * Constructs a custom application listener. -- * -- * @param metrics the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- */ -- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, -- final boolean trackFilters) { -- this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); -- } -- -- /** -- * Constructs a custom application listener. -- * -- * @param metrics the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -- */ -- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, -- final boolean trackFilters, -- final Supplier reservoirSupplier) { -- this.metrics = metrics; -- this.clock = clock; -- this.trackFilters = trackFilters; -- this.reservoirSupplier = reservoirSupplier; -- } -- -- /** -- * A private class to maintain the metric for a method annotated with the -- * {@link ExceptionMetered} annotation, which needs to maintain both a meter -- * and a cause for which the meter should be updated. -- */ -- private static class ExceptionMeterMetric { -- public final Meter meter; -- public final Class cause; -- -- public ExceptionMeterMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final ExceptionMetered exceptionMetered) { -- final MetricName name = chooseName(exceptionMetered.name(), -- exceptionMetered.absolute(), method, ExceptionMetered.DEFAULT_NAME_SUFFIX); -- this.meter = registry.meter(name); -- this.cause = exceptionMetered.cause(); -- } -+public class InstrumentedResourceMethodApplicationListener -+ implements ApplicationEventListener, ModelProcessor { -+ -+ private static final String[] REQUEST_FILTERING = {"request", "filtering"}; -+ private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; -+ private static final String TOTAL = "total"; -+ -+ private final MetricRegistry metrics; -+ private final ConcurrentMap timers = new ConcurrentHashMap<>(); -+ private final ConcurrentMap meters = new ConcurrentHashMap<>(); -+ private final ConcurrentMap exceptionMeters = -+ new ConcurrentHashMap<>(); -+ private final ConcurrentMap responseMeters = -+ new ConcurrentHashMap<>(); -+ -+ private final Clock clock; -+ private final boolean trackFilters; -+ private final Supplier reservoirSupplier; -+ -+ /** -+ * Construct an application event listener using the given metrics registry. -+ * -+ *

    When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} -+ * should be added to a Jersey {@code ResourceConfig} as a singleton. -+ * -+ * @param metrics a {@link MetricRegistry} -+ */ -+ public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { -+ this(metrics, Clock.defaultClock(), false); -+ } -+ -+ /** -+ * Constructs a custom application listener. -+ * -+ * @param metrics the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be -+ * tracked -+ */ -+ public InstrumentedResourceMethodApplicationListener( -+ final MetricRegistry metrics, final Clock clock, final boolean trackFilters) { -+ this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); -+ } -+ -+ /** -+ * Constructs a custom application listener. -+ * -+ * @param metrics the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be -+ * tracked -+ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -+ */ -+ public InstrumentedResourceMethodApplicationListener( -+ final MetricRegistry metrics, -+ final Clock clock, -+ final boolean trackFilters, -+ final Supplier reservoirSupplier) { -+ this.metrics = metrics; -+ this.clock = clock; -+ this.trackFilters = trackFilters; -+ this.reservoirSupplier = reservoirSupplier; -+ } -+ -+ /** -+ * A private class to maintain the metric for a method annotated with the {@link ExceptionMetered} -+ * annotation, which needs to maintain both a meter and a cause for which the meter should be -+ * updated. -+ */ -+ private static class ExceptionMeterMetric { -+ public final Meter meter; -+ public final Class cause; -+ -+ public ExceptionMeterMetric( -+ final MetricRegistry registry, -+ final ResourceMethod method, -+ final ExceptionMetered exceptionMetered) { -+ final MetricName name = -+ chooseName( -+ exceptionMetered.name(), -+ exceptionMetered.absolute(), -+ method, -+ ExceptionMetered.DEFAULT_NAME_SUFFIX); -+ this.meter = registry.meter(name); -+ this.cause = exceptionMetered.cause(); - } -- -- /** -- * A private class to maintain the metrics for a method annotated with the -- * {@link ResponseMetered} annotation, which needs to maintain meters for -- * different response codes -- */ -- private static class ResponseMeterMetric { -- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -- private final List meters; -- private final Map responseCodeMeters; -- private final MetricRegistry metricRegistry; -- private final MetricName metricName; -- private final ResponseMeteredLevel level; -- -- public ResponseMeterMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final ResponseMetered responseMetered) { -- this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); -- this.level = responseMetered.level(); -- this.meters = COARSE_METER_LEVELS.contains(level) ? -- Collections.unmodifiableList(Arrays.asList( -- registry.meter(metricName.resolve("1xx-responses")), // 1xx -- registry.meter(metricName.resolve("2xx-responses")), // 2xx -- registry.meter(metricName.resolve("3xx-responses")), // 3xx -- registry.meter(metricName.resolve("4xx-responses")), // 4xx -- registry.meter(metricName.resolve("5xx-responses")) // 5xx -- )) : Collections.emptyList(); -- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : Collections.emptyMap(); -- this.metricRegistry = registry; -- } -- -- public void mark(int statusCode) { -- if (DETAILED_METER_LEVELS.contains(level)) { -- getResponseCodeMeter(statusCode).mark(); -- } -- -- if (COARSE_METER_LEVELS.contains(level)) { -- final int responseStatus = statusCode / 100; -- if (responseStatus >= 1 && responseStatus <= 5) { -- meters.get(responseStatus - 1).mark(); -- } -- } -- } -- -- private Meter getResponseCodeMeter(int statusCode) { -- return responseCodeMeters -- .computeIfAbsent(statusCode, sc -> metricRegistry -- .meter(metricName.resolve(String.format("%d-responses", sc)))); -- } -+ } -+ -+ /** -+ * A private class to maintain the metrics for a method annotated with the {@link ResponseMetered} -+ * annotation, which needs to maintain meters for different response codes -+ */ -+ private static class ResponseMeterMetric { -+ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -+ private static final Set DETAILED_METER_LEVELS = -+ EnumSet.of(DETAILED, ALL); -+ private final List meters; -+ private final Map responseCodeMeters; -+ private final MetricRegistry metricRegistry; -+ private final MetricName metricName; -+ private final ResponseMeteredLevel level; -+ -+ public ResponseMeterMetric( -+ final MetricRegistry registry, -+ final ResourceMethod method, -+ final ResponseMetered responseMetered) { -+ this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); -+ this.level = responseMetered.level(); -+ this.meters = -+ COARSE_METER_LEVELS.contains(level) -+ ? unmodifiableList( -+ Arrays.asList( -+ registry.meter(metricName.resolve("1xx-responses")), // 1xx -+ registry.meter(metricName.resolve("2xx-responses")), // 2xx -+ registry.meter(metricName.resolve("3xx-responses")), // 3xx -+ registry.meter(metricName.resolve("4xx-responses")), // 4xx -+ registry.meter(metricName.resolve("5xx-responses")) // 5xx -+ )) -+ : ImmutableList.of(); -+ this.responseCodeMeters = -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); -+ this.metricRegistry = registry; - } - -- private static class TimerRequestEventListener implements RequestEventListener { -- -- private final ConcurrentMap timers; -- private final Clock clock; -- private final long start; -- private Timer.Context resourceMethodStartContext; -- private Timer.Context requestMatchedContext; -- private Timer.Context responseFiltersStartContext; -- -- public TimerRequestEventListener(final ConcurrentMap timers, final Clock clock) { -- this.timers = timers; -- this.clock = clock; -- start = clock.getTick(); -- } -- -- @Override -- public void onEvent(RequestEvent event) { -- switch (event.getType()) { -- case RESOURCE_METHOD_START: -- resourceMethodStartContext = context(event); -- break; -- case REQUEST_MATCHED: -- requestMatchedContext = context(event); -- break; -- case RESP_FILTERS_START: -- responseFiltersStartContext = context(event); -- break; -- case RESOURCE_METHOD_FINISHED: -- if (resourceMethodStartContext != null) { -- resourceMethodStartContext.close(); -- } -- break; -- case REQUEST_FILTERED: -- if (requestMatchedContext != null) { -- requestMatchedContext.close(); -- } -- break; -- case RESP_FILTERS_FINISHED: -- if (responseFiltersStartContext != null) { -- responseFiltersStartContext.close(); -- } -- break; -- case FINISHED: -- if (requestMatchedContext != null && responseFiltersStartContext != null) { -- final Timer timer = timer(event); -- if (timer != null) { -- timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); -- } -- } -- break; -- default: -- break; -- } -- } -- -- private Timer timer(RequestEvent event) { -- final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); -- if (resourceMethod == null) { -- return null; -- } -- return timers.get(new EventTypeAndMethod(event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); -- } -+ public void mark(int statusCode) { -+ if (DETAILED_METER_LEVELS.contains(level)) { -+ getResponseCodeMeter(statusCode).mark(); -+ } - -- private Timer.Context context(RequestEvent event) { -- final Timer timer = timer(event); -- return timer != null ? timer.time() : null; -+ if (COARSE_METER_LEVELS.contains(level)) { -+ final int responseStatus = statusCode / 100; -+ if (responseStatus >= 1 && responseStatus <= 5) { -+ meters.get(responseStatus - 1).mark(); - } -+ } - } - -- private static class MeterRequestEventListener implements RequestEventListener { -- private final ConcurrentMap meters; -- -- public MeterRequestEventListener(final ConcurrentMap meters) { -- this.meters = meters; -- } -- -- @Override -- public void onEvent(RequestEvent event) { -- if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { -- final Meter meter = this.meters.get(event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); -- if (meter != null) { -- meter.mark(); -- } -- } -- } -+ private Meter getResponseCodeMeter(int statusCode) { -+ return responseCodeMeters.computeIfAbsent( -+ statusCode, -+ sc -> metricRegistry.meter(metricName.resolve(String.format("%d-responses", sc)))); - } -+ } - -- private static class ExceptionMeterRequestEventListener implements RequestEventListener { -- private final ConcurrentMap exceptionMeters; -+ private static class TimerRequestEventListener implements RequestEventListener { - -- public ExceptionMeterRequestEventListener(final ConcurrentMap exceptionMeters) { -- this.exceptionMeters = exceptionMeters; -- } -+ private final ConcurrentMap timers; -+ private final Clock clock; -+ private final long start; -+ private Timer.Context resourceMethodStartContext; -+ private Timer.Context requestMatchedContext; -+ private Timer.Context responseFiltersStartContext; -+ -+ public TimerRequestEventListener( -+ final ConcurrentMap timers, final Clock clock) { -+ this.timers = timers; -+ this.clock = clock; -+ start = clock.getTick(); -+ } - -- @Override -- public void onEvent(RequestEvent event) { -- if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { -- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -- final ExceptionMeterMetric metric = (method != null) ? -- this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) : null; -- -- if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) || -- (event.getException().getCause() != null && -- metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -- metric.meter.mark(); -- } -- } -+ @Override -+ public void onEvent(RequestEvent event) { -+ switch (event.getType()) { -+ case RESOURCE_METHOD_START: -+ resourceMethodStartContext = context(event); -+ break; -+ case REQUEST_MATCHED: -+ requestMatchedContext = context(event); -+ break; -+ case RESP_FILTERS_START: -+ responseFiltersStartContext = context(event); -+ break; -+ case RESOURCE_METHOD_FINISHED: -+ if (resourceMethodStartContext != null) { -+ resourceMethodStartContext.close(); -+ } -+ break; -+ case REQUEST_FILTERED: -+ if (requestMatchedContext != null) { -+ requestMatchedContext.close(); -+ } -+ break; -+ case RESP_FILTERS_FINISHED: -+ if (responseFiltersStartContext != null) { -+ responseFiltersStartContext.close(); -+ } -+ break; -+ case FINISHED: -+ if (requestMatchedContext != null && responseFiltersStartContext != null) { -+ final Timer timer = timer(event); -+ if (timer != null) { -+ timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); - } -- } -+ } -+ break; -+ default: -+ break; -+ } - } - -- private static class ResponseMeterRequestEventListener implements RequestEventListener { -- private final ConcurrentMap responseMeters; -- -- public ResponseMeterRequestEventListener(final ConcurrentMap responseMeters) { -- this.responseMeters = responseMeters; -- } -- -- @Override -- public void onEvent(RequestEvent event) { -- if (event.getType() == RequestEvent.Type.FINISHED) { -- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -- final ResponseMeterMetric metric = (method != null) ? -- this.responseMeters.get(method.getInvocable().getDefinitionMethod()) : null; -- -- if (metric != null) { -- ContainerResponse containerResponse = event.getContainerResponse(); -- if (containerResponse == null && event.getException() != null) { -- metric.mark(500); -- } else if (containerResponse != null) { -- metric.mark(containerResponse.getStatus()); -- } -- } -- } -- } -+ private Timer timer(RequestEvent event) { -+ final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); -+ if (resourceMethod == null) { -+ return null; -+ } -+ return timers.get( -+ new EventTypeAndMethod( -+ event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); - } - -- private static class ChainedRequestEventListener implements RequestEventListener { -- private final RequestEventListener[] listeners; -+ private Timer.Context context(RequestEvent event) { -+ final Timer timer = timer(event); -+ return timer != null ? timer.time() : null; -+ } -+ } - -- private ChainedRequestEventListener(final RequestEventListener... listeners) { -- this.listeners = listeners; -- } -+ private static class MeterRequestEventListener implements RequestEventListener { -+ private final ConcurrentMap meters; - -- @Override -- public void onEvent(final RequestEvent event) { -- for (RequestEventListener listener : listeners) { -- listener.onEvent(event); -- } -- } -+ public MeterRequestEventListener(final ConcurrentMap meters) { -+ this.meters = meters; - } - - @Override -- public void onEvent(ApplicationEvent event) { -- if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { -- registerMetricsForModel(event.getResourceModel()); -- } -+ public void onEvent(RequestEvent event) { -+ if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { -+ final Meter meter = -+ this.meters.get( -+ event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); -+ if (meter != null) { -+ meter.mark(); -+ } -+ } - } -+ } - -- @Override -- public ResourceModel processResourceModel(ResourceModel resourceModel, Configuration configuration) { -- return resourceModel; -+ private static class ExceptionMeterRequestEventListener implements RequestEventListener { -+ private final ConcurrentMap exceptionMeters; -+ -+ public ExceptionMeterRequestEventListener( -+ final ConcurrentMap exceptionMeters) { -+ this.exceptionMeters = exceptionMeters; - } - - @Override -- public ResourceModel processSubResource(ResourceModel subResourceModel, Configuration configuration) { -- registerMetricsForModel(subResourceModel); -- return subResourceModel; -+ public void onEvent(RequestEvent event) { -+ if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { -+ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -+ final ExceptionMeterMetric metric = -+ (method != null) -+ ? this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) -+ : null; -+ -+ if (metric != null) { -+ if (metric.cause.isInstance(event.getException()) -+ || (event.getException().getCause() != null -+ && metric.cause.isInstance(event.getException().getCause()))) { -+ metric.meter.mark(); -+ } -+ } -+ } - } -+ } - -- private void registerMetricsForModel(ResourceModel resourceModel) { -- for (final Resource resource : resourceModel.getResources()) { -- -- final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); -- final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); -- final ExceptionMetered classLevelExceptionMetered = getClassLevelAnnotation(resource, ExceptionMetered.class); -- final ResponseMetered classLevelResponseMetered = getClassLevelAnnotation(resource, ResponseMetered.class); -- -- for (final ResourceMethod method : resource.getAllMethods()) { -- registerTimedAnnotations(method, classLevelTimed); -- registerMeteredAnnotations(method, classLevelMetered); -- registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); -- registerResponseMeteredAnnotations(method, classLevelResponseMetered); -- } -- -- for (final Resource childResource : resource.getChildResources()) { -- -- final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); -- final Metered classLevelMeteredChild = getClassLevelAnnotation(childResource, Metered.class); -- final ExceptionMetered classLevelExceptionMeteredChild = getClassLevelAnnotation(childResource, ExceptionMetered.class); -- final ResponseMetered classLevelResponseMeteredChild = getClassLevelAnnotation(childResource, ResponseMetered.class); -+ private static class ResponseMeterRequestEventListener implements RequestEventListener { -+ private final ConcurrentMap responseMeters; - -- for (final ResourceMethod method : childResource.getAllMethods()) { -- registerTimedAnnotations(method, classLevelTimedChild); -- registerMeteredAnnotations(method, classLevelMeteredChild); -- registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); -- registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); -- } -- } -- } -+ public ResponseMeterRequestEventListener( -+ final ConcurrentMap responseMeters) { -+ this.responseMeters = responseMeters; - } - - @Override -- public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ public void onEvent(RequestEvent event) { -+ if (event.getType() == RequestEvent.Type.FINISHED) { -+ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -+ final ResponseMeterMetric metric = -+ (method != null) -+ ? this.responseMeters.get(method.getInvocable().getDefinitionMethod()) -+ : null; -+ -+ if (metric != null) { -+ ContainerResponse containerResponse = event.getContainerResponse(); -+ if (containerResponse == null && event.getException() != null) { -+ metric.mark(500); -+ } else if (containerResponse != null) { -+ metric.mark(containerResponse.getStatus()); -+ } -+ } -+ } - } -+ } - -- private T getClassLevelAnnotation(final Resource resource, final Class annotationClazz) { -- T annotation = null; -- -- for (final Class clazz : resource.getHandlerClasses()) { -- annotation = clazz.getAnnotation(annotationClazz); -+ private static class ChainedRequestEventListener implements RequestEventListener { -+ private final RequestEventListener[] listeners; - -- if (annotation != null) { -- break; -- } -- } -- return annotation; -+ private ChainedRequestEventListener(final RequestEventListener... listeners) { -+ this.listeners = listeners; - } - -- private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -- if (classLevelTimed != null) { -- registerTimers(method, definitionMethod, classLevelTimed); -- return; -- } -- -- final Timed annotation = definitionMethod.getAnnotation(Timed.class); -- if (annotation != null) { -- registerTimers(method, definitionMethod, annotation); -- } -+ @Override -+ public void onEvent(final RequestEvent event) { -+ for (RequestEventListener listener : listeners) { -+ listener.onEvent(event); -+ } - } -+ } - -- private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { -- timers.putIfAbsent(EventTypeAndMethod.requestMethodStart(definitionMethod), timerMetric(metrics, method, annotation)); -- if (trackFilters) { -- timers.putIfAbsent(EventTypeAndMethod.requestMatched(definitionMethod), timerMetric(metrics, method, annotation, REQUEST_FILTERING)); -- timers.putIfAbsent(EventTypeAndMethod.respFiltersStart(definitionMethod), timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); -- timers.putIfAbsent(EventTypeAndMethod.finished(definitionMethod), timerMetric(metrics, method, annotation, TOTAL)); -- } -+ @Override -+ public void onEvent(ApplicationEvent event) { -+ if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { -+ registerMetricsForModel(event.getResourceModel()); -+ } -+ } -+ -+ @Override -+ public ResourceModel processResourceModel( -+ ResourceModel resourceModel, Configuration configuration) { -+ return resourceModel; -+ } -+ -+ @Override -+ public ResourceModel processSubResource( -+ ResourceModel subResourceModel, Configuration configuration) { -+ registerMetricsForModel(subResourceModel); -+ return subResourceModel; -+ } -+ -+ private void registerMetricsForModel(ResourceModel resourceModel) { -+ for (final Resource resource : resourceModel.getResources()) { -+ -+ final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); -+ final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); -+ final ExceptionMetered classLevelExceptionMetered = -+ getClassLevelAnnotation(resource, ExceptionMetered.class); -+ final ResponseMetered classLevelResponseMetered = -+ getClassLevelAnnotation(resource, ResponseMetered.class); -+ -+ for (final ResourceMethod method : resource.getAllMethods()) { -+ registerTimedAnnotations(method, classLevelTimed); -+ registerMeteredAnnotations(method, classLevelMetered); -+ registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); -+ registerResponseMeteredAnnotations(method, classLevelResponseMetered); -+ } -+ -+ for (final Resource childResource : resource.getChildResources()) { -+ -+ final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); -+ final Metered classLevelMeteredChild = -+ getClassLevelAnnotation(childResource, Metered.class); -+ final ExceptionMetered classLevelExceptionMeteredChild = -+ getClassLevelAnnotation(childResource, ExceptionMetered.class); -+ final ResponseMetered classLevelResponseMeteredChild = -+ getClassLevelAnnotation(childResource, ResponseMetered.class); -+ -+ for (final ResourceMethod method : childResource.getAllMethods()) { -+ registerTimedAnnotations(method, classLevelTimedChild); -+ registerMeteredAnnotations(method, classLevelMeteredChild); -+ registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); -+ registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); -+ } -+ } -+ } -+ } -+ -+ @Override -+ public RequestEventListener onRequest(final RequestEvent event) { -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); -+ } -+ -+ private T getClassLevelAnnotation( -+ final Resource resource, final Class annotationClazz) { -+ T annotation = null; -+ -+ for (final Class clazz : resource.getHandlerClasses()) { -+ annotation = clazz.getAnnotation(annotationClazz); -+ -+ if (annotation != null) { -+ break; -+ } -+ } -+ return annotation; -+ } -+ -+ private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ if (classLevelTimed != null) { -+ registerTimers(method, definitionMethod, classLevelTimed); -+ return; - } - -- private void registerMeteredAnnotations(final ResourceMethod method, final Metered classLevelMetered) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ final Timed annotation = definitionMethod.getAnnotation(Timed.class); -+ if (annotation != null) { -+ registerTimers(method, definitionMethod, annotation); -+ } -+ } -+ -+ private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { -+ timers.putIfAbsent( -+ EventTypeAndMethod.requestMethodStart(definitionMethod), -+ timerMetric(metrics, method, annotation)); -+ if (trackFilters) { -+ timers.putIfAbsent( -+ EventTypeAndMethod.requestMatched(definitionMethod), -+ timerMetric(metrics, method, annotation, REQUEST_FILTERING)); -+ timers.putIfAbsent( -+ EventTypeAndMethod.respFiltersStart(definitionMethod), -+ timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); -+ timers.putIfAbsent( -+ EventTypeAndMethod.finished(definitionMethod), -+ timerMetric(metrics, method, annotation, TOTAL)); -+ } -+ } - -- if (classLevelMetered != null) { -- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); -- return; -- } -- final Metered annotation = definitionMethod.getAnnotation(Metered.class); -+ private void registerMeteredAnnotations( -+ final ResourceMethod method, final Metered classLevelMetered) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - -- if (annotation != null) { -- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); -- } -+ if (classLevelMetered != null) { -+ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); -+ return; - } -+ final Metered annotation = definitionMethod.getAnnotation(Metered.class); - -- private void registerExceptionMeteredAnnotations(final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ if (annotation != null) { -+ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); -+ } -+ } - -- if (classLevelExceptionMetered != null) { -- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); -- return; -- } -- final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); -+ private void registerExceptionMeteredAnnotations( -+ final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - -- if (annotation != null) { -- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); -- } -+ if (classLevelExceptionMetered != null) { -+ exceptionMeters.putIfAbsent( -+ definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); -+ return; - } -+ final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); - -- private void registerResponseMeteredAnnotations(final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ if (annotation != null) { -+ exceptionMeters.putIfAbsent( -+ definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); -+ } -+ } - -- if (classLevelResponseMetered != null) { -- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); -- return; -- } -- final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); -+ private void registerResponseMeteredAnnotations( -+ final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - -- if (annotation != null) { -- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); -- } -+ if (classLevelResponseMetered != null) { -+ responseMeters.putIfAbsent( -+ definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); -+ return; - } -+ final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); - -- private Timer timerMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final Timed timed, -- final String... suffixes) { -- final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); -- return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); -+ if (annotation != null) { -+ responseMeters.putIfAbsent( -+ definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); - } -- -- private Meter meterMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final Metered metered) { -- final MetricName name = chooseName(metered.name(), metered.absolute(), method); -- return registry.meter(name, () -> new Meter(clock)); -+ } -+ -+ private Timer timerMetric( -+ final MetricRegistry registry, -+ final ResourceMethod method, -+ final Timed timed, -+ final String... suffixes) { -+ final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); -+ return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); -+ } -+ -+ private Meter meterMetric( -+ final MetricRegistry registry, final ResourceMethod method, final Metered metered) { -+ final MetricName name = chooseName(metered.name(), metered.absolute(), method); -+ return registry.meter(name, () -> new Meter(clock)); -+ } -+ -+ protected static MetricName chooseName( -+ final String explicitName, -+ final boolean absolute, -+ final ResourceMethod method, -+ final String... suffixes) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ MetricName metricName; -+ if (!Strings.isNullOrEmpty(explicitName)) { -+ metricName = -+ absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); -+ } else { -+ metricName = name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); - } -- -- protected static MetricName chooseName(final String explicitName, final boolean absolute, final ResourceMethod method, -- final String... suffixes) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -- MetricName metricName; -- if (explicitName != null && !explicitName.isEmpty()) { -- metricName = absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); -- } else { -- metricName = name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); -- } -- for (String suffix : suffixes) { -- metricName = metricName.resolve(suffix); -- } -- return metricName; -+ for (String suffix : suffixes) { -+ metricName = metricName.resolve(suffix); - } -+ return metricName; -+ } - -- private static class EventTypeAndMethod { -+ private static class EventTypeAndMethod { - -- private final RequestEvent.Type type; -- private final Method method; -- -- private EventTypeAndMethod(RequestEvent.Type type, Method method) { -- this.type = type; -- this.method = method; -- } -- -- static EventTypeAndMethod requestMethodStart(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); -- } -+ private final RequestEvent.Type type; -+ private final Method method; - -- static EventTypeAndMethod requestMatched(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); -- } -+ private EventTypeAndMethod(RequestEvent.Type type, Method method) { -+ this.type = type; -+ this.method = method; -+ } - -- static EventTypeAndMethod respFiltersStart(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); -- } -+ static EventTypeAndMethod requestMethodStart(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); -+ } - -- static EventTypeAndMethod finished(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); -- } -+ static EventTypeAndMethod requestMatched(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); -+ } - -- @Override -- public boolean equals(Object o) { -- if (this == o) { -- return true; -- } -- if (o == null || getClass() != o.getClass()) { -- return false; -- } -+ static EventTypeAndMethod respFiltersStart(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); -+ } - -- EventTypeAndMethod that = (EventTypeAndMethod) o; -+ static EventTypeAndMethod finished(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); -+ } - -- if (type != that.type) { -- return false; -- } -- return method.equals(that.method); -- } -+ @Override -+ public boolean equals(Object o) { -+ if (this == o) { -+ return true; -+ } -+ if (o == null || getClass() != o.getClass()) { -+ return false; -+ } -+ -+ EventTypeAndMethod that = (EventTypeAndMethod) o; -+ -+ if (type != that.type) { -+ return false; -+ } -+ return method.equals(that.method); -+ } - -- @Override -- public int hashCode() { -- int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -- } -+ @Override -+ public int hashCode() { -+ int result = type.hashCode(); -+ return 31 * result + method.hashCode(); - } -+ } - } ---- a/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/MetricsFeature.java -+++ b/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/MetricsFeature.java -@@ -7,91 +7,96 @@ import io.dropwizard.metrics5.Reservoir; - import io.dropwizard.metrics5.SharedMetricRegistries; - import jakarta.ws.rs.core.Feature; - import jakarta.ws.rs.core.FeatureContext; -- - import java.util.function.Supplier; - - /** -- * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} -- * for recording request events. -+ * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} for -+ * recording request events. - */ - public class MetricsFeature implements Feature { - -- private final MetricRegistry registry; -- private final Clock clock; -- private final boolean trackFilters; -- private final Supplier reservoirSupplier; -+ private final MetricRegistry registry; -+ private final Clock clock; -+ private final boolean trackFilters; -+ private final Supplier reservoirSupplier; - -- /* -- * @param registry the metrics registry where the metrics will be stored -- */ -- public MetricsFeature(MetricRegistry registry) { -- this(registry, Clock.defaultClock()); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ */ -+ public MetricsFeature(MetricRegistry registry) { -+ this(registry, Clock.defaultClock()); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -- */ -- public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { -- this(registry, Clock.defaultClock(), false, reservoirSupplier); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -+ */ -+ public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { -+ this(registry, Clock.defaultClock(), false, reservoirSupplier); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- */ -- public MetricsFeature(MetricRegistry registry, Clock clock) { -- this(registry, clock, false); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ */ -+ public MetricsFeature(MetricRegistry registry, Clock clock) { -+ this(registry, clock, false); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- */ -- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { -- this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be tracked -+ */ -+ public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { -+ this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -- */ -- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters, Supplier reservoirSupplier) { -- this.registry = registry; -- this.clock = clock; -- this.trackFilters = trackFilters; -- this.reservoirSupplier = reservoirSupplier; -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be tracked -+ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -+ */ -+ public MetricsFeature( -+ MetricRegistry registry, -+ Clock clock, -+ boolean trackFilters, -+ Supplier reservoirSupplier) { -+ this.registry = registry; -+ this.clock = clock; -+ this.trackFilters = trackFilters; -+ this.reservoirSupplier = reservoirSupplier; -+ } - -- public MetricsFeature(String registryName) { -- this(SharedMetricRegistries.getOrCreate(registryName)); -- } -+ public MetricsFeature(String registryName) { -+ this(SharedMetricRegistries.getOrCreate(registryName)); -+ } - -- /** -- * A call-back method called when the feature is to be enabled in a given -- * runtime configuration scope. -- *

    -- * The responsibility of the feature is to properly update the supplied runtime configuration context -- * and return {@code true} if the feature was successfully enabled or {@code false} otherwise. -- *

    -- * Note that under some circumstances the feature may decide not to enable itself, which -- * is indicated by returning {@code false}. In such case the configuration context does -- * not add the feature to the collection of enabled features and a subsequent call to -- * {@link jakarta.ws.rs.core.Configuration#isEnabled(jakarta.ws.rs.core.Feature)} or -- * {@link jakarta.ws.rs.core.Configuration#isEnabled(Class)} method -- * would return {@code false}. -- *

    -- * -- * @param context configurable context in which the feature should be enabled. -- * @return {@code true} if the feature was successfully enabled, {@code false} -- * otherwise. -- */ -- @Override -- public boolean configure(FeatureContext context) { -- context.register(new InstrumentedResourceMethodApplicationListener(registry, clock, trackFilters, reservoirSupplier)); -- return true; -- } -+ /** -+ * A call-back method called when the feature is to be enabled in a given runtime configuration -+ * scope. -+ * -+ *

    The responsibility of the feature is to properly update the supplied runtime configuration -+ * context and return {@code true} if the feature was successfully enabled or {@code false} -+ * otherwise. -+ * -+ *

    Note that under some circumstances the feature may decide not to enable itself, which is -+ * indicated by returning {@code false}. In such case the configuration context does not add the -+ * feature to the collection of enabled features and a subsequent call to {@link -+ * jakarta.ws.rs.core.Configuration#isEnabled(jakarta.ws.rs.core.Feature)} or {@link -+ * jakarta.ws.rs.core.Configuration#isEnabled(Class)} method would return {@code false}. -+ * -+ *

    -+ * -+ * @param context configurable context in which the feature should be enabled. -+ * @return {@code true} if the feature was successfully enabled, {@code false} otherwise. -+ */ -+ @Override -+ public boolean configure(FeatureContext context) { -+ context.register( -+ new InstrumentedResourceMethodApplicationListener( -+ registry, clock, trackFilters, reservoirSupplier)); -+ return true; -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java -@@ -1,44 +1,44 @@ - package io.dropwizard.metrics5.jersey3; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.UniformReservoir; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceTimedPerClass; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; -- --class CustomReservoirImplementationTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -+final class CustomReservoirImplementationTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- private MetricRegistry registry; -+ private MetricRegistry registry; - -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- return new ResourceConfig() -+ return new ResourceConfig() - .register(new MetricsFeature(this.registry, UniformReservoir::new)) - .register(InstrumentedResourceTimedPerClass.class); -- } -+ } - -- @Test -- void timerHistogramIsUsingCustomReservoirImplementation() { -- assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); -+ @Test -+ void timerHistogramIsUsingCustomReservoirImplementation() { -+ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); - -- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); -- assertThat(timer) -+ final Timer timer = -+ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); -+ assertThat(timer) - .extracting("histogram") - .extracting("reservoir") - .isInstanceOf(UniformReservoir.class); -- } -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java -@@ -1,162 +1,137 @@ - package io.dropwizard.metrics5.jersey3; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedFilteredResource; - import io.dropwizard.metrics5.jersey3.resources.TestRequestFilter; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} with filter tracking -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} with filter tracking - */ --class SingletonFilterMetricsJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- private TestClock testClock; -- -- @Override -- protected Application configure() { -- registry = new MetricRegistry(); -- testClock = new TestClock(); -- ResourceConfig config = new ResourceConfig(); -- config = config.register(new MetricsFeature(this.registry, testClock, true)); -- config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -- } -- -- @BeforeEach -- void resetClock() { -- testClock.tick = 0; -- } -- -- @Test -- void timedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -- } -- -- @Test -- void explicitNamesAreTimed() { -- assertThat(target("named") -- .request() -- .get(String.class)) -- .isEqualTo("fancy"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -- } -- -- @Test -- void absoluteNamesAreTimed() { -- assertThat(target("absolute") -- .request() -- .get(String.class)) -- .isEqualTo("absolute"); -- -- final Timer timer = registry.timer("absolutelyFancy"); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -- } -- -- @Test -- void requestFiltersOfTimedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -- } -- -- @Test -- void responseFiltersOfTimedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- } -- -- @Test -- void totalTimeOfTimedMethodsIsTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); -- } -- -- @Test -- void requestFiltersOfNamedMethodsAreTimed() { -- assertThat(target("named") -- .request() -- .get(String.class)) -- .isEqualTo("fancy"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -- } -- -- @Test -- void requestFiltersOfAbsoluteMethodsAreTimed() { -- assertThat(target("absolute") -- .request() -- .get(String.class)) -- .isEqualTo("absolute"); -- -- final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -- } -- -- @Test -- void subResourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, -- "timed")); -- assertThat(timer.getCount()).isEqualTo(1); -- -- } -+final class SingletonFilterMetricsJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } -+ -+ private MetricRegistry registry; -+ -+ private TestClock testClock; -+ -+ @Override -+ protected Application configure() { -+ registry = new MetricRegistry(); -+ testClock = new TestClock(); -+ ResourceConfig config = new ResourceConfig(); -+ config = config.register(new MetricsFeature(this.registry, testClock, true)); -+ config = config.register(new TestRequestFilter(testClock)); -+ return config.register(new InstrumentedFilteredResource(testClock)); -+ } -+ -+ @BeforeEach -+ void resetClock() { -+ testClock.tick = 0; -+ } -+ -+ @Test -+ void timedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -+ } -+ -+ @Test -+ void explicitNamesAreTimed() { -+ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); -+ -+ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -+ } -+ -+ @Test -+ void absoluteNamesAreTimed() { -+ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); -+ -+ final Timer timer = registry.timer("absolutelyFancy"); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -+ } -+ -+ @Test -+ void requestFiltersOfTimedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -+ } -+ -+ @Test -+ void responseFiltersOfTimedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void totalTimeOfTimedMethodsIsTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); -+ } -+ -+ @Test -+ void requestFiltersOfNamedMethodsAreTimed() { -+ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); -+ -+ final Timer timer = -+ registry.timer( -+ name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -+ } -+ -+ @Test -+ void requestFiltersOfAbsoluteMethodsAreTimed() { -+ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); -+ -+ final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -+ } -+ -+ @Test -+ void subResourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer( -+ name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, "timed")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -1,98 +1,92 @@ - package io.dropwizard.metrics5.jersey3; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceExceptionMeteredPerClass; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceExceptionMeteredPerClass; - import jakarta.ws.rs.ProcessingException; - import jakarta.ws.rs.core.Application; --import org.glassfish.jersey.server.ResourceConfig; --import org.glassfish.jersey.test.JerseyTest; --import org.junit.jupiter.api.Test; -- - import java.io.IOException; - import java.util.logging.Level; - import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+import org.glassfish.jersey.server.ResourceConfig; -+import org.glassfish.jersey.test.JerseyTest; -+import org.junit.jupiter.api.Test; - - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -+final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- private MetricRegistry registry; -+ private MetricRegistry registry; - -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- ResourceConfig config = new ResourceConfig(); -+ ResourceConfig config = new ResourceConfig(); - -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); -+ } - -- return config; -- } -+ @Test -+ void exceptionMeteredMethodsAreExceptionMetered() { -+ final Meter meter = -+ registry.meter( -+ name( -+ InstrumentedResourceExceptionMeteredPerClass.class, -+ "exceptionMetered", -+ "exceptions")); - -- @Test -- void exceptionMeteredMethodsAreExceptionMetered() { -- final Meter meter = registry.meter(name(InstrumentedResourceExceptionMeteredPerClass.class, -- "exceptionMetered", -- "exceptions")); -+ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(target("exception-metered") -- .request() -- .get(String.class)) -- .isEqualTo("fuh"); -- -- assertThat(meter.getCount()).isZero(); -- -- try { -- target("exception-metered") -- .queryParam("splode", true) -- .request() -- .get(String.class); -+ assertThat(meter.getCount()).isEqualTo(0); - -- failBecauseExceptionWasNotThrown(ProcessingException.class); -- } catch (ProcessingException e) { -- assertThat(e.getCause()).isInstanceOf(IOException.class); -- } -+ try { -+ target("exception-metered").queryParam("splode", true).request().get(String.class); - -- assertThat(meter.getCount()).isEqualTo(1); -+ failBecauseExceptionWasNotThrown(ProcessingException.class); -+ } catch (ProcessingException e) { -+ assertThat(e.getCause()).isInstanceOf(IOException.class); - } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- final Meter meter = registry.meter(name(InstrumentedSubResourceExceptionMeteredPerClass.class, -- "exceptionMetered", -- "exceptions")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - -- assertThat(target("subresource/exception-metered") -- .request() -- .get(String.class)) -- .isEqualTo("fuh"); -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ final Meter meter = -+ registry.meter( -+ name( -+ InstrumentedSubResourceExceptionMeteredPerClass.class, -+ "exceptionMetered", -+ "exceptions")); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(target("subresource/exception-metered").request().get(String.class)) -+ .isEqualTo("fuh"); - -- try { -- target("subresource/exception-metered") -- .queryParam("splode", true) -- .request() -- .get(String.class); -+ assertThat(meter.getCount()).isEqualTo(0); - -- failBecauseExceptionWasNotThrown(ProcessingException.class); -- } catch (ProcessingException e) { -- assertThat(e.getCause()).isInstanceOf(IOException.class); -- } -+ try { -+ target("subresource/exception-metered") -+ .queryParam("splode", true) -+ .request() -+ .get(String.class); - -- assertThat(meter.getCount()).isEqualTo(1); -+ failBecauseExceptionWasNotThrown(ProcessingException.class); -+ } catch (ProcessingException e) { -+ assertThat(e.getCause()).isInstanceOf(IOException.class); - } - -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.jersey3; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -@@ -9,197 +13,156 @@ import jakarta.ws.rs.NotFoundException; - import jakarta.ws.rs.ProcessingException; - import jakarta.ws.rs.core.Application; - import jakarta.ws.rs.core.Response; -+import java.io.IOException; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.client.ClientResponse; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.io.IOException; --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link org.glassfish.jersey.server.ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link org.glassfish.jersey.server.ResourceConfig} - */ --class SingletonMetricsJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -- -- ResourceConfig config = new ResourceConfig(); -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -+final class SingletonMetricsJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- return config; -- } -- -- @Test -- void timedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- } -+ private MetricRegistry registry; - -- @Test -- void meteredMethodsAreMetered() { -- assertThat(target("metered") -- .request() -- .get(String.class)) -- .isEqualTo("woo"); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); -- assertThat(meter.getCount()).isEqualTo(1); -- } -+ ResourceConfig config = new ResourceConfig(); -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResource.class); -+ } - -- @Test -- void exceptionMeteredMethodsAreExceptionMetered() { -- final Meter meter = registry.meter(name(InstrumentedResource.class, -- "exceptionMetered", -- "exceptions")); -+ @Test -+ void timedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); - -- assertThat(target("exception-metered") -- .request() -- .get(String.class)) -- .isEqualTo("fuh"); -+ final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - -- try { -- target("exception-metered") -- .queryParam("splode", true) -- .request() -- .get(String.class); -+ @Test -+ void meteredMethodsAreMetered() { -+ assertThat(target("metered").request().get(String.class)).isEqualTo("woo"); - -- failBecauseExceptionWasNotThrown(ProcessingException.class); -- } catch (ProcessingException e) { -- assertThat(e.getCause()).isInstanceOf(IOException.class); -- } -+ final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - -- assertThat(meter.getCount()).isEqualTo(1); -- } -+ @Test -+ void exceptionMeteredMethodsAreExceptionMetered() { -+ final Meter meter = -+ registry.meter(name(InstrumentedResource.class, "exceptionMetered", "exceptions")); - -- @Test -- void responseMeteredMethodsAreMetered() { -- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, -- "response2xxMetered", -- "2xx-responses")); -- final Meter meter4xx = registry.meter(name(InstrumentedResource.class, -- "response4xxMetered", -- "4xx-responses")); -- final Meter meter5xx = registry.meter(name(InstrumentedResource.class, -- "response5xxMetered", -- "5xx-responses")); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(target("response-2xx-metered") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -+ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter4xx.getCount()).isZero(); -- assertThat(target("response-4xx-metered") -- .request() -- .get().getStatus()) -- .isEqualTo(400); -+ assertThat(meter.getCount()).isEqualTo(0); - -- assertThat(meter5xx.getCount()).isZero(); -- assertThat(target("response-5xx-metered") -- .request() -- .get().getStatus()) -- .isEqualTo(500); -+ try { -+ target("exception-metered").queryParam("splode", true).request().get(String.class); - -- assertThat(meter2xx.getCount()).isEqualTo(1); -- assertThat(meter4xx.getCount()).isEqualTo(1); -- assertThat(meter5xx.getCount()).isEqualTo(1); -+ failBecauseExceptionWasNotThrown(ProcessingException.class); -+ } catch (ProcessingException e) { -+ assertThat(e.getCause()).isInstanceOf(IOException.class); - } - -- @Test -- void responseMeteredMethodsAreMeteredWithDetailedLevel() { -- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, -- "responseMeteredDetailed", -- "2xx-responses")); -- final Meter meter200 = registry.meter(name(InstrumentedResource.class, -- "responseMeteredDetailed", -- "200-responses")); -- final Meter meter201 = registry.meter(name(InstrumentedResource.class, -- "responseMeteredDetailed", -- "201-responses")); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -- assertThat(target("response-metered-detailed") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -- assertThat(target("response-metered-detailed") -+ assertThat(meter.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredMethodsAreMetered() { -+ final Meter meter2xx = -+ registry.meter(name(InstrumentedResource.class, "response2xxMetered", "2xx-responses")); -+ final Meter meter4xx = -+ registry.meter(name(InstrumentedResource.class, "response4xxMetered", "4xx-responses")); -+ final Meter meter5xx = -+ registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); -+ -+ assertThat(meter4xx.getCount()).isEqualTo(0); -+ assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); -+ -+ assertThat(meter5xx.getCount()).isEqualTo(0); -+ assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter4xx.getCount()).isEqualTo(1); -+ assertThat(meter5xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredMethodsAreMeteredWithDetailedLevel() { -+ final Meter meter2xx = -+ registry.meter( -+ name(InstrumentedResource.class, "responseMeteredDetailed", "2xx-responses")); -+ final Meter meter200 = -+ registry.meter( -+ name(InstrumentedResource.class, "responseMeteredDetailed", "200-responses")); -+ final Meter meter201 = -+ registry.meter( -+ name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); -+ assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); -+ assertThat( -+ target("response-metered-detailed") - .queryParam("status_code", 201) - .request() -- .get().getStatus()) -- .isEqualTo(201); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -+ .get() -+ .getStatus()) -+ .isEqualTo(201); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredMethodsAreMeteredWithAllLevel() { -+ final Meter meter2xx = -+ registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); -+ final Meter meter200 = -+ registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void resourceNotFound() { -+ final Response response = target().path("not-found").request().get(); -+ assertThat(response.getStatus()).isEqualTo(404); -+ -+ try { -+ target().path("not-found").request().get(ClientResponse.class); -+ failBecauseExceptionWasNotThrown(NotFoundException.class); -+ } catch (NotFoundException e) { -+ assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); - } -+ } - -- @Test -- public void responseMeteredMethodsAreMeteredWithAllLevel() { -- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, -- "responseMeteredAll", -- "2xx-responses")); -- final Meter meter200 = registry.meter(name(InstrumentedResource.class, -- "responseMeteredAll", -- "200-responses")); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(target("response-metered-all") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -- -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -- } -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); - -- @Test -- void testResourceNotFound() { -- final Response response = target().path("not-found").request().get(); -- assertThat(response.getStatus()).isEqualTo(404); -- -- try { -- target().path("not-found").request().get(ClientResponse.class); -- failBecauseExceptionWasNotThrown(NotFoundException.class); -- } catch (NotFoundException e) { -- assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); -- } -- } -- -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); -- assertThat(timer.getCount()).isEqualTo(1); -- } -+ final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -1,66 +1,56 @@ - package io.dropwizard.metrics5.jersey3; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceMeteredPerClass; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceMeteredPerClass; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -- -- ResourceConfig config = new ResourceConfig(); -- -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -+final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- return config; -- } -+ private MetricRegistry registry; - -- @Test -- void meteredPerClassMethodsAreMetered() { -- assertThat(target("meteredPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- final Meter meter = registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); -+ ResourceConfig config = new ResourceConfig(); - -- assertThat(meter.getCount()).isEqualTo(1); -- } -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResourceMeteredPerClass.class); -+ } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/meteredPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Test -+ void meteredPerClassMethodsAreMetered() { -+ assertThat(target("meteredPerClass").request().get(String.class)).isEqualTo("yay"); - -- final Meter meter = registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); -- assertThat(meter.getCount()).isEqualTo(1); -+ final Meter meter = -+ registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); - -- } -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/meteredPerClass").request().get(String.class)).isEqualTo("yay"); - -+ final Meter meter = -+ registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -1,152 +1,158 @@ - package io.dropwizard.metrics5.jersey3; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jersey3.exception.mapper.TestExceptionMapper; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceResponseMeteredPerClass; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceResponseMeteredPerClass; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -+final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- private MetricRegistry registry; -+ private MetricRegistry registry; - -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -+ ResourceConfig config = new ResourceConfig(); - -- ResourceConfig config = new ResourceConfig(); -+ config = config.register(new MetricsFeature(this.registry)); -+ config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -+ return config.register(new TestExceptionMapper()); -+ } - -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -- } -+ @Test -+ void responseMetered2xxPerClassMethodsAreMetered() { -+ assertThat(target("responseMetered2xxPerClass").request().get().getStatus()).isEqualTo(200); - -- @Test -- void responseMetered2xxPerClassMethodsAreMetered() { -- assertThat(target("responseMetered2xxPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -- -- final Meter meter2xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMetered2xxPerClass", -- "2xx-responses")); -+ final Meter meter2xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMetered2xxPerClass", -+ "2xx-responses")); - -- assertThat(meter2xx.getCount()).isEqualTo(1); -- } -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ } - -- @Test -- void responseMetered4xxPerClassMethodsAreMetered() { -- assertThat(target("responseMetered4xxPerClass") -- .request() -- .get().getStatus()) -+ @Test -+ void responseMetered4xxPerClassMethodsAreMetered() { -+ assertThat(target("responseMetered4xxPerClass").request().get().getStatus()).isEqualTo(400); -+ assertThat(target("responseMeteredBadRequestPerClass").request().get().getStatus()) - .isEqualTo(400); -- assertThat(target("responseMeteredBadRequestPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(400); -- -- final Meter meter4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMetered4xxPerClass", -- "4xx-responses")); -- final Meter meterException4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMeteredBadRequestPerClass", -- "4xx-responses")); - -- assertThat(meter4xx.getCount()).isEqualTo(1); -- assertThat(meterException4xx.getCount()).isEqualTo(1); -- } -- -- @Test -- void responseMetered5xxPerClassMethodsAreMetered() { -- assertThat(target("responseMetered5xxPerClass") -- .request() -- .get().getStatus()) -+ final Meter meter4xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMetered4xxPerClass", -+ "4xx-responses")); -+ final Meter meterException4xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMeteredBadRequestPerClass", -+ "4xx-responses")); -+ -+ assertThat(meter4xx.getCount()).isEqualTo(1); -+ assertThat(meterException4xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMetered5xxPerClassMethodsAreMetered() { -+ assertThat(target("responseMetered5xxPerClass").request().get().getStatus()).isEqualTo(500); -+ -+ final Meter meter5xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMetered5xxPerClass", -+ "5xx-responses")); -+ -+ assertThat(meter5xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredMappedExceptionPerClassMethodsAreMetered() { -+ assertThat(target("responseMeteredTestExceptionPerClass").request().get().getStatus()) - .isEqualTo(500); - -- final Meter meter5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMetered5xxPerClass", -- "5xx-responses")); -- -- assertThat(meter5xx.getCount()).isEqualTo(1); -+ final Meter meterTestException = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMeteredTestExceptionPerClass", -+ "5xx-responses")); -+ -+ assertThat(meterTestException.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { -+ try { -+ target("responseMeteredRuntimeExceptionPerClass").request().get(); -+ fail("expected RuntimeException"); -+ } catch (Exception e) { -+ assertThat(e.getCause()).isInstanceOf(RuntimeException.class); - } - -- @Test -- void responseMeteredMappedExceptionPerClassMethodsAreMetered() { -- assertThat(target("responseMeteredTestExceptionPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(500); -- -- final Meter meterTestException = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMeteredTestExceptionPerClass", -- "5xx-responses")); -- -- assertThat(meterTestException.getCount()).isEqualTo(1); -- } -- -- @Test -- void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { -- try { -- target("responseMeteredRuntimeExceptionPerClass") -- .request() -- .get(); -- fail("expected RuntimeException"); -- } catch (Exception e) { -- assertThat(e.getCause()).isInstanceOf(RuntimeException.class); -- } -- -- final Meter meterException5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMeteredRuntimeExceptionPerClass", -- "5xx-responses")); -- -- assertThat(meterException5xx.getCount()).isEqualTo(1); -- } -- -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- final Meter meter2xx = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, -+ final Meter meterException5xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMeteredRuntimeExceptionPerClass", -+ "5xx-responses")); -+ -+ assertThat(meterException5xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ final Meter meter2xx = -+ registry.meter( -+ name( -+ InstrumentedSubResourceResponseMeteredPerClass.class, - "responseMeteredPerClass", - "2xx-responses")); -- final Meter meter200 = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, -+ final Meter meter200 = -+ registry.meter( -+ name( -+ InstrumentedSubResourceResponseMeteredPerClass.class, - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - -- assertThat(target("subresource/responseMeteredPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -+ assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) -+ .isEqualTo(200); - -- final Meter meter = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, -- "responseMeteredPerClass", "2xx-responses")); -- assertThat(meter.getCount()).isEqualTo(1); -+ final Meter meter = -+ registry.meter( -+ name( -+ InstrumentedSubResourceResponseMeteredPerClass.class, -+ "responseMeteredPerClass", -+ "2xx-responses")); -+ assertThat(meter.getCount()).isEqualTo(1); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -- } -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java -@@ -1,66 +1,56 @@ - package io.dropwizard.metrics5.jersey3; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedResourceTimedPerClass; - import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceTimedPerClass; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -- -- ResourceConfig config = new ResourceConfig(); -- -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -+final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- return config; -- } -+ private MetricRegistry registry; - -- @Test -- void timedPerClassMethodsAreTimed() { -- assertThat(target("timedPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); -+ ResourceConfig config = new ResourceConfig(); - -- assertThat(timer.getCount()).isEqualTo(1); -- } -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResourceTimedPerClass.class); -+ } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/timedPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Test -+ void timedPerClassMethodsAreTimed() { -+ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); - -- final Timer timer = registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); -- assertThat(timer.getCount()).isEqualTo(1); -+ final Timer timer = -+ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); - -- } -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/timedPerClass").request().get(String.class)).isEqualTo("yay"); - -+ final Timer timer = -+ registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/TestClock.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/TestClock.java -@@ -4,10 +4,10 @@ import io.dropwizard.metrics5.Clock; - - public class TestClock extends Clock { - -- public long tick; -+ public long tick; - -- @Override -- public long getTick() { -- return tick; -- } -+ @Override -+ public long getTick() { -+ return tick; -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/exception/TestException.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/exception/TestException.java -@@ -1,9 +1,9 @@ - package io.dropwizard.metrics5.jersey3.exception; - - public class TestException extends RuntimeException { -- private static final long serialVersionUID = 1L; -+ private static final long serialVersionUID = 1L; - -- public TestException(String message) { -- super(message); -- } -+ public TestException(String message) { -+ super(message); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/exception/mapper/TestExceptionMapper.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/exception/mapper/TestExceptionMapper.java -@@ -7,8 +7,8 @@ import jakarta.ws.rs.ext.Provider; - - @Provider - public class TestExceptionMapper implements ExceptionMapper { -- @Override -- public Response toResponse(TestException exception) { -- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -- } -+ @Override -+ public Response toResponse(TestException exception) { -+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java -@@ -11,51 +11,50 @@ import jakarta.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedFilteredResource { - -- private final TestClock testClock; -- -- public InstrumentedFilteredResource(TestClock testClock) { -- this.testClock = testClock; -- } -+ private final TestClock testClock; -+ -+ public InstrumentedFilteredResource(TestClock testClock) { -+ this.testClock = testClock; -+ } -+ -+ @GET -+ @Path("/timed") -+ @Timed -+ public String timed() { -+ testClock.tick++; -+ return "yay"; -+ } -+ -+ @GET -+ @Path("/named") -+ @Timed(name = "fancyName") -+ public String named() { -+ testClock.tick++; -+ return "fancy"; -+ } -+ -+ @GET -+ @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) -+ public String absolute() { -+ testClock.tick++; -+ return "absolute"; -+ } -+ -+ @Path("/subresource") -+ public InstrumentedFilteredSubResource locateSubResource() { -+ return new InstrumentedFilteredSubResource(); -+ } -+ -+ @Produces(MediaType.TEXT_PLAIN) -+ public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { -- testClock.tick++; -- return "yay"; -- } -- -- @GET -- @Timed(name = "fancyName") -- @Path("/named") -- public String named() { -- testClock.tick++; -- return "fancy"; -- } -- -- @GET -- @Timed(name = "absolutelyFancy", absolute = true) -- @Path("/absolute") -- public String absolute() { -- testClock.tick++; -- return "absolute"; -- } -- -- @Path("/subresource") -- public InstrumentedFilteredSubResource locateSubResource() { -- return new InstrumentedFilteredSubResource(); -- } -- -- @Produces(MediaType.TEXT_PLAIN) -- public class InstrumentedFilteredSubResource { -- -- @GET -- @Timed -- @Path("/timed") -- public String timed() { -- testClock.tick += 2; -- return "yay"; -- } -- -+ testClock.tick += 2; -+ return "yay"; - } -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.jersey3.resources; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+ - import io.dropwizard.metrics5.annotation.ExceptionMetered; - import io.dropwizard.metrics5.annotation.Metered; - import io.dropwizard.metrics5.annotation.ResponseMetered; -@@ -13,81 +17,81 @@ import jakarta.ws.rs.core.MediaType; - import jakarta.ws.rs.core.Response; - import java.io.IOException; - --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -- - @Path("/") - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { -- @GET -- @Timed -- @Path("/timed") -- public String timed() { -- return "yay"; -- } -+ @GET -+ @Path("/timed") -+ @Timed -+ public String timed() { -+ return "yay"; -+ } - -- @GET -- @Metered -- @Path("/metered") -- public String metered() { -- return "woo"; -- } -+ @GET -+ @Metered -+ @Path("/metered") -+ public String metered() { -+ return "woo"; -+ } - -- @GET -- @ExceptionMetered(cause = IOException.class) -- @Path("/exception-metered") -- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { -- if (splode) { -- throw new IOException("AUGH"); -- } -- return "fuh"; -+ @ExceptionMetered(cause = IOException.class) -+ @GET -+ @Path("/exception-metered") -+ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) -+ throws IOException { -+ if (splode) { -+ throw new IOException("AUGH"); - } -+ return "fuh"; -+ } - -- @GET -- @ResponseMetered(level = DETAILED) -- @Path("/response-metered-detailed") -- public Response responseMeteredDetailed(@QueryParam("status_code") @DefaultValue("200") int statusCode) { -- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -- } -+ @GET -+ @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) -+ public Response responseMeteredDetailed( -+ @QueryParam("status_code") @DefaultValue("200") int statusCode) { -+ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -+ } - -- @GET -- @ResponseMetered(level = COARSE) -- @Path("/response-metered-coarse") -- public Response responseMeteredCoarse(@QueryParam("status_code") @DefaultValue("200") int statusCode) { -- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -- } -+ @GET -+ @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) -+ public Response responseMeteredCoarse( -+ @QueryParam("status_code") @DefaultValue("200") int statusCode) { -+ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -+ } - -- @GET -- @ResponseMetered(level = ALL) -- @Path("/response-metered-all") -- public Response responseMeteredAll(@QueryParam("status_code") @DefaultValue("200") int statusCode) { -- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -- } -+ @GET -+ @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) -+ public Response responseMeteredAll( -+ @QueryParam("status_code") @DefaultValue("200") int statusCode) { -+ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -+ } - -- @GET -- @ResponseMetered -- @Path("/response-2xx-metered") -- public Response response2xxMetered() { -- return Response.ok().build(); -- } -+ @GET -+ @Path("/response-2xx-metered") -+ @ResponseMetered -+ public Response response2xxMetered() { -+ return Response.ok().build(); -+ } - -- @GET -- @ResponseMetered -- @Path("/response-4xx-metered") -- public Response response4xxMetered() { -- return Response.status(Response.Status.BAD_REQUEST).build(); -- } -+ @GET -+ @Path("/response-4xx-metered") -+ @ResponseMetered -+ public Response response4xxMetered() { -+ return Response.status(Response.Status.BAD_REQUEST).build(); -+ } - -- @GET -- @ResponseMetered -- @Path("/response-5xx-metered") -- public Response response5xxMetered() { -- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -- } -+ @GET -+ @Path("/response-5xx-metered") -+ @ResponseMetered -+ public Response response5xxMetered() { -+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -+ } - -- @Path("/subresource") -- public InstrumentedSubResource locateSubResource() { -- return new InstrumentedSubResource(); -- } -+ @Path("/subresource") -+ public InstrumentedSubResource locateSubResource() { -+ return new InstrumentedSubResource(); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceExceptionMeteredPerClass.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceExceptionMeteredPerClass.java -@@ -7,7 +7,6 @@ import jakarta.ws.rs.Path; - import jakarta.ws.rs.Produces; - import jakarta.ws.rs.QueryParam; - import jakarta.ws.rs.core.MediaType; -- - import java.io.IOException; - - @ExceptionMetered(cause = IOException.class) -@@ -15,18 +14,18 @@ import java.io.IOException; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceExceptionMeteredPerClass { - -- @GET -- @Path("/exception-metered") -- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { -- if (splode) { -- throw new IOException("AUGH"); -- } -- return "fuh"; -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { -- return new InstrumentedSubResourceExceptionMeteredPerClass(); -+ @GET -+ @Path("/exception-metered") -+ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) -+ throws IOException { -+ if (splode) { -+ throw new IOException("AUGH"); - } -+ return "fuh"; -+ } - -+ @Path("/subresource") -+ public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { -+ return new InstrumentedSubResourceExceptionMeteredPerClass(); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceMeteredPerClass.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceMeteredPerClass.java -@@ -11,15 +11,14 @@ import jakarta.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceMeteredPerClass { - -- @GET -- @Path("/meteredPerClass") -- public String meteredPerClass() { -- return "yay"; -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceMeteredPerClass locateSubResource() { -- return new InstrumentedSubResourceMeteredPerClass(); -- } -+ @GET -+ @Path("/meteredPerClass") -+ public String meteredPerClass() { -+ return "yay"; -+ } - -+ @Path("/subresource") -+ public InstrumentedSubResourceMeteredPerClass locateSubResource() { -+ return new InstrumentedSubResourceMeteredPerClass(); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceResponseMeteredPerClass.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceResponseMeteredPerClass.java -@@ -14,45 +14,44 @@ import jakarta.ws.rs.core.Response; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceResponseMeteredPerClass { - -- @GET -- @Path("/responseMetered2xxPerClass") -- public Response responseMetered2xxPerClass() { -- return Response.ok().build(); -- } -- -- @GET -- @Path("/responseMetered4xxPerClass") -- public Response responseMetered4xxPerClass() { -- return Response.status(Response.Status.BAD_REQUEST).build(); -- } -- -- @GET -- @Path("/responseMetered5xxPerClass") -- public Response responseMetered5xxPerClass() { -- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -- } -- -- @GET -- @Path("/responseMeteredBadRequestPerClass") -- public String responseMeteredBadRequestPerClass() { -- throw new BadRequestException(); -- } -- -- @GET -- @Path("/responseMeteredRuntimeExceptionPerClass") -- public String responseMeteredRuntimeExceptionPerClass() { -- throw new RuntimeException(); -- } -- -- @GET -- @Path("/responseMeteredTestExceptionPerClass") -- public String responseMeteredTestExceptionPerClass() { -- throw new TestException("test"); -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { -- return new InstrumentedSubResourceResponseMeteredPerClass(); -- } -- -+ @GET -+ @Path("/responseMetered2xxPerClass") -+ public Response responseMetered2xxPerClass() { -+ return Response.ok().build(); -+ } -+ -+ @GET -+ @Path("/responseMetered4xxPerClass") -+ public Response responseMetered4xxPerClass() { -+ return Response.status(Response.Status.BAD_REQUEST).build(); -+ } -+ -+ @GET -+ @Path("/responseMetered5xxPerClass") -+ public Response responseMetered5xxPerClass() { -+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -+ } -+ -+ @GET -+ @Path("/responseMeteredBadRequestPerClass") -+ public String responseMeteredBadRequestPerClass() { -+ throw new BadRequestException(); -+ } -+ -+ @GET -+ @Path("/responseMeteredRuntimeExceptionPerClass") -+ public String responseMeteredRuntimeExceptionPerClass() { -+ throw new RuntimeException(); -+ } -+ -+ @GET -+ @Path("/responseMeteredTestExceptionPerClass") -+ public String responseMeteredTestExceptionPerClass() { -+ throw new TestException("test"); -+ } -+ -+ @Path("/subresource") -+ public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { -+ return new InstrumentedSubResourceResponseMeteredPerClass(); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceTimedPerClass.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResourceTimedPerClass.java -@@ -11,15 +11,14 @@ import jakarta.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceTimedPerClass { - -- @GET -- @Path("/timedPerClass") -- public String timedPerClass() { -- return "yay"; -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceTimedPerClass locateSubResource() { -- return new InstrumentedSubResourceTimedPerClass(); -- } -+ @GET -+ @Path("/timedPerClass") -+ public String timedPerClass() { -+ return "yay"; -+ } - -+ @Path("/subresource") -+ public InstrumentedSubResourceTimedPerClass locateSubResource() { -+ return new InstrumentedSubResourceTimedPerClass(); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java -@@ -9,11 +9,10 @@ import jakarta.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResource { - -- @GET -- @Timed -- @Path("/timed") -- public String timed() { -- return "yay"; -- } -- -+ @GET -+ @Path("/timed") -+ @Timed -+ public String timed() { -+ return "yay"; -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceExceptionMeteredPerClass.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceExceptionMeteredPerClass.java -@@ -7,18 +7,18 @@ import jakarta.ws.rs.Path; - import jakarta.ws.rs.Produces; - import jakarta.ws.rs.QueryParam; - import jakarta.ws.rs.core.MediaType; -- - import java.io.IOException; - - @ExceptionMetered(cause = IOException.class) - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceExceptionMeteredPerClass { -- @GET -- @Path("/exception-metered") -- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { -- if (splode) { -- throw new IOException("AUGH"); -- } -- return "fuh"; -+ @GET -+ @Path("/exception-metered") -+ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) -+ throws IOException { -+ if (splode) { -+ throw new IOException("AUGH"); - } -+ return "fuh"; -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceMeteredPerClass.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceMeteredPerClass.java -@@ -9,9 +9,9 @@ import jakarta.ws.rs.core.MediaType; - @Metered - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceMeteredPerClass { -- @GET -- @Path("/meteredPerClass") -- public String meteredPerClass() { -- return "yay"; -- } -+ @GET -+ @Path("/meteredPerClass") -+ public String meteredPerClass() { -+ return "yay"; -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceResponseMeteredPerClass.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceResponseMeteredPerClass.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.jersey3.resources; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+ - import io.dropwizard.metrics5.annotation.ResponseMetered; - import jakarta.ws.rs.GET; - import jakarta.ws.rs.Path; -@@ -7,14 +9,12 @@ import jakarta.ws.rs.Produces; - import jakarta.ws.rs.core.MediaType; - import jakarta.ws.rs.core.Response; - --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -- - @ResponseMetered(level = ALL) - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceResponseMeteredPerClass { -- @GET -- @Path("/responseMeteredPerClass") -- public Response responseMeteredPerClass() { -- return Response.status(Response.Status.OK).build(); -- } -+ @GET -+ @Path("/responseMeteredPerClass") -+ public Response responseMeteredPerClass() { -+ return Response.status(Response.Status.OK).build(); -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceTimedPerClass.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResourceTimedPerClass.java -@@ -9,9 +9,9 @@ import jakarta.ws.rs.core.MediaType; - @Timed - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceTimedPerClass { -- @GET -- @Path("/timedPerClass") -- public String timedPerClass() { -- return "yay"; -- } -+ @GET -+ @Path("/timedPerClass") -+ public String timedPerClass() { -+ return "yay"; -+ } - } ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/TestRequestFilter.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/TestRequestFilter.java -@@ -3,19 +3,18 @@ package io.dropwizard.metrics5.jersey3.resources; - import io.dropwizard.metrics5.jersey3.TestClock; - import jakarta.ws.rs.container.ContainerRequestContext; - import jakarta.ws.rs.container.ContainerRequestFilter; -- - import java.io.IOException; - - public class TestRequestFilter implements ContainerRequestFilter { - -- private final TestClock testClock; -+ private final TestClock testClock; - -- public TestRequestFilter(TestClock testClock) { -- this.testClock = testClock; -- } -+ public TestRequestFilter(TestClock testClock) { -+ this.testClock = testClock; -+ } - -- @Override -- public void filter(ContainerRequestContext containerRequestContext) throws IOException { -- testClock.tick += 4; -- } -+ @Override -+ public void filter(ContainerRequestContext containerRequestContext) throws IOException { -+ testClock.tick += 4; -+ } - } ---- a/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java -@@ -1,5 +1,14 @@ - package io.dropwizard.metrics5.jersey31; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; -+ -+import com.google.common.base.Strings; -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Meter; -@@ -14,20 +23,9 @@ import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; - import io.dropwizard.metrics5.annotation.Timed; - import jakarta.ws.rs.core.Configuration; - import jakarta.ws.rs.ext.Provider; --import org.glassfish.jersey.server.ContainerResponse; --import org.glassfish.jersey.server.model.ModelProcessor; --import org.glassfish.jersey.server.model.Resource; --import org.glassfish.jersey.server.model.ResourceMethod; --import org.glassfish.jersey.server.model.ResourceModel; --import org.glassfish.jersey.server.monitoring.ApplicationEvent; --import org.glassfish.jersey.server.monitoring.ApplicationEventListener; --import org.glassfish.jersey.server.monitoring.RequestEvent; --import org.glassfish.jersey.server.monitoring.RequestEventListener; -- - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -36,518 +34,573 @@ import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.ConcurrentMap; - import java.util.concurrent.TimeUnit; - import java.util.function.Supplier; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import org.glassfish.jersey.server.ContainerResponse; -+import org.glassfish.jersey.server.model.ModelProcessor; -+import org.glassfish.jersey.server.model.Resource; -+import org.glassfish.jersey.server.model.ResourceMethod; -+import org.glassfish.jersey.server.model.ResourceModel; -+import org.glassfish.jersey.server.monitoring.ApplicationEvent; -+import org.glassfish.jersey.server.monitoring.ApplicationEventListener; -+import org.glassfish.jersey.server.monitoring.RequestEvent; -+import org.glassfish.jersey.server.monitoring.RequestEventListener; - - /** -- * An application event listener that listens for Jersey application initialization to -- * be finished, then creates a map of resource method that have metrics annotations. -- *

    -- * Finally, it listens for method start events, and returns a {@link RequestEventListener} -- * that updates the relevant metric for suitably annotated methods when it gets the -- * request events indicating that the method is about to be invoked, or just got done -- * being invoked. -+ * An application event listener that listens for Jersey application initialization to be finished, -+ * then creates a map of resource method that have metrics annotations. -+ * -+ *

    Finally, it listens for method start events, and returns a {@link RequestEventListener} that -+ * updates the relevant metric for suitably annotated methods when it gets the request events -+ * indicating that the method is about to be invoked, or just got done being invoked. - */ - @Provider --public class InstrumentedResourceMethodApplicationListener implements ApplicationEventListener, ModelProcessor { -- -- private static final String[] REQUEST_FILTERING = {"request", "filtering"}; -- private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; -- private static final String TOTAL = "total"; -- -- private final MetricRegistry metrics; -- private final ConcurrentMap timers = new ConcurrentHashMap<>(); -- private final ConcurrentMap meters = new ConcurrentHashMap<>(); -- private final ConcurrentMap exceptionMeters = new ConcurrentHashMap<>(); -- private final ConcurrentMap responseMeters = new ConcurrentHashMap<>(); -- -- private final Clock clock; -- private final boolean trackFilters; -- private final Supplier reservoirSupplier; -- -- /** -- * Construct an application event listener using the given metrics registry. -- *

    -- * When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} -- * should be added to a Jersey {@code ResourceConfig} as a singleton. -- * -- * @param metrics a {@link MetricRegistry} -- */ -- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { -- this(metrics, Clock.defaultClock(), false); -- } -- -- /** -- * Constructs a custom application listener. -- * -- * @param metrics the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- */ -- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, -- final boolean trackFilters) { -- this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); -- } -- -- /** -- * Constructs a custom application listener. -- * -- * @param metrics the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -- */ -- public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics, final Clock clock, -- final boolean trackFilters, -- final Supplier reservoirSupplier) { -- this.metrics = metrics; -- this.clock = clock; -- this.trackFilters = trackFilters; -- this.reservoirSupplier = reservoirSupplier; -- } -- -- /** -- * A private class to maintain the metric for a method annotated with the -- * {@link ExceptionMetered} annotation, which needs to maintain both a meter -- * and a cause for which the meter should be updated. -- */ -- private static class ExceptionMeterMetric { -- public final Meter meter; -- public final Class cause; -- -- public ExceptionMeterMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final ExceptionMetered exceptionMetered) { -- final MetricName name = chooseName(exceptionMetered.name(), -- exceptionMetered.absolute(), method, ExceptionMetered.DEFAULT_NAME_SUFFIX); -- this.meter = registry.meter(name); -- this.cause = exceptionMetered.cause(); -- } -+public class InstrumentedResourceMethodApplicationListener -+ implements ApplicationEventListener, ModelProcessor { -+ -+ private static final String[] REQUEST_FILTERING = {"request", "filtering"}; -+ private static final String[] RESPONSE_FILTERING = {"response", "filtering"}; -+ private static final String TOTAL = "total"; -+ -+ private final MetricRegistry metrics; -+ private final ConcurrentMap timers = new ConcurrentHashMap<>(); -+ private final ConcurrentMap meters = new ConcurrentHashMap<>(); -+ private final ConcurrentMap exceptionMeters = -+ new ConcurrentHashMap<>(); -+ private final ConcurrentMap responseMeters = -+ new ConcurrentHashMap<>(); -+ -+ private final Clock clock; -+ private final boolean trackFilters; -+ private final Supplier reservoirSupplier; -+ -+ /** -+ * Construct an application event listener using the given metrics registry. -+ * -+ *

    When using this constructor, the {@link InstrumentedResourceMethodApplicationListener} -+ * should be added to a Jersey {@code ResourceConfig} as a singleton. -+ * -+ * @param metrics a {@link MetricRegistry} -+ */ -+ public InstrumentedResourceMethodApplicationListener(final MetricRegistry metrics) { -+ this(metrics, Clock.defaultClock(), false); -+ } -+ -+ /** -+ * Constructs a custom application listener. -+ * -+ * @param metrics the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be -+ * tracked -+ */ -+ public InstrumentedResourceMethodApplicationListener( -+ final MetricRegistry metrics, final Clock clock, final boolean trackFilters) { -+ this(metrics, clock, trackFilters, ExponentiallyDecayingReservoir::new); -+ } -+ -+ /** -+ * Constructs a custom application listener. -+ * -+ * @param metrics the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be -+ * tracked -+ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -+ */ -+ public InstrumentedResourceMethodApplicationListener( -+ final MetricRegistry metrics, -+ final Clock clock, -+ final boolean trackFilters, -+ final Supplier reservoirSupplier) { -+ this.metrics = metrics; -+ this.clock = clock; -+ this.trackFilters = trackFilters; -+ this.reservoirSupplier = reservoirSupplier; -+ } -+ -+ /** -+ * A private class to maintain the metric for a method annotated with the {@link ExceptionMetered} -+ * annotation, which needs to maintain both a meter and a cause for which the meter should be -+ * updated. -+ */ -+ private static class ExceptionMeterMetric { -+ public final Meter meter; -+ public final Class cause; -+ -+ public ExceptionMeterMetric( -+ final MetricRegistry registry, -+ final ResourceMethod method, -+ final ExceptionMetered exceptionMetered) { -+ final MetricName name = -+ chooseName( -+ exceptionMetered.name(), -+ exceptionMetered.absolute(), -+ method, -+ ExceptionMetered.DEFAULT_NAME_SUFFIX); -+ this.meter = registry.meter(name); -+ this.cause = exceptionMetered.cause(); - } -- -- /** -- * A private class to maintain the metrics for a method annotated with the -- * {@link ResponseMetered} annotation, which needs to maintain meters for -- * different response codes -- */ -- private static class ResponseMeterMetric { -- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -- private final List meters; -- private final Map responseCodeMeters; -- private final MetricRegistry metricRegistry; -- private final MetricName metricName; -- private final ResponseMeteredLevel level; -- -- public ResponseMeterMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final ResponseMetered responseMetered) { -- this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); -- this.level = responseMetered.level(); -- this.meters = COARSE_METER_LEVELS.contains(level) ? -- Collections.unmodifiableList(Arrays.asList( -- registry.meter(metricName.resolve("1xx-responses")), // 1xx -- registry.meter(metricName.resolve("2xx-responses")), // 2xx -- registry.meter(metricName.resolve("3xx-responses")), // 3xx -- registry.meter(metricName.resolve("4xx-responses")), // 4xx -- registry.meter(metricName.resolve("5xx-responses")) // 5xx -- )) : Collections.emptyList(); -- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : Collections.emptyMap(); -- this.metricRegistry = registry; -- } -- -- public void mark(int statusCode) { -- if (DETAILED_METER_LEVELS.contains(level)) { -- getResponseCodeMeter(statusCode).mark(); -- } -- -- if (COARSE_METER_LEVELS.contains(level)) { -- final int responseStatus = statusCode / 100; -- if (responseStatus >= 1 && responseStatus <= 5) { -- meters.get(responseStatus - 1).mark(); -- } -- } -- } -- -- private Meter getResponseCodeMeter(int statusCode) { -- return responseCodeMeters -- .computeIfAbsent(statusCode, sc -> metricRegistry -- .meter(metricName.resolve(String.format("%d-responses", sc)))); -- } -+ } -+ -+ /** -+ * A private class to maintain the metrics for a method annotated with the {@link ResponseMetered} -+ * annotation, which needs to maintain meters for different response codes -+ */ -+ private static class ResponseMeterMetric { -+ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -+ private static final Set DETAILED_METER_LEVELS = -+ EnumSet.of(DETAILED, ALL); -+ private final List meters; -+ private final Map responseCodeMeters; -+ private final MetricRegistry metricRegistry; -+ private final MetricName metricName; -+ private final ResponseMeteredLevel level; -+ -+ public ResponseMeterMetric( -+ final MetricRegistry registry, -+ final ResourceMethod method, -+ final ResponseMetered responseMetered) { -+ this.metricName = chooseName(responseMetered.name(), responseMetered.absolute(), method); -+ this.level = responseMetered.level(); -+ this.meters = -+ COARSE_METER_LEVELS.contains(level) -+ ? unmodifiableList( -+ Arrays.asList( -+ registry.meter(metricName.resolve("1xx-responses")), // 1xx -+ registry.meter(metricName.resolve("2xx-responses")), // 2xx -+ registry.meter(metricName.resolve("3xx-responses")), // 3xx -+ registry.meter(metricName.resolve("4xx-responses")), // 4xx -+ registry.meter(metricName.resolve("5xx-responses")) // 5xx -+ )) -+ : ImmutableList.of(); -+ this.responseCodeMeters = -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); -+ this.metricRegistry = registry; - } - -- private static class TimerRequestEventListener implements RequestEventListener { -- -- private final ConcurrentMap timers; -- private final Clock clock; -- private final long start; -- private Timer.Context resourceMethodStartContext; -- private Timer.Context requestMatchedContext; -- private Timer.Context responseFiltersStartContext; -- -- public TimerRequestEventListener(final ConcurrentMap timers, final Clock clock) { -- this.timers = timers; -- this.clock = clock; -- start = clock.getTick(); -- } -- -- @Override -- public void onEvent(RequestEvent event) { -- switch (event.getType()) { -- case RESOURCE_METHOD_START: -- resourceMethodStartContext = context(event); -- break; -- case REQUEST_MATCHED: -- requestMatchedContext = context(event); -- break; -- case RESP_FILTERS_START: -- responseFiltersStartContext = context(event); -- break; -- case RESOURCE_METHOD_FINISHED: -- if (resourceMethodStartContext != null) { -- resourceMethodStartContext.close(); -- } -- break; -- case REQUEST_FILTERED: -- if (requestMatchedContext != null) { -- requestMatchedContext.close(); -- } -- break; -- case RESP_FILTERS_FINISHED: -- if (responseFiltersStartContext != null) { -- responseFiltersStartContext.close(); -- } -- break; -- case FINISHED: -- if (requestMatchedContext != null && responseFiltersStartContext != null) { -- final Timer timer = timer(event); -- if (timer != null) { -- timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); -- } -- } -- break; -- default: -- break; -- } -- } -- -- private Timer timer(RequestEvent event) { -- final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); -- if (resourceMethod == null) { -- return null; -- } -- return timers.get(new EventTypeAndMethod(event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); -- } -+ public void mark(int statusCode) { -+ if (DETAILED_METER_LEVELS.contains(level)) { -+ getResponseCodeMeter(statusCode).mark(); -+ } - -- private Timer.Context context(RequestEvent event) { -- final Timer timer = timer(event); -- return timer != null ? timer.time() : null; -+ if (COARSE_METER_LEVELS.contains(level)) { -+ final int responseStatus = statusCode / 100; -+ if (responseStatus >= 1 && responseStatus <= 5) { -+ meters.get(responseStatus - 1).mark(); - } -+ } - } - -- private static class MeterRequestEventListener implements RequestEventListener { -- private final ConcurrentMap meters; -- -- public MeterRequestEventListener(final ConcurrentMap meters) { -- this.meters = meters; -- } -- -- @Override -- public void onEvent(RequestEvent event) { -- if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { -- final Meter meter = this.meters.get(event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); -- if (meter != null) { -- meter.mark(); -- } -- } -- } -+ private Meter getResponseCodeMeter(int statusCode) { -+ return responseCodeMeters.computeIfAbsent( -+ statusCode, -+ sc -> metricRegistry.meter(metricName.resolve(String.format("%d-responses", sc)))); - } -+ } - -- private static class ExceptionMeterRequestEventListener implements RequestEventListener { -- private final ConcurrentMap exceptionMeters; -+ private static class TimerRequestEventListener implements RequestEventListener { - -- public ExceptionMeterRequestEventListener(final ConcurrentMap exceptionMeters) { -- this.exceptionMeters = exceptionMeters; -- } -+ private final ConcurrentMap timers; -+ private final Clock clock; -+ private final long start; -+ private Timer.Context resourceMethodStartContext; -+ private Timer.Context requestMatchedContext; -+ private Timer.Context responseFiltersStartContext; -+ -+ public TimerRequestEventListener( -+ final ConcurrentMap timers, final Clock clock) { -+ this.timers = timers; -+ this.clock = clock; -+ start = clock.getTick(); -+ } - -- @Override -- public void onEvent(RequestEvent event) { -- if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { -- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -- final ExceptionMeterMetric metric = (method != null) ? -- this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) : null; -- -- if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) || -- (event.getException().getCause() != null && -- metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -- metric.meter.mark(); -- } -- } -+ @Override -+ public void onEvent(RequestEvent event) { -+ switch (event.getType()) { -+ case RESOURCE_METHOD_START: -+ resourceMethodStartContext = context(event); -+ break; -+ case REQUEST_MATCHED: -+ requestMatchedContext = context(event); -+ break; -+ case RESP_FILTERS_START: -+ responseFiltersStartContext = context(event); -+ break; -+ case RESOURCE_METHOD_FINISHED: -+ if (resourceMethodStartContext != null) { -+ resourceMethodStartContext.close(); -+ } -+ break; -+ case REQUEST_FILTERED: -+ if (requestMatchedContext != null) { -+ requestMatchedContext.close(); -+ } -+ break; -+ case RESP_FILTERS_FINISHED: -+ if (responseFiltersStartContext != null) { -+ responseFiltersStartContext.close(); -+ } -+ break; -+ case FINISHED: -+ if (requestMatchedContext != null && responseFiltersStartContext != null) { -+ final Timer timer = timer(event); -+ if (timer != null) { -+ timer.update(clock.getTick() - start, TimeUnit.NANOSECONDS); - } -- } -+ } -+ break; -+ default: -+ break; -+ } - } - -- private static class ResponseMeterRequestEventListener implements RequestEventListener { -- private final ConcurrentMap responseMeters; -- -- public ResponseMeterRequestEventListener(final ConcurrentMap responseMeters) { -- this.responseMeters = responseMeters; -- } -- -- @Override -- public void onEvent(RequestEvent event) { -- if (event.getType() == RequestEvent.Type.FINISHED) { -- final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -- final ResponseMeterMetric metric = (method != null) ? -- this.responseMeters.get(method.getInvocable().getDefinitionMethod()) : null; -- -- if (metric != null) { -- ContainerResponse containerResponse = event.getContainerResponse(); -- if (containerResponse == null && event.getException() != null) { -- metric.mark(500); -- } else if (containerResponse != null) { -- metric.mark(containerResponse.getStatus()); -- } -- } -- } -- } -+ private Timer timer(RequestEvent event) { -+ final ResourceMethod resourceMethod = event.getUriInfo().getMatchedResourceMethod(); -+ if (resourceMethod == null) { -+ return null; -+ } -+ return timers.get( -+ new EventTypeAndMethod( -+ event.getType(), resourceMethod.getInvocable().getDefinitionMethod())); - } - -- private static class ChainedRequestEventListener implements RequestEventListener { -- private final RequestEventListener[] listeners; -+ private Timer.Context context(RequestEvent event) { -+ final Timer timer = timer(event); -+ return timer != null ? timer.time() : null; -+ } -+ } - -- private ChainedRequestEventListener(final RequestEventListener... listeners) { -- this.listeners = listeners; -- } -+ private static class MeterRequestEventListener implements RequestEventListener { -+ private final ConcurrentMap meters; - -- @Override -- public void onEvent(final RequestEvent event) { -- for (RequestEventListener listener : listeners) { -- listener.onEvent(event); -- } -- } -+ public MeterRequestEventListener(final ConcurrentMap meters) { -+ this.meters = meters; - } - - @Override -- public void onEvent(ApplicationEvent event) { -- if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { -- registerMetricsForModel(event.getResourceModel()); -- } -+ public void onEvent(RequestEvent event) { -+ if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { -+ final Meter meter = -+ this.meters.get( -+ event.getUriInfo().getMatchedResourceMethod().getInvocable().getDefinitionMethod()); -+ if (meter != null) { -+ meter.mark(); -+ } -+ } - } -+ } - -- @Override -- public ResourceModel processResourceModel(ResourceModel resourceModel, Configuration configuration) { -- return resourceModel; -+ private static class ExceptionMeterRequestEventListener implements RequestEventListener { -+ private final ConcurrentMap exceptionMeters; -+ -+ public ExceptionMeterRequestEventListener( -+ final ConcurrentMap exceptionMeters) { -+ this.exceptionMeters = exceptionMeters; - } - - @Override -- public ResourceModel processSubResource(ResourceModel subResourceModel, Configuration configuration) { -- registerMetricsForModel(subResourceModel); -- return subResourceModel; -+ public void onEvent(RequestEvent event) { -+ if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { -+ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -+ final ExceptionMeterMetric metric = -+ (method != null) -+ ? this.exceptionMeters.get(method.getInvocable().getDefinitionMethod()) -+ : null; -+ -+ if (metric != null) { -+ if (metric.cause.isInstance(event.getException()) -+ || (event.getException().getCause() != null -+ && metric.cause.isInstance(event.getException().getCause()))) { -+ metric.meter.mark(); -+ } -+ } -+ } - } -+ } - -- private void registerMetricsForModel(ResourceModel resourceModel) { -- for (final Resource resource : resourceModel.getResources()) { -- -- final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); -- final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); -- final ExceptionMetered classLevelExceptionMetered = getClassLevelAnnotation(resource, ExceptionMetered.class); -- final ResponseMetered classLevelResponseMetered = getClassLevelAnnotation(resource, ResponseMetered.class); -- -- for (final ResourceMethod method : resource.getAllMethods()) { -- registerTimedAnnotations(method, classLevelTimed); -- registerMeteredAnnotations(method, classLevelMetered); -- registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); -- registerResponseMeteredAnnotations(method, classLevelResponseMetered); -- } -- -- for (final Resource childResource : resource.getChildResources()) { -- -- final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); -- final Metered classLevelMeteredChild = getClassLevelAnnotation(childResource, Metered.class); -- final ExceptionMetered classLevelExceptionMeteredChild = getClassLevelAnnotation(childResource, ExceptionMetered.class); -- final ResponseMetered classLevelResponseMeteredChild = getClassLevelAnnotation(childResource, ResponseMetered.class); -+ private static class ResponseMeterRequestEventListener implements RequestEventListener { -+ private final ConcurrentMap responseMeters; - -- for (final ResourceMethod method : childResource.getAllMethods()) { -- registerTimedAnnotations(method, classLevelTimedChild); -- registerMeteredAnnotations(method, classLevelMeteredChild); -- registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); -- registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); -- } -- } -- } -+ public ResponseMeterRequestEventListener( -+ final ConcurrentMap responseMeters) { -+ this.responseMeters = responseMeters; - } - - @Override -- public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ public void onEvent(RequestEvent event) { -+ if (event.getType() == RequestEvent.Type.FINISHED) { -+ final ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); -+ final ResponseMeterMetric metric = -+ (method != null) -+ ? this.responseMeters.get(method.getInvocable().getDefinitionMethod()) -+ : null; -+ -+ if (metric != null) { -+ ContainerResponse containerResponse = event.getContainerResponse(); -+ if (containerResponse == null && event.getException() != null) { -+ metric.mark(500); -+ } else if (containerResponse != null) { -+ metric.mark(containerResponse.getStatus()); -+ } -+ } -+ } - } -+ } - -- private T getClassLevelAnnotation(final Resource resource, final Class annotationClazz) { -- T annotation = null; -- -- for (final Class clazz : resource.getHandlerClasses()) { -- annotation = clazz.getAnnotation(annotationClazz); -+ private static class ChainedRequestEventListener implements RequestEventListener { -+ private final RequestEventListener[] listeners; - -- if (annotation != null) { -- break; -- } -- } -- return annotation; -+ private ChainedRequestEventListener(final RequestEventListener... listeners) { -+ this.listeners = listeners; - } - -- private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -- if (classLevelTimed != null) { -- registerTimers(method, definitionMethod, classLevelTimed); -- return; -- } -- -- final Timed annotation = definitionMethod.getAnnotation(Timed.class); -- if (annotation != null) { -- registerTimers(method, definitionMethod, annotation); -- } -+ @Override -+ public void onEvent(final RequestEvent event) { -+ for (RequestEventListener listener : listeners) { -+ listener.onEvent(event); -+ } - } -+ } - -- private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { -- timers.putIfAbsent(EventTypeAndMethod.requestMethodStart(definitionMethod), timerMetric(metrics, method, annotation)); -- if (trackFilters) { -- timers.putIfAbsent(EventTypeAndMethod.requestMatched(definitionMethod), timerMetric(metrics, method, annotation, REQUEST_FILTERING)); -- timers.putIfAbsent(EventTypeAndMethod.respFiltersStart(definitionMethod), timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); -- timers.putIfAbsent(EventTypeAndMethod.finished(definitionMethod), timerMetric(metrics, method, annotation, TOTAL)); -- } -+ @Override -+ public void onEvent(ApplicationEvent event) { -+ if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) { -+ registerMetricsForModel(event.getResourceModel()); -+ } -+ } -+ -+ @Override -+ public ResourceModel processResourceModel( -+ ResourceModel resourceModel, Configuration configuration) { -+ return resourceModel; -+ } -+ -+ @Override -+ public ResourceModel processSubResource( -+ ResourceModel subResourceModel, Configuration configuration) { -+ registerMetricsForModel(subResourceModel); -+ return subResourceModel; -+ } -+ -+ private void registerMetricsForModel(ResourceModel resourceModel) { -+ for (final Resource resource : resourceModel.getResources()) { -+ -+ final Timed classLevelTimed = getClassLevelAnnotation(resource, Timed.class); -+ final Metered classLevelMetered = getClassLevelAnnotation(resource, Metered.class); -+ final ExceptionMetered classLevelExceptionMetered = -+ getClassLevelAnnotation(resource, ExceptionMetered.class); -+ final ResponseMetered classLevelResponseMetered = -+ getClassLevelAnnotation(resource, ResponseMetered.class); -+ -+ for (final ResourceMethod method : resource.getAllMethods()) { -+ registerTimedAnnotations(method, classLevelTimed); -+ registerMeteredAnnotations(method, classLevelMetered); -+ registerExceptionMeteredAnnotations(method, classLevelExceptionMetered); -+ registerResponseMeteredAnnotations(method, classLevelResponseMetered); -+ } -+ -+ for (final Resource childResource : resource.getChildResources()) { -+ -+ final Timed classLevelTimedChild = getClassLevelAnnotation(childResource, Timed.class); -+ final Metered classLevelMeteredChild = -+ getClassLevelAnnotation(childResource, Metered.class); -+ final ExceptionMetered classLevelExceptionMeteredChild = -+ getClassLevelAnnotation(childResource, ExceptionMetered.class); -+ final ResponseMetered classLevelResponseMeteredChild = -+ getClassLevelAnnotation(childResource, ResponseMetered.class); -+ -+ for (final ResourceMethod method : childResource.getAllMethods()) { -+ registerTimedAnnotations(method, classLevelTimedChild); -+ registerMeteredAnnotations(method, classLevelMeteredChild); -+ registerExceptionMeteredAnnotations(method, classLevelExceptionMeteredChild); -+ registerResponseMeteredAnnotations(method, classLevelResponseMeteredChild); -+ } -+ } -+ } -+ } -+ -+ @Override -+ public RequestEventListener onRequest(final RequestEvent event) { -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); -+ } -+ -+ private T getClassLevelAnnotation( -+ final Resource resource, final Class annotationClazz) { -+ T annotation = null; -+ -+ for (final Class clazz : resource.getHandlerClasses()) { -+ annotation = clazz.getAnnotation(annotationClazz); -+ -+ if (annotation != null) { -+ break; -+ } -+ } -+ return annotation; -+ } -+ -+ private void registerTimedAnnotations(final ResourceMethod method, final Timed classLevelTimed) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ if (classLevelTimed != null) { -+ registerTimers(method, definitionMethod, classLevelTimed); -+ return; - } - -- private void registerMeteredAnnotations(final ResourceMethod method, final Metered classLevelMetered) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ final Timed annotation = definitionMethod.getAnnotation(Timed.class); -+ if (annotation != null) { -+ registerTimers(method, definitionMethod, annotation); -+ } -+ } -+ -+ private void registerTimers(ResourceMethod method, Method definitionMethod, Timed annotation) { -+ timers.putIfAbsent( -+ EventTypeAndMethod.requestMethodStart(definitionMethod), -+ timerMetric(metrics, method, annotation)); -+ if (trackFilters) { -+ timers.putIfAbsent( -+ EventTypeAndMethod.requestMatched(definitionMethod), -+ timerMetric(metrics, method, annotation, REQUEST_FILTERING)); -+ timers.putIfAbsent( -+ EventTypeAndMethod.respFiltersStart(definitionMethod), -+ timerMetric(metrics, method, annotation, RESPONSE_FILTERING)); -+ timers.putIfAbsent( -+ EventTypeAndMethod.finished(definitionMethod), -+ timerMetric(metrics, method, annotation, TOTAL)); -+ } -+ } - -- if (classLevelMetered != null) { -- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); -- return; -- } -- final Metered annotation = definitionMethod.getAnnotation(Metered.class); -+ private void registerMeteredAnnotations( -+ final ResourceMethod method, final Metered classLevelMetered) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - -- if (annotation != null) { -- meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); -- } -+ if (classLevelMetered != null) { -+ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, classLevelMetered)); -+ return; - } -+ final Metered annotation = definitionMethod.getAnnotation(Metered.class); - -- private void registerExceptionMeteredAnnotations(final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ if (annotation != null) { -+ meters.putIfAbsent(definitionMethod, meterMetric(metrics, method, annotation)); -+ } -+ } - -- if (classLevelExceptionMetered != null) { -- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); -- return; -- } -- final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); -+ private void registerExceptionMeteredAnnotations( -+ final ResourceMethod method, final ExceptionMetered classLevelExceptionMetered) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - -- if (annotation != null) { -- exceptionMeters.putIfAbsent(definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); -- } -+ if (classLevelExceptionMetered != null) { -+ exceptionMeters.putIfAbsent( -+ definitionMethod, new ExceptionMeterMetric(metrics, method, classLevelExceptionMetered)); -+ return; - } -+ final ExceptionMetered annotation = definitionMethod.getAnnotation(ExceptionMetered.class); - -- private void registerResponseMeteredAnnotations(final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ if (annotation != null) { -+ exceptionMeters.putIfAbsent( -+ definitionMethod, new ExceptionMeterMetric(metrics, method, annotation)); -+ } -+ } - -- if (classLevelResponseMetered != null) { -- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); -- return; -- } -- final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); -+ private void registerResponseMeteredAnnotations( -+ final ResourceMethod method, final ResponseMetered classLevelResponseMetered) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - -- if (annotation != null) { -- responseMeters.putIfAbsent(definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); -- } -+ if (classLevelResponseMetered != null) { -+ responseMeters.putIfAbsent( -+ definitionMethod, new ResponseMeterMetric(metrics, method, classLevelResponseMetered)); -+ return; - } -+ final ResponseMetered annotation = definitionMethod.getAnnotation(ResponseMetered.class); - -- private Timer timerMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final Timed timed, -- final String... suffixes) { -- final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); -- return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); -+ if (annotation != null) { -+ responseMeters.putIfAbsent( -+ definitionMethod, new ResponseMeterMetric(metrics, method, annotation)); - } -- -- private Meter meterMetric(final MetricRegistry registry, -- final ResourceMethod method, -- final Metered metered) { -- final MetricName name = chooseName(metered.name(), metered.absolute(), method); -- return registry.meter(name, () -> new Meter(clock)); -+ } -+ -+ private Timer timerMetric( -+ final MetricRegistry registry, -+ final ResourceMethod method, -+ final Timed timed, -+ final String... suffixes) { -+ final MetricName name = chooseName(timed.name(), timed.absolute(), method, suffixes); -+ return registry.timer(name, () -> new Timer(reservoirSupplier.get(), clock)); -+ } -+ -+ private Meter meterMetric( -+ final MetricRegistry registry, final ResourceMethod method, final Metered metered) { -+ final MetricName name = chooseName(metered.name(), metered.absolute(), method); -+ return registry.meter(name, () -> new Meter(clock)); -+ } -+ -+ protected static MetricName chooseName( -+ final String explicitName, -+ final boolean absolute, -+ final ResourceMethod method, -+ final String... suffixes) { -+ final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -+ MetricName metricName; -+ if (!Strings.isNullOrEmpty(explicitName)) { -+ metricName = -+ absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); -+ } else { -+ metricName = name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); - } -- -- protected static MetricName chooseName(final String explicitName, final boolean absolute, final ResourceMethod method, -- final String... suffixes) { -- final Method definitionMethod = method.getInvocable().getDefinitionMethod(); -- MetricName metricName; -- if (explicitName != null && !explicitName.isEmpty()) { -- metricName = absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); -- } else { -- metricName = name(definitionMethod.getDeclaringClass(), definitionMethod.getName()); -- } -- for (String suffix : suffixes) { -- metricName = metricName.resolve(suffix); -- } -- return metricName; -+ for (String suffix : suffixes) { -+ metricName = metricName.resolve(suffix); - } -+ return metricName; -+ } - -- private static class EventTypeAndMethod { -+ private static class EventTypeAndMethod { - -- private final RequestEvent.Type type; -- private final Method method; -- -- private EventTypeAndMethod(RequestEvent.Type type, Method method) { -- this.type = type; -- this.method = method; -- } -- -- static EventTypeAndMethod requestMethodStart(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); -- } -+ private final RequestEvent.Type type; -+ private final Method method; - -- static EventTypeAndMethod requestMatched(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); -- } -+ private EventTypeAndMethod(RequestEvent.Type type, Method method) { -+ this.type = type; -+ this.method = method; -+ } - -- static EventTypeAndMethod respFiltersStart(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); -- } -+ static EventTypeAndMethod requestMethodStart(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.RESOURCE_METHOD_START, method); -+ } - -- static EventTypeAndMethod finished(Method method) { -- return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); -- } -+ static EventTypeAndMethod requestMatched(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.REQUEST_MATCHED, method); -+ } - -- @Override -- public boolean equals(Object o) { -- if (this == o) { -- return true; -- } -- if (o == null || getClass() != o.getClass()) { -- return false; -- } -+ static EventTypeAndMethod respFiltersStart(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.RESP_FILTERS_START, method); -+ } - -- EventTypeAndMethod that = (EventTypeAndMethod) o; -+ static EventTypeAndMethod finished(Method method) { -+ return new EventTypeAndMethod(RequestEvent.Type.FINISHED, method); -+ } - -- if (type != that.type) { -- return false; -- } -- return method.equals(that.method); -- } -+ @Override -+ public boolean equals(Object o) { -+ if (this == o) { -+ return true; -+ } -+ if (o == null || getClass() != o.getClass()) { -+ return false; -+ } -+ -+ EventTypeAndMethod that = (EventTypeAndMethod) o; -+ -+ if (type != that.type) { -+ return false; -+ } -+ return method.equals(that.method); -+ } - -- @Override -- public int hashCode() { -- int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -- } -+ @Override -+ public int hashCode() { -+ int result = type.hashCode(); -+ return 31 * result + method.hashCode(); - } -+ } - } ---- a/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/MetricsFeature.java -+++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/MetricsFeature.java -@@ -7,91 +7,96 @@ import io.dropwizard.metrics5.Reservoir; - import io.dropwizard.metrics5.SharedMetricRegistries; - import jakarta.ws.rs.core.Feature; - import jakarta.ws.rs.core.FeatureContext; -- - import java.util.function.Supplier; - - /** -- * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} -- * for recording request events. -+ * A {@link Feature} which registers a {@link InstrumentedResourceMethodApplicationListener} for -+ * recording request events. - */ - public class MetricsFeature implements Feature { - -- private final MetricRegistry registry; -- private final Clock clock; -- private final boolean trackFilters; -- private final Supplier reservoirSupplier; -+ private final MetricRegistry registry; -+ private final Clock clock; -+ private final boolean trackFilters; -+ private final Supplier reservoirSupplier; - -- /* -- * @param registry the metrics registry where the metrics will be stored -- */ -- public MetricsFeature(MetricRegistry registry) { -- this(registry, Clock.defaultClock()); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ */ -+ public MetricsFeature(MetricRegistry registry) { -+ this(registry, Clock.defaultClock()); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -- */ -- public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { -- this(registry, Clock.defaultClock(), false, reservoirSupplier); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -+ */ -+ public MetricsFeature(MetricRegistry registry, Supplier reservoirSupplier) { -+ this(registry, Clock.defaultClock(), false, reservoirSupplier); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- */ -- public MetricsFeature(MetricRegistry registry, Clock clock) { -- this(registry, clock, false); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ */ -+ public MetricsFeature(MetricRegistry registry, Clock clock) { -+ this(registry, clock, false); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- */ -- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { -- this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be tracked -+ */ -+ public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters) { -+ this(registry, clock, trackFilters, ExponentiallyDecayingReservoir::new); -+ } - -- /* -- * @param registry the metrics registry where the metrics will be stored -- * @param clock the {@link Clock} to track time (used mostly in testing) in timers -- * @param trackFilters whether the processing time for request and response filters should be tracked -- * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -- */ -- public MetricsFeature(MetricRegistry registry, Clock clock, boolean trackFilters, Supplier reservoirSupplier) { -- this.registry = registry; -- this.clock = clock; -- this.trackFilters = trackFilters; -- this.reservoirSupplier = reservoirSupplier; -- } -+ /* -+ * @param registry the metrics registry where the metrics will be stored -+ * @param clock the {@link Clock} to track time (used mostly in testing) in timers -+ * @param trackFilters whether the processing time for request and response filters should be tracked -+ * @param reservoirSupplier Supplier for creating the {@link Reservoir} for {@link Timer timers}. -+ */ -+ public MetricsFeature( -+ MetricRegistry registry, -+ Clock clock, -+ boolean trackFilters, -+ Supplier reservoirSupplier) { -+ this.registry = registry; -+ this.clock = clock; -+ this.trackFilters = trackFilters; -+ this.reservoirSupplier = reservoirSupplier; -+ } - -- public MetricsFeature(String registryName) { -- this(SharedMetricRegistries.getOrCreate(registryName)); -- } -+ public MetricsFeature(String registryName) { -+ this(SharedMetricRegistries.getOrCreate(registryName)); -+ } - -- /** -- * A call-back method called when the feature is to be enabled in a given -- * runtime configuration scope. -- *

    -- * The responsibility of the feature is to properly update the supplied runtime configuration context -- * and return {@code true} if the feature was successfully enabled or {@code false} otherwise. -- *

    -- * Note that under some circumstances the feature may decide not to enable itself, which -- * is indicated by returning {@code false}. In such case the configuration context does -- * not add the feature to the collection of enabled features and a subsequent call to -- * {@link jakarta.ws.rs.core.Configuration#isEnabled(Feature)} or -- * {@link jakarta.ws.rs.core.Configuration#isEnabled(Class)} method -- * would return {@code false}. -- *

    -- * -- * @param context configurable context in which the feature should be enabled. -- * @return {@code true} if the feature was successfully enabled, {@code false} -- * otherwise. -- */ -- @Override -- public boolean configure(FeatureContext context) { -- context.register(new InstrumentedResourceMethodApplicationListener(registry, clock, trackFilters, reservoirSupplier)); -- return true; -- } -+ /** -+ * A call-back method called when the feature is to be enabled in a given runtime configuration -+ * scope. -+ * -+ *

    The responsibility of the feature is to properly update the supplied runtime configuration -+ * context and return {@code true} if the feature was successfully enabled or {@code false} -+ * otherwise. -+ * -+ *

    Note that under some circumstances the feature may decide not to enable itself, which is -+ * indicated by returning {@code false}. In such case the configuration context does not add the -+ * feature to the collection of enabled features and a subsequent call to {@link -+ * jakarta.ws.rs.core.Configuration#isEnabled(Feature)} or {@link -+ * jakarta.ws.rs.core.Configuration#isEnabled(Class)} method would return {@code false}. -+ * -+ *

    -+ * -+ * @param context configurable context in which the feature should be enabled. -+ * @return {@code true} if the feature was successfully enabled, {@code false} otherwise. -+ */ -+ @Override -+ public boolean configure(FeatureContext context) { -+ context.register( -+ new InstrumentedResourceMethodApplicationListener( -+ registry, clock, trackFilters, reservoirSupplier)); -+ return true; -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java -@@ -1,44 +1,44 @@ - package io.dropwizard.metrics5.jersey31; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.UniformReservoir; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceTimedPerClass; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; -- --class CustomReservoirImplementationTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -+final class CustomReservoirImplementationTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- private MetricRegistry registry; -+ private MetricRegistry registry; - -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- return new ResourceConfig() -+ return new ResourceConfig() - .register(new MetricsFeature(this.registry, UniformReservoir::new)) - .register(InstrumentedResourceTimedPerClass.class); -- } -+ } - -- @Test -- void timerHistogramIsUsingCustomReservoirImplementation() { -- assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); -+ @Test -+ void timerHistogramIsUsingCustomReservoirImplementation() { -+ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); - -- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); -- assertThat(timer) -+ final Timer timer = -+ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); -+ assertThat(timer) - .extracting("histogram") - .extracting("reservoir") - .isInstanceOf(UniformReservoir.class); -- } -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java -@@ -1,162 +1,137 @@ - package io.dropwizard.metrics5.jersey31; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedFilteredResource; - import io.dropwizard.metrics5.jersey31.resources.TestRequestFilter; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} with filter tracking -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} with filter tracking - */ --class SingletonFilterMetricsJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- private TestClock testClock; -- -- @Override -- protected Application configure() { -- registry = new MetricRegistry(); -- testClock = new TestClock(); -- ResourceConfig config = new ResourceConfig(); -- config = config.register(new MetricsFeature(this.registry, testClock, true)); -- config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -- } -- -- @BeforeEach -- void resetClock() { -- testClock.tick = 0; -- } -- -- @Test -- void timedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -- } -- -- @Test -- void explicitNamesAreTimed() { -- assertThat(target("named") -- .request() -- .get(String.class)) -- .isEqualTo("fancy"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -- } -- -- @Test -- void absoluteNamesAreTimed() { -- assertThat(target("absolute") -- .request() -- .get(String.class)) -- .isEqualTo("absolute"); -- -- final Timer timer = registry.timer("absolutelyFancy"); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -- } -- -- @Test -- void requestFiltersOfTimedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -- } -- -- @Test -- void responseFiltersOfTimedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- } -- -- @Test -- void totalTimeOfTimedMethodsIsTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); -- } -- -- @Test -- void requestFiltersOfNamedMethodsAreTimed() { -- assertThat(target("named") -- .request() -- .get(String.class)) -- .isEqualTo("fancy"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); -- -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -- } -- -- @Test -- void requestFiltersOfAbsoluteMethodsAreTimed() { -- assertThat(target("absolute") -- .request() -- .get(String.class)) -- .isEqualTo("absolute"); -- -- final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -- } -- -- @Test -- void subResourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -- -- final Timer timer = registry.timer(name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, -- "timed")); -- assertThat(timer.getCount()).isEqualTo(1); -- -- } -+final class SingletonFilterMetricsJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } -+ -+ private MetricRegistry registry; -+ -+ private TestClock testClock; -+ -+ @Override -+ protected Application configure() { -+ registry = new MetricRegistry(); -+ testClock = new TestClock(); -+ ResourceConfig config = new ResourceConfig(); -+ config = config.register(new MetricsFeature(this.registry, testClock, true)); -+ config = config.register(new TestRequestFilter(testClock)); -+ return config.register(new InstrumentedFilteredResource(testClock)); -+ } -+ -+ @BeforeEach -+ void resetClock() { -+ testClock.tick = 0; -+ } -+ -+ @Test -+ void timedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -+ } -+ -+ @Test -+ void explicitNamesAreTimed() { -+ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); -+ -+ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -+ } -+ -+ @Test -+ void absoluteNamesAreTimed() { -+ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); -+ -+ final Timer timer = registry.timer("absolutelyFancy"); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(1); -+ } -+ -+ @Test -+ void requestFiltersOfTimedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -+ } -+ -+ @Test -+ void responseFiltersOfTimedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void totalTimeOfTimedMethodsIsTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(5); -+ } -+ -+ @Test -+ void requestFiltersOfNamedMethodsAreTimed() { -+ assertThat(target("named").request().get(String.class)).isEqualTo("fancy"); -+ -+ final Timer timer = -+ registry.timer( -+ name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); -+ -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -+ } -+ -+ @Test -+ void requestFiltersOfAbsoluteMethodsAreTimed() { -+ assertThat(target("absolute").request().get(String.class)).isEqualTo("absolute"); -+ -+ final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()[0]).isEqualTo(4); -+ } -+ -+ @Test -+ void subResourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); -+ -+ final Timer timer = -+ registry.timer( -+ name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, "timed")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -1,98 +1,92 @@ - package io.dropwizard.metrics5.jersey31; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceExceptionMeteredPerClass; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceExceptionMeteredPerClass; - import jakarta.ws.rs.ProcessingException; - import jakarta.ws.rs.core.Application; --import org.glassfish.jersey.server.ResourceConfig; --import org.glassfish.jersey.test.JerseyTest; --import org.junit.jupiter.api.Test; -- - import java.io.IOException; - import java.util.logging.Level; - import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+import org.glassfish.jersey.server.ResourceConfig; -+import org.glassfish.jersey.test.JerseyTest; -+import org.junit.jupiter.api.Test; - - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -+final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- private MetricRegistry registry; -+ private MetricRegistry registry; - -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- ResourceConfig config = new ResourceConfig(); -+ ResourceConfig config = new ResourceConfig(); - -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); -+ } - -- return config; -- } -+ @Test -+ void exceptionMeteredMethodsAreExceptionMetered() { -+ final Meter meter = -+ registry.meter( -+ name( -+ InstrumentedResourceExceptionMeteredPerClass.class, -+ "exceptionMetered", -+ "exceptions")); - -- @Test -- void exceptionMeteredMethodsAreExceptionMetered() { -- final Meter meter = registry.meter(name(InstrumentedResourceExceptionMeteredPerClass.class, -- "exceptionMetered", -- "exceptions")); -+ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(target("exception-metered") -- .request() -- .get(String.class)) -- .isEqualTo("fuh"); -- -- assertThat(meter.getCount()).isZero(); -- -- try { -- target("exception-metered") -- .queryParam("splode", true) -- .request() -- .get(String.class); -+ assertThat(meter.getCount()).isEqualTo(0); - -- failBecauseExceptionWasNotThrown(ProcessingException.class); -- } catch (ProcessingException e) { -- assertThat(e.getCause()).isInstanceOf(IOException.class); -- } -+ try { -+ target("exception-metered").queryParam("splode", true).request().get(String.class); - -- assertThat(meter.getCount()).isEqualTo(1); -+ failBecauseExceptionWasNotThrown(ProcessingException.class); -+ } catch (ProcessingException e) { -+ assertThat(e.getCause()).isInstanceOf(IOException.class); - } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- final Meter meter = registry.meter(name(InstrumentedSubResourceExceptionMeteredPerClass.class, -- "exceptionMetered", -- "exceptions")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - -- assertThat(target("subresource/exception-metered") -- .request() -- .get(String.class)) -- .isEqualTo("fuh"); -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ final Meter meter = -+ registry.meter( -+ name( -+ InstrumentedSubResourceExceptionMeteredPerClass.class, -+ "exceptionMetered", -+ "exceptions")); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(target("subresource/exception-metered").request().get(String.class)) -+ .isEqualTo("fuh"); - -- try { -- target("subresource/exception-metered") -- .queryParam("splode", true) -- .request() -- .get(String.class); -+ assertThat(meter.getCount()).isEqualTo(0); - -- failBecauseExceptionWasNotThrown(ProcessingException.class); -- } catch (ProcessingException e) { -- assertThat(e.getCause()).isInstanceOf(IOException.class); -- } -+ try { -+ target("subresource/exception-metered") -+ .queryParam("splode", true) -+ .request() -+ .get(String.class); - -- assertThat(meter.getCount()).isEqualTo(1); -+ failBecauseExceptionWasNotThrown(ProcessingException.class); -+ } catch (ProcessingException e) { -+ assertThat(e.getCause()).isInstanceOf(IOException.class); - } - -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.jersey31; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -@@ -9,214 +13,167 @@ import jakarta.ws.rs.NotFoundException; - import jakarta.ws.rs.ProcessingException; - import jakarta.ws.rs.core.Application; - import jakarta.ws.rs.core.Response; -+import java.io.IOException; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.client.ClientResponse; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.io.IOException; --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -- -- ResourceConfig config = new ResourceConfig(); -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -- } -+final class SingletonMetricsJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- @Test -- void timedMethodsAreTimed() { -- assertThat(target("timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ private MetricRegistry registry; - -- final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- assertThat(timer.getCount()).isEqualTo(1); -- } -- -- @Test -- void meteredMethodsAreMetered() { -- assertThat(target("metered") -- .request() -- .get(String.class)) -- .isEqualTo("woo"); -+ ResourceConfig config = new ResourceConfig(); -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResource.class); -+ } - -- final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); -- assertThat(meter.getCount()).isEqualTo(1); -- } -+ @Test -+ void timedMethodsAreTimed() { -+ assertThat(target("timed").request().get(String.class)).isEqualTo("yay"); - -- @Test -- void exceptionMeteredMethodsAreExceptionMetered() { -- final Meter meter = registry.meter(name(InstrumentedResource.class, -- "exceptionMetered", -- "exceptions")); -+ final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); - -- assertThat(target("exception-metered") -- .request() -- .get(String.class)) -- .isEqualTo("fuh"); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - -- assertThat(meter.getCount()).isZero(); -+ @Test -+ void meteredMethodsAreMetered() { -+ assertThat(target("metered").request().get(String.class)).isEqualTo("woo"); - -- try { -- target("exception-metered") -- .queryParam("splode", true) -- .request() -- .get(String.class); -+ final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - -- failBecauseExceptionWasNotThrown(ProcessingException.class); -- } catch (ProcessingException e) { -- assertThat(e.getCause()).isInstanceOf(IOException.class); -- } -+ @Test -+ void exceptionMeteredMethodsAreExceptionMetered() { -+ final Meter meter = -+ registry.meter(name(InstrumentedResource.class, "exceptionMetered", "exceptions")); - -- assertThat(meter.getCount()).isEqualTo(1); -- } -+ assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- @Test -- void responseMeteredMethodsAreMetered() { -- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, -- "response2xxMetered", -- "2xx-responses")); -- final Meter meter4xx = registry.meter(name(InstrumentedResource.class, -- "response4xxMetered", -- "4xx-responses")); -- final Meter meter5xx = registry.meter(name(InstrumentedResource.class, -- "response5xxMetered", -- "5xx-responses")); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(target("response-2xx-metered") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -+ assertThat(meter.getCount()).isEqualTo(0); - -- assertThat(meter4xx.getCount()).isZero(); -- assertThat(target("response-4xx-metered") -- .request() -- .get().getStatus()) -- .isEqualTo(400); -- -- assertThat(meter5xx.getCount()).isZero(); -- assertThat(target("response-5xx-metered") -- .request() -- .get().getStatus()) -- .isEqualTo(500); -- } -- -- @Test -- public void responseMeteredMethodsAreMeteredWithCoarseLevel() { -- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, -- "responseMeteredCoarse", -- "2xx-responses")); -- final Meter meter200 = registry.meter(name(InstrumentedResource.class, -- "responseMeteredCoarse", -- "200-responses")); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(target("response-metered-coarse") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -+ try { -+ target("exception-metered").queryParam("splode", true).request().get(String.class); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isZero(); -+ failBecauseExceptionWasNotThrown(ProcessingException.class); -+ } catch (ProcessingException e) { -+ assertThat(e.getCause()).isInstanceOf(IOException.class); - } - -- @Test -- public void responseMeteredMethodsAreMeteredWithDetailedLevel() { -- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, -- "responseMeteredDetailed", -- "2xx-responses")); -- final Meter meter200 = registry.meter(name(InstrumentedResource.class, -- "responseMeteredDetailed", -- "200-responses")); -- final Meter meter201 = registry.meter(name(InstrumentedResource.class, -- "responseMeteredDetailed", -- "201-responses")); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -- assertThat(target("response-metered-detailed") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -- assertThat(target("response-metered-detailed") -+ assertThat(meter.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredMethodsAreMetered() { -+ final Meter meter2xx = -+ registry.meter(name(InstrumentedResource.class, "response2xxMetered", "2xx-responses")); -+ final Meter meter4xx = -+ registry.meter(name(InstrumentedResource.class, "response4xxMetered", "4xx-responses")); -+ final Meter meter5xx = -+ registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); -+ -+ assertThat(meter4xx.getCount()).isEqualTo(0); -+ assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); -+ -+ assertThat(meter5xx.getCount()).isEqualTo(0); -+ assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); -+ } -+ -+ @Test -+ void responseMeteredMethodsAreMeteredWithCoarseLevel() { -+ final Meter meter2xx = -+ registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "2xx-responses")); -+ final Meter meter200 = -+ registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void responseMeteredMethodsAreMeteredWithDetailedLevel() { -+ final Meter meter2xx = -+ registry.meter( -+ name(InstrumentedResource.class, "responseMeteredDetailed", "2xx-responses")); -+ final Meter meter200 = -+ registry.meter( -+ name(InstrumentedResource.class, "responseMeteredDetailed", "200-responses")); -+ final Meter meter201 = -+ registry.meter( -+ name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); -+ assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); -+ assertThat( -+ target("response-metered-detailed") - .queryParam("status_code", 201) - .request() -- .get().getStatus()) -- .isEqualTo(201); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -- } -- -- @Test -- public void responseMeteredMethodsAreMeteredWithAllLevel() { -- final Meter meter2xx = registry.meter(name(InstrumentedResource.class, -- "responseMeteredAll", -- "2xx-responses")); -- final Meter meter200 = registry.meter(name(InstrumentedResource.class, -- "responseMeteredAll", -- "200-responses")); -- -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(target("response-metered-all") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -- -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -- } -- -- @Test -- void testResourceNotFound() { -- final Response response = target().path("not-found").request().get(); -- assertThat(response.getStatus()).isEqualTo(404); -- -- try { -- target().path("not-found").request().get(ClientResponse.class); -- failBecauseExceptionWasNotThrown(NotFoundException.class); -- } catch (NotFoundException e) { -- assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); -- } -+ .get() -+ .getStatus()) -+ .isEqualTo(201); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredMethodsAreMeteredWithAllLevel() { -+ final Meter meter2xx = -+ registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); -+ final Meter meter200 = -+ registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); -+ -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void resourceNotFound() { -+ final Response response = target().path("not-found").request().get(); -+ assertThat(response.getStatus()).isEqualTo(404); -+ -+ try { -+ target().path("not-found").request().get(ClientResponse.class); -+ failBecauseExceptionWasNotThrown(NotFoundException.class); -+ } catch (NotFoundException e) { -+ assertThat(e.getMessage()).isEqualTo("HTTP 404 Not Found"); - } -+ } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/timed") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/timed").request().get(String.class)).isEqualTo("yay"); - -- final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); -- assertThat(timer.getCount()).isEqualTo(1); -- -- } -+ final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -1,66 +1,56 @@ - package io.dropwizard.metrics5.jersey31; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceMeteredPerClass; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceMeteredPerClass; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -- -- ResourceConfig config = new ResourceConfig(); -- -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -+final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- return config; -- } -+ private MetricRegistry registry; - -- @Test -- void meteredPerClassMethodsAreMetered() { -- assertThat(target("meteredPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- final Meter meter = registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); -+ ResourceConfig config = new ResourceConfig(); - -- assertThat(meter.getCount()).isEqualTo(1); -- } -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResourceMeteredPerClass.class); -+ } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/meteredPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Test -+ void meteredPerClassMethodsAreMetered() { -+ assertThat(target("meteredPerClass").request().get(String.class)).isEqualTo("yay"); - -- final Meter meter = registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); -- assertThat(meter.getCount()).isEqualTo(1); -+ final Meter meter = -+ registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); - -- } -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/meteredPerClass").request().get(String.class)).isEqualTo("yay"); - -+ final Meter meter = -+ registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); -+ assertThat(meter.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -1,147 +1,150 @@ - package io.dropwizard.metrics5.jersey31; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.jersey31.exception.mapper.TestExceptionMapper; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceResponseMeteredPerClass; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceResponseMeteredPerClass; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -+final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- private MetricRegistry registry; -+ private MetricRegistry registry; - -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -+ ResourceConfig config = new ResourceConfig(); - -- ResourceConfig config = new ResourceConfig(); -+ config = config.register(new MetricsFeature(this.registry)); -+ config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -+ return config.register(new TestExceptionMapper()); -+ } - -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -- } -- -- @Test -- void responseMetered2xxPerClassMethodsAreMetered() { -- assertThat(target("responseMetered2xxPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(200); -+ @Test -+ void responseMetered2xxPerClassMethodsAreMetered() { -+ assertThat(target("responseMetered2xxPerClass").request().get().getStatus()).isEqualTo(200); - -- final Meter meter2xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMetered2xxPerClass", -- "2xx-responses")); -+ final Meter meter2xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMetered2xxPerClass", -+ "2xx-responses")); - -- assertThat(meter2xx.getCount()).isEqualTo(1); -- } -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ } - -- @Test -- void responseMetered4xxPerClassMethodsAreMetered() { -- assertThat(target("responseMetered4xxPerClass") -- .request() -- .get().getStatus()) -+ @Test -+ void responseMetered4xxPerClassMethodsAreMetered() { -+ assertThat(target("responseMetered4xxPerClass").request().get().getStatus()).isEqualTo(400); -+ assertThat(target("responseMeteredBadRequestPerClass").request().get().getStatus()) - .isEqualTo(400); -- assertThat(target("responseMeteredBadRequestPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(400); -- -- final Meter meter4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMetered4xxPerClass", -- "4xx-responses")); -- final Meter meterException4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMeteredBadRequestPerClass", -- "4xx-responses")); - -- assertThat(meter4xx.getCount()).isEqualTo(1); -- assertThat(meterException4xx.getCount()).isEqualTo(1); -- } -- -- @Test -- void responseMetered5xxPerClassMethodsAreMetered() { -- assertThat(target("responseMetered5xxPerClass") -- .request() -- .get().getStatus()) -+ final Meter meter4xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMetered4xxPerClass", -+ "4xx-responses")); -+ final Meter meterException4xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMeteredBadRequestPerClass", -+ "4xx-responses")); -+ -+ assertThat(meter4xx.getCount()).isEqualTo(1); -+ assertThat(meterException4xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMetered5xxPerClassMethodsAreMetered() { -+ assertThat(target("responseMetered5xxPerClass").request().get().getStatus()).isEqualTo(500); -+ -+ final Meter meter5xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMetered5xxPerClass", -+ "5xx-responses")); -+ -+ assertThat(meter5xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredMappedExceptionPerClassMethodsAreMetered() { -+ assertThat(target("responseMeteredTestExceptionPerClass").request().get().getStatus()) - .isEqualTo(500); - -- final Meter meter5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMetered5xxPerClass", -- "5xx-responses")); -- -- assertThat(meter5xx.getCount()).isEqualTo(1); -+ final Meter meterTestException = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMeteredTestExceptionPerClass", -+ "5xx-responses")); -+ -+ assertThat(meterTestException.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { -+ try { -+ target("responseMeteredRuntimeExceptionPerClass").request().get(); -+ fail("expected RuntimeException"); -+ } catch (Exception e) { -+ assertThat(e.getCause()).isInstanceOf(RuntimeException.class); - } - -- @Test -- void responseMeteredMappedExceptionPerClassMethodsAreMetered() { -- assertThat(target("responseMeteredTestExceptionPerClass") -- .request() -- .get().getStatus()) -- .isEqualTo(500); -- -- final Meter meterTestException = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMeteredTestExceptionPerClass", -- "5xx-responses")); -- -- assertThat(meterTestException.getCount()).isEqualTo(1); -- } -- -- @Test -- void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { -- try { -- target("responseMeteredRuntimeExceptionPerClass") -- .request() -- .get(); -- fail("expected RuntimeException"); -- } catch (Exception e) { -- assertThat(e.getCause()).isInstanceOf(RuntimeException.class); -- } -- -- final Meter meterException5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, -- "responseMeteredRuntimeExceptionPerClass", -- "5xx-responses")); -- -- assertThat(meterException5xx.getCount()).isEqualTo(1); -- } -- -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- final Meter meter2xx = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, -+ final Meter meterException5xx = -+ registry.meter( -+ name( -+ InstrumentedResourceResponseMeteredPerClass.class, -+ "responseMeteredRuntimeExceptionPerClass", -+ "5xx-responses")); -+ -+ assertThat(meterException5xx.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ final Meter meter2xx = -+ registry.meter( -+ name( -+ InstrumentedSubResourceResponseMeteredPerClass.class, - "responseMeteredPerClass", - "2xx-responses")); -- final Meter meter200 = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, -+ final Meter meter200 = -+ registry.meter( -+ name( -+ InstrumentedSubResourceResponseMeteredPerClass.class, - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - -- assertThat(target("subresource/responseMeteredPerClass") -- .request() -- .get().getStatus()) -+ assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -- } -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java -@@ -1,66 +1,56 @@ - package io.dropwizard.metrics5.jersey31; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedResourceTimedPerClass; - import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceTimedPerClass; - import jakarta.ws.rs.core.Application; -+import java.util.logging.Level; -+import java.util.logging.Logger; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --import java.util.logging.Level; --import java.util.logging.Logger; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static org.assertj.core.api.Assertions.assertThat; -- - /** -- * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton -- * in a Jersey {@link ResourceConfig} -+ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a -+ * Jersey {@link ResourceConfig} - */ --class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { -- static { -- Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -- } -- -- private MetricRegistry registry; -- -- @Override -- protected Application configure() { -- this.registry = new MetricRegistry(); -- -- ResourceConfig config = new ResourceConfig(); -- -- config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -+final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { -+ static { -+ Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); -+ } - -- return config; -- } -+ private MetricRegistry registry; - -- @Test -- void timedPerClassMethodsAreTimed() { -- assertThat(target("timedPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Override -+ protected Application configure() { -+ this.registry = new MetricRegistry(); - -- final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); -+ ResourceConfig config = new ResourceConfig(); - -- assertThat(timer.getCount()).isEqualTo(1); -- } -+ config = config.register(new MetricsFeature(this.registry)); -+ return config.register(InstrumentedResourceTimedPerClass.class); -+ } - -- @Test -- void subresourcesFromLocatorsRegisterMetrics() { -- assertThat(target("subresource/timedPerClass") -- .request() -- .get(String.class)) -- .isEqualTo("yay"); -+ @Test -+ void timedPerClassMethodsAreTimed() { -+ assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); - -- final Timer timer = registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); -- assertThat(timer.getCount()).isEqualTo(1); -+ final Timer timer = -+ registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); - -- } -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - -+ @Test -+ void subresourcesFromLocatorsRegisterMetrics() { -+ assertThat(target("subresource/timedPerClass").request().get(String.class)).isEqualTo("yay"); - -+ final Timer timer = -+ registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/TestClock.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/TestClock.java -@@ -4,10 +4,10 @@ import io.dropwizard.metrics5.Clock; - - public class TestClock extends Clock { - -- public long tick; -+ public long tick; - -- @Override -- public long getTick() { -- return tick; -- } -+ @Override -+ public long getTick() { -+ return tick; -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/exception/TestException.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/exception/TestException.java -@@ -1,9 +1,9 @@ - package io.dropwizard.metrics5.jersey31.exception; - - public class TestException extends RuntimeException { -- private static final long serialVersionUID = 1L; -+ private static final long serialVersionUID = 1L; - -- public TestException(String message) { -- super(message); -- } -+ public TestException(String message) { -+ super(message); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/exception/mapper/TestExceptionMapper.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/exception/mapper/TestExceptionMapper.java -@@ -7,8 +7,8 @@ import jakarta.ws.rs.ext.Provider; - - @Provider - public class TestExceptionMapper implements ExceptionMapper { -- @Override -- public Response toResponse(TestException exception) { -- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -- } -+ @Override -+ public Response toResponse(TestException exception) { -+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java -@@ -11,51 +11,50 @@ import jakarta.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedFilteredResource { - -- private final TestClock testClock; -- -- public InstrumentedFilteredResource(TestClock testClock) { -- this.testClock = testClock; -- } -+ private final TestClock testClock; -+ -+ public InstrumentedFilteredResource(TestClock testClock) { -+ this.testClock = testClock; -+ } -+ -+ @GET -+ @Path("/timed") -+ @Timed -+ public String timed() { -+ testClock.tick++; -+ return "yay"; -+ } -+ -+ @GET -+ @Path("/named") -+ @Timed(name = "fancyName") -+ public String named() { -+ testClock.tick++; -+ return "fancy"; -+ } -+ -+ @GET -+ @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) -+ public String absolute() { -+ testClock.tick++; -+ return "absolute"; -+ } -+ -+ @Path("/subresource") -+ public InstrumentedFilteredSubResource locateSubResource() { -+ return new InstrumentedFilteredSubResource(); -+ } -+ -+ @Produces(MediaType.TEXT_PLAIN) -+ public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { -- testClock.tick++; -- return "yay"; -- } -- -- @GET -- @Timed(name = "fancyName") -- @Path("/named") -- public String named() { -- testClock.tick++; -- return "fancy"; -- } -- -- @GET -- @Timed(name = "absolutelyFancy", absolute = true) -- @Path("/absolute") -- public String absolute() { -- testClock.tick++; -- return "absolute"; -- } -- -- @Path("/subresource") -- public InstrumentedFilteredSubResource locateSubResource() { -- return new InstrumentedFilteredSubResource(); -- } -- -- @Produces(MediaType.TEXT_PLAIN) -- public class InstrumentedFilteredSubResource { -- -- @GET -- @Timed -- @Path("/timed") -- public String timed() { -- testClock.tick += 2; -- return "yay"; -- } -- -+ testClock.tick += 2; -+ return "yay"; - } -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.jersey31.resources; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+ - import io.dropwizard.metrics5.annotation.ExceptionMetered; - import io.dropwizard.metrics5.annotation.Metered; - import io.dropwizard.metrics5.annotation.ResponseMetered; -@@ -11,84 +15,83 @@ import jakarta.ws.rs.Produces; - import jakarta.ws.rs.QueryParam; - import jakarta.ws.rs.core.MediaType; - import jakarta.ws.rs.core.Response; -- - import java.io.IOException; - --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -- - @Path("/") - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { -- @GET -- @Timed -- @Path("/timed") -- public String timed() { -- return "yay"; -- } -+ @GET -+ @Path("/timed") -+ @Timed -+ public String timed() { -+ return "yay"; -+ } - -- @GET -- @Metered -- @Path("/metered") -- public String metered() { -- return "woo"; -- } -+ @GET -+ @Metered -+ @Path("/metered") -+ public String metered() { -+ return "woo"; -+ } - -- @GET -- @ExceptionMetered(cause = IOException.class) -- @Path("/exception-metered") -- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { -- if (splode) { -- throw new IOException("AUGH"); -- } -- return "fuh"; -+ @ExceptionMetered(cause = IOException.class) -+ @GET -+ @Path("/exception-metered") -+ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) -+ throws IOException { -+ if (splode) { -+ throw new IOException("AUGH"); - } -+ return "fuh"; -+ } - -- @GET -- @ResponseMetered(level = DETAILED) -- @Path("/response-metered-detailed") -- public Response responseMeteredDetailed(@QueryParam("status_code") @DefaultValue("200") int statusCode) { -- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -- } -+ @GET -+ @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) -+ public Response responseMeteredDetailed( -+ @QueryParam("status_code") @DefaultValue("200") int statusCode) { -+ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -+ } - -- @GET -- @ResponseMetered(level = COARSE) -- @Path("/response-metered-coarse") -- public Response responseMeteredCoarse(@QueryParam("status_code") @DefaultValue("200") int statusCode) { -- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -- } -+ @GET -+ @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) -+ public Response responseMeteredCoarse( -+ @QueryParam("status_code") @DefaultValue("200") int statusCode) { -+ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -+ } - -- @GET -- @ResponseMetered(level = ALL) -- @Path("/response-metered-all") -- public Response responseMeteredAll(@QueryParam("status_code") @DefaultValue("200") int statusCode) { -- return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -- } -+ @GET -+ @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) -+ public Response responseMeteredAll( -+ @QueryParam("status_code") @DefaultValue("200") int statusCode) { -+ return Response.status(Response.Status.fromStatusCode(statusCode)).build(); -+ } - -- @GET -- @ResponseMetered -- @Path("/response-2xx-metered") -- public Response response2xxMetered() { -- return Response.ok().build(); -- } -+ @GET -+ @Path("/response-2xx-metered") -+ @ResponseMetered -+ public Response response2xxMetered() { -+ return Response.ok().build(); -+ } - -- @GET -- @ResponseMetered -- @Path("/response-4xx-metered") -- public Response response4xxMetered() { -- return Response.status(Response.Status.BAD_REQUEST).build(); -- } -+ @GET -+ @Path("/response-4xx-metered") -+ @ResponseMetered -+ public Response response4xxMetered() { -+ return Response.status(Response.Status.BAD_REQUEST).build(); -+ } - -- @GET -- @ResponseMetered -- @Path("/response-5xx-metered") -- public Response response5xxMetered() { -- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -- } -+ @GET -+ @Path("/response-5xx-metered") -+ @ResponseMetered -+ public Response response5xxMetered() { -+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -+ } - -- @Path("/subresource") -- public InstrumentedSubResource locateSubResource() { -- return new InstrumentedSubResource(); -- } -+ @Path("/subresource") -+ public InstrumentedSubResource locateSubResource() { -+ return new InstrumentedSubResource(); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceExceptionMeteredPerClass.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceExceptionMeteredPerClass.java -@@ -7,7 +7,6 @@ import jakarta.ws.rs.Path; - import jakarta.ws.rs.Produces; - import jakarta.ws.rs.QueryParam; - import jakarta.ws.rs.core.MediaType; -- - import java.io.IOException; - - @ExceptionMetered(cause = IOException.class) -@@ -15,18 +14,18 @@ import java.io.IOException; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceExceptionMeteredPerClass { - -- @GET -- @Path("/exception-metered") -- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { -- if (splode) { -- throw new IOException("AUGH"); -- } -- return "fuh"; -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { -- return new InstrumentedSubResourceExceptionMeteredPerClass(); -+ @GET -+ @Path("/exception-metered") -+ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) -+ throws IOException { -+ if (splode) { -+ throw new IOException("AUGH"); - } -+ return "fuh"; -+ } - -+ @Path("/subresource") -+ public InstrumentedSubResourceExceptionMeteredPerClass locateSubResource() { -+ return new InstrumentedSubResourceExceptionMeteredPerClass(); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceMeteredPerClass.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceMeteredPerClass.java -@@ -11,15 +11,14 @@ import jakarta.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceMeteredPerClass { - -- @GET -- @Path("/meteredPerClass") -- public String meteredPerClass() { -- return "yay"; -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceMeteredPerClass locateSubResource() { -- return new InstrumentedSubResourceMeteredPerClass(); -- } -+ @GET -+ @Path("/meteredPerClass") -+ public String meteredPerClass() { -+ return "yay"; -+ } - -+ @Path("/subresource") -+ public InstrumentedSubResourceMeteredPerClass locateSubResource() { -+ return new InstrumentedSubResourceMeteredPerClass(); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceResponseMeteredPerClass.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceResponseMeteredPerClass.java -@@ -14,45 +14,44 @@ import jakarta.ws.rs.core.Response; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceResponseMeteredPerClass { - -- @GET -- @Path("/responseMetered2xxPerClass") -- public Response responseMetered2xxPerClass() { -- return Response.ok().build(); -- } -- -- @GET -- @Path("/responseMetered4xxPerClass") -- public Response responseMetered4xxPerClass() { -- return Response.status(Response.Status.BAD_REQUEST).build(); -- } -- -- @GET -- @Path("/responseMetered5xxPerClass") -- public Response responseMetered5xxPerClass() { -- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -- } -- -- @GET -- @Path("/responseMeteredBadRequestPerClass") -- public String responseMeteredBadRequestPerClass() { -- throw new BadRequestException(); -- } -- -- @GET -- @Path("/responseMeteredRuntimeExceptionPerClass") -- public String responseMeteredRuntimeExceptionPerClass() { -- throw new RuntimeException(); -- } -- -- @GET -- @Path("/responseMeteredTestExceptionPerClass") -- public String responseMeteredTestExceptionPerClass() { -- throw new TestException("test"); -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { -- return new InstrumentedSubResourceResponseMeteredPerClass(); -- } -- -+ @GET -+ @Path("/responseMetered2xxPerClass") -+ public Response responseMetered2xxPerClass() { -+ return Response.ok().build(); -+ } -+ -+ @GET -+ @Path("/responseMetered4xxPerClass") -+ public Response responseMetered4xxPerClass() { -+ return Response.status(Response.Status.BAD_REQUEST).build(); -+ } -+ -+ @GET -+ @Path("/responseMetered5xxPerClass") -+ public Response responseMetered5xxPerClass() { -+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -+ } -+ -+ @GET -+ @Path("/responseMeteredBadRequestPerClass") -+ public String responseMeteredBadRequestPerClass() { -+ throw new BadRequestException(); -+ } -+ -+ @GET -+ @Path("/responseMeteredRuntimeExceptionPerClass") -+ public String responseMeteredRuntimeExceptionPerClass() { -+ throw new RuntimeException(); -+ } -+ -+ @GET -+ @Path("/responseMeteredTestExceptionPerClass") -+ public String responseMeteredTestExceptionPerClass() { -+ throw new TestException("test"); -+ } -+ -+ @Path("/subresource") -+ public InstrumentedSubResourceResponseMeteredPerClass locateSubResource() { -+ return new InstrumentedSubResourceResponseMeteredPerClass(); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceTimedPerClass.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResourceTimedPerClass.java -@@ -11,15 +11,14 @@ import jakarta.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResourceTimedPerClass { - -- @GET -- @Path("/timedPerClass") -- public String timedPerClass() { -- return "yay"; -- } -- -- @Path("/subresource") -- public InstrumentedSubResourceTimedPerClass locateSubResource() { -- return new InstrumentedSubResourceTimedPerClass(); -- } -+ @GET -+ @Path("/timedPerClass") -+ public String timedPerClass() { -+ return "yay"; -+ } - -+ @Path("/subresource") -+ public InstrumentedSubResourceTimedPerClass locateSubResource() { -+ return new InstrumentedSubResourceTimedPerClass(); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java -@@ -9,11 +9,10 @@ import jakarta.ws.rs.core.MediaType; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResource { - -- @GET -- @Timed -- @Path("/timed") -- public String timed() { -- return "yay"; -- } -- -+ @GET -+ @Path("/timed") -+ @Timed -+ public String timed() { -+ return "yay"; -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceExceptionMeteredPerClass.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceExceptionMeteredPerClass.java -@@ -7,18 +7,18 @@ import jakarta.ws.rs.Path; - import jakarta.ws.rs.Produces; - import jakarta.ws.rs.QueryParam; - import jakarta.ws.rs.core.MediaType; -- - import java.io.IOException; - - @ExceptionMetered(cause = IOException.class) - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceExceptionMeteredPerClass { -- @GET -- @Path("/exception-metered") -- public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) throws IOException { -- if (splode) { -- throw new IOException("AUGH"); -- } -- return "fuh"; -+ @GET -+ @Path("/exception-metered") -+ public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) -+ throws IOException { -+ if (splode) { -+ throw new IOException("AUGH"); - } -+ return "fuh"; -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceMeteredPerClass.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceMeteredPerClass.java -@@ -9,9 +9,9 @@ import jakarta.ws.rs.core.MediaType; - @Metered - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceMeteredPerClass { -- @GET -- @Path("/meteredPerClass") -- public String meteredPerClass() { -- return "yay"; -- } -+ @GET -+ @Path("/meteredPerClass") -+ public String meteredPerClass() { -+ return "yay"; -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceResponseMeteredPerClass.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceResponseMeteredPerClass.java -@@ -11,9 +11,9 @@ import jakarta.ws.rs.core.Response; - @ResponseMetered(level = ResponseMeteredLevel.ALL) - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceResponseMeteredPerClass { -- @GET -- @Path("/responseMeteredPerClass") -- public Response responseMeteredPerClass() { -- return Response.status(Response.Status.OK).build(); -- } -+ @GET -+ @Path("/responseMeteredPerClass") -+ public Response responseMeteredPerClass() { -+ return Response.status(Response.Status.OK).build(); -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceTimedPerClass.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResourceTimedPerClass.java -@@ -9,9 +9,9 @@ import jakarta.ws.rs.core.MediaType; - @Timed - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedSubResourceTimedPerClass { -- @GET -- @Path("/timedPerClass") -- public String timedPerClass() { -- return "yay"; -- } -+ @GET -+ @Path("/timedPerClass") -+ public String timedPerClass() { -+ return "yay"; -+ } - } ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/TestRequestFilter.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/TestRequestFilter.java -@@ -3,19 +3,18 @@ package io.dropwizard.metrics5.jersey31.resources; - import io.dropwizard.metrics5.jersey31.TestClock; - import jakarta.ws.rs.container.ContainerRequestContext; - import jakarta.ws.rs.container.ContainerRequestFilter; -- - import java.io.IOException; - - public class TestRequestFilter implements ContainerRequestFilter { - -- private final TestClock testClock; -+ private final TestClock testClock; - -- public TestRequestFilter(TestClock testClock) { -- this.testClock = testClock; -- } -+ public TestRequestFilter(TestClock testClock) { -+ this.testClock = testClock; -+ } - -- @Override -- public void filter(ContainerRequestContext containerRequestContext) throws IOException { -- testClock.tick += 4; -- } -+ @Override -+ public void filter(ContainerRequestContext containerRequestContext) throws IOException { -+ testClock.tick += 4; -+ } - } ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java -@@ -2,62 +2,63 @@ package io.dropwizard.metrics5.jetty10; - - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Timer; -+import java.util.List; - import org.eclipse.jetty.io.Connection; - import org.eclipse.jetty.io.EndPoint; - import org.eclipse.jetty.server.ConnectionFactory; - import org.eclipse.jetty.server.Connector; - import org.eclipse.jetty.util.component.ContainerLifeCycle; - --import java.util.List; -- - public class InstrumentedConnectionFactory extends ContainerLifeCycle implements ConnectionFactory { -- private final ConnectionFactory connectionFactory; -- private final Timer timer; -- private final Counter counter; -- -- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { -- this(connectionFactory, timer, null); -- } -- -- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer, Counter counter) { -- this.connectionFactory = connectionFactory; -- this.timer = timer; -- this.counter = counter; -- addBean(connectionFactory); -- } -- -- @Override -- public String getProtocol() { -- return connectionFactory.getProtocol(); -- } -- -- @Override -- public List getProtocols() { -- return connectionFactory.getProtocols(); -- } -- -- @Override -- public Connection newConnection(Connector connector, EndPoint endPoint) { -- final Connection connection = connectionFactory.newConnection(connector, endPoint); -- connection.addEventListener(new Connection.Listener() { -- private Timer.Context context; -- -- @Override -- public void onOpened(Connection connection) { -- this.context = timer.time(); -- if (counter != null) { -- counter.inc(); -- } -+ private final ConnectionFactory connectionFactory; -+ private final Timer timer; -+ private final Counter counter; -+ -+ public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { -+ this(connectionFactory, timer, null); -+ } -+ -+ public InstrumentedConnectionFactory( -+ ConnectionFactory connectionFactory, Timer timer, Counter counter) { -+ this.connectionFactory = connectionFactory; -+ this.timer = timer; -+ this.counter = counter; -+ addBean(connectionFactory); -+ } -+ -+ @Override -+ public String getProtocol() { -+ return connectionFactory.getProtocol(); -+ } -+ -+ @Override -+ public List getProtocols() { -+ return connectionFactory.getProtocols(); -+ } -+ -+ @Override -+ public Connection newConnection(Connector connector, EndPoint endPoint) { -+ final Connection connection = connectionFactory.newConnection(connector, endPoint); -+ connection.addEventListener( -+ new Connection.Listener() { -+ private Timer.Context context; -+ -+ @Override -+ public void onOpened(Connection connection) { -+ this.context = timer.time(); -+ if (counter != null) { -+ counter.inc(); - } -+ } - -- @Override -- public void onClosed(Connection connection) { -- context.stop(); -- if (counter != null) { -- counter.dec(); -- } -+ @Override -+ public void onClosed(Connection connection) { -+ context.stop(); -+ if (counter != null) { -+ counter.dec(); - } -+ } - }); -- return connection; -- } -+ return connection; -+ } - } ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java -@@ -1,5 +1,13 @@ - package io.dropwizard.metrics5.jetty10; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; -+ -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -7,439 +15,450 @@ import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.RatioGauge; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; --import org.eclipse.jetty.http.HttpMethod; --import org.eclipse.jetty.server.AsyncContextState; --import org.eclipse.jetty.server.Handler; --import org.eclipse.jetty.server.HttpChannelState; --import org.eclipse.jetty.server.Request; --import org.eclipse.jetty.server.handler.HandlerWrapper; -- --import javax.servlet.AsyncEvent; --import javax.servlet.AsyncListener; --import javax.servlet.ServletException; --import javax.servlet.http.HttpServletRequest; --import javax.servlet.http.HttpServletResponse; - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; - import java.util.Set; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import javax.servlet.AsyncEvent; -+import javax.servlet.AsyncListener; -+import javax.servlet.ServletException; -+import javax.servlet.http.HttpServletRequest; -+import javax.servlet.http.HttpServletResponse; -+import org.eclipse.jetty.http.HttpMethod; -+import org.eclipse.jetty.server.AsyncContextState; -+import org.eclipse.jetty.server.Handler; -+import org.eclipse.jetty.server.HttpChannelState; -+import org.eclipse.jetty.server.Request; -+import org.eclipse.jetty.server.handler.HandlerWrapper; - - /** - * A Jetty {@link Handler} which records various metrics about an underlying {@link Handler} - * instance. - */ - public class InstrumentedHandler extends HandlerWrapper { -- private static final String NAME_REQUESTS = "requests"; -- private static final String NAME_DISPATCHES = "dispatches"; -- private static final String NAME_ACTIVE_REQUESTS = "active-requests"; -- private static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; -- private static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; -- private static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; -- private static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; -- private static final String NAME_1XX_RESPONSES = "1xx-responses"; -- private static final String NAME_2XX_RESPONSES = "2xx-responses"; -- private static final String NAME_3XX_RESPONSES = "3xx-responses"; -- private static final String NAME_4XX_RESPONSES = "4xx-responses"; -- private static final String NAME_5XX_RESPONSES = "5xx-responses"; -- private static final String NAME_GET_REQUESTS = "get-requests"; -- private static final String NAME_POST_REQUESTS = "post-requests"; -- private static final String NAME_HEAD_REQUESTS = "head-requests"; -- private static final String NAME_PUT_REQUESTS = "put-requests"; -- private static final String NAME_DELETE_REQUESTS = "delete-requests"; -- private static final String NAME_OPTIONS_REQUESTS = "options-requests"; -- private static final String NAME_TRACE_REQUESTS = "trace-requests"; -- private static final String NAME_CONNECT_REQUESTS = "connect-requests"; -- private static final String NAME_MOVE_REQUESTS = "move-requests"; -- private static final String NAME_OTHER_REQUESTS = "other-requests"; -- private static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; -- private static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; -- private static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; -- private static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; -- private static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; -- private static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; -- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -- -- private final MetricRegistry metricRegistry; -- -- private String name; -- private final String prefix; -- -- // the requests handled by this handler, excluding active -- private Timer requests; -- -- // the number of dispatches seen by this handler, excluding active -- private Timer dispatches; -- -- // the number of active requests -- private Counter activeRequests; -- -- // the number of active dispatches -- private Counter activeDispatches; -- -- // the number of requests currently suspended. -- private Counter activeSuspended; -- -- // the number of requests that have been asynchronously dispatched -- private Meter asyncDispatches; -- -- // the number of requests that expired while suspended -- private Meter asyncTimeouts; -- -- private final ResponseMeteredLevel responseMeteredLevel; -- private List responses; -- private Map responseCodeMeters; -- -- private Timer getRequests; -- private Timer postRequests; -- private Timer headRequests; -- private Timer putRequests; -- private Timer deleteRequests; -- private Timer optionsRequests; -- private Timer traceRequests; -- private Timer connectRequests; -- private Timer moveRequests; -- private Timer otherRequests; -- -- private AsyncListener listener; -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- */ -- public InstrumentedHandler(MetricRegistry registry) { -- this(registry, null); -+ private static final String NAME_REQUESTS = "requests"; -+ private static final String NAME_DISPATCHES = "dispatches"; -+ private static final String NAME_ACTIVE_REQUESTS = "active-requests"; -+ private static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; -+ private static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; -+ private static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; -+ private static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; -+ private static final String NAME_1XX_RESPONSES = "1xx-responses"; -+ private static final String NAME_2XX_RESPONSES = "2xx-responses"; -+ private static final String NAME_3XX_RESPONSES = "3xx-responses"; -+ private static final String NAME_4XX_RESPONSES = "4xx-responses"; -+ private static final String NAME_5XX_RESPONSES = "5xx-responses"; -+ private static final String NAME_GET_REQUESTS = "get-requests"; -+ private static final String NAME_POST_REQUESTS = "post-requests"; -+ private static final String NAME_HEAD_REQUESTS = "head-requests"; -+ private static final String NAME_PUT_REQUESTS = "put-requests"; -+ private static final String NAME_DELETE_REQUESTS = "delete-requests"; -+ private static final String NAME_OPTIONS_REQUESTS = "options-requests"; -+ private static final String NAME_TRACE_REQUESTS = "trace-requests"; -+ private static final String NAME_CONNECT_REQUESTS = "connect-requests"; -+ private static final String NAME_MOVE_REQUESTS = "move-requests"; -+ private static final String NAME_OTHER_REQUESTS = "other-requests"; -+ private static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; -+ private static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; -+ private static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; -+ private static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; -+ private static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; -+ private static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; -+ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -+ private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -+ -+ private final MetricRegistry metricRegistry; -+ -+ private String name; -+ private final String prefix; -+ -+ // the requests handled by this handler, excluding active -+ private Timer requests; -+ -+ // the number of dispatches seen by this handler, excluding active -+ private Timer dispatches; -+ -+ // the number of active requests -+ private Counter activeRequests; -+ -+ // the number of active dispatches -+ private Counter activeDispatches; -+ -+ // the number of requests currently suspended. -+ private Counter activeSuspended; -+ -+ // the number of requests that have been asynchronously dispatched -+ private Meter asyncDispatches; -+ -+ // the number of requests that expired while suspended -+ private Meter asyncTimeouts; -+ -+ private final ResponseMeteredLevel responseMeteredLevel; -+ private List responses; -+ private Map responseCodeMeters; -+ -+ private Timer getRequests; -+ private Timer postRequests; -+ private Timer headRequests; -+ private Timer putRequests; -+ private Timer deleteRequests; -+ private Timer optionsRequests; -+ private Timer traceRequests; -+ private Timer connectRequests; -+ private Timer moveRequests; -+ private Timer otherRequests; -+ -+ private AsyncListener listener; -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ */ -+ public InstrumentedHandler(MetricRegistry registry) { -+ this(registry, null); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param prefix the prefix to use for the metrics names -+ */ -+ public InstrumentedHandler(MetricRegistry registry, String prefix) { -+ this(registry, prefix, COARSE); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param prefix the prefix to use for the metrics names -+ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are -+ * instrumented -+ */ -+ public InstrumentedHandler( -+ MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { -+ this.metricRegistry = registry; -+ this.prefix = prefix; -+ this.responseMeteredLevel = responseMeteredLevel; -+ } -+ -+ public String getName() { -+ return name; -+ } -+ -+ public void setName(String name) { -+ this.name = name; -+ } -+ -+ @Override -+ protected void doStart() throws Exception { -+ super.doStart(); -+ -+ final MetricName prefix = getMetricPrefix(); -+ -+ this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); -+ this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); -+ -+ this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); -+ this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -+ this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -+ -+ this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); -+ this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -+ -+ this.responseCodeMeters = -+ DETAILED_METER_LEVELS.contains(responseMeteredLevel) -+ ? new ConcurrentHashMap<>() -+ : ImmutableMap.of(); -+ -+ this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); -+ this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); -+ this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); -+ this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); -+ this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); -+ this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); -+ this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); -+ this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); -+ this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); -+ this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); -+ -+ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -+ this.responses = -+ unmodifiableList( -+ Arrays.asList( -+ metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx -+ metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx -+ metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx -+ metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx -+ metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx -+ )); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_4XX_1M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_4XX_5M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_4XX_15M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of( -+ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_5XX_1M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_5XX_5M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_5XX_15M), -+ new RatioGauge() { -+ @Override -+ public Ratio getRatio() { -+ return Ratio.of( -+ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } -+ }); -+ } else { -+ this.responses = ImmutableList.of(); - } - -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param prefix the prefix to use for the metrics names -- */ -- public InstrumentedHandler(MetricRegistry registry, String prefix) { -- this(registry, prefix, COARSE); -+ this.listener = new AsyncAttachingListener(); -+ } -+ -+ @Override -+ protected void doStop() throws Exception { -+ final MetricName prefix = getMetricPrefix(); -+ -+ metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); -+ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -+ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -+ metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); -+ metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -+ metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); -+ -+ if (responseCodeMeters != null) { -+ responseCodeMeters.keySet().stream() -+ .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) -+ .forEach(metricRegistry::remove); - } - -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param prefix the prefix to use for the metrics names -- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented -- */ -- public InstrumentedHandler(MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { -- this.metricRegistry = registry; -- this.prefix = prefix; -- this.responseMeteredLevel = responseMeteredLevel; -+ super.doStop(); -+ } -+ -+ @Override -+ public void handle( -+ String path, -+ Request request, -+ HttpServletRequest httpRequest, -+ HttpServletResponse httpResponse) -+ throws IOException, ServletException { -+ -+ activeDispatches.inc(); -+ -+ final long start; -+ final HttpChannelState state = request.getHttpChannelState(); -+ if (state.isInitial()) { -+ // new request -+ activeRequests.inc(); -+ start = request.getTimeStamp(); -+ state.addListener(listener); -+ } else { -+ // resumed request -+ start = System.currentTimeMillis(); -+ activeSuspended.dec(); -+ if (state.getState() == HttpChannelState.State.HANDLING) { -+ asyncDispatches.mark(); -+ } - } - -- public String getName() { -- return name; -+ try { -+ super.handle(path, request, httpRequest, httpResponse); -+ } finally { -+ final long now = System.currentTimeMillis(); -+ final long dispatched = now - start; -+ -+ activeDispatches.dec(); -+ dispatches.update(dispatched, TimeUnit.MILLISECONDS); -+ -+ if (state.isSuspended()) { -+ activeSuspended.inc(); -+ } else if (state.isInitial()) { -+ updateResponses(httpRequest, httpResponse, start, request.isHandled()); -+ } -+ // else onCompletion will handle it. - } -- -- public void setName(String name) { -- this.name = name; -+ } -+ -+ private Timer requestTimer(String method) { -+ final HttpMethod m = HttpMethod.fromString(method); -+ if (m == null) { -+ return otherRequests; -+ } else { -+ switch (m) { -+ case GET: -+ return getRequests; -+ case POST: -+ return postRequests; -+ case PUT: -+ return putRequests; -+ case HEAD: -+ return headRequests; -+ case DELETE: -+ return deleteRequests; -+ case OPTIONS: -+ return optionsRequests; -+ case TRACE: -+ return traceRequests; -+ case CONNECT: -+ return connectRequests; -+ case MOVE: -+ return moveRequests; -+ default: -+ return otherRequests; -+ } - } -- -- @Override -- protected void doStart() throws Exception { -- super.doStart(); -- -- final MetricName prefix = getMetricPrefix(); -- -- this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); -- this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); -- -- this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); -- this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -- this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -- -- this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); -- this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -- -- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); -- -- this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); -- this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); -- this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); -- this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); -- this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); -- this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); -- this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); -- this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); -- this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); -- this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); -- -- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -- this.responses = Collections.unmodifiableList(Arrays.asList( -- metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx -- metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx -- metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx -- metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx -- metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx -- )); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_1M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_5M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_15M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_1M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_5M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_15M), new RatioGauge() { -- @Override -- public Ratio getRatio() { -- return Ratio.of(responses.get(4).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -- }); -- } else { -- this.responses = Collections.emptyList(); -- } -- -- this.listener = new AsyncAttachingListener(); -+ } -+ -+ private void updateResponses( -+ HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { -+ if (isHandled) { -+ mark(response.getStatus()); -+ } else { -+ mark(404); -+ ; // will end up with a 404 response sent by HttpChannel.handle -+ } -+ activeRequests.dec(); -+ final long elapsedTime = System.currentTimeMillis() - start; -+ requests.update(elapsedTime, TimeUnit.MILLISECONDS); -+ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -+ } -+ -+ private void mark(int statusCode) { -+ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -+ getResponseCodeMeter(statusCode).mark(); - } - -- @Override -- protected void doStop() throws Exception { -- final MetricName prefix = getMetricPrefix(); -- -- metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); -- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -- metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); -- metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -- metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); -- -- if (responseCodeMeters != null) { -- responseCodeMeters.keySet().stream() -- .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) -- .forEach(metricRegistry::remove); -- } -- -- super.doStop(); -+ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -+ final int responseStatus = statusCode / 100; -+ if (responseStatus >= 1 && responseStatus <= 5) { -+ responses.get(responseStatus - 1).mark(); -+ } - } -+ } - -- @Override -- public void handle(String path, -- Request request, -- HttpServletRequest httpRequest, -- HttpServletResponse httpResponse) throws IOException, ServletException { -- -- activeDispatches.inc(); -- -- final long start; -- final HttpChannelState state = request.getHttpChannelState(); -- if (state.isInitial()) { -- // new request -- activeRequests.inc(); -- start = request.getTimeStamp(); -- state.addListener(listener); -- } else { -- // resumed request -- start = System.currentTimeMillis(); -- activeSuspended.dec(); -- if (state.getState() == HttpChannelState.State.HANDLING) { -- asyncDispatches.mark(); -- } -- } -+ private Meter getResponseCodeMeter(int statusCode) { -+ return responseCodeMeters.computeIfAbsent( -+ statusCode, -+ sc -> metricRegistry.meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); -+ } - -- try { -- super.handle(path, request, httpRequest, httpResponse); -- } finally { -- final long now = System.currentTimeMillis(); -- final long dispatched = now - start; -+ private MetricName getMetricPrefix() { -+ return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); -+ } - -- activeDispatches.dec(); -- dispatches.update(dispatched, TimeUnit.MILLISECONDS); -+ private class AsyncAttachingListener implements AsyncListener { - -- if (state.isSuspended()) { -- activeSuspended.inc(); -- } else if (state.isInitial()) { -- updateResponses(httpRequest, httpResponse, start, request.isHandled()); -- } -- // else onCompletion will handle it. -- } -- } -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException {} - -- private Timer requestTimer(String method) { -- final HttpMethod m = HttpMethod.fromString(method); -- if (m == null) { -- return otherRequests; -- } else { -- switch (m) { -- case GET: -- return getRequests; -- case POST: -- return postRequests; -- case PUT: -- return putRequests; -- case HEAD: -- return headRequests; -- case DELETE: -- return deleteRequests; -- case OPTIONS: -- return optionsRequests; -- case TRACE: -- return traceRequests; -- case CONNECT: -- return connectRequests; -- case MOVE: -- return moveRequests; -- default: -- return otherRequests; -- } -- } -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException { -+ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); - } - -- private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { -- if (isHandled) { -- mark(response.getStatus()); -- } else { -- mark(404);; // will end up with a 404 response sent by HttpChannel.handle -- } -- activeRequests.dec(); -- final long elapsedTime = System.currentTimeMillis() - start; -- requests.update(elapsedTime, TimeUnit.MILLISECONDS); -- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -- } -+ @Override -+ public void onError(AsyncEvent event) throws IOException {} - -- private void mark(int statusCode) { -- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -- getResponseCodeMeter(statusCode).mark(); -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException {} -+ } -+ ; - -- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -- final int responseStatus = statusCode / 100; -- if (responseStatus >= 1 && responseStatus <= 5) { -- responses.get(responseStatus - 1).mark(); -- } -- } -- } -+ private class InstrumentedAsyncListener implements AsyncListener { -+ private final long startTime; - -- private Meter getResponseCodeMeter(int statusCode) { -- return responseCodeMeters -- .computeIfAbsent(statusCode, sc -> metricRegistry -- .meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); -+ InstrumentedAsyncListener() { -+ this.startTime = System.currentTimeMillis(); - } - -- private MetricName getMetricPrefix() { -- return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException { -+ asyncTimeouts.mark(); - } - -- private class AsyncAttachingListener implements AsyncListener { -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException {} -- -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); -- } -- -- @Override -- public void onError(AsyncEvent event) throws IOException {} -- -- @Override -- public void onComplete(AsyncEvent event) throws IOException {} -- }; -- -- private class InstrumentedAsyncListener implements AsyncListener { -- private final long startTime; -- -- InstrumentedAsyncListener() { -- this.startTime = System.currentTimeMillis(); -- } -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException { -- asyncTimeouts.mark(); -- } -- -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- } -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException {} - -- @Override -- public void onError(AsyncEvent event) throws IOException { -- } -+ @Override -+ public void onError(AsyncEvent event) throws IOException {} - -- @Override -- public void onComplete(AsyncEvent event) throws IOException { -- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -- final HttpServletRequest request = (HttpServletRequest) state.getRequest(); -- final HttpServletResponse response = (HttpServletResponse) state.getResponse(); -- updateResponses(request, response, startTime, true); -- if (!state.getHttpChannelState().isSuspended()) { -- activeSuspended.dec(); -- } -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException { -+ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -+ final HttpServletRequest request = (HttpServletRequest) state.getRequest(); -+ final HttpServletResponse response = (HttpServletResponse) state.getResponse(); -+ updateResponses(request, response, startTime, true); -+ if (!state.getHttpChannelState().isSuspended()) { -+ activeSuspended.dec(); -+ } - } -+ } - } ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java -@@ -1,5 +1,12 @@ - package io.dropwizard.metrics5.jetty10; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; -+ -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -7,418 +14,402 @@ import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.RatioGauge; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; --import org.eclipse.jetty.http.HttpMethod; --import org.eclipse.jetty.server.AsyncContextState; --import org.eclipse.jetty.server.HttpChannel.Listener; --import org.eclipse.jetty.server.HttpChannelState; --import org.eclipse.jetty.server.Request; -- --import javax.servlet.AsyncEvent; --import javax.servlet.AsyncListener; --import javax.servlet.http.HttpServletRequest; --import javax.servlet.http.HttpServletResponse; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; - import java.util.Set; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import javax.servlet.AsyncEvent; -+import javax.servlet.AsyncListener; -+import javax.servlet.http.HttpServletRequest; -+import javax.servlet.http.HttpServletResponse; -+import org.eclipse.jetty.http.HttpMethod; -+import org.eclipse.jetty.server.AsyncContextState; -+import org.eclipse.jetty.server.HttpChannel.Listener; -+import org.eclipse.jetty.server.HttpChannelState; -+import org.eclipse.jetty.server.Request; - - /** -- * A Jetty {@link org.eclipse.jetty.server.HttpChannel.Listener} implementation which records various metrics about -- * underlying channel instance. Unlike {@link InstrumentedHandler} that uses internal API, this class should be -- * future proof. To install it, just add instance of this class to {@link org.eclipse.jetty.server.Connector} as bean. -+ * A Jetty {@link org.eclipse.jetty.server.HttpChannel.Listener} implementation which records -+ * various metrics about underlying channel instance. Unlike {@link InstrumentedHandler} that uses -+ * internal API, this class should be future proof. To install it, just add instance of this class -+ * to {@link org.eclipse.jetty.server.Connector} as bean. - * - * @since TBD - */ --public class InstrumentedHttpChannelListener -- implements Listener { -- private static final String START_ATTR = InstrumentedHttpChannelListener.class.getName() + ".start"; -- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -- -- private final MetricRegistry metricRegistry; -- -- // the requests handled by this handler, excluding active -- private final Timer requests; -- -- // the number of dispatches seen by this handler, excluding active -- private final Timer dispatches; -- -- // the number of active requests -- private final Counter activeRequests; -- -- // the number of active dispatches -- private final Counter activeDispatches; -- -- // the number of requests currently suspended. -- private final Counter activeSuspended; -- -- // the number of requests that have been asynchronously dispatched -- private final Meter asyncDispatches; -- -- // the number of requests that expired while suspended -- private final Meter asyncTimeouts; -- -- private final ResponseMeteredLevel responseMeteredLevel; -- private final List responses; -- private final Map responseCodeMeters; -- private final MetricName prefix; -- private final Timer getRequests; -- private final Timer postRequests; -- private final Timer headRequests; -- private final Timer putRequests; -- private final Timer deleteRequests; -- private final Timer optionsRequests; -- private final Timer traceRequests; -- private final Timer connectRequests; -- private final Timer moveRequests; -- private final Timer otherRequests; -- -- private final AsyncListener listener; -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- */ -- public InstrumentedHttpChannelListener(MetricRegistry registry) { -- this(registry, null, COARSE); -- } -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param pref the prefix to use for the metrics names -- */ -- public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref) { -- this(registry, pref, COARSE); -- } -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param pref the prefix to use for the metrics names -- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented -- */ -- public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref, ResponseMeteredLevel responseMeteredLevel) { -- this.metricRegistry = registry; -- -- this.prefix = (pref == null) ? MetricName.build(getClass().getName()) : pref; -- -- this.requests = metricRegistry.timer(prefix.resolve("requests")); -- this.dispatches = metricRegistry.timer(prefix.resolve("dispatches")); -- -- this.activeRequests = metricRegistry.counter(prefix.resolve("active-requests")); -- this.activeDispatches = metricRegistry.counter(prefix.resolve("active-dispatches")); -- this.activeSuspended = metricRegistry.counter(prefix.resolve("active-suspended")); -- -- this.asyncDispatches = metricRegistry.meter(prefix.resolve("async-dispatches")); -- this.asyncTimeouts = metricRegistry.meter(prefix.resolve("async-timeouts")); -- -- this.responseMeteredLevel = responseMeteredLevel; -- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); -- this.responses = COARSE_METER_LEVELS.contains(responseMeteredLevel) ? -- Collections.unmodifiableList(Arrays.asList( -- registry.meter(prefix.resolve("1xx-responses")), // 1xx -- registry.meter(prefix.resolve("2xx-responses")), // 2xx -- registry.meter(prefix.resolve("3xx-responses")), // 3xx -- registry.meter(prefix.resolve("4xx-responses")), // 4xx -- registry.meter(prefix.resolve("5xx-responses")) // 5xx -- )) : Collections.emptyList(); -- -- this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); -- this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); -- this.headRequests = metricRegistry.timer(prefix.resolve("head-requests")); -- this.putRequests = metricRegistry.timer(prefix.resolve("put-requests")); -- this.deleteRequests = metricRegistry.timer(prefix.resolve("delete-requests")); -- this.optionsRequests = metricRegistry.timer(prefix.resolve("options-requests")); -- this.traceRequests = metricRegistry.timer(prefix.resolve("trace-requests")); -- this.connectRequests = metricRegistry.timer(prefix.resolve("connect-requests")); -- this.moveRequests = metricRegistry.timer(prefix.resolve("move-requests")); -- this.otherRequests = metricRegistry.timer(prefix.resolve("other-requests")); -- -- metricRegistry.register(prefix.resolve("percent-4xx-1m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -+public class InstrumentedHttpChannelListener implements Listener { -+ private static final String START_ATTR = -+ InstrumentedHttpChannelListener.class.getName() + ".start"; -+ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -+ private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -+ -+ private final MetricRegistry metricRegistry; -+ -+ // the requests handled by this handler, excluding active -+ private final Timer requests; -+ -+ // the number of dispatches seen by this handler, excluding active -+ private final Timer dispatches; -+ -+ // the number of active requests -+ private final Counter activeRequests; -+ -+ // the number of active dispatches -+ private final Counter activeDispatches; -+ -+ // the number of requests currently suspended. -+ private final Counter activeSuspended; -+ -+ // the number of requests that have been asynchronously dispatched -+ private final Meter asyncDispatches; -+ -+ // the number of requests that expired while suspended -+ private final Meter asyncTimeouts; -+ -+ private final ResponseMeteredLevel responseMeteredLevel; -+ private final List responses; -+ private final Map responseCodeMeters; -+ private final MetricName prefix; -+ private final Timer getRequests; -+ private final Timer postRequests; -+ private final Timer headRequests; -+ private final Timer putRequests; -+ private final Timer deleteRequests; -+ private final Timer optionsRequests; -+ private final Timer traceRequests; -+ private final Timer connectRequests; -+ private final Timer moveRequests; -+ private final Timer otherRequests; -+ -+ private final AsyncListener listener; -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ */ -+ public InstrumentedHttpChannelListener(MetricRegistry registry) { -+ this(registry, null, COARSE); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param pref the prefix to use for the metrics names -+ */ -+ public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref) { -+ this(registry, pref, COARSE); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param pref the prefix to use for the metrics names -+ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are -+ * instrumented -+ */ -+ public InstrumentedHttpChannelListener( -+ MetricRegistry registry, MetricName pref, ResponseMeteredLevel responseMeteredLevel) { -+ this.metricRegistry = registry; -+ -+ this.prefix = (pref == null) ? MetricName.build(getClass().getName()) : pref; -+ -+ this.requests = metricRegistry.timer(prefix.resolve("requests")); -+ this.dispatches = metricRegistry.timer(prefix.resolve("dispatches")); -+ -+ this.activeRequests = metricRegistry.counter(prefix.resolve("active-requests")); -+ this.activeDispatches = metricRegistry.counter(prefix.resolve("active-dispatches")); -+ this.activeSuspended = metricRegistry.counter(prefix.resolve("active-suspended")); -+ -+ this.asyncDispatches = metricRegistry.meter(prefix.resolve("async-dispatches")); -+ this.asyncTimeouts = metricRegistry.meter(prefix.resolve("async-timeouts")); -+ -+ this.responseMeteredLevel = responseMeteredLevel; -+ this.responseCodeMeters = -+ DETAILED_METER_LEVELS.contains(responseMeteredLevel) -+ ? new ConcurrentHashMap<>() -+ : ImmutableMap.of(); -+ this.responses = -+ COARSE_METER_LEVELS.contains(responseMeteredLevel) -+ ? unmodifiableList( -+ Arrays.asList( -+ registry.meter(prefix.resolve("1xx-responses")), // 1xx -+ registry.meter(prefix.resolve("2xx-responses")), // 2xx -+ registry.meter(prefix.resolve("3xx-responses")), // 3xx -+ registry.meter(prefix.resolve("4xx-responses")), // 4xx -+ registry.meter(prefix.resolve("5xx-responses")) // 5xx -+ )) -+ : ImmutableList.of(); -+ -+ this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); -+ this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); -+ this.headRequests = metricRegistry.timer(prefix.resolve("head-requests")); -+ this.putRequests = metricRegistry.timer(prefix.resolve("put-requests")); -+ this.deleteRequests = metricRegistry.timer(prefix.resolve("delete-requests")); -+ this.optionsRequests = metricRegistry.timer(prefix.resolve("options-requests")); -+ this.traceRequests = metricRegistry.timer(prefix.resolve("trace-requests")); -+ this.connectRequests = metricRegistry.timer(prefix.resolve("connect-requests")); -+ this.moveRequests = metricRegistry.timer(prefix.resolve("move-requests")); -+ this.otherRequests = metricRegistry.timer(prefix.resolve("other-requests")); -+ -+ metricRegistry.register( -+ prefix.resolve("percent-4xx-1m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-4xx-5m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-4xx-5m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-4xx-15m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-4xx-15m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of( -+ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-5xx-1m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-5xx-1m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-5xx-5m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-5xx-5m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-5xx-15m"), new RatioGauge() { -- @Override -- public RatioGauge.Ratio getRatio() { -- return Ratio.of(responses.get(4).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-5xx-15m"), -+ new RatioGauge() { -+ @Override -+ public RatioGauge.Ratio getRatio() { -+ return Ratio.of( -+ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } - }); - -- this.listener = new AsyncAttachingListener(); -- } -+ this.listener = new AsyncAttachingListener(); -+ } - -- @Override -- public void onRequestBegin(final Request request) { -+ @Override -+ public void onRequestBegin(final Request request) {} - -- } -+ @Override -+ public void onBeforeDispatch(final Request request) { -+ before(request); -+ } - -- @Override -- public void onBeforeDispatch(final Request request) { -- before(request); -- } -+ @Override -+ public void onDispatchFailure(final Request request, final Throwable failure) {} - -- @Override -- public void onDispatchFailure(final Request request, final Throwable failure) { -+ @Override -+ public void onAfterDispatch(final Request request) { -+ after(request); -+ } - -- } -+ @Override -+ public void onRequestContent(final Request request, final ByteBuffer content) {} - -- @Override -- public void onAfterDispatch(final Request request) { -- after(request); -- } -+ @Override -+ public void onRequestContentEnd(final Request request) {} - -- @Override -- public void onRequestContent(final Request request, final ByteBuffer content) { -+ @Override -+ public void onRequestTrailers(final Request request) {} - -- } -+ @Override -+ public void onRequestEnd(final Request request) {} - -- @Override -- public void onRequestContentEnd(final Request request) { -+ @Override -+ public void onRequestFailure(final Request request, final Throwable failure) {} - -- } -+ @Override -+ public void onResponseBegin(final Request request) {} - -- @Override -- public void onRequestTrailers(final Request request) { -+ @Override -+ public void onResponseCommit(final Request request) {} - -- } -+ @Override -+ public void onResponseContent(final Request request, final ByteBuffer content) {} - -- @Override -- public void onRequestEnd(final Request request) { -+ @Override -+ public void onResponseEnd(final Request request) {} - -- } -+ @Override -+ public void onResponseFailure(final Request request, final Throwable failure) {} - -- @Override -- public void onRequestFailure(final Request request, final Throwable failure) { -+ @Override -+ public void onComplete(final Request request) {} - -- } -- -- @Override -- public void onResponseBegin(final Request request) { -+ private void before(final Request request) { -+ activeDispatches.inc(); - -+ final long start; -+ final HttpChannelState state = request.getHttpChannelState(); -+ if (state.isInitial()) { -+ // new request -+ activeRequests.inc(); -+ start = request.getTimeStamp(); -+ state.addListener(listener); -+ } else { -+ // resumed request -+ start = System.currentTimeMillis(); -+ activeSuspended.dec(); -+ if (state.isAsyncStarted()) { -+ asyncDispatches.mark(); -+ } - } -- -- @Override -- public void onResponseCommit(final Request request) { -- -+ request.setAttribute(START_ATTR, start); -+ } -+ -+ private void after(final Request request) { -+ final long start = (long) request.getAttribute(START_ATTR); -+ final long now = System.currentTimeMillis(); -+ final long dispatched = now - start; -+ -+ activeDispatches.dec(); -+ dispatches.update(dispatched, TimeUnit.MILLISECONDS); -+ -+ final HttpChannelState state = request.getHttpChannelState(); -+ if (state.isSuspended()) { -+ activeSuspended.inc(); -+ } else if (state.isInitial()) { -+ updateResponses(request, request.getResponse(), start, request.isHandled()); - } -- -- @Override -- public void onResponseContent(final Request request, final ByteBuffer content) { -- -+ // else onCompletion will handle it. -+ } -+ -+ private void updateResponses( -+ HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { -+ if (isHandled) { -+ mark(response.getStatus()); -+ } else { -+ mark(404); // will end up with a 404 response sent by HttpChannel.handle -+ } -+ activeRequests.dec(); -+ final long elapsedTime = System.currentTimeMillis() - start; -+ requests.update(elapsedTime, TimeUnit.MILLISECONDS); -+ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -+ } -+ -+ private void mark(int statusCode) { -+ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -+ getResponseCodeMeter(statusCode).mark(); - } - -- @Override -- public void onResponseEnd(final Request request) { -- -+ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -+ final int responseStatus = statusCode / 100; -+ if (responseStatus >= 1 && responseStatus <= 5) { -+ responses.get(responseStatus - 1).mark(); -+ } -+ } -+ } -+ -+ private Meter getResponseCodeMeter(int statusCode) { -+ return responseCodeMeters.computeIfAbsent( -+ statusCode, sc -> metricRegistry.meter(prefix.resolve(String.format("%d-responses", sc)))); -+ } -+ -+ private Timer requestTimer(String method) { -+ final HttpMethod m = HttpMethod.fromString(method); -+ if (m == null) { -+ return otherRequests; -+ } else { -+ switch (m) { -+ case GET: -+ return getRequests; -+ case POST: -+ return postRequests; -+ case PUT: -+ return putRequests; -+ case HEAD: -+ return headRequests; -+ case DELETE: -+ return deleteRequests; -+ case OPTIONS: -+ return optionsRequests; -+ case TRACE: -+ return traceRequests; -+ case CONNECT: -+ return connectRequests; -+ case MOVE: -+ return moveRequests; -+ default: -+ return otherRequests; -+ } - } -+ } -+ -+ private class AsyncAttachingListener implements AsyncListener { - - @Override -- public void onResponseFailure(final Request request, final Throwable failure) { -+ public void onTimeout(AsyncEvent event) throws IOException {} - -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException { -+ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); - } - - @Override -- public void onComplete(final Request request) { -- -- } -+ public void onError(AsyncEvent event) throws IOException {} - -- private void before(final Request request) { -- activeDispatches.inc(); -- -- final long start; -- final HttpChannelState state = request.getHttpChannelState(); -- if (state.isInitial()) { -- // new request -- activeRequests.inc(); -- start = request.getTimeStamp(); -- state.addListener(listener); -- } else { -- // resumed request -- start = System.currentTimeMillis(); -- activeSuspended.dec(); -- if (state.isAsyncStarted()) { -- asyncDispatches.mark(); -- } -- } -- request.setAttribute(START_ATTR, start); -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException {} -+ } -+ ; - -- private void after(final Request request) { -- final long start = (long) request.getAttribute(START_ATTR); -- final long now = System.currentTimeMillis(); -- final long dispatched = now - start; -- -- activeDispatches.dec(); -- dispatches.update(dispatched, TimeUnit.MILLISECONDS); -- -- final HttpChannelState state = request.getHttpChannelState(); -- if (state.isSuspended()) { -- activeSuspended.inc(); -- } else if (state.isInitial()) { -- updateResponses(request, request.getResponse(), start, request.isHandled()); -- } -- // else onCompletion will handle it. -- } -+ private class InstrumentedAsyncListener implements AsyncListener { -+ private final long startTime; - -- private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { -- if (isHandled) { -- mark(response.getStatus()); -- } else { -- mark(404); // will end up with a 404 response sent by HttpChannel.handle -- } -- activeRequests.dec(); -- final long elapsedTime = System.currentTimeMillis() - start; -- requests.update(elapsedTime, TimeUnit.MILLISECONDS); -- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -+ InstrumentedAsyncListener() { -+ this.startTime = System.currentTimeMillis(); - } - -- private void mark(int statusCode) { -- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -- getResponseCodeMeter(statusCode).mark(); -- } -- -- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -- final int responseStatus = statusCode / 100; -- if (responseStatus >= 1 && responseStatus <= 5) { -- responses.get(responseStatus - 1).mark(); -- } -- } -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException { -+ asyncTimeouts.mark(); - } - -- private Meter getResponseCodeMeter(int statusCode) { -- return responseCodeMeters -- .computeIfAbsent(statusCode, sc -> metricRegistry -- .meter(prefix.resolve(String.format("%d-responses", sc)))); -- } -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException {} - -- private Timer requestTimer(String method) { -- final HttpMethod m = HttpMethod.fromString(method); -- if (m == null) { -- return otherRequests; -- } else { -- switch (m) { -- case GET: -- return getRequests; -- case POST: -- return postRequests; -- case PUT: -- return putRequests; -- case HEAD: -- return headRequests; -- case DELETE: -- return deleteRequests; -- case OPTIONS: -- return optionsRequests; -- case TRACE: -- return traceRequests; -- case CONNECT: -- return connectRequests; -- case MOVE: -- return moveRequests; -- default: -- return otherRequests; -- } -- } -- } -+ @Override -+ public void onError(AsyncEvent event) throws IOException {} - -- private class AsyncAttachingListener implements AsyncListener { -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException {} -- -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); -- } -- -- @Override -- public void onError(AsyncEvent event) throws IOException {} -- -- @Override -- public void onComplete(AsyncEvent event) throws IOException {} -- }; -- -- private class InstrumentedAsyncListener implements AsyncListener { -- private final long startTime; -- -- InstrumentedAsyncListener() { -- this.startTime = System.currentTimeMillis(); -- } -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException { -- asyncTimeouts.mark(); -- } -- -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- } -- -- @Override -- public void onError(AsyncEvent event) throws IOException { -- } -- -- @Override -- public void onComplete(AsyncEvent event) throws IOException { -- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -- final HttpServletRequest request = (HttpServletRequest) state.getRequest(); -- final HttpServletResponse response = (HttpServletResponse) state.getResponse(); -- updateResponses(request, response, startTime, true); -- if (!state.getHttpChannelState().isSuspended()) { -- activeSuspended.dec(); -- } -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException { -+ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -+ final HttpServletRequest request = (HttpServletRequest) state.getRequest(); -+ final HttpServletResponse response = (HttpServletResponse) state.getResponse(); -+ updateResponses(request, response, startTime, true); -+ if (!state.getHttpChannelState().isSuspended()) { -+ activeSuspended.dec(); -+ } - } -+ } - } ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPool.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPool.java -@@ -1,120 +1,131 @@ - package io.dropwizard.metrics5.jetty10; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.RatioGauge; -+import java.util.concurrent.BlockingQueue; - import org.eclipse.jetty.util.annotation.Name; - import org.eclipse.jetty.util.thread.QueuedThreadPool; - --import java.util.concurrent.BlockingQueue; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -- - public class InstrumentedQueuedThreadPool extends QueuedThreadPool { -- private static final String NAME_UTILIZATION = "utilization"; -- private static final String NAME_UTILIZATION_MAX = "utilization-max"; -- private static final String NAME_SIZE = "size"; -- private static final String NAME_JOBS = "jobs"; -- private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; -- -- private final MetricRegistry metricRegistry; -- private String prefix; -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { -- this(registry, 200); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads) { -- this(registry, maxThreads, 8); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads) { -- this(registry, maxThreads, minThreads, 60000); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout) { -- this(registry, maxThreads, minThreads, idleTimeout, null); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("queue") BlockingQueue queue) { -- this(registry, maxThreads, minThreads, idleTimeout, queue, null); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("queue") BlockingQueue queue, -- @Name("prefix") String prefix) { -- super(maxThreads, minThreads, idleTimeout, queue); -- this.metricRegistry = registry; -- this.prefix = prefix; -- } -- -- public String getPrefix() { -- return prefix; -- } -- -- public void setPrefix(String prefix) { -- this.prefix = prefix; -- } -- -- @Override -- protected void doStart() throws Exception { -- super.doStart(); -- -- final MetricName prefix = getMetricPrefix(); -- -- metricRegistry.register(prefix.resolve("utilization"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(getThreads() - getIdleThreads(), getThreads()); -- } -+ private static final String NAME_UTILIZATION = "utilization"; -+ private static final String NAME_UTILIZATION_MAX = "utilization-max"; -+ private static final String NAME_SIZE = "size"; -+ private static final String NAME_JOBS = "jobs"; -+ private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; -+ -+ private final MetricRegistry metricRegistry; -+ private String prefix; -+ -+ public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { -+ this(registry, 200); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, @Name("maxThreads") int maxThreads) { -+ this(registry, maxThreads, 8); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads) { -+ this(registry, maxThreads, minThreads, 60000); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout) { -+ this(registry, maxThreads, minThreads, idleTimeout, null); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("queue") BlockingQueue queue) { -+ this(registry, maxThreads, minThreads, idleTimeout, queue, null); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("queue") BlockingQueue queue, -+ @Name("prefix") String prefix) { -+ super(maxThreads, minThreads, idleTimeout, queue); -+ this.metricRegistry = registry; -+ this.prefix = prefix; -+ } -+ -+ public String getPrefix() { -+ return prefix; -+ } -+ -+ public void setPrefix(String prefix) { -+ this.prefix = prefix; -+ } -+ -+ @Override -+ protected void doStart() throws Exception { -+ super.doStart(); -+ -+ final MetricName prefix = getMetricPrefix(); -+ -+ metricRegistry.register( -+ prefix.resolve("utilization"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(getThreads() - getIdleThreads(), getThreads()); -+ } - }); -- metricRegistry.register(prefix.resolve("utilization-max"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); -- } -+ metricRegistry.register( -+ prefix.resolve("utilization-max"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); -+ } - }); -- // This assumes the QueuedThreadPool is using a BlockingArrayQueue or -- // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. -- -- metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); -- metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); -- metricRegistry.register(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- BlockingQueue queue = getQueue(); -- return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); -- } -+ // This assumes the QueuedThreadPool is using a BlockingArrayQueue or -+ // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. -+ -+ metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); -+ metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); -+ metricRegistry.register( -+ prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ BlockingQueue queue = getQueue(); -+ return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); -+ } - }); -- } -- -- @Override -- protected void doStop() throws Exception { -- final MetricName prefix = getMetricPrefix(); -- -- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); -- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); -- metricRegistry.remove(prefix.resolve(NAME_SIZE)); -- metricRegistry.remove(prefix.resolve(NAME_JOBS)); -- metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); -- -- super.doStop(); -- } -- -- private MetricName getMetricPrefix() { -- return this.prefix == null ? name(QueuedThreadPool.class, getName()) : name(this.prefix, getName()); -- } -+ } -+ -+ @Override -+ protected void doStop() throws Exception { -+ final MetricName prefix = getMetricPrefix(); -+ -+ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); -+ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); -+ metricRegistry.remove(prefix.resolve(NAME_SIZE)); -+ metricRegistry.remove(prefix.resolve(NAME_JOBS)); -+ metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); -+ -+ super.doStop(); -+ } -+ -+ private MetricName getMetricPrefix() { -+ return this.prefix == null -+ ? name(QueuedThreadPool.class, getName()) -+ : name(this.prefix, getName()); -+ } - } ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java -@@ -1,8 +1,15 @@ - package io.dropwizard.metrics5.jetty10; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -+import java.io.IOException; -+import java.io.PrintWriter; -+import javax.servlet.ServletException; -+import javax.servlet.http.HttpServletRequest; -+import javax.servlet.http.HttpServletResponse; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; - import org.eclipse.jetty.server.HttpConnectionFactory; -@@ -14,80 +21,75 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import javax.servlet.ServletException; --import javax.servlet.http.HttpServletRequest; --import javax.servlet.http.HttpServletResponse; --import java.io.IOException; --import java.io.PrintWriter; -- --import static org.assertj.core.api.Assertions.assertThat; -- --class InstrumentedConnectionFactoryTest { -- private final MetricRegistry registry = new MetricRegistry(); -- private final Server server = new Server(); -- private final ServerConnector connector = -- new ServerConnector(server, new InstrumentedConnectionFactory(new HttpConnectionFactory(), -- registry.timer("http.connections"), -- registry.counter("http.active-connections"))); -- private final HttpClient client = new HttpClient(); -- -- @BeforeEach -- void setUp() throws Exception { -- server.setHandler(new AbstractHandler() { -- @Override -- public void handle(String target, -- Request baseRequest, -- HttpServletRequest request, -- HttpServletResponse response) throws IOException, ServletException { -- try (PrintWriter writer = response.getWriter()) { -- writer.println("OK"); -- } -+final class InstrumentedConnectionFactoryTest { -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final Server server = new Server(); -+ private final ServerConnector connector = -+ new ServerConnector( -+ server, -+ new InstrumentedConnectionFactory( -+ new HttpConnectionFactory(), -+ registry.timer("http.connections"), -+ registry.counter("http.active-connections"))); -+ private final HttpClient client = new HttpClient(); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ server.setHandler( -+ new AbstractHandler() { -+ @Override -+ public void handle( -+ String target, -+ Request baseRequest, -+ HttpServletRequest request, -+ HttpServletResponse response) -+ throws IOException, ServletException { -+ try (PrintWriter writer = response.getWriter()) { -+ writer.println("OK"); - } -+ } - }); - -- server.addConnector(connector); -- server.start(); -+ server.addConnector(connector); -+ server.start(); - -- client.start(); -- } -+ client.start(); -+ } - -- @AfterEach -- void tearDown() throws Exception { -- server.stop(); -- client.stop(); -- } -+ @AfterEach -+ void tearDown() throws Exception { -+ server.stop(); -+ client.stop(); -+ } - -- @Test -- void instrumentsConnectionTimes() throws Exception { -- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -- assertThat(response.getStatus()) -- .isEqualTo(200); -+ @Test -+ void instrumentsConnectionTimes() throws Exception { -+ final ContentResponse response = -+ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -+ assertThat(response.getStatus()).isEqualTo(200); - -- client.stop(); // close the connection -+ client.stop(); // close the connection - -- Thread.sleep(100); // make sure the connection is closed -+ Thread.sleep(100); // make sure the connection is closed - -- final Timer timer = registry.timer(MetricRegistry.name("http.connections")); -- assertThat(timer.getCount()) -- .isEqualTo(1); -- } -+ final Timer timer = registry.timer(MetricRegistry.name("http.connections")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - -- @Test -- void instrumentsActiveConnections() throws Exception { -- final Counter counter = registry.counter("http.active-connections"); -+ @Test -+ void instrumentsActiveConnections() throws Exception { -+ final Counter counter = registry.counter("http.active-connections"); - -- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -- assertThat(response.getStatus()) -- .isEqualTo(200); -+ final ContentResponse response = -+ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -+ assertThat(response.getStatus()).isEqualTo(200); - -- assertThat(counter.getCount()) -- .isEqualTo(1); -+ assertThat(counter.getCount()).isEqualTo(1); - -- client.stop(); // close the connection -+ client.stop(); // close the connection - -- Thread.sleep(100); // make sure the connection is closed -+ Thread.sleep(100); // make sure the connection is closed - -- assertThat(counter.getCount()) -- .isEqualTo(0); -- } -+ assertThat(counter.getCount()).isEqualTo(0); -+ } - } ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java -@@ -1,7 +1,22 @@ - package io.dropwizard.metrics5.jetty10; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.nio.charset.StandardCharsets.UTF_8; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; -+import java.io.IOException; -+import java.util.concurrent.TimeUnit; -+import javax.servlet.AsyncContext; -+import javax.servlet.ServletException; -+import javax.servlet.ServletOutputStream; -+import javax.servlet.WriteListener; -+import javax.servlet.http.HttpServletRequest; -+import javax.servlet.http.HttpServletResponse; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; - import org.eclipse.jetty.server.Request; -@@ -13,234 +28,221 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Disabled; - import org.junit.jupiter.api.Test; - --import javax.servlet.AsyncContext; --import javax.servlet.ServletException; --import javax.servlet.ServletOutputStream; --import javax.servlet.WriteListener; --import javax.servlet.http.HttpServletRequest; --import javax.servlet.http.HttpServletResponse; --import java.io.IOException; --import java.nio.charset.StandardCharsets; --import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; -- --class InstrumentedHandlerTest { -- private final HttpClient client = new HttpClient(); -- private final MetricRegistry registry = new MetricRegistry(); -- private final Server server = new Server(); -- private final ServerConnector connector = new ServerConnector(server); -- private final InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); -- -- @BeforeEach -- void setUp() throws Exception { -- handler.setName("handler"); -- handler.setHandler(new TestHandler()); -- server.addConnector(connector); -- server.setHandler(handler); -- server.start(); -- client.start(); -- } -- -- @AfterEach -- void tearDown() throws Exception { -- server.stop(); -- client.stop(); -- } -- -- @Test -- void hasAName() throws Exception { -- assertThat(handler.getName()) -- .isEqualTo("handler"); -- } -- -- @Test -- void createsAndRemovesMetricsForTheHandler() throws Exception { -- final ContentResponse response = client.GET(uri("/hello")); -- -- assertThat(response.getStatus()) -- .isEqualTo(404); -- -- assertThat(registry.getNames()) -- .containsOnly( -- MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.404-responses"), -- MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), -- MetricRegistry.name(TestHandler.class, "handler.requests"), -- MetricRegistry.name(TestHandler.class, "handler.active-suspended"), -- MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), -- MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), -- MetricRegistry.name(TestHandler.class, "handler.get-requests"), -- MetricRegistry.name(TestHandler.class, "handler.put-requests"), -- MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), -- MetricRegistry.name(TestHandler.class, "handler.trace-requests"), -- MetricRegistry.name(TestHandler.class, "handler.other-requests"), -- MetricRegistry.name(TestHandler.class, "handler.connect-requests"), -- MetricRegistry.name(TestHandler.class, "handler.dispatches"), -- MetricRegistry.name(TestHandler.class, "handler.head-requests"), -- MetricRegistry.name(TestHandler.class, "handler.post-requests"), -- MetricRegistry.name(TestHandler.class, "handler.options-requests"), -- MetricRegistry.name(TestHandler.class, "handler.active-requests"), -- MetricRegistry.name(TestHandler.class, "handler.delete-requests"), -- MetricRegistry.name(TestHandler.class, "handler.move-requests") -- ); -- -- server.stop(); -- -- assertThat(registry.getNames()) -- .isEmpty(); -- } -- -- @Test -- void responseTimesAreRecordedForBlockingResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/blocking")); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- -- assertResponseTimesValid(); -- } -- -- @Test -- void doStopDoesNotThrowNPE() throws Exception { -- InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); -- handler.setHandler(new TestHandler()); -- -- assertThatCode(handler::doStop).doesNotThrowAnyException(); -- } -- -- @Test -- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { -- InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); -- handler.setHandler(new TestHandler()); -- handler.setName("handler"); -- handler.doStart(); -- assertThat(registry.getGauges()).containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); -- } -- -- @Test -- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { -- InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); -- handler.setHandler(new TestHandler()); -- handler.setName("handler"); -- handler.doStart(); -- assertThat(registry.getGauges()).doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); -- } -- -- @Test -- @Disabled("flaky on virtual machines") -- void responseTimesAreRecordedForAsyncResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/async")); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- -- assertResponseTimesValid(); -- } -- -- private void assertResponseTimesValid() { -- assertThat(registry.getMeters().get(metricName().resolve("200-responses")) -- .getCount()).isGreaterThan(0L); -- -- -- assertThat(registry.getTimers().get(metricName().resolve("get-requests")) -- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); -- -- assertThat(registry.getTimers().get(metricName().resolve("requests")) -- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); -- } -- -- private String uri(String path) { -- return "http://localhost:" + connector.getLocalPort() + path; -- } -- -- private MetricName metricName() { -- return MetricRegistry.name(TestHandler.class.getName(), "handler"); -- } -- -- /** -- * test handler. -- *

    -- * Supports -- *

    -- * /blocking - uses the standard servlet api -- * /async - uses the 3.1 async api to complete the request -- *

    -- * all other requests will return 404 -- */ -- private static class TestHandler extends AbstractHandler { -- @Override -- public void handle( -- String path, -- Request request, -- final HttpServletRequest httpServletRequest, -- final HttpServletResponse httpServletResponse -- ) throws IOException, ServletException { -- switch (path) { -- case "/blocking": -- request.setHandled(true); -+final class InstrumentedHandlerTest { -+ private final HttpClient client = new HttpClient(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final Server server = new Server(); -+ private final ServerConnector connector = new ServerConnector(server); -+ private final InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ handler.setName("handler"); -+ handler.setHandler(new TestHandler()); -+ server.addConnector(connector); -+ server.setHandler(handler); -+ server.start(); -+ client.start(); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ server.stop(); -+ client.stop(); -+ } -+ -+ @Test -+ void hasAName() throws Exception { -+ assertThat(handler.getName()).isEqualTo("handler"); -+ } -+ -+ @Test -+ void createsAndRemovesMetricsForTheHandler() throws Exception { -+ final ContentResponse response = client.GET(uri("/hello")); -+ -+ assertThat(response.getStatus()).isEqualTo(404); -+ -+ assertThat(registry.getNames()) -+ .containsOnly( -+ MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.404-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), -+ MetricRegistry.name(TestHandler.class, "handler.requests"), -+ MetricRegistry.name(TestHandler.class, "handler.active-suspended"), -+ MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), -+ MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), -+ MetricRegistry.name(TestHandler.class, "handler.get-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.put-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), -+ MetricRegistry.name(TestHandler.class, "handler.trace-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.other-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.connect-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.dispatches"), -+ MetricRegistry.name(TestHandler.class, "handler.head-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.post-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.options-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.active-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.delete-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.move-requests")); -+ -+ server.stop(); -+ -+ assertThat(registry.getNames()).isEmpty(); -+ } -+ -+ @Test -+ void responseTimesAreRecordedForBlockingResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/blocking")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ -+ assertResponseTimesValid(); -+ } -+ -+ @Test -+ void doStopDoesNotThrowNPE() throws Exception { -+ InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); -+ handler.setHandler(new TestHandler()); -+ -+ assertThatCode(handler::doStop).doesNotThrowAnyException(); -+ } -+ -+ @Test -+ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { -+ InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); -+ handler.setHandler(new TestHandler()); -+ handler.setName("handler"); -+ handler.doStart(); -+ assertThat(registry.getGauges()) -+ .containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); -+ } -+ -+ @Test -+ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { -+ InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); -+ handler.setHandler(new TestHandler()); -+ handler.setName("handler"); -+ handler.doStart(); -+ assertThat(registry.getGauges()) -+ .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); -+ } -+ -+ @Disabled("flaky on virtual machines") -+ @Test -+ void responseTimesAreRecordedForAsyncResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/async")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ -+ assertResponseTimesValid(); -+ } -+ -+ private void assertResponseTimesValid() { -+ assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) -+ .isPositive(); -+ -+ assertThat( -+ registry -+ .getTimers() -+ .get(metricName().resolve("get-requests")) -+ .getSnapshot() -+ .getMedian()) -+ .isPositive() -+ .isLessThan(TimeUnit.SECONDS.toNanos(1)); -+ -+ assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) -+ .isPositive() -+ .isLessThan(TimeUnit.SECONDS.toNanos(1)); -+ } -+ -+ private String uri(String path) { -+ return "http://localhost:" + connector.getLocalPort() + path; -+ } -+ -+ private MetricName metricName() { -+ return MetricRegistry.name(TestHandler.class.getName(), "handler"); -+ } -+ -+ /** -+ * test handler. -+ * -+ *

    Supports -+ * -+ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the -+ * request -+ * -+ *

    all other requests will return 404 -+ */ -+ private static class TestHandler extends AbstractHandler { -+ @Override -+ public void handle( -+ String path, -+ Request request, -+ final HttpServletRequest httpServletRequest, -+ final HttpServletResponse httpServletResponse) -+ throws IOException, ServletException { -+ switch (path) { -+ case "/blocking": -+ request.setHandled(true); -+ try { -+ Thread.sleep(100); -+ } catch (InterruptedException e) { -+ Thread.currentThread().interrupt(); -+ } -+ httpServletResponse.setStatus(200); -+ httpServletResponse.setContentType("text/plain"); -+ httpServletResponse.getWriter().write("some content from the blocking request\n"); -+ break; -+ case "/async": -+ request.setHandled(true); -+ final AsyncContext context = request.startAsync(); -+ Thread t = -+ new Thread( -+ () -> { - try { -- Thread.sleep(100); -+ Thread.sleep(100); - } catch (InterruptedException e) { -- Thread.currentThread().interrupt(); -+ Thread.currentThread().interrupt(); - } - httpServletResponse.setStatus(200); - httpServletResponse.setContentType("text/plain"); -- httpServletResponse.getWriter().write("some content from the blocking request\n"); -- break; -- case "/async": -- request.setHandled(true); -- final AsyncContext context = request.startAsync(); -- Thread t = new Thread(() -> { -- try { -- Thread.sleep(100); -- } catch (InterruptedException e) { -- Thread.currentThread().interrupt(); -- } -- httpServletResponse.setStatus(200); -- httpServletResponse.setContentType("text/plain"); -- final ServletOutputStream servletOutputStream; -- try { -- servletOutputStream = httpServletResponse.getOutputStream(); -- servletOutputStream.setWriteListener( -- new WriteListener() { -- @Override -- public void onWritePossible() throws IOException { -- servletOutputStream.write("some content from the async\n" -- .getBytes(StandardCharsets.UTF_8)); -- context.complete(); -- } -- -- @Override -- public void onError(Throwable throwable) { -- context.complete(); -- } -- } -- ); -- } catch (IOException e) { -- context.complete(); -- } -- }); -- t.start(); -- break; -- default: -- break; -- } -- } -+ final ServletOutputStream servletOutputStream; -+ try { -+ servletOutputStream = httpServletResponse.getOutputStream(); -+ servletOutputStream.setWriteListener( -+ new WriteListener() { -+ @Override -+ public void onWritePossible() throws IOException { -+ servletOutputStream.write( -+ "some content from the async\n".getBytes(UTF_8)); -+ context.complete(); -+ } -+ -+ @Override -+ public void onError(Throwable throwable) { -+ context.complete(); -+ } -+ }); -+ } catch (IOException e) { -+ context.complete(); -+ } -+ }); -+ t.start(); -+ break; -+ default: -+ break; -+ } - } -+ } - } ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java -@@ -1,7 +1,17 @@ - package io.dropwizard.metrics5.jetty10; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; -+import java.io.IOException; -+import javax.servlet.AsyncContext; -+import javax.servlet.ServletOutputStream; -+import javax.servlet.WriteListener; -+import javax.servlet.http.HttpServletRequest; -+import javax.servlet.http.HttpServletResponse; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; - import org.eclipse.jetty.server.Request; -@@ -12,202 +22,190 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import javax.servlet.AsyncContext; --import javax.servlet.ServletOutputStream; --import javax.servlet.WriteListener; --import javax.servlet.http.HttpServletRequest; --import javax.servlet.http.HttpServletResponse; --import java.io.IOException; --import java.nio.charset.StandardCharsets; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static org.assertj.core.api.Assertions.assertThat; -- --class InstrumentedHttpChannelListenerTest { -- private final HttpClient client = new HttpClient(); -- private final Server server = new Server(); -- private final ServerConnector connector = new ServerConnector(server); -- private final TestHandler handler = new TestHandler(); -- private MetricRegistry registry; -- -- @BeforeEach -- void setUp() throws Exception { -- registry = new MetricRegistry(); -- connector.addBean(new InstrumentedHttpChannelListener(registry, MetricRegistry.name(TestHandler.class, "handler"), ALL)); -- server.addConnector(connector); -- server.setHandler(handler); -- server.start(); -- client.start(); -- } -- -- @AfterEach -- void tearDown() throws Exception { -- server.stop(); -- client.stop(); -- } -- -- @Test -- void createsMetricsForTheHandler() throws Exception { -- final ContentResponse response = client.GET(uri("/hello")); -- -- assertThat(response.getStatus()) -- .isEqualTo(404); -- -- assertThat(registry.getNames()) -- .containsOnly( -- metricName("1xx-responses"), -- metricName("2xx-responses"), -- metricName("3xx-responses"), -- metricName("404-responses"), -- metricName("4xx-responses"), -- metricName("5xx-responses"), -- metricName("percent-4xx-1m"), -- metricName("percent-4xx-5m"), -- metricName("percent-4xx-15m"), -- metricName("percent-5xx-1m"), -- metricName("percent-5xx-5m"), -- metricName("percent-5xx-15m"), -- metricName("requests"), -- metricName("active-suspended"), -- metricName("async-dispatches"), -- metricName("async-timeouts"), -- metricName("get-requests"), -- metricName("put-requests"), -- metricName("active-dispatches"), -- metricName("trace-requests"), -- metricName("other-requests"), -- metricName("connect-requests"), -- metricName("dispatches"), -- metricName("head-requests"), -- metricName("post-requests"), -- metricName("options-requests"), -- metricName("active-requests"), -- metricName("delete-requests"), -- metricName("move-requests") -- ); -+final class InstrumentedHttpChannelListenerTest { -+ private final HttpClient client = new HttpClient(); -+ private final Server server = new Server(); -+ private final ServerConnector connector = new ServerConnector(server); -+ private final TestHandler handler = new TestHandler(); -+ private MetricRegistry registry; -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ registry = new MetricRegistry(); -+ connector.addBean( -+ new InstrumentedHttpChannelListener( -+ registry, MetricRegistry.name(TestHandler.class, "handler"), ALL)); -+ server.addConnector(connector); -+ server.setHandler(handler); -+ server.start(); -+ client.start(); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ server.stop(); -+ client.stop(); -+ } -+ -+ @Test -+ void createsMetricsForTheHandler() throws Exception { -+ final ContentResponse response = client.GET(uri("/hello")); -+ -+ assertThat(response.getStatus()).isEqualTo(404); -+ -+ assertThat(registry.getNames()) -+ .containsOnly( -+ metricName("1xx-responses"), -+ metricName("2xx-responses"), -+ metricName("3xx-responses"), -+ metricName("404-responses"), -+ metricName("4xx-responses"), -+ metricName("5xx-responses"), -+ metricName("percent-4xx-1m"), -+ metricName("percent-4xx-5m"), -+ metricName("percent-4xx-15m"), -+ metricName("percent-5xx-1m"), -+ metricName("percent-5xx-5m"), -+ metricName("percent-5xx-15m"), -+ metricName("requests"), -+ metricName("active-suspended"), -+ metricName("async-dispatches"), -+ metricName("async-timeouts"), -+ metricName("get-requests"), -+ metricName("put-requests"), -+ metricName("active-dispatches"), -+ metricName("trace-requests"), -+ metricName("other-requests"), -+ metricName("connect-requests"), -+ metricName("dispatches"), -+ metricName("head-requests"), -+ metricName("post-requests"), -+ metricName("options-requests"), -+ metricName("active-requests"), -+ metricName("delete-requests"), -+ metricName("move-requests")); -+ } -+ -+ @Test -+ void responseTimesAreRecordedForBlockingResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/blocking")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.getMediaType()).isEqualTo("text/plain"); -+ assertThat(response.getContentAsString()).isEqualTo("some content from the blocking request"); -+ -+ assertResponseTimesValid(); -+ } -+ -+ @Test -+ void responseTimesAreRecordedForAsyncResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/async")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.getMediaType()).isEqualTo("text/plain"); -+ assertThat(response.getContentAsString()).isEqualTo("some content from the async"); -+ -+ assertResponseTimesValid(); -+ } -+ -+ private void assertResponseTimesValid() { -+ try { -+ Thread.sleep(100); -+ } catch (InterruptedException e) { -+ Thread.currentThread().interrupt(); - } - -- -- @Test -- void responseTimesAreRecordedForBlockingResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/blocking")); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.getMediaType()).isEqualTo("text/plain"); -- assertThat(response.getContentAsString()).isEqualTo("some content from the blocking request"); -- -- assertResponseTimesValid(); -- } -- -- @Test -- void responseTimesAreRecordedForAsyncResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/async")); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.getMediaType()).isEqualTo("text/plain"); -- assertThat(response.getContentAsString()).isEqualTo("some content from the async"); -- -- assertResponseTimesValid(); -- } -- -- private void assertResponseTimesValid() { -- try { -+ assertThat(registry.getMeters().get(metricName("2xx-responses")).getCount()).isPositive(); -+ assertThat(registry.getMeters().get(metricName("200-responses")).getCount()).isPositive(); -+ -+ assertThat(registry.getTimers().get(metricName("get-requests")).getSnapshot().getMedian()) -+ .isPositive(); -+ -+ assertThat(registry.getTimers().get(metricName("requests")).getSnapshot().getMedian()) -+ .isPositive(); -+ } -+ -+ private String uri(String path) { -+ return "http://localhost:" + connector.getLocalPort() + path; -+ } -+ -+ private MetricName metricName(String metricName) { -+ return MetricRegistry.name(TestHandler.class.getName(), "handler", metricName); -+ } -+ -+ /** -+ * test handler. -+ * -+ *

    Supports -+ * -+ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the -+ * request -+ * -+ *

    all other requests will return 404 -+ */ -+ private static class TestHandler extends AbstractHandler { -+ @Override -+ public void handle( -+ String path, -+ Request request, -+ final HttpServletRequest httpServletRequest, -+ final HttpServletResponse httpServletResponse) -+ throws IOException { -+ switch (path) { -+ case "/blocking": -+ request.setHandled(true); -+ httpServletResponse.setStatus(200); -+ httpServletResponse.setContentType("text/plain"); -+ httpServletResponse.getWriter().write("some content from the blocking request"); -+ try { - Thread.sleep(100); -- } catch (InterruptedException e) { -+ } catch (InterruptedException e) { -+ httpServletResponse.setStatus(500); - Thread.currentThread().interrupt(); -- } -- -- assertThat(registry.getMeters().get(metricName("2xx-responses")) -- .getCount()).isPositive(); -- assertThat(registry.getMeters().get(metricName("200-responses")) -- .getCount()).isPositive(); -- -- assertThat(registry.getTimers().get(metricName("get-requests")) -- .getSnapshot().getMedian()).isPositive(); -- -- assertThat(registry.getTimers().get(metricName("requests")) -- .getSnapshot().getMedian()).isPositive(); -- } -- -- private String uri(String path) { -- return "http://localhost:" + connector.getLocalPort() + path; -- } -- -- private MetricName metricName(String metricName) { -- return MetricRegistry.name(TestHandler.class.getName(), "handler", metricName); -- } -- -- /** -- * test handler. -- *

    -- * Supports -- *

    -- * /blocking - uses the standard servlet api -- * /async - uses the 3.1 async api to complete the request -- *

    -- * all other requests will return 404 -- */ -- private static class TestHandler extends AbstractHandler { -- @Override -- public void handle( -- String path, -- Request request, -- final HttpServletRequest httpServletRequest, -- final HttpServletResponse httpServletResponse) throws IOException { -- switch (path) { -- case "/blocking": -- request.setHandled(true); -+ } -+ break; -+ case "/async": -+ request.setHandled(true); -+ final AsyncContext context = request.startAsync(); -+ Thread t = -+ new Thread( -+ () -> { - httpServletResponse.setStatus(200); - httpServletResponse.setContentType("text/plain"); -- httpServletResponse.getWriter().write("some content from the blocking request"); - try { -- Thread.sleep(100); -+ Thread.sleep(100); - } catch (InterruptedException e) { -- httpServletResponse.setStatus(500); -- Thread.currentThread().interrupt(); -+ httpServletResponse.setStatus(500); -+ Thread.currentThread().interrupt(); -+ } -+ final ServletOutputStream servletOutputStream; -+ try { -+ servletOutputStream = httpServletResponse.getOutputStream(); -+ servletOutputStream.setWriteListener( -+ new WriteListener() { -+ @Override -+ public void onWritePossible() throws IOException { -+ servletOutputStream.write( -+ "some content from the async".getBytes(UTF_8)); -+ context.complete(); -+ } -+ -+ @Override -+ public void onError(Throwable throwable) { -+ context.complete(); -+ } -+ }); -+ } catch (IOException e) { -+ context.complete(); - } -- break; -- case "/async": -- request.setHandled(true); -- final AsyncContext context = request.startAsync(); -- Thread t = new Thread(() -> { -- httpServletResponse.setStatus(200); -- httpServletResponse.setContentType("text/plain"); -- try { -- Thread.sleep(100); -- } catch (InterruptedException e) { -- httpServletResponse.setStatus(500); -- Thread.currentThread().interrupt(); -- } -- final ServletOutputStream servletOutputStream; -- try { -- servletOutputStream = httpServletResponse.getOutputStream(); -- servletOutputStream.setWriteListener( -- new WriteListener() { -- @Override -- public void onWritePossible() throws IOException { -- servletOutputStream.write("some content from the async" -- .getBytes(StandardCharsets.UTF_8)); -- context.complete(); -- } -- -- @Override -- public void onError(Throwable throwable) { -- context.complete(); -- } -- } -- ); -- } catch (IOException e) { -- context.complete(); -- } -- }); -- t.start(); -- break; -- default: -- break; -- } -- } -+ }); -+ t.start(); -+ break; -+ default: -+ break; -+ } - } -+ } - } ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java -@@ -1,52 +1,52 @@ - package io.dropwizard.metrics5.jetty10; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import org.eclipse.jetty.util.thread.QueuedThreadPool; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; -- --class InstrumentedQueuedThreadPoolTest { -- private static final String PREFIX = "prefix"; -- -- private MetricRegistry metricRegistry; -- private InstrumentedQueuedThreadPool iqtp; -- -- @BeforeEach -- void setUp() { -- metricRegistry = new MetricRegistry(); -- iqtp = new InstrumentedQueuedThreadPool(metricRegistry); -- } -- -- @Test -- void customMetricsPrefix() throws Exception { -- iqtp.setPrefix(PREFIX); -- iqtp.start(); -- -- assertThat(metricRegistry.getNames()) -- .extracting(MetricName::getKey) -- .overridingErrorMessage("Custom metrics prefix doesn't match") -- .allSatisfy(name -> assertThat(name).startsWith(PREFIX)); -- -- iqtp.stop(); -- assertThat(metricRegistry.getMetrics()) -- .overridingErrorMessage("The default metrics prefix was changed") -- .isEmpty(); -- } -- -- @Test -- void metricsPrefixBackwardCompatible() throws Exception { -- iqtp.start(); -- assertThat(metricRegistry.getNames()) -- .extracting(MetricName::getKey) -- .overridingErrorMessage("The default metrics prefix was changed") -- .allSatisfy(name -> assertThat(name).startsWith(QueuedThreadPool.class.getName())); -- -- iqtp.stop(); -- assertThat(metricRegistry.getMetrics()) -- .overridingErrorMessage("The default metrics prefix was changed") -- .isEmpty(); -- } -+final class InstrumentedQueuedThreadPoolTest { -+ private static final String PREFIX = "prefix"; -+ -+ private MetricRegistry metricRegistry; -+ private InstrumentedQueuedThreadPool iqtp; -+ -+ @BeforeEach -+ void setUp() { -+ metricRegistry = new MetricRegistry(); -+ iqtp = new InstrumentedQueuedThreadPool(metricRegistry); -+ } -+ -+ @Test -+ void customMetricsPrefix() throws Exception { -+ iqtp.setPrefix(PREFIX); -+ iqtp.start(); -+ -+ assertThat(metricRegistry.getNames()) -+ .extracting(MetricName::getKey) -+ .overridingErrorMessage("Custom metrics prefix doesn't match") -+ .allSatisfy(name -> assertThat(name).startsWith(PREFIX)); -+ -+ iqtp.stop(); -+ assertThat(metricRegistry.getMetrics()) -+ .overridingErrorMessage("The default metrics prefix was changed") -+ .isEmpty(); -+ } -+ -+ @Test -+ void metricsPrefixBackwardCompatible() throws Exception { -+ iqtp.start(); -+ assertThat(metricRegistry.getNames()) -+ .extracting(MetricName::getKey) -+ .overridingErrorMessage("The default metrics prefix was changed") -+ .allSatisfy(name -> assertThat(name).startsWith(QueuedThreadPool.class.getName())); -+ -+ iqtp.stop(); -+ assertThat(metricRegistry.getMetrics()) -+ .overridingErrorMessage("The default metrics prefix was changed") -+ .isEmpty(); -+ } - } ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java -@@ -2,62 +2,63 @@ package io.dropwizard.metrics5.jetty11; - - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Timer; -+import java.util.List; - import org.eclipse.jetty.io.Connection; - import org.eclipse.jetty.io.EndPoint; - import org.eclipse.jetty.server.ConnectionFactory; - import org.eclipse.jetty.server.Connector; - import org.eclipse.jetty.util.component.ContainerLifeCycle; - --import java.util.List; -- - public class InstrumentedConnectionFactory extends ContainerLifeCycle implements ConnectionFactory { -- private final ConnectionFactory connectionFactory; -- private final Timer timer; -- private final Counter counter; -- -- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { -- this(connectionFactory, timer, null); -- } -- -- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer, Counter counter) { -- this.connectionFactory = connectionFactory; -- this.timer = timer; -- this.counter = counter; -- addBean(connectionFactory); -- } -- -- @Override -- public String getProtocol() { -- return connectionFactory.getProtocol(); -- } -- -- @Override -- public List getProtocols() { -- return connectionFactory.getProtocols(); -- } -- -- @Override -- public Connection newConnection(Connector connector, EndPoint endPoint) { -- final Connection connection = connectionFactory.newConnection(connector, endPoint); -- connection.addEventListener(new Connection.Listener() { -- private Timer.Context context; -- -- @Override -- public void onOpened(Connection connection) { -- this.context = timer.time(); -- if (counter != null) { -- counter.inc(); -- } -+ private final ConnectionFactory connectionFactory; -+ private final Timer timer; -+ private final Counter counter; -+ -+ public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { -+ this(connectionFactory, timer, null); -+ } -+ -+ public InstrumentedConnectionFactory( -+ ConnectionFactory connectionFactory, Timer timer, Counter counter) { -+ this.connectionFactory = connectionFactory; -+ this.timer = timer; -+ this.counter = counter; -+ addBean(connectionFactory); -+ } -+ -+ @Override -+ public String getProtocol() { -+ return connectionFactory.getProtocol(); -+ } -+ -+ @Override -+ public List getProtocols() { -+ return connectionFactory.getProtocols(); -+ } -+ -+ @Override -+ public Connection newConnection(Connector connector, EndPoint endPoint) { -+ final Connection connection = connectionFactory.newConnection(connector, endPoint); -+ connection.addEventListener( -+ new Connection.Listener() { -+ private Timer.Context context; -+ -+ @Override -+ public void onOpened(Connection connection) { -+ this.context = timer.time(); -+ if (counter != null) { -+ counter.inc(); - } -+ } - -- @Override -- public void onClosed(Connection connection) { -- context.stop(); -- if (counter != null) { -- counter.dec(); -- } -+ @Override -+ public void onClosed(Connection connection) { -+ context.stop(); -+ if (counter != null) { -+ counter.dec(); - } -+ } - }); -- return connection; -- } -+ return connection; -+ } - } ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java -@@ -1,5 +1,13 @@ - package io.dropwizard.metrics5.jetty11; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; -+ -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -12,433 +20,444 @@ import jakarta.servlet.AsyncListener; - import jakarta.servlet.ServletException; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; --import org.eclipse.jetty.http.HttpMethod; --import org.eclipse.jetty.server.AsyncContextState; --import org.eclipse.jetty.server.Handler; --import org.eclipse.jetty.server.HttpChannelState; --import org.eclipse.jetty.server.Request; --import org.eclipse.jetty.server.handler.HandlerWrapper; -- - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; - import java.util.Set; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import org.eclipse.jetty.http.HttpMethod; -+import org.eclipse.jetty.server.AsyncContextState; -+import org.eclipse.jetty.server.Handler; -+import org.eclipse.jetty.server.HttpChannelState; -+import org.eclipse.jetty.server.Request; -+import org.eclipse.jetty.server.handler.HandlerWrapper; - - /** - * A Jetty {@link Handler} which records various metrics about an underlying {@link Handler} - * instance. - */ - public class InstrumentedHandler extends HandlerWrapper { -- private static final String NAME_REQUESTS = "requests"; -- private static final String NAME_DISPATCHES = "dispatches"; -- private static final String NAME_ACTIVE_REQUESTS = "active-requests"; -- private static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; -- private static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; -- private static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; -- private static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; -- private static final String NAME_1XX_RESPONSES = "1xx-responses"; -- private static final String NAME_2XX_RESPONSES = "2xx-responses"; -- private static final String NAME_3XX_RESPONSES = "3xx-responses"; -- private static final String NAME_4XX_RESPONSES = "4xx-responses"; -- private static final String NAME_5XX_RESPONSES = "5xx-responses"; -- private static final String NAME_GET_REQUESTS = "get-requests"; -- private static final String NAME_POST_REQUESTS = "post-requests"; -- private static final String NAME_HEAD_REQUESTS = "head-requests"; -- private static final String NAME_PUT_REQUESTS = "put-requests"; -- private static final String NAME_DELETE_REQUESTS = "delete-requests"; -- private static final String NAME_OPTIONS_REQUESTS = "options-requests"; -- private static final String NAME_TRACE_REQUESTS = "trace-requests"; -- private static final String NAME_CONNECT_REQUESTS = "connect-requests"; -- private static final String NAME_MOVE_REQUESTS = "move-requests"; -- private static final String NAME_OTHER_REQUESTS = "other-requests"; -- private static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; -- private static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; -- private static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; -- private static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; -- private static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; -- private static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; -- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -- -- private final MetricRegistry metricRegistry; -- -- private String name; -- private final String prefix; -- -- // the requests handled by this handler, excluding active -- private Timer requests; -- -- // the number of dispatches seen by this handler, excluding active -- private Timer dispatches; -- -- // the number of active requests -- private Counter activeRequests; -- -- // the number of active dispatches -- private Counter activeDispatches; -- -- // the number of requests currently suspended. -- private Counter activeSuspended; -- -- // the number of requests that have been asynchronously dispatched -- private Meter asyncDispatches; -- -- // the number of requests that expired while suspended -- private Meter asyncTimeouts; -- -- private final ResponseMeteredLevel responseMeteredLevel; -- private List responses; -- private Map responseCodeMeters; -- -- private Timer getRequests; -- private Timer postRequests; -- private Timer headRequests; -- private Timer putRequests; -- private Timer deleteRequests; -- private Timer optionsRequests; -- private Timer traceRequests; -- private Timer connectRequests; -- private Timer moveRequests; -- private Timer otherRequests; -- -- private AsyncListener listener; -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- */ -- public InstrumentedHandler(MetricRegistry registry) { -- this(registry, null); -+ private static final String NAME_REQUESTS = "requests"; -+ private static final String NAME_DISPATCHES = "dispatches"; -+ private static final String NAME_ACTIVE_REQUESTS = "active-requests"; -+ private static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; -+ private static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; -+ private static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; -+ private static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; -+ private static final String NAME_1XX_RESPONSES = "1xx-responses"; -+ private static final String NAME_2XX_RESPONSES = "2xx-responses"; -+ private static final String NAME_3XX_RESPONSES = "3xx-responses"; -+ private static final String NAME_4XX_RESPONSES = "4xx-responses"; -+ private static final String NAME_5XX_RESPONSES = "5xx-responses"; -+ private static final String NAME_GET_REQUESTS = "get-requests"; -+ private static final String NAME_POST_REQUESTS = "post-requests"; -+ private static final String NAME_HEAD_REQUESTS = "head-requests"; -+ private static final String NAME_PUT_REQUESTS = "put-requests"; -+ private static final String NAME_DELETE_REQUESTS = "delete-requests"; -+ private static final String NAME_OPTIONS_REQUESTS = "options-requests"; -+ private static final String NAME_TRACE_REQUESTS = "trace-requests"; -+ private static final String NAME_CONNECT_REQUESTS = "connect-requests"; -+ private static final String NAME_MOVE_REQUESTS = "move-requests"; -+ private static final String NAME_OTHER_REQUESTS = "other-requests"; -+ private static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; -+ private static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; -+ private static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; -+ private static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; -+ private static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; -+ private static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; -+ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -+ private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -+ -+ private final MetricRegistry metricRegistry; -+ -+ private String name; -+ private final String prefix; -+ -+ // the requests handled by this handler, excluding active -+ private Timer requests; -+ -+ // the number of dispatches seen by this handler, excluding active -+ private Timer dispatches; -+ -+ // the number of active requests -+ private Counter activeRequests; -+ -+ // the number of active dispatches -+ private Counter activeDispatches; -+ -+ // the number of requests currently suspended. -+ private Counter activeSuspended; -+ -+ // the number of requests that have been asynchronously dispatched -+ private Meter asyncDispatches; -+ -+ // the number of requests that expired while suspended -+ private Meter asyncTimeouts; -+ -+ private final ResponseMeteredLevel responseMeteredLevel; -+ private List responses; -+ private Map responseCodeMeters; -+ -+ private Timer getRequests; -+ private Timer postRequests; -+ private Timer headRequests; -+ private Timer putRequests; -+ private Timer deleteRequests; -+ private Timer optionsRequests; -+ private Timer traceRequests; -+ private Timer connectRequests; -+ private Timer moveRequests; -+ private Timer otherRequests; -+ -+ private AsyncListener listener; -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ */ -+ public InstrumentedHandler(MetricRegistry registry) { -+ this(registry, null); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param prefix the prefix to use for the metrics names -+ */ -+ public InstrumentedHandler(MetricRegistry registry, String prefix) { -+ this(registry, prefix, COARSE); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param prefix the prefix to use for the metrics names -+ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are -+ * instrumented -+ */ -+ public InstrumentedHandler( -+ MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { -+ this.responseMeteredLevel = responseMeteredLevel; -+ this.metricRegistry = registry; -+ this.prefix = prefix; -+ } -+ -+ public String getName() { -+ return name; -+ } -+ -+ public void setName(String name) { -+ this.name = name; -+ } -+ -+ @Override -+ protected void doStart() throws Exception { -+ super.doStart(); -+ -+ final MetricName prefix = getMetricPrefix(); -+ -+ this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); -+ this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); -+ -+ this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); -+ this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -+ this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -+ -+ this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); -+ this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -+ -+ this.responseCodeMeters = -+ DETAILED_METER_LEVELS.contains(responseMeteredLevel) -+ ? new ConcurrentHashMap<>() -+ : ImmutableMap.of(); -+ -+ this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); -+ this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); -+ this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); -+ this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); -+ this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); -+ this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); -+ this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); -+ this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); -+ this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); -+ this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); -+ -+ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -+ this.responses = -+ unmodifiableList( -+ Arrays.asList( -+ metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx -+ metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx -+ metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx -+ metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx -+ metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx -+ )); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_4XX_1M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_4XX_5M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_4XX_15M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of( -+ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_5XX_1M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_5XX_5M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_5XX_15M), -+ new RatioGauge() { -+ @Override -+ public Ratio getRatio() { -+ return Ratio.of( -+ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } -+ }); -+ } else { -+ this.responses = ImmutableList.of(); - } - -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param prefix the prefix to use for the metrics names -- */ -- public InstrumentedHandler(MetricRegistry registry, String prefix) { -- this(registry, prefix, COARSE); -+ this.listener = new AsyncAttachingListener(); -+ } -+ -+ @Override -+ protected void doStop() throws Exception { -+ final MetricName prefix = getMetricPrefix(); -+ -+ metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); -+ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -+ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -+ metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); -+ metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -+ metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); -+ -+ if (responseCodeMeters != null) { -+ responseCodeMeters.keySet().stream() -+ .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) -+ .forEach(metricRegistry::remove); - } -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param prefix the prefix to use for the metrics names -- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented -- */ -- public InstrumentedHandler(MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { -- this.responseMeteredLevel = responseMeteredLevel; -- this.metricRegistry = registry; -- this.prefix = prefix; -+ super.doStop(); -+ } -+ -+ @Override -+ public void handle( -+ String path, -+ Request request, -+ HttpServletRequest httpRequest, -+ HttpServletResponse httpResponse) -+ throws IOException, ServletException { -+ -+ activeDispatches.inc(); -+ -+ final long start; -+ final HttpChannelState state = request.getHttpChannelState(); -+ if (state.isInitial()) { -+ // new request -+ activeRequests.inc(); -+ start = request.getTimeStamp(); -+ state.addListener(listener); -+ } else { -+ // resumed request -+ start = System.currentTimeMillis(); -+ activeSuspended.dec(); -+ if (state.getState() == HttpChannelState.State.HANDLING) { -+ asyncDispatches.mark(); -+ } - } - -- public String getName() { -- return name; -+ try { -+ super.handle(path, request, httpRequest, httpResponse); -+ } finally { -+ final long now = System.currentTimeMillis(); -+ final long dispatched = now - start; -+ -+ activeDispatches.dec(); -+ dispatches.update(dispatched, TimeUnit.MILLISECONDS); -+ -+ if (state.isSuspended()) { -+ activeSuspended.inc(); -+ } else if (state.isInitial()) { -+ updateResponses(httpRequest, httpResponse, start, request.isHandled()); -+ } -+ // else onCompletion will handle it. - } -- -- public void setName(String name) { -- this.name = name; -+ } -+ -+ private Timer requestTimer(String method) { -+ final HttpMethod m = HttpMethod.fromString(method); -+ if (m == null) { -+ return otherRequests; -+ } else { -+ switch (m) { -+ case GET: -+ return getRequests; -+ case POST: -+ return postRequests; -+ case PUT: -+ return putRequests; -+ case HEAD: -+ return headRequests; -+ case DELETE: -+ return deleteRequests; -+ case OPTIONS: -+ return optionsRequests; -+ case TRACE: -+ return traceRequests; -+ case CONNECT: -+ return connectRequests; -+ case MOVE: -+ return moveRequests; -+ default: -+ return otherRequests; -+ } - } -- -- @Override -- protected void doStart() throws Exception { -- super.doStart(); -- -- final MetricName prefix = getMetricPrefix(); -- -- this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); -- this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); -- -- this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); -- this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -- this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -- -- this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); -- this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -- -- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); -- -- this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); -- this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); -- this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); -- this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); -- this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); -- this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); -- this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); -- this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); -- this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); -- this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); -- -- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -- this.responses = Collections.unmodifiableList(Arrays.asList( -- metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx -- metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx -- metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx -- metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx -- metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx -- )); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_1M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_5M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_15M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_1M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_5M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_15M), new RatioGauge() { -- @Override -- public Ratio getRatio() { -- return Ratio.of(responses.get(4).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -- }); -- } else { -- this.responses = Collections.emptyList(); -- } -- -- this.listener = new AsyncAttachingListener(); -+ } -+ -+ private void updateResponses( -+ HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { -+ if (isHandled) { -+ mark(response.getStatus()); -+ } else { -+ mark(404); -+ ; // will end up with a 404 response sent by HttpChannel.handle - } -- -- @Override -- protected void doStop() throws Exception { -- final MetricName prefix = getMetricPrefix(); -- -- metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); -- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -- metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); -- metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -- metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); -- -- if (responseCodeMeters != null) { -- responseCodeMeters.keySet().stream() -- .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) -- .forEach(metricRegistry::remove); -- } -- super.doStop(); -+ activeRequests.dec(); -+ final long elapsedTime = System.currentTimeMillis() - start; -+ requests.update(elapsedTime, TimeUnit.MILLISECONDS); -+ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -+ } -+ -+ private MetricName getMetricPrefix() { -+ return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); -+ } -+ -+ private void mark(int statusCode) { -+ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -+ getResponseCodeMeter(statusCode).mark(); - } - -- @Override -- public void handle(String path, -- Request request, -- HttpServletRequest httpRequest, -- HttpServletResponse httpResponse) throws IOException, ServletException { -- -- activeDispatches.inc(); -- -- final long start; -- final HttpChannelState state = request.getHttpChannelState(); -- if (state.isInitial()) { -- // new request -- activeRequests.inc(); -- start = request.getTimeStamp(); -- state.addListener(listener); -- } else { -- // resumed request -- start = System.currentTimeMillis(); -- activeSuspended.dec(); -- if (state.getState() == HttpChannelState.State.HANDLING) { -- asyncDispatches.mark(); -- } -- } -+ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -+ final int responseStatus = statusCode / 100; -+ if (responseStatus >= 1 && responseStatus <= 5) { -+ responses.get(responseStatus - 1).mark(); -+ } -+ } -+ } - -- try { -- super.handle(path, request, httpRequest, httpResponse); -- } finally { -- final long now = System.currentTimeMillis(); -- final long dispatched = now - start; -+ private Meter getResponseCodeMeter(int statusCode) { -+ return responseCodeMeters.computeIfAbsent( -+ statusCode, -+ sc -> metricRegistry.meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); -+ } - -- activeDispatches.dec(); -- dispatches.update(dispatched, TimeUnit.MILLISECONDS); -+ private class AsyncAttachingListener implements AsyncListener { - -- if (state.isSuspended()) { -- activeSuspended.inc(); -- } else if (state.isInitial()) { -- updateResponses(httpRequest, httpResponse, start, request.isHandled()); -- } -- // else onCompletion will handle it. -- } -- } -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException {} - -- private Timer requestTimer(String method) { -- final HttpMethod m = HttpMethod.fromString(method); -- if (m == null) { -- return otherRequests; -- } else { -- switch (m) { -- case GET: -- return getRequests; -- case POST: -- return postRequests; -- case PUT: -- return putRequests; -- case HEAD: -- return headRequests; -- case DELETE: -- return deleteRequests; -- case OPTIONS: -- return optionsRequests; -- case TRACE: -- return traceRequests; -- case CONNECT: -- return connectRequests; -- case MOVE: -- return moveRequests; -- default: -- return otherRequests; -- } -- } -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException { -+ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); - } - -- private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { -- if (isHandled) { -- mark(response.getStatus()); -- } else { -- mark(404);; // will end up with a 404 response sent by HttpChannel.handle -- } -- activeRequests.dec(); -- final long elapsedTime = System.currentTimeMillis() - start; -- requests.update(elapsedTime, TimeUnit.MILLISECONDS); -- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -- } -+ @Override -+ public void onError(AsyncEvent event) throws IOException {} - -- private MetricName getMetricPrefix() { -- return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException {} -+ } -+ ; - -- private void mark(int statusCode) { -- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -- getResponseCodeMeter(statusCode).mark(); -- } -+ private class InstrumentedAsyncListener implements AsyncListener { -+ private final long startTime; - -- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -- final int responseStatus = statusCode / 100; -- if (responseStatus >= 1 && responseStatus <= 5) { -- responses.get(responseStatus - 1).mark(); -- } -- } -+ InstrumentedAsyncListener() { -+ this.startTime = System.currentTimeMillis(); - } - -- private Meter getResponseCodeMeter(int statusCode) { -- return responseCodeMeters -- .computeIfAbsent(statusCode, sc -> metricRegistry -- .meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException { -+ asyncTimeouts.mark(); - } - -- private class AsyncAttachingListener implements AsyncListener { -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException {} -- -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); -- } -- -- @Override -- public void onError(AsyncEvent event) throws IOException {} -- -- @Override -- public void onComplete(AsyncEvent event) throws IOException {} -- }; -- -- private class InstrumentedAsyncListener implements AsyncListener { -- private final long startTime; -- -- InstrumentedAsyncListener() { -- this.startTime = System.currentTimeMillis(); -- } -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException { -- asyncTimeouts.mark(); -- } -- -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- } -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException {} - -- @Override -- public void onError(AsyncEvent event) throws IOException { -- } -+ @Override -+ public void onError(AsyncEvent event) throws IOException {} - -- @Override -- public void onComplete(AsyncEvent event) throws IOException { -- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -- final HttpServletRequest request = (HttpServletRequest) state.getRequest(); -- final HttpServletResponse response = (HttpServletResponse) state.getResponse(); -- updateResponses(request, response, startTime, true); -- if (!state.getHttpChannelState().isSuspended()) { -- activeSuspended.dec(); -- } -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException { -+ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -+ final HttpServletRequest request = (HttpServletRequest) state.getRequest(); -+ final HttpServletResponse response = (HttpServletResponse) state.getResponse(); -+ updateResponses(request, response, startTime, true); -+ if (!state.getHttpChannelState().isSuspended()) { -+ activeSuspended.dec(); -+ } - } -+ } - } ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java -@@ -1,5 +1,12 @@ - package io.dropwizard.metrics5.jetty11; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; -+ -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -11,415 +18,398 @@ import jakarta.servlet.AsyncEvent; - import jakarta.servlet.AsyncListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; --import org.eclipse.jetty.http.HttpMethod; --import org.eclipse.jetty.server.AsyncContextState; --import org.eclipse.jetty.server.HttpChannel.Listener; --import org.eclipse.jetty.server.HttpChannelState; --import org.eclipse.jetty.server.Request; -- - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; - import java.util.Set; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -- -+import org.eclipse.jetty.http.HttpMethod; -+import org.eclipse.jetty.server.AsyncContextState; -+import org.eclipse.jetty.server.HttpChannel.Listener; -+import org.eclipse.jetty.server.HttpChannelState; -+import org.eclipse.jetty.server.Request; - - /** -- * A Jetty {@link org.eclipse.jetty.server.HttpChannel.Listener} implementation which records various metrics about -- * underlying channel instance. Unlike {@link InstrumentedHandler} that uses internal API, this class should be -- * future proof. To install it, just add instance of this class to {@link org.eclipse.jetty.server.Connector} as bean. -+ * A Jetty {@link org.eclipse.jetty.server.HttpChannel.Listener} implementation which records -+ * various metrics about underlying channel instance. Unlike {@link InstrumentedHandler} that uses -+ * internal API, this class should be future proof. To install it, just add instance of this class -+ * to {@link org.eclipse.jetty.server.Connector} as bean. - * - * @since TBD - */ --public class InstrumentedHttpChannelListener -- implements Listener { -- private static final String START_ATTR = InstrumentedHttpChannelListener.class.getName() + ".start"; -- private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -- private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -- -- private final MetricRegistry metricRegistry; -- -- // the requests handled by this handler, excluding active -- private final Timer requests; -- -- // the number of dispatches seen by this handler, excluding active -- private final Timer dispatches; -- -- // the number of active requests -- private final Counter activeRequests; -- -- // the number of active dispatches -- private final Counter activeDispatches; -- -- // the number of requests currently suspended. -- private final Counter activeSuspended; -- -- // the number of requests that have been asynchronously dispatched -- private final Meter asyncDispatches; -- -- // the number of requests that expired while suspended -- private final Meter asyncTimeouts; -- -- private final ResponseMeteredLevel responseMeteredLevel; -- private final List responses; -- private final Map responseCodeMeters; -- private final MetricName prefix; -- private final Timer getRequests; -- private final Timer postRequests; -- private final Timer headRequests; -- private final Timer putRequests; -- private final Timer deleteRequests; -- private final Timer optionsRequests; -- private final Timer traceRequests; -- private final Timer connectRequests; -- private final Timer moveRequests; -- private final Timer otherRequests; -- -- private final AsyncListener listener; -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- */ -- public InstrumentedHttpChannelListener(MetricRegistry registry) { -- this(registry, null, COARSE); -- } -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param pref the prefix to use for the metrics names -- */ -- public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref) { -- this(registry, pref, COARSE); -- } -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param pref the prefix to use for the metrics names -- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented -- */ -- public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref, ResponseMeteredLevel responseMeteredLevel) { -- this.metricRegistry = registry; -- -- this.prefix = (pref == null) ? MetricName.build(getClass().getName()) : pref; -- -- this.requests = metricRegistry.timer(prefix.resolve("requests")); -- this.dispatches = metricRegistry.timer(prefix.resolve("dispatches")); -- -- this.activeRequests = metricRegistry.counter(prefix.resolve("active-requests")); -- this.activeDispatches = metricRegistry.counter(prefix.resolve("active-dispatches")); -- this.activeSuspended = metricRegistry.counter(prefix.resolve("active-suspended")); -- -- this.asyncDispatches = metricRegistry.meter(prefix.resolve("async-dispatches")); -- this.asyncTimeouts = metricRegistry.meter(prefix.resolve("async-timeouts")); -- -- this.responseMeteredLevel = responseMeteredLevel; -- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); -- this.responses = COARSE_METER_LEVELS.contains(responseMeteredLevel) ? -- Collections.unmodifiableList(Arrays.asList( -- registry.meter(prefix.resolve("1xx-responses")), // 1xx -- registry.meter(prefix.resolve("2xx-responses")), // 2xx -- registry.meter(prefix.resolve("3xx-responses")), // 3xx -- registry.meter(prefix.resolve("4xx-responses")), // 4xx -- registry.meter(prefix.resolve("5xx-responses")) // 5xx -- )) : Collections.emptyList(); -- -- this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); -- this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); -- this.headRequests = metricRegistry.timer(prefix.resolve("head-requests")); -- this.putRequests = metricRegistry.timer(prefix.resolve("put-requests")); -- this.deleteRequests = metricRegistry.timer(prefix.resolve("delete-requests")); -- this.optionsRequests = metricRegistry.timer(prefix.resolve("options-requests")); -- this.traceRequests = metricRegistry.timer(prefix.resolve("trace-requests")); -- this.connectRequests = metricRegistry.timer(prefix.resolve("connect-requests")); -- this.moveRequests = metricRegistry.timer(prefix.resolve("move-requests")); -- this.otherRequests = metricRegistry.timer(prefix.resolve("other-requests")); -- -- metricRegistry.register(prefix.resolve("percent-4xx-1m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -+public class InstrumentedHttpChannelListener implements Listener { -+ private static final String START_ATTR = -+ InstrumentedHttpChannelListener.class.getName() + ".start"; -+ private static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -+ private static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -+ -+ private final MetricRegistry metricRegistry; -+ -+ // the requests handled by this handler, excluding active -+ private final Timer requests; -+ -+ // the number of dispatches seen by this handler, excluding active -+ private final Timer dispatches; -+ -+ // the number of active requests -+ private final Counter activeRequests; -+ -+ // the number of active dispatches -+ private final Counter activeDispatches; -+ -+ // the number of requests currently suspended. -+ private final Counter activeSuspended; -+ -+ // the number of requests that have been asynchronously dispatched -+ private final Meter asyncDispatches; -+ -+ // the number of requests that expired while suspended -+ private final Meter asyncTimeouts; -+ -+ private final ResponseMeteredLevel responseMeteredLevel; -+ private final List responses; -+ private final Map responseCodeMeters; -+ private final MetricName prefix; -+ private final Timer getRequests; -+ private final Timer postRequests; -+ private final Timer headRequests; -+ private final Timer putRequests; -+ private final Timer deleteRequests; -+ private final Timer optionsRequests; -+ private final Timer traceRequests; -+ private final Timer connectRequests; -+ private final Timer moveRequests; -+ private final Timer otherRequests; -+ -+ private final AsyncListener listener; -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ */ -+ public InstrumentedHttpChannelListener(MetricRegistry registry) { -+ this(registry, null, COARSE); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param pref the prefix to use for the metrics names -+ */ -+ public InstrumentedHttpChannelListener(MetricRegistry registry, MetricName pref) { -+ this(registry, pref, COARSE); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param pref the prefix to use for the metrics names -+ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are -+ * instrumented -+ */ -+ public InstrumentedHttpChannelListener( -+ MetricRegistry registry, MetricName pref, ResponseMeteredLevel responseMeteredLevel) { -+ this.metricRegistry = registry; -+ -+ this.prefix = (pref == null) ? MetricName.build(getClass().getName()) : pref; -+ -+ this.requests = metricRegistry.timer(prefix.resolve("requests")); -+ this.dispatches = metricRegistry.timer(prefix.resolve("dispatches")); -+ -+ this.activeRequests = metricRegistry.counter(prefix.resolve("active-requests")); -+ this.activeDispatches = metricRegistry.counter(prefix.resolve("active-dispatches")); -+ this.activeSuspended = metricRegistry.counter(prefix.resolve("active-suspended")); -+ -+ this.asyncDispatches = metricRegistry.meter(prefix.resolve("async-dispatches")); -+ this.asyncTimeouts = metricRegistry.meter(prefix.resolve("async-timeouts")); -+ -+ this.responseMeteredLevel = responseMeteredLevel; -+ this.responseCodeMeters = -+ DETAILED_METER_LEVELS.contains(responseMeteredLevel) -+ ? new ConcurrentHashMap<>() -+ : ImmutableMap.of(); -+ this.responses = -+ COARSE_METER_LEVELS.contains(responseMeteredLevel) -+ ? unmodifiableList( -+ Arrays.asList( -+ registry.meter(prefix.resolve("1xx-responses")), // 1xx -+ registry.meter(prefix.resolve("2xx-responses")), // 2xx -+ registry.meter(prefix.resolve("3xx-responses")), // 3xx -+ registry.meter(prefix.resolve("4xx-responses")), // 4xx -+ registry.meter(prefix.resolve("5xx-responses")) // 5xx -+ )) -+ : ImmutableList.of(); -+ -+ this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); -+ this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); -+ this.headRequests = metricRegistry.timer(prefix.resolve("head-requests")); -+ this.putRequests = metricRegistry.timer(prefix.resolve("put-requests")); -+ this.deleteRequests = metricRegistry.timer(prefix.resolve("delete-requests")); -+ this.optionsRequests = metricRegistry.timer(prefix.resolve("options-requests")); -+ this.traceRequests = metricRegistry.timer(prefix.resolve("trace-requests")); -+ this.connectRequests = metricRegistry.timer(prefix.resolve("connect-requests")); -+ this.moveRequests = metricRegistry.timer(prefix.resolve("move-requests")); -+ this.otherRequests = metricRegistry.timer(prefix.resolve("other-requests")); -+ -+ metricRegistry.register( -+ prefix.resolve("percent-4xx-1m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-4xx-5m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-4xx-5m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-4xx-15m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-4xx-15m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of( -+ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-5xx-1m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-5xx-1m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-5xx-5m"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-5xx-5m"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } - }); - -- metricRegistry.register(prefix.resolve("percent-5xx-15m"), new RatioGauge() { -- @Override -- public RatioGauge.Ratio getRatio() { -- return Ratio.of(responses.get(4).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -+ metricRegistry.register( -+ prefix.resolve("percent-5xx-15m"), -+ new RatioGauge() { -+ @Override -+ public RatioGauge.Ratio getRatio() { -+ return Ratio.of( -+ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } - }); - -- this.listener = new AsyncAttachingListener(); -- } -+ this.listener = new AsyncAttachingListener(); -+ } - -- @Override -- public void onRequestBegin(final Request request) { -+ @Override -+ public void onRequestBegin(final Request request) {} - -- } -- -- @Override -- public void onBeforeDispatch(final Request request) { -- before(request); -- } -+ @Override -+ public void onBeforeDispatch(final Request request) { -+ before(request); -+ } - -- @Override -- public void onDispatchFailure(final Request request, final Throwable failure) { -+ @Override -+ public void onDispatchFailure(final Request request, final Throwable failure) {} - -- } -+ @Override -+ public void onAfterDispatch(final Request request) { -+ after(request); -+ } - -- @Override -- public void onAfterDispatch(final Request request) { -- after(request); -- } -+ @Override -+ public void onRequestContent(final Request request, final ByteBuffer content) {} - -- @Override -- public void onRequestContent(final Request request, final ByteBuffer content) { -+ @Override -+ public void onRequestContentEnd(final Request request) {} - -- } -+ @Override -+ public void onRequestTrailers(final Request request) {} - -- @Override -- public void onRequestContentEnd(final Request request) { -+ @Override -+ public void onRequestEnd(final Request request) {} - -- } -+ @Override -+ public void onRequestFailure(final Request request, final Throwable failure) {} - -- @Override -- public void onRequestTrailers(final Request request) { -+ @Override -+ public void onResponseBegin(final Request request) {} - -- } -+ @Override -+ public void onResponseCommit(final Request request) {} - -- @Override -- public void onRequestEnd(final Request request) { -+ @Override -+ public void onResponseContent(final Request request, final ByteBuffer content) {} - -- } -+ @Override -+ public void onResponseEnd(final Request request) {} - -- @Override -- public void onRequestFailure(final Request request, final Throwable failure) { -+ @Override -+ public void onResponseFailure(final Request request, final Throwable failure) {} - -- } -+ @Override -+ public void onComplete(final Request request) {} - -- @Override -- public void onResponseBegin(final Request request) { -+ private void before(final Request request) { -+ activeDispatches.inc(); - -+ final long start; -+ final HttpChannelState state = request.getHttpChannelState(); -+ if (state.isInitial()) { -+ // new request -+ activeRequests.inc(); -+ start = request.getTimeStamp(); -+ state.addListener(listener); -+ } else { -+ // resumed request -+ start = System.currentTimeMillis(); -+ activeSuspended.dec(); -+ if (state.isAsyncStarted()) { -+ asyncDispatches.mark(); -+ } - } -- -- @Override -- public void onResponseCommit(final Request request) { -- -+ request.setAttribute(START_ATTR, start); -+ } -+ -+ private void after(final Request request) { -+ final long start = (long) request.getAttribute(START_ATTR); -+ final long now = System.currentTimeMillis(); -+ final long dispatched = now - start; -+ -+ activeDispatches.dec(); -+ dispatches.update(dispatched, TimeUnit.MILLISECONDS); -+ -+ final HttpChannelState state = request.getHttpChannelState(); -+ if (state.isSuspended()) { -+ activeSuspended.inc(); -+ } else if (state.isInitial()) { -+ updateResponses(request, request.getResponse(), start, request.isHandled()); - } -- -- @Override -- public void onResponseContent(final Request request, final ByteBuffer content) { -- -+ // else onCompletion will handle it. -+ } -+ -+ private void updateResponses( -+ HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { -+ if (isHandled) { -+ mark(response.getStatus()); -+ } else { -+ mark(404); // will end up with a 404 response sent by HttpChannel.handle -+ } -+ activeRequests.dec(); -+ final long elapsedTime = System.currentTimeMillis() - start; -+ requests.update(elapsedTime, TimeUnit.MILLISECONDS); -+ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -+ } -+ -+ private void mark(int statusCode) { -+ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -+ getResponseCodeMeter(statusCode).mark(); - } - -- @Override -- public void onResponseEnd(final Request request) { -- -+ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -+ final int responseStatus = statusCode / 100; -+ if (responseStatus >= 1 && responseStatus <= 5) { -+ responses.get(responseStatus - 1).mark(); -+ } - } -+ } -+ -+ private Meter getResponseCodeMeter(int statusCode) { -+ return responseCodeMeters.computeIfAbsent( -+ statusCode, sc -> metricRegistry.meter(prefix.resolve(String.format("%d-responses", sc)))); -+ } -+ -+ private Timer requestTimer(String method) { -+ final HttpMethod m = HttpMethod.fromString(method); -+ if (m == null) { -+ return otherRequests; -+ } else { -+ switch (m) { -+ case GET: -+ return getRequests; -+ case POST: -+ return postRequests; -+ case PUT: -+ return putRequests; -+ case HEAD: -+ return headRequests; -+ case DELETE: -+ return deleteRequests; -+ case OPTIONS: -+ return optionsRequests; -+ case TRACE: -+ return traceRequests; -+ case CONNECT: -+ return connectRequests; -+ case MOVE: -+ return moveRequests; -+ default: -+ return otherRequests; -+ } -+ } -+ } -+ -+ private class AsyncAttachingListener implements AsyncListener { - - @Override -- public void onResponseFailure(final Request request, final Throwable failure) { -+ public void onTimeout(AsyncEvent event) throws IOException {} - -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException { -+ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); - } - - @Override -- public void onComplete(final Request request) { -- -- } -+ public void onError(AsyncEvent event) throws IOException {} - -- private void before(final Request request) { -- activeDispatches.inc(); -- -- final long start; -- final HttpChannelState state = request.getHttpChannelState(); -- if (state.isInitial()) { -- // new request -- activeRequests.inc(); -- start = request.getTimeStamp(); -- state.addListener(listener); -- } else { -- // resumed request -- start = System.currentTimeMillis(); -- activeSuspended.dec(); -- if (state.isAsyncStarted()) { -- asyncDispatches.mark(); -- } -- } -- request.setAttribute(START_ATTR, start); -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException {} -+ } -+ ; - -- private void after(final Request request) { -- final long start = (long) request.getAttribute(START_ATTR); -- final long now = System.currentTimeMillis(); -- final long dispatched = now - start; -- -- activeDispatches.dec(); -- dispatches.update(dispatched, TimeUnit.MILLISECONDS); -- -- final HttpChannelState state = request.getHttpChannelState(); -- if (state.isSuspended()) { -- activeSuspended.inc(); -- } else if (state.isInitial()) { -- updateResponses(request, request.getResponse(), start, request.isHandled()); -- } -- // else onCompletion will handle it. -- } -+ private class InstrumentedAsyncListener implements AsyncListener { -+ private final long startTime; - -- private void updateResponses(HttpServletRequest request, HttpServletResponse response, long start, boolean isHandled) { -- if (isHandled) { -- mark(response.getStatus()); -- } else { -- mark(404); // will end up with a 404 response sent by HttpChannel.handle -- } -- activeRequests.dec(); -- final long elapsedTime = System.currentTimeMillis() - start; -- requests.update(elapsedTime, TimeUnit.MILLISECONDS); -- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -+ InstrumentedAsyncListener() { -+ this.startTime = System.currentTimeMillis(); - } - -- private void mark(int statusCode) { -- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -- getResponseCodeMeter(statusCode).mark(); -- } -- -- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -- final int responseStatus = statusCode / 100; -- if (responseStatus >= 1 && responseStatus <= 5) { -- responses.get(responseStatus - 1).mark(); -- } -- } -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException { -+ asyncTimeouts.mark(); - } - -- private Meter getResponseCodeMeter(int statusCode) { -- return responseCodeMeters -- .computeIfAbsent(statusCode, sc -> metricRegistry -- .meter(prefix.resolve(String.format("%d-responses", sc)))); -- } -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException {} - -- private Timer requestTimer(String method) { -- final HttpMethod m = HttpMethod.fromString(method); -- if (m == null) { -- return otherRequests; -- } else { -- switch (m) { -- case GET: -- return getRequests; -- case POST: -- return postRequests; -- case PUT: -- return putRequests; -- case HEAD: -- return headRequests; -- case DELETE: -- return deleteRequests; -- case OPTIONS: -- return optionsRequests; -- case TRACE: -- return traceRequests; -- case CONNECT: -- return connectRequests; -- case MOVE: -- return moveRequests; -- default: -- return otherRequests; -- } -- } -- } -+ @Override -+ public void onError(AsyncEvent event) throws IOException {} - -- private class AsyncAttachingListener implements AsyncListener { -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException {} -- -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); -- } -- -- @Override -- public void onError(AsyncEvent event) throws IOException {} -- -- @Override -- public void onComplete(AsyncEvent event) throws IOException {} -- }; -- -- private class InstrumentedAsyncListener implements AsyncListener { -- private final long startTime; -- -- InstrumentedAsyncListener() { -- this.startTime = System.currentTimeMillis(); -- } -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException { -- asyncTimeouts.mark(); -- } -- -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- } -- -- @Override -- public void onError(AsyncEvent event) throws IOException { -- } -- -- @Override -- public void onComplete(AsyncEvent event) throws IOException { -- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -- final HttpServletRequest request = (HttpServletRequest) state.getRequest(); -- final HttpServletResponse response = (HttpServletResponse) state.getResponse(); -- updateResponses(request, response, startTime, true); -- if (!state.getHttpChannelState().isSuspended()) { -- activeSuspended.dec(); -- } -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException { -+ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -+ final HttpServletRequest request = (HttpServletRequest) state.getRequest(); -+ final HttpServletResponse response = (HttpServletResponse) state.getResponse(); -+ updateResponses(request, response, startTime, true); -+ if (!state.getHttpChannelState().isSuspended()) { -+ activeSuspended.dec(); -+ } - } -+ } - } ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPool.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPool.java -@@ -1,119 +1,130 @@ - package io.dropwizard.metrics5.jetty11; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.RatioGauge; -+import java.util.concurrent.BlockingQueue; - import org.eclipse.jetty.util.annotation.Name; - import org.eclipse.jetty.util.thread.QueuedThreadPool; - --import java.util.concurrent.BlockingQueue; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -- - public class InstrumentedQueuedThreadPool extends QueuedThreadPool { -- private static final String NAME_UTILIZATION = "utilization"; -- private static final String NAME_UTILIZATION_MAX = "utilization-max"; -- private static final String NAME_SIZE = "size"; -- private static final String NAME_JOBS = "jobs"; -- private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; -- -- private final MetricRegistry metricRegistry; -- private String prefix; -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { -- this(registry, 200); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads) { -- this(registry, maxThreads, 8); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads) { -- this(registry, maxThreads, minThreads, 60000); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout) { -- this(registry, maxThreads, minThreads, idleTimeout, null); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("queue") BlockingQueue queue) { -- this(registry, maxThreads, minThreads, idleTimeout, queue, null); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("queue") BlockingQueue queue, -- @Name("prefix") String prefix) { -- super(maxThreads, minThreads, idleTimeout, queue); -- this.metricRegistry = registry; -- this.prefix = prefix; -- } -- -- public String getPrefix() { -- return prefix; -- } -- -- public void setPrefix(String prefix) { -- this.prefix = prefix; -- } -- -- @Override -- protected void doStart() throws Exception { -- super.doStart(); -- -- final MetricName prefix = getMetricPrefix(); -- -- metricRegistry.register(prefix.resolve(NAME_UTILIZATION), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(getThreads() - getIdleThreads(), getThreads()); -- } -+ private static final String NAME_UTILIZATION = "utilization"; -+ private static final String NAME_UTILIZATION_MAX = "utilization-max"; -+ private static final String NAME_SIZE = "size"; -+ private static final String NAME_JOBS = "jobs"; -+ private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; -+ -+ private final MetricRegistry metricRegistry; -+ private String prefix; -+ -+ public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { -+ this(registry, 200); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, @Name("maxThreads") int maxThreads) { -+ this(registry, maxThreads, 8); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads) { -+ this(registry, maxThreads, minThreads, 60000); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout) { -+ this(registry, maxThreads, minThreads, idleTimeout, null); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("queue") BlockingQueue queue) { -+ this(registry, maxThreads, minThreads, idleTimeout, queue, null); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("queue") BlockingQueue queue, -+ @Name("prefix") String prefix) { -+ super(maxThreads, minThreads, idleTimeout, queue); -+ this.metricRegistry = registry; -+ this.prefix = prefix; -+ } -+ -+ public String getPrefix() { -+ return prefix; -+ } -+ -+ public void setPrefix(String prefix) { -+ this.prefix = prefix; -+ } -+ -+ @Override -+ protected void doStart() throws Exception { -+ super.doStart(); -+ -+ final MetricName prefix = getMetricPrefix(); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_UTILIZATION), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(getThreads() - getIdleThreads(), getThreads()); -+ } - }); -- metricRegistry.register(prefix.resolve(NAME_UTILIZATION_MAX), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); -- } -+ metricRegistry.register( -+ prefix.resolve(NAME_UTILIZATION_MAX), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(getThreads() - getIdleThreads(), getMaxThreads()); -+ } - }); -- metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); -- // This assumes the QueuedThreadPool is using a BlockingArrayQueue or -- // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. -- metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); -- metricRegistry.register(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- BlockingQueue queue = getQueue(); -- return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); -- } -+ metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); -+ // This assumes the QueuedThreadPool is using a BlockingArrayQueue or -+ // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. -+ metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); -+ metricRegistry.register( -+ prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ BlockingQueue queue = getQueue(); -+ return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); -+ } - }); -- } -- -- @Override -- protected void doStop() throws Exception { -- final MetricName prefix = getMetricPrefix(); -- -- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); -- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); -- metricRegistry.remove(prefix.resolve(NAME_SIZE)); -- metricRegistry.remove(prefix.resolve(NAME_JOBS)); -- metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); -- -- super.doStop(); -- } -- -- private MetricName getMetricPrefix() { -- return this.prefix == null ? name(QueuedThreadPool.class, getName()) : name(this.prefix, getName()); -- } -+ } -+ -+ @Override -+ protected void doStop() throws Exception { -+ final MetricName prefix = getMetricPrefix(); -+ -+ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); -+ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); -+ metricRegistry.remove(prefix.resolve(NAME_SIZE)); -+ metricRegistry.remove(prefix.resolve(NAME_JOBS)); -+ metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); -+ -+ super.doStop(); -+ } -+ -+ private MetricName getMetricPrefix() { -+ return this.prefix == null -+ ? name(QueuedThreadPool.class, getName()) -+ : name(this.prefix, getName()); -+ } - } ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java -@@ -1,11 +1,15 @@ - package io.dropwizard.metrics5.jetty11; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; - import jakarta.servlet.ServletException; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; -+import java.io.IOException; -+import java.io.PrintWriter; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; - import org.eclipse.jetty.server.HttpConnectionFactory; -@@ -17,77 +21,75 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --import java.io.IOException; --import java.io.PrintWriter; -- --import static org.assertj.core.api.Assertions.assertThat; -- --class InstrumentedConnectionFactoryTest { -- private final MetricRegistry registry = new MetricRegistry(); -- private final Server server = new Server(); -- private final ServerConnector connector = -- new ServerConnector(server, new InstrumentedConnectionFactory(new HttpConnectionFactory(), -- registry.timer("http.connections"), -- registry.counter("http.active-connections"))); -- private final HttpClient client = new HttpClient(); -- -- @BeforeEach -- void setUp() throws Exception { -- server.setHandler(new AbstractHandler() { -- @Override -- public void handle(String target, -- Request baseRequest, -- HttpServletRequest request, -- HttpServletResponse response) throws IOException, ServletException { -- try (PrintWriter writer = response.getWriter()) { -- writer.println("OK"); -- } -+final class InstrumentedConnectionFactoryTest { -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final Server server = new Server(); -+ private final ServerConnector connector = -+ new ServerConnector( -+ server, -+ new InstrumentedConnectionFactory( -+ new HttpConnectionFactory(), -+ registry.timer("http.connections"), -+ registry.counter("http.active-connections"))); -+ private final HttpClient client = new HttpClient(); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ server.setHandler( -+ new AbstractHandler() { -+ @Override -+ public void handle( -+ String target, -+ Request baseRequest, -+ HttpServletRequest request, -+ HttpServletResponse response) -+ throws IOException, ServletException { -+ try (PrintWriter writer = response.getWriter()) { -+ writer.println("OK"); - } -+ } - }); - -- server.addConnector(connector); -- server.start(); -+ server.addConnector(connector); -+ server.start(); - -- client.start(); -- } -+ client.start(); -+ } - -- @AfterEach -- void tearDown() throws Exception { -- server.stop(); -- client.stop(); -- } -+ @AfterEach -+ void tearDown() throws Exception { -+ server.stop(); -+ client.stop(); -+ } - -- @Test -- void instrumentsConnectionTimes() throws Exception { -- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -- assertThat(response.getStatus()) -- .isEqualTo(200); -+ @Test -+ void instrumentsConnectionTimes() throws Exception { -+ final ContentResponse response = -+ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -+ assertThat(response.getStatus()).isEqualTo(200); - -- client.stop(); // close the connection -+ client.stop(); // close the connection - -- Thread.sleep(100); // make sure the connection is closed -+ Thread.sleep(100); // make sure the connection is closed - -- final Timer timer = registry.timer(MetricRegistry.name("http.connections")); -- assertThat(timer.getCount()) -- .isEqualTo(1); -- } -+ final Timer timer = registry.timer(MetricRegistry.name("http.connections")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } - -- @Test -- void instrumentsActiveConnections() throws Exception { -- final Counter counter = registry.counter("http.active-connections"); -+ @Test -+ void instrumentsActiveConnections() throws Exception { -+ final Counter counter = registry.counter("http.active-connections"); - -- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -- assertThat(response.getStatus()) -- .isEqualTo(200); -+ final ContentResponse response = -+ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -+ assertThat(response.getStatus()).isEqualTo(200); - -- assertThat(counter.getCount()) -- .isEqualTo(1); -+ assertThat(counter.getCount()).isEqualTo(1); +- assertThat(SharedMetricRegistries.names()).containsOnly("one"); ++ assertThat(SharedMetricRegistries.names()).containsExactly("one"); + } -- client.stop(); // close the connection -+ client.stop(); // close the connection + @Test +@@ -60,7 +59,7 @@ class SharedMetricRegistriesTest { + () -> { + SharedMetricRegistries.getDefault(); + }); +- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); ++ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); + } -- Thread.sleep(100); // make sure the connection is closed -+ Thread.sleep(100); // make sure the connection is closed + @Test +@@ -81,7 +80,8 @@ class SharedMetricRegistriesTest { + SharedMetricRegistries.setDefault("foobah"); + SharedMetricRegistries.setDefault("borg"); + }); +- assertTrue(exception.getMessage().contains("Default metric registry name is already set.")); ++ assertThat(exception.getMessage().contains("Default metric registry name is already set.")) ++ .isTrue(); + } -- assertThat(counter.getCount()) -- .isEqualTo(0); -- } -+ assertThat(counter.getCount()).isEqualTo(0); -+ } - } ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java -@@ -1,5 +1,12 @@ - package io.dropwizard.metrics5.jetty11; + @Test +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.nio.charset.StandardCharsets.UTF_8; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import jakarta.servlet.AsyncContext; -@@ -8,6 +15,8 @@ import jakarta.servlet.ServletOutputStream; - import jakarta.servlet.WriteListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; -+import java.io.IOException; -+import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; - import org.eclipse.jetty.server.Request; -@@ -19,228 +28,221 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; --import java.io.IOException; --import java.nio.charset.StandardCharsets; --import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; -- --class InstrumentedHandlerTest { -- private final HttpClient client = new HttpClient(); -- private final MetricRegistry registry = new MetricRegistry(); -- private final Server server = new Server(); -- private final ServerConnector connector = new ServerConnector(server); -- private final InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); -- -- @BeforeEach -- void setUp() throws Exception { -- handler.setName("handler"); -- handler.setHandler(new TestHandler()); -- server.addConnector(connector); -- server.setHandler(handler); -- server.start(); -- client.start(); -- } -- -- @AfterEach -- void tearDown() throws Exception { -- server.stop(); -- client.stop(); -- } -- -- @Test -- void hasAName() throws Exception { -- assertThat(handler.getName()) -- .isEqualTo("handler"); -- } -- -- @Test -- void createsAndRemovesMetricsForTheHandler() throws Exception { -- final ContentResponse response = client.GET(uri("/hello")); -- -- assertThat(response.getStatus()) -- .isEqualTo(404); -- -- assertThat(registry.getNames()) -- .containsOnly( -- MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.404-responses"), -- MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), -- MetricRegistry.name(TestHandler.class, "handler.requests"), -- MetricRegistry.name(TestHandler.class, "handler.active-suspended"), -- MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), -- MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), -- MetricRegistry.name(TestHandler.class, "handler.get-requests"), -- MetricRegistry.name(TestHandler.class, "handler.put-requests"), -- MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), -- MetricRegistry.name(TestHandler.class, "handler.trace-requests"), -- MetricRegistry.name(TestHandler.class, "handler.other-requests"), -- MetricRegistry.name(TestHandler.class, "handler.connect-requests"), -- MetricRegistry.name(TestHandler.class, "handler.dispatches"), -- MetricRegistry.name(TestHandler.class, "handler.head-requests"), -- MetricRegistry.name(TestHandler.class, "handler.post-requests"), -- MetricRegistry.name(TestHandler.class, "handler.options-requests"), -- MetricRegistry.name(TestHandler.class, "handler.active-requests"), -- MetricRegistry.name(TestHandler.class, "handler.delete-requests"), -- MetricRegistry.name(TestHandler.class, "handler.move-requests") -- ); -- -- server.stop(); -- -- assertThat(registry.getNames()) -- .isEmpty(); -- } -- -- @Test -- void responseTimesAreRecordedForBlockingResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/blocking")); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- -- assertResponseTimesValid(); -- } -- -- @Test -- void doStopDoesNotThrowNPE() throws Exception { -- InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); -- handler.setHandler(new TestHandler()); -- -- assertThatCode(handler::doStop).doesNotThrowAnyException(); -- } -- -- @Test -- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { -- InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); -- handler.setHandler(new TestHandler()); -- handler.setName("handler"); -- handler.doStart(); -- assertThat(registry.getGauges()).containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); -- } -- -- @Test -- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { -- InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); -- handler.setHandler(new TestHandler()); -- handler.setName("handler"); -- handler.doStart(); -- assertThat(registry.getGauges()).doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); -- } -- -- @Test -- @Disabled("flaky on virtual machines") -- void responseTimesAreRecordedForAsyncResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/async")); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- -- assertResponseTimesValid(); -- } -- -- private void assertResponseTimesValid() { -- assertThat(registry.getMeters().get(metricName().resolve("200-responses")) -- .getCount()).isGreaterThan(0L); -- -- -- assertThat(registry.getTimers().get(metricName().resolve("get-requests")) -- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); -- -- assertThat(registry.getTimers().get(metricName().resolve("requests")) -- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); -- } -- -- private String uri(String path) { -- return "http://localhost:" + connector.getLocalPort() + path; -- } -- -- private MetricName metricName() { -- return MetricRegistry.name(TestHandler.class.getName(), "handler"); -- } -- -- /** -- * test handler. -- *

    -- * Supports -- *

    -- * /blocking - uses the standard servlet api -- * /async - uses the 3.1 async api to complete the request -- *

    -- * all other requests will return 404 -- */ -- private static class TestHandler extends AbstractHandler { -- @Override -- public void handle( -- String path, -- Request request, -- final HttpServletRequest httpServletRequest, -- final HttpServletResponse httpServletResponse -- ) throws IOException, ServletException { -- switch (path) { -- case "/blocking": -- request.setHandled(true); -+final class InstrumentedHandlerTest { -+ private final HttpClient client = new HttpClient(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final Server server = new Server(); -+ private final ServerConnector connector = new ServerConnector(server); -+ private final InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ handler.setName("handler"); -+ handler.setHandler(new TestHandler()); -+ server.addConnector(connector); -+ server.setHandler(handler); -+ server.start(); -+ client.start(); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ server.stop(); -+ client.stop(); -+ } -+ -+ @Test -+ void hasAName() throws Exception { -+ assertThat(handler.getName()).isEqualTo("handler"); -+ } -+ -+ @Test -+ void createsAndRemovesMetricsForTheHandler() throws Exception { -+ final ContentResponse response = client.GET(uri("/hello")); -+ -+ assertThat(response.getStatus()).isEqualTo(404); -+ -+ assertThat(registry.getNames()) -+ .containsOnly( -+ MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.404-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), -+ MetricRegistry.name(TestHandler.class, "handler.requests"), -+ MetricRegistry.name(TestHandler.class, "handler.active-suspended"), -+ MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), -+ MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), -+ MetricRegistry.name(TestHandler.class, "handler.get-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.put-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), -+ MetricRegistry.name(TestHandler.class, "handler.trace-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.other-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.connect-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.dispatches"), -+ MetricRegistry.name(TestHandler.class, "handler.head-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.post-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.options-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.active-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.delete-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.move-requests")); -+ -+ server.stop(); -+ -+ assertThat(registry.getNames()).isEmpty(); -+ } -+ -+ @Test -+ void responseTimesAreRecordedForBlockingResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/blocking")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ -+ assertResponseTimesValid(); -+ } -+ -+ @Test -+ void doStopDoesNotThrowNPE() throws Exception { -+ InstrumentedHandler handler = new InstrumentedHandler(registry, null, ALL); -+ handler.setHandler(new TestHandler()); -+ -+ assertThatCode(handler::doStop).doesNotThrowAnyException(); -+ } -+ -+ @Test -+ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { -+ InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); -+ handler.setHandler(new TestHandler()); -+ handler.setName("handler"); -+ handler.doStart(); -+ assertThat(registry.getGauges()) -+ .containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); -+ } -+ -+ @Test -+ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { -+ InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); -+ handler.setHandler(new TestHandler()); -+ handler.setName("handler"); -+ handler.doStart(); -+ assertThat(registry.getGauges()) -+ .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); -+ } -+ -+ @Disabled("flaky on virtual machines") -+ @Test -+ void responseTimesAreRecordedForAsyncResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/async")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ -+ assertResponseTimesValid(); -+ } -+ -+ private void assertResponseTimesValid() { -+ assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) -+ .isPositive(); -+ -+ assertThat( -+ registry -+ .getTimers() -+ .get(metricName().resolve("get-requests")) -+ .getSnapshot() -+ .getMedian()) -+ .isPositive() -+ .isLessThan(TimeUnit.SECONDS.toNanos(1)); -+ -+ assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) -+ .isPositive() -+ .isLessThan(TimeUnit.SECONDS.toNanos(1)); -+ } -+ -+ private String uri(String path) { -+ return "http://localhost:" + connector.getLocalPort() + path; -+ } -+ -+ private MetricName metricName() { -+ return MetricRegistry.name(TestHandler.class.getName(), "handler"); -+ } -+ -+ /** -+ * test handler. -+ * -+ *

    Supports -+ * -+ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the -+ * request -+ * -+ *

    all other requests will return 404 -+ */ -+ private static class TestHandler extends AbstractHandler { -+ @Override -+ public void handle( -+ String path, -+ Request request, -+ final HttpServletRequest httpServletRequest, -+ final HttpServletResponse httpServletResponse) -+ throws IOException, ServletException { -+ switch (path) { -+ case "/blocking": -+ request.setHandled(true); -+ try { -+ Thread.sleep(100); -+ } catch (InterruptedException e) { -+ Thread.currentThread().interrupt(); -+ } -+ httpServletResponse.setStatus(200); -+ httpServletResponse.setContentType("text/plain"); -+ httpServletResponse.getWriter().write("some content from the blocking request\n"); -+ break; -+ case "/async": -+ request.setHandled(true); -+ final AsyncContext context = request.startAsync(); -+ Thread t = -+ new Thread( -+ () -> { - try { -- Thread.sleep(100); -+ Thread.sleep(100); - } catch (InterruptedException e) { -- Thread.currentThread().interrupt(); -+ Thread.currentThread().interrupt(); - } - httpServletResponse.setStatus(200); - httpServletResponse.setContentType("text/plain"); -- httpServletResponse.getWriter().write("some content from the blocking request\n"); -- break; -- case "/async": -- request.setHandled(true); -- final AsyncContext context = request.startAsync(); -- Thread t = new Thread(() -> { -- try { -- Thread.sleep(100); -- } catch (InterruptedException e) { -- Thread.currentThread().interrupt(); -- } -- httpServletResponse.setStatus(200); -- httpServletResponse.setContentType("text/plain"); -- final ServletOutputStream servletOutputStream; -- try { -- servletOutputStream = httpServletResponse.getOutputStream(); -- servletOutputStream.setWriteListener( -- new WriteListener() { -- @Override -- public void onWritePossible() throws IOException { -- servletOutputStream.write("some content from the async\n" -- .getBytes(StandardCharsets.UTF_8)); -- context.complete(); -- } -- -- @Override -- public void onError(Throwable throwable) { -- context.complete(); -- } -- } -- ); -- } catch (IOException e) { -- context.complete(); -- } -- }); -- t.start(); -- break; -- default: -- break; -- } -- } -+ final ServletOutputStream servletOutputStream; -+ try { -+ servletOutputStream = httpServletResponse.getOutputStream(); -+ servletOutputStream.setWriteListener( -+ new WriteListener() { -+ @Override -+ public void onWritePossible() throws IOException { -+ servletOutputStream.write( -+ "some content from the async\n".getBytes(UTF_8)); -+ context.complete(); -+ } -+ -+ @Override -+ public void onError(Throwable throwable) { -+ context.complete(); -+ } -+ }); -+ } catch (IOException e) { -+ context.complete(); -+ } -+ }); -+ t.start(); -+ break; -+ default: -+ break; -+ } - } -+ } - } ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.jetty11; - -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import jakarta.servlet.AsyncContext; -@@ -7,6 +11,7 @@ import jakarta.servlet.ServletOutputStream; - import jakarta.servlet.WriteListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; -+import java.io.IOException; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; - import org.eclipse.jetty.server.Request; -@@ -17,197 +22,190 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; +-class SimpleSettableGaugeTest { ++final class SimpleSettableGaugeTest { + + @Test + void defaultValue() { +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java +@@ -3,7 +3,6 @@ package io.dropwizard.metrics5; + import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; +@@ -20,11 +19,11 @@ import org.junit.jupiter.api.Test; + import org.slf4j.Logger; + import org.slf4j.Marker; + +-class Slf4jReporterTest { ++final class Slf4jReporterTest { + +- private final Logger logger = mock(Logger.class); +- private final Marker marker = mock(Marker.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final Logger logger = mock(); ++ private final Marker marker = mock(); ++ private final MetricRegistry registry = mock(); + + /** + * The set of disabled metric attributes to pass to the Slf4jReporter builder in the default +@@ -79,7 +78,7 @@ class Slf4jReporterTest { + } + + private Timer timer() { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + + when(timer.getMeanRate()).thenReturn(2.0); +@@ -87,7 +86,7 @@ class Slf4jReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -104,10 +103,10 @@ class Slf4jReporterTest { + } + + private Histogram histogram() { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -124,7 +123,7 @@ class Slf4jReporterTest { + } + + private Meter meter() { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -134,7 +133,7 @@ class Slf4jReporterTest { + } + + private Counter counter() { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + return counter; + } +@@ -168,7 +167,7 @@ class Slf4jReporterTest { + + @Test + void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); ++ disabledMetricAttributes = EnumSet.of(COUNT, MetricAttribute.MIN, P50); + reportsHistogramValuesAtError( + "type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " + + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); +@@ -192,7 +191,7 @@ class Slf4jReporterTest { + + @Test + void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, P50, M1_RATE); + reportsMeterValuesAtError( + "type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " + + "mean_rate=2.0, rate_unit=events/second"); +@@ -218,7 +217,7 @@ class Slf4jReporterTest { + + @Test + void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, STDDEV, P999, MEAN_RATE); + reportsTimerValuesAtError( + "type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " + + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java +@@ -12,11 +12,11 @@ import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Test; --import java.io.IOException; --import java.nio.charset.StandardCharsets; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static org.assertj.core.api.Assertions.assertThat; -- --class InstrumentedHttpChannelListenerTest { -- private final HttpClient client = new HttpClient(); -- private final Server server = new Server(); -- private final ServerConnector connector = new ServerConnector(server); -- private final TestHandler handler = new TestHandler(); -- private MetricRegistry registry; -- -- @BeforeEach -- void setUp() throws Exception { -- registry = new MetricRegistry(); -- connector.addBean(new InstrumentedHttpChannelListener(registry, MetricRegistry.name(TestHandler.class, "handler"), ALL)); -- server.addConnector(connector); -- server.setHandler(handler); -- server.start(); -- client.start(); -+final class InstrumentedHttpChannelListenerTest { -+ private final HttpClient client = new HttpClient(); -+ private final Server server = new Server(); -+ private final ServerConnector connector = new ServerConnector(server); -+ private final TestHandler handler = new TestHandler(); -+ private MetricRegistry registry; -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ registry = new MetricRegistry(); -+ connector.addBean( -+ new InstrumentedHttpChannelListener( -+ registry, MetricRegistry.name(TestHandler.class, "handler"), ALL)); -+ server.addConnector(connector); -+ server.setHandler(handler); -+ server.start(); -+ client.start(); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ server.stop(); -+ client.stop(); -+ } -+ -+ @Test -+ void createsMetricsForTheHandler() throws Exception { -+ final ContentResponse response = client.GET(uri("/hello")); -+ -+ assertThat(response.getStatus()).isEqualTo(404); -+ -+ assertThat(registry.getNames()) -+ .containsOnly( -+ metricName("1xx-responses"), -+ metricName("2xx-responses"), -+ metricName("3xx-responses"), -+ metricName("404-responses"), -+ metricName("4xx-responses"), -+ metricName("5xx-responses"), -+ metricName("percent-4xx-1m"), -+ metricName("percent-4xx-5m"), -+ metricName("percent-4xx-15m"), -+ metricName("percent-5xx-1m"), -+ metricName("percent-5xx-5m"), -+ metricName("percent-5xx-15m"), -+ metricName("requests"), -+ metricName("active-suspended"), -+ metricName("async-dispatches"), -+ metricName("async-timeouts"), -+ metricName("get-requests"), -+ metricName("put-requests"), -+ metricName("active-dispatches"), -+ metricName("trace-requests"), -+ metricName("other-requests"), -+ metricName("connect-requests"), -+ metricName("dispatches"), -+ metricName("head-requests"), -+ metricName("post-requests"), -+ metricName("options-requests"), -+ metricName("active-requests"), -+ metricName("delete-requests"), -+ metricName("move-requests")); -+ } -+ -+ @Test -+ void responseTimesAreRecordedForBlockingResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/blocking")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.getMediaType()).isEqualTo("text/plain"); -+ assertThat(response.getContentAsString()).isEqualTo("some content from the blocking request"); -+ -+ assertResponseTimesValid(); -+ } -+ -+ @Test -+ void responseTimesAreRecordedForAsyncResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/async")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.getMediaType()).isEqualTo("text/plain"); -+ assertThat(response.getContentAsString()).isEqualTo("some content from the async"); -+ -+ assertResponseTimesValid(); -+ } -+ -+ private void assertResponseTimesValid() { -+ try { -+ Thread.sleep(100); -+ } catch (InterruptedException e) { -+ Thread.currentThread().interrupt(); - } + @SuppressWarnings("Duplicates") +-class SlidingTimeWindowArrayReservoirTest { ++final class SlidingTimeWindowArrayReservoirTest { -- @AfterEach -- void tearDown() throws Exception { -- server.stop(); -- client.stop(); -- } -- -- @Test -- void createsMetricsForTheHandler() throws Exception { -- final ContentResponse response = client.GET(uri("/hello")); -- -- assertThat(response.getStatus()) -- .isEqualTo(404); -- -- assertThat(registry.getNames()) -- .containsOnly( -- metricName("1xx-responses"), -- metricName("2xx-responses"), -- metricName("3xx-responses"), -- metricName("404-responses"), -- metricName("4xx-responses"), -- metricName("5xx-responses"), -- metricName("percent-4xx-1m"), -- metricName("percent-4xx-5m"), -- metricName("percent-4xx-15m"), -- metricName("percent-5xx-1m"), -- metricName("percent-5xx-5m"), -- metricName("percent-5xx-15m"), -- metricName("requests"), -- metricName("active-suspended"), -- metricName("async-dispatches"), -- metricName("async-timeouts"), -- metricName("get-requests"), -- metricName("put-requests"), -- metricName("active-dispatches"), -- metricName("trace-requests"), -- metricName("other-requests"), -- metricName("connect-requests"), -- metricName("dispatches"), -- metricName("head-requests"), -- metricName("post-requests"), -- metricName("options-requests"), -- metricName("active-requests"), -- metricName("delete-requests"), -- metricName("move-requests") -- ); -- } -- -- -- @Test -- void responseTimesAreRecordedForBlockingResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/blocking")); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.getMediaType()).isEqualTo("text/plain"); -- assertThat(response.getContentAsString()).isEqualTo("some content from the blocking request"); -- -- assertResponseTimesValid(); -- } -- -- @Test -- void responseTimesAreRecordedForAsyncResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/async")); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.getMediaType()).isEqualTo("text/plain"); -- assertThat(response.getContentAsString()).isEqualTo("some content from the async"); -- -- assertResponseTimesValid(); -- } -- -- private void assertResponseTimesValid() { -- try { -+ assertThat(registry.getMeters().get(metricName("2xx-responses")).getCount()).isPositive(); -+ assertThat(registry.getMeters().get(metricName("200-responses")).getCount()).isPositive(); -+ -+ assertThat(registry.getTimers().get(metricName("get-requests")).getSnapshot().getMedian()) -+ .isPositive(); -+ -+ assertThat(registry.getTimers().get(metricName("requests")).getSnapshot().getMedian()) -+ .isPositive(); -+ } -+ -+ private String uri(String path) { -+ return "http://localhost:" + connector.getLocalPort() + path; -+ } -+ -+ private MetricName metricName(String metricName) { -+ return MetricRegistry.name(TestHandler.class.getName(), "handler", metricName); -+ } -+ -+ /** -+ * test handler. -+ * -+ *

    Supports -+ * -+ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the -+ * request -+ * -+ *

    all other requests will return 404 -+ */ -+ private static class TestHandler extends AbstractHandler { -+ @Override -+ public void handle( -+ String path, -+ Request request, -+ final HttpServletRequest httpServletRequest, -+ final HttpServletResponse httpServletResponse) -+ throws IOException { -+ switch (path) { -+ case "/blocking": -+ request.setHandled(true); -+ httpServletResponse.setStatus(200); -+ httpServletResponse.setContentType("text/plain"); -+ httpServletResponse.getWriter().write("some content from the blocking request"); -+ try { - Thread.sleep(100); -- } catch (InterruptedException e) { -+ } catch (InterruptedException e) { -+ httpServletResponse.setStatus(500); - Thread.currentThread().interrupt(); -- } -- -- assertThat(registry.getMeters().get(metricName("2xx-responses")) -- .getCount()).isPositive(); -- assertThat(registry.getMeters().get(metricName("200-responses")) -- .getCount()).isPositive(); -- -- assertThat(registry.getTimers().get(metricName("get-requests")) -- .getSnapshot().getMedian()).isPositive(); -- -- assertThat(registry.getTimers().get(metricName("requests")) -- .getSnapshot().getMedian()).isPositive(); -- } -- -- private String uri(String path) { -- return "http://localhost:" + connector.getLocalPort() + path; -- } -- -- private MetricName metricName(String metricName) { -- return MetricRegistry.name(TestHandler.class.getName(), "handler", metricName); -- } -- -- /** -- * test handler. -- *

    -- * Supports -- *

    -- * /blocking - uses the standard servlet api -- * /async - uses the 3.1 async api to complete the request -- *

    -- * all other requests will return 404 -- */ -- private static class TestHandler extends AbstractHandler { -- @Override -- public void handle( -- String path, -- Request request, -- final HttpServletRequest httpServletRequest, -- final HttpServletResponse httpServletResponse) throws IOException { -- switch (path) { -- case "/blocking": -- request.setHandled(true); -+ } -+ break; -+ case "/async": -+ request.setHandled(true); -+ final AsyncContext context = request.startAsync(); -+ Thread t = -+ new Thread( -+ () -> { - httpServletResponse.setStatus(200); - httpServletResponse.setContentType("text/plain"); -- httpServletResponse.getWriter().write("some content from the blocking request"); - try { -- Thread.sleep(100); -+ Thread.sleep(100); - } catch (InterruptedException e) { -- httpServletResponse.setStatus(500); -- Thread.currentThread().interrupt(); -+ httpServletResponse.setStatus(500); -+ Thread.currentThread().interrupt(); -+ } -+ final ServletOutputStream servletOutputStream; -+ try { -+ servletOutputStream = httpServletResponse.getOutputStream(); -+ servletOutputStream.setWriteListener( -+ new WriteListener() { -+ @Override -+ public void onWritePossible() throws IOException { -+ servletOutputStream.write( -+ "some content from the async".getBytes(UTF_8)); -+ context.complete(); -+ } -+ -+ @Override -+ public void onError(Throwable throwable) { -+ context.complete(); -+ } -+ }); -+ } catch (IOException e) { -+ context.complete(); - } -- break; -- case "/async": -- request.setHandled(true); -- final AsyncContext context = request.startAsync(); -- Thread t = new Thread(() -> { -- httpServletResponse.setStatus(200); -- httpServletResponse.setContentType("text/plain"); -- try { -- Thread.sleep(100); -- } catch (InterruptedException e) { -- httpServletResponse.setStatus(500); -- Thread.currentThread().interrupt(); -- } -- final ServletOutputStream servletOutputStream; -- try { -- servletOutputStream = httpServletResponse.getOutputStream(); -- servletOutputStream.setWriteListener( -- new WriteListener() { -- @Override -- public void onWritePossible() throws IOException { -- servletOutputStream.write("some content from the async" -- .getBytes(StandardCharsets.UTF_8)); -- context.complete(); -- } -- -- @Override -- public void onError(Throwable throwable) { -- context.complete(); -- } -- } -- ); -- } catch (IOException e) { -- context.complete(); -- } -- }); -- t.start(); -- break; -- default: -- break; -- } -- } -+ }); -+ t.start(); -+ break; -+ default: -+ break; -+ } - } -+ } - } ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java -@@ -1,52 +1,52 @@ - package io.dropwizard.metrics5.jetty11; + @Test + void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import org.eclipse.jetty.util.thread.QueuedThreadPool; +@@ -30,7 +30,7 @@ class SlidingTimeWindowArrayReservoirTest { + + @Test + void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); + +@@ -82,7 +82,7 @@ class SlidingTimeWindowArrayReservoirTest { + } + + @Test +- void testGetTickOverflow() { ++ void getTickOverflow() { + final Random random = new Random(0); + final int window = 128; + AtomicLong counter = new AtomicLong(0L); +@@ -99,7 +99,7 @@ class SlidingTimeWindowArrayReservoirTest { + // Set the clock to overflow in (2*window+1)ns + final ManualClock clock = new ManualClock(); + clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); ++ assertThat(clock.getTick() * 256).isPositive(); + + // Create the reservoir + final SlidingTimeWindowArrayReservoir reservoir = +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java +@@ -7,7 +7,7 @@ import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; -- --class InstrumentedQueuedThreadPoolTest { -- private static final String PREFIX = "prefix"; -- -- private MetricRegistry metricRegistry; -- private InstrumentedQueuedThreadPool iqtp; -- -- @BeforeEach -- void setUp() { -- metricRegistry = new MetricRegistry(); -- iqtp = new InstrumentedQueuedThreadPool(metricRegistry); -- } -- -- @Test -- void customMetricsPrefix() throws Exception { -- iqtp.setPrefix(PREFIX); -- iqtp.start(); -- -- assertThat(metricRegistry.getNames()) -- .extracting(MetricName::getKey) -- .overridingErrorMessage("Custom metrics prefix doesn't match") -- .allSatisfy(name -> assertThat(name).startsWith(PREFIX)); -- -- iqtp.stop(); -- assertThat(metricRegistry.getMetrics()) -- .overridingErrorMessage("The default metrics prefix was changed") -- .isEmpty(); -- } -- -- @Test -- void metricsPrefixBackwardCompatible() throws Exception { -- iqtp.start(); -- assertThat(metricRegistry.getNames()) -- .extracting(MetricName::getKey) -- .overridingErrorMessage("The default metrics prefix was changed") -- .allSatisfy(name -> assertThat(name).startsWith(QueuedThreadPool.class.getName())); -- -- iqtp.stop(); -- assertThat(metricRegistry.getMetrics()) -- .overridingErrorMessage("The default metrics prefix was changed") -- .isEmpty(); -- } -+final class InstrumentedQueuedThreadPoolTest { -+ private static final String PREFIX = "prefix"; -+ -+ private MetricRegistry metricRegistry; -+ private InstrumentedQueuedThreadPool iqtp; -+ -+ @BeforeEach -+ void setUp() { -+ metricRegistry = new MetricRegistry(); -+ iqtp = new InstrumentedQueuedThreadPool(metricRegistry); -+ } -+ -+ @Test -+ void customMetricsPrefix() throws Exception { -+ iqtp.setPrefix(PREFIX); -+ iqtp.start(); -+ -+ assertThat(metricRegistry.getNames()) -+ .extracting(MetricName::getKey) -+ .overridingErrorMessage("Custom metrics prefix doesn't match") -+ .allSatisfy(name -> assertThat(name).startsWith(PREFIX)); -+ -+ iqtp.stop(); -+ assertThat(metricRegistry.getMetrics()) -+ .overridingErrorMessage("The default metrics prefix was changed") -+ .isEmpty(); -+ } -+ -+ @Test -+ void metricsPrefixBackwardCompatible() throws Exception { -+ iqtp.start(); -+ assertThat(metricRegistry.getNames()) -+ .extracting(MetricName::getKey) -+ .overridingErrorMessage("The default metrics prefix was changed") -+ .allSatisfy(name -> assertThat(name).startsWith(QueuedThreadPool.class.getName())); -+ -+ iqtp.stop(); -+ assertThat(metricRegistry.getMetrics()) -+ .overridingErrorMessage("The default metrics prefix was changed") -+ .isEmpty(); -+ } - } ---- a/metrics-jetty12-ee10/src/main/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10Handler.java -+++ b/metrics-jetty12-ee10/src/main/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10Handler.java -@@ -1,10 +1,14 @@ - package io.dropwizard.metrics.jetty12.ee10; +-class SlidingTimeWindowMovingAveragesTest { ++final class SlidingTimeWindowMovingAveragesTest { -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+ -+import io.dropwizard.metrics.jetty12.AbstractInstrumentedHandler; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; --import io.dropwizard.metrics.jetty12.AbstractInstrumentedHandler; - import jakarta.servlet.AsyncEvent; - import jakarta.servlet.AsyncListener; -+import java.io.IOException; -+import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.ee10.servlet.AsyncContextState; - import org.eclipse.jetty.ee10.servlet.ServletApiRequest; - import org.eclipse.jetty.ee10.servlet.ServletApiResponse; -@@ -15,162 +19,160 @@ import org.eclipse.jetty.server.Request; - import org.eclipse.jetty.server.Response; - import org.eclipse.jetty.util.Callback; - --import java.io.IOException; --import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -- - /** - * A Jetty {@link Handler} which records various metrics about an underlying {@link Handler} -- * instance. This {@link Handler} requires a {@link org.eclipse.jetty.ee10.servlet.ServletContextHandler} to be present. -- * For correct behaviour, the {@link org.eclipse.jetty.ee10.servlet.ServletContextHandler} should be before this handler -- * in the handler chain. To achieve this, one can use -- * {@link org.eclipse.jetty.ee10.servlet.ServletContextHandler#insertHandler(Singleton)}. -+ * instance. This {@link Handler} requires a {@link -+ * org.eclipse.jetty.ee10.servlet.ServletContextHandler} to be present. For correct behaviour, the -+ * {@link org.eclipse.jetty.ee10.servlet.ServletContextHandler} should be before this handler in the -+ * handler chain. To achieve this, one can use {@link -+ * org.eclipse.jetty.ee10.servlet.ServletContextHandler#insertHandler(Singleton)}. - */ - public class InstrumentedEE10Handler extends AbstractInstrumentedHandler { -- private AsyncListener listener; -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- */ -- public InstrumentedEE10Handler(MetricRegistry registry) { -- super(registry, null); -+ private AsyncListener listener; -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ */ -+ public InstrumentedEE10Handler(MetricRegistry registry) { -+ super(registry, null); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param prefix the prefix to use for the metrics names -+ */ -+ public InstrumentedEE10Handler(MetricRegistry registry, String prefix) { -+ super(registry, prefix, COARSE); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param prefix the prefix to use for the metrics names -+ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are -+ * instrumented -+ */ -+ public InstrumentedEE10Handler( -+ MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { -+ super(registry, prefix, responseMeteredLevel); -+ } -+ -+ @Override -+ protected void doStart() throws Exception { -+ super.doStart(); -+ -+ this.listener = new AsyncAttachingListener(); -+ } -+ -+ @Override -+ protected void doStop() throws Exception { -+ super.doStop(); -+ } -+ -+ @Override -+ public boolean handle(Request request, Response response, Callback callback) throws Exception { -+ ServletContextRequest servletContextRequest = Request.as(request, ServletContextRequest.class); -+ -+ // only handle servlet requests with the InstrumentedHandler -+ // because it depends on the ServletRequestState -+ if (servletContextRequest == null) { -+ return super.handle(request, response, callback); + private ManualClock clock; + private SlidingTimeWindowMovingAverages movingAverages; +@@ -42,7 +42,7 @@ class SlidingTimeWindowMovingAveragesTest { + + SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); + +- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(0L))).isEqualTo(0); ++ assertThat(stwm.calculateIndexOfTick(Instant.EPOCH)).isEqualTo(0); + assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L))).isEqualTo(1); + } + +@@ -60,7 +60,7 @@ class SlidingTimeWindowMovingAveragesTest { } -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param prefix the prefix to use for the metrics names -- */ -- public InstrumentedEE10Handler(MetricRegistry registry, String prefix) { -- super(registry, prefix, COARSE); -+ activeDispatches.inc(); -+ -+ final long start; -+ final ServletChannelState state = servletContextRequest.getServletRequestState(); -+ if (state.isInitial()) { -+ // new request -+ activeRequests.inc(); -+ start = Request.getTimeStamp(request); -+ state.addListener(listener); -+ } else { -+ // resumed request -+ start = System.currentTimeMillis(); -+ activeSuspended.dec(); -+ if (state.getState() == ServletChannelState.State.HANDLING) { -+ asyncDispatches.mark(); -+ } - } + // verify that no cleanup happened yet +- assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.ofEpochSecond(0L)); ++ assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.EPOCH); + + assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); + assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java +@@ -9,10 +9,10 @@ import java.util.Arrays; + import java.util.Random; + import org.junit.jupiter.api.Test; + +-class SlidingTimeWindowReservoirTest { ++final class SlidingTimeWindowReservoirTest { + @Test + void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowReservoir reservoir = + new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); + +@@ -26,7 +26,7 @@ class SlidingTimeWindowReservoirTest { + + @Test + void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + when(clock.getTick()).thenReturn(0L); + + final SlidingTimeWindowReservoir reservoir = +@@ -51,7 +51,7 @@ class SlidingTimeWindowReservoirTest { + } + + @Test +- void testGetTickOverflow() { ++ void getTickOverflow() { + final Random random = new Random(0); + final int window = 128; + +@@ -72,7 +72,7 @@ class SlidingTimeWindowReservoirTest { + + // Set the clock to overflow in (2*window+1)ns + clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); ++ assertThat(clock.getTick() * 256).isPositive(); + + int updatesAfterThreshold = 0; + while (true) { +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-class SlidingWindowReservoirTest { ++final class SlidingWindowReservoirTest { + private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); + + @Test +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java +@@ -12,8 +12,8 @@ import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicBoolean; + import org.junit.jupiter.api.Test; + +-class TimerTest { +- private final Reservoir reservoir = mock(Reservoir.class); ++final class TimerTest { ++ private final Reservoir reservoir = mock(); + private final Clock clock = + new Clock() { + // a mock clock that increments its ticker by 50msec per call +@@ -28,23 +28,23 @@ class TimerTest { + + @Test + void hasRates() { +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + +- assertThat(timer.getSum()).isZero(); ++ assertThat(timer.getSum()).isEqualTo(0); + +- assertThat(timer.getMeanRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param prefix the prefix to use for the metrics names -- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented -- */ -- public InstrumentedEE10Handler(MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { -- super(registry, prefix, responseMeteredLevel); -- } -+ boolean handled = false; - -- @Override -- protected void doStart() throws Exception { -- super.doStart(); -+ try { -+ handled = super.handle(request, response, callback); -+ } finally { -+ final long now = System.currentTimeMillis(); -+ final long dispatched = now - start; - -- this.listener = new AsyncAttachingListener(); -+ activeDispatches.dec(); -+ dispatches.update(dispatched, TimeUnit.MILLISECONDS); -+ -+ if (state.isSuspended()) { -+ activeSuspended.inc(); -+ } else if (state.isInitial()) { -+ updateResponses(request, response, start, handled); -+ } -+ // else onCompletion will handle it. - } +- assertThat(timer.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); + } -+ return handled; -+ } -+ -+ private class AsyncAttachingListener implements AsyncListener { -+ - @Override -- protected void doStop() throws Exception { -- super.doStop(); -- } -+ public void onTimeout(AsyncEvent event) throws IOException {} + @Test + void updatesTheCountAndSumOnUpdates() { +- assertThat(timer.getCount()).isZero(); +- assertThat(timer.getSum()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); ++ assertThat(timer.getSum()).isEqualTo(0); - @Override -- public boolean handle(Request request, Response response, Callback callback) throws Exception { -- ServletContextRequest servletContextRequest = Request.as(request, ServletContextRequest.class); -- -- // only handle servlet requests with the InstrumentedHandler -- // because it depends on the ServletRequestState -- if (servletContextRequest == null) { -- return super.handle(request, response, callback); -- } -- -- activeDispatches.inc(); -- -- final long start; -- final ServletChannelState state = servletContextRequest.getServletRequestState(); -- if (state.isInitial()) { -- // new request -- activeRequests.inc(); -- start = Request.getTimeStamp(request); -- state.addListener(listener); -- } else { -- // resumed request -- start = System.currentTimeMillis(); -- activeSuspended.dec(); -- if (state.getState() == ServletChannelState.State.HANDLING) { -- asyncDispatches.mark(); -- } -- } -- -- boolean handled = false; -- -- try { -- handled = super.handle(request, response, callback); -- } finally { -- final long now = System.currentTimeMillis(); -- final long dispatched = now - start; -- -- activeDispatches.dec(); -- dispatches.update(dispatched, TimeUnit.MILLISECONDS); -- -- if (state.isSuspended()) { -- activeSuspended.inc(); -- } else if (state.isInitial()) { -- updateResponses(request, response, start, handled); -- } -- // else onCompletion will handle it. -- } -- -- return handled; -+ public void onStartAsync(AsyncEvent event) throws IOException { -+ event.getAsyncContext().addListener(new InstrumentedAsyncListener()); - } + timer.update(1, TimeUnit.SECONDS); + timer.update(5, TimeUnit.SECONDS); +@@ -101,7 +101,7 @@ class TimerTest { -- private class AsyncAttachingListener implements AsyncListener { -+ @Override -+ public void onError(AsyncEvent event) throws IOException {} + @Test + void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(reservoir.getSnapshot()).thenReturn(snapshot); -- @Override -- public void onTimeout(AsyncEvent event) throws IOException {} -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException {} -+ } + assertThat(timer.getSnapshot()).isEqualTo(snapshot); +@@ -111,8 +111,8 @@ class TimerTest { + void ignoresNegativeValues() { + timer.update(-1, TimeUnit.SECONDS); -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- event.getAsyncContext().addListener(new InstrumentedAsyncListener()); -- } -+ private class InstrumentedAsyncListener implements AsyncListener { -+ private final long startTime; - -- @Override -- public void onError(AsyncEvent event) throws IOException {} -+ InstrumentedAsyncListener() { -+ this.startTime = System.currentTimeMillis(); -+ } - -- @Override -- public void onComplete(AsyncEvent event) throws IOException {} -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException { -+ asyncTimeouts.mark(); - } +- assertThat(timer.getCount()).isZero(); +- assertThat(timer.getSum()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); ++ assertThat(timer.getSum()).isEqualTo(0); -- private class InstrumentedAsyncListener implements AsyncListener { -- private final long startTime; -- -- InstrumentedAsyncListener() { -- this.startTime = System.currentTimeMillis(); -- } -- -- @Override -- public void onTimeout(AsyncEvent event) throws IOException { -- asyncTimeouts.mark(); -- } -- -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -- } -- -- @Override -- public void onError(AsyncEvent event) throws IOException { -- } -- -- @Override -- public void onComplete(AsyncEvent event) throws IOException { -- final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -- final ServletApiRequest request = (ServletApiRequest) state.getRequest(); -- final ServletApiResponse response = (ServletApiResponse) state.getResponse(); -- updateResponses(request.getRequest(), response.getResponse(), startTime, true); -- -- final ServletContextRequest servletContextRequest = Request.as(request.getRequest(), ServletContextRequest.class); -- final ServletChannelState servletRequestState = servletContextRequest.getServletRequestState(); -- if (!servletRequestState.isSuspended()) { -- activeSuspended.dec(); -- } -- } -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException {} -+ -+ @Override -+ public void onError(AsyncEvent event) throws IOException {} -+ -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException { -+ final AsyncContextState state = (AsyncContextState) event.getAsyncContext(); -+ final ServletApiRequest request = (ServletApiRequest) state.getRequest(); -+ final ServletApiResponse response = (ServletApiResponse) state.getResponse(); -+ updateResponses(request.getRequest(), response.getResponse(), startTime, true); -+ -+ final ServletContextRequest servletContextRequest = -+ Request.as(request.getRequest(), ServletContextRequest.class); -+ final ServletChannelState servletRequestState = -+ servletContextRequest.getServletRequestState(); -+ if (!servletRequestState.isSuspended()) { -+ activeSuspended.dec(); -+ } - } -+ } - } ---- a/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java -+++ b/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java -@@ -1,7 +1,21 @@ - package io.dropwizard.metrics.jetty12.ee10; + verifyNoInteractions(reservoir); + } +@@ -130,15 +130,15 @@ class TimerTest { + void java8NegativeDuration() { + timer.update(Duration.ofMillis(-5678)); + +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + verifyNoInteractions(reservoir); + } + + @Test + void tryWithResourcesWork() { +- assertThat(timer.getCount()).isZero(); +- assertThat(timer.getSum()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); ++ assertThat(timer.getSum()).isEqualTo(0); + + int dummy = 0; + try (Timer.Context context = timer.time()) { +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java +@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.nio.charset.StandardCharsets.UTF_8; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatCode; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; -+import jakarta.servlet.AsyncContext; -+import jakarta.servlet.ServletOutputStream; -+import jakarta.servlet.WriteListener; -+import jakarta.servlet.http.HttpServletRequest; -+import jakarta.servlet.http.HttpServletResponse; -+import java.io.IOException; -+import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.client.ContentResponse; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.ee10.servlet.DefaultServlet; -@@ -13,262 +27,251 @@ import org.eclipse.jetty.server.Response; - import org.eclipse.jetty.server.Server; - import org.eclipse.jetty.server.ServerConnector; - import org.eclipse.jetty.util.Callback; -- --import jakarta.servlet.AsyncContext; --import jakarta.servlet.ServletOutputStream; --import jakarta.servlet.WriteListener; --import jakarta.servlet.http.HttpServletRequest; --import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; --import java.io.IOException; --import java.nio.charset.StandardCharsets; --import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatCode; -- --public class InstrumentedEE10HandlerTest { -- private final HttpClient client = new HttpClient(); -- private final MetricRegistry registry = new MetricRegistry(); -- private final Server server = new Server(); -- private final ServerConnector connector = new ServerConnector(server); -- private final InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); -- -- @BeforeEach -- public void setUp() throws Exception { -- handler.setName("handler"); -- -- TestHandler testHandler = new TestHandler(); -- // a servlet handler needs a servlet mapping, else the request will be short-circuited -- // so use the DefaultServlet here -- testHandler.addServletWithMapping(DefaultServlet.class, "/"); -- -- // builds the following handler chain: -- // ServletContextHandler -> InstrumentedHandler -> TestHandler -- // the ServletContextHandler is needed to utilize servlet related classes -- ServletContextHandler servletContextHandler = new ServletContextHandler(); -- servletContextHandler.setHandler(testHandler); -- servletContextHandler.insertHandler(handler); -- server.setHandler(servletContextHandler); -- -- server.addConnector(connector); -- server.start(); -- client.start(); -- } -- -- @AfterEach -- public void tearDown() throws Exception { -- server.stop(); -- client.stop(); -- } -- -- @Test -- public void hasAName() throws Exception { -- assertThat(handler.getName()) -- .isEqualTo("handler"); -- } -- -- @Test -- public void createsAndRemovesMetricsForTheHandler() throws Exception { -- final ContentResponse response = client.GET(uri("/hello")); -- -- assertThat(response.getStatus()) -- .isEqualTo(404); -- -- assertThat(registry.getNames()) -- .containsOnly( -- MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.404-responses"), -- MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), -- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), -- MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), -- MetricRegistry.name(TestHandler.class, "handler.requests"), -- MetricRegistry.name(TestHandler.class, "handler.active-suspended"), -- MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), -- MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), -- MetricRegistry.name(TestHandler.class, "handler.get-requests"), -- MetricRegistry.name(TestHandler.class, "handler.put-requests"), -- MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), -- MetricRegistry.name(TestHandler.class, "handler.trace-requests"), -- MetricRegistry.name(TestHandler.class, "handler.other-requests"), -- MetricRegistry.name(TestHandler.class, "handler.connect-requests"), -- MetricRegistry.name(TestHandler.class, "handler.dispatches"), -- MetricRegistry.name(TestHandler.class, "handler.head-requests"), -- MetricRegistry.name(TestHandler.class, "handler.post-requests"), -- MetricRegistry.name(TestHandler.class, "handler.options-requests"), -- MetricRegistry.name(TestHandler.class, "handler.active-requests"), -- MetricRegistry.name(TestHandler.class, "handler.delete-requests"), -- MetricRegistry.name(TestHandler.class, "handler.move-requests") -- ); -- -- server.stop(); -- -- assertThat(registry.getNames()) -- .isEmpty(); -- } -- -- @Test -- @Disabled("flaky on virtual machines") -- public void responseTimesAreRecordedForBlockingResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/blocking")); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- -- assertResponseTimesValid(); -- } -- -- @Test -- public void doStopDoesNotThrowNPE() throws Exception { -- InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); -- handler.setHandler(new TestHandler()); -- -- assertThatCode(handler::doStop).doesNotThrowAnyException(); -- } -- -- @Test -- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { -- InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "coarse", COARSE); -- handler.setHandler(new TestHandler()); -- handler.setName("handler"); -- handler.doStart(); -- assertThat(registry.getGauges()).containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); -- } -- -- @Test -- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { -- InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "detailed", DETAILED); -- handler.setHandler(new TestHandler()); -- handler.setName("handler"); -- handler.doStart(); -- assertThat(registry.getGauges()).doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); -- } -- -- @Test -- @Disabled("flaky on virtual machines") -- public void responseTimesAreRecordedForAsyncResponses() throws Exception { -- -- final ContentResponse response = client.GET(uri("/async")); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- -- assertResponseTimesValid(); -- } -- -- private void assertResponseTimesValid() { -- assertThat(registry.getMeters().get(metricName().resolve("2xx-responses")) -- .getCount()).isGreaterThan(0L); -- assertThat(registry.getMeters().get(metricName().resolve(".200-responses")) -- .getCount()).isGreaterThan(0L); -- -- -- assertThat(registry.getTimers().get(metricName().resolve(".get-requests")) -- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); -- -- assertThat(registry.getTimers().get(metricName().resolve(".requests")) -- .getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1)); -- } -- -- private String uri(String path) { -- return "http://localhost:" + connector.getLocalPort() + path; -- } -- -- private MetricName metricName() { -- return MetricRegistry.name(TestHandler.class.getName(), "handler"); -- } -- -- /** -- * test handler. -- *

    -- * Supports -- *

    -- * /blocking - uses the standard servlet api -- * /async - uses the 3.1 async api to complete the request -- *

    -- * all other requests will return 404 -- */ -- private static class TestHandler extends ServletHandler { -- @Override -- public boolean handle(Request request, Response response, Callback callback) throws Exception { -- ServletContextRequest servletContextRequest = Request.as(request, ServletContextRequest.class); -- if (servletContextRequest == null) { -- return false; -- } -- -- HttpServletRequest httpServletRequest = servletContextRequest.getServletApiRequest(); -- HttpServletResponse httpServletResponse = servletContextRequest.getHttpServletResponse(); -- -- String path = request.getHttpURI().getPath(); -- switch (path) { -- case "/blocking": -+final class InstrumentedEE10HandlerTest { -+ private final HttpClient client = new HttpClient(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final Server server = new Server(); -+ private final ServerConnector connector = new ServerConnector(server); -+ private final InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ handler.setName("handler"); -+ -+ TestHandler testHandler = new TestHandler(); -+ // a servlet handler needs a servlet mapping, else the request will be short-circuited -+ // so use the DefaultServlet here -+ testHandler.addServletWithMapping(DefaultServlet.class, "/"); -+ -+ // builds the following handler chain: -+ // ServletContextHandler -> InstrumentedHandler -> TestHandler -+ // the ServletContextHandler is needed to utilize servlet related classes -+ ServletContextHandler servletContextHandler = new ServletContextHandler(); -+ servletContextHandler.setHandler(testHandler); -+ servletContextHandler.insertHandler(handler); -+ server.setHandler(servletContextHandler); -+ -+ server.addConnector(connector); -+ server.start(); -+ client.start(); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ server.stop(); -+ client.stop(); -+ } -+ -+ @Test -+ void hasAName() throws Exception { -+ assertThat(handler.getName()).isEqualTo("handler"); -+ } -+ -+ @Test -+ void createsAndRemovesMetricsForTheHandler() throws Exception { -+ final ContentResponse response = client.GET(uri("/hello")); -+ -+ assertThat(response.getStatus()).isEqualTo(404); -+ -+ assertThat(registry.getNames()) -+ .containsOnly( -+ MetricRegistry.name(TestHandler.class, "handler.1xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.2xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.3xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.4xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.404-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.5xx-responses"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"), -+ MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"), -+ MetricRegistry.name(TestHandler.class, "handler.requests"), -+ MetricRegistry.name(TestHandler.class, "handler.active-suspended"), -+ MetricRegistry.name(TestHandler.class, "handler.async-dispatches"), -+ MetricRegistry.name(TestHandler.class, "handler.async-timeouts"), -+ MetricRegistry.name(TestHandler.class, "handler.get-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.put-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.active-dispatches"), -+ MetricRegistry.name(TestHandler.class, "handler.trace-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.other-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.connect-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.dispatches"), -+ MetricRegistry.name(TestHandler.class, "handler.head-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.post-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.options-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.active-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.delete-requests"), -+ MetricRegistry.name(TestHandler.class, "handler.move-requests")); -+ -+ server.stop(); -+ -+ assertThat(registry.getNames()).isEmpty(); -+ } -+ -+ @Disabled("flaky on virtual machines") -+ @Test -+ void responseTimesAreRecordedForBlockingResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/blocking")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ -+ assertResponseTimesValid(); -+ } -+ -+ @Test -+ void doStopDoesNotThrowNPE() throws Exception { -+ InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); -+ handler.setHandler(new TestHandler()); -+ -+ assertThatCode(handler::doStop).doesNotThrowAnyException(); -+ } -+ -+ @Test -+ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { -+ InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "coarse", COARSE); -+ handler.setHandler(new TestHandler()); -+ handler.setName("handler"); -+ handler.doStart(); -+ assertThat(registry.getGauges()) -+ .containsKey(MetricName.build("coarse", "handler", "percent-4xx-1m")); -+ } -+ -+ @Test -+ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { -+ InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "detailed", DETAILED); -+ handler.setHandler(new TestHandler()); -+ handler.setName("handler"); -+ handler.doStart(); -+ assertThat(registry.getGauges()) -+ .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); -+ } -+ -+ @Disabled("flaky on virtual machines") +-class UniformReservoirTest { +- @Test ++final class UniformReservoirTest { + @SuppressWarnings("unchecked") + @Test -+ void responseTimesAreRecordedForAsyncResponses() throws Exception { -+ -+ final ContentResponse response = client.GET(uri("/async")); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ -+ assertResponseTimesValid(); -+ } -+ -+ private void assertResponseTimesValid() { -+ assertThat(registry.getMeters().get(metricName().resolve("2xx-responses")).getCount()) -+ .isPositive(); -+ assertThat(registry.getMeters().get(metricName().resolve(".200-responses")).getCount()) -+ .isPositive(); -+ -+ assertThat( -+ registry -+ .getTimers() -+ .get(metricName().resolve(".get-requests")) -+ .getSnapshot() -+ .getMedian()) -+ .isPositive() -+ .isLessThan(TimeUnit.SECONDS.toNanos(1)); -+ -+ assertThat( -+ registry.getTimers().get(metricName().resolve(".requests")).getSnapshot().getMedian()) -+ .isPositive() -+ .isLessThan(TimeUnit.SECONDS.toNanos(1)); -+ } -+ -+ private String uri(String path) { -+ return "http://localhost:" + connector.getLocalPort() + path; -+ } -+ -+ private MetricName metricName() { -+ return MetricRegistry.name(TestHandler.class.getName(), "handler"); -+ } -+ -+ /** -+ * test handler. -+ * -+ *

    Supports -+ * -+ *

    /blocking - uses the standard servlet api /async - uses the 3.1 async api to complete the -+ * request -+ * -+ *

    all other requests will return 404 -+ */ -+ private static class TestHandler extends ServletHandler { -+ @Override -+ public boolean handle(Request request, Response response, Callback callback) throws Exception { -+ ServletContextRequest servletContextRequest = -+ Request.as(request, ServletContextRequest.class); -+ if (servletContextRequest == null) { -+ return false; -+ } -+ -+ HttpServletRequest httpServletRequest = servletContextRequest.getServletApiRequest(); -+ HttpServletResponse httpServletResponse = servletContextRequest.getHttpServletResponse(); -+ -+ String path = request.getHttpURI().getPath(); -+ switch (path) { -+ case "/blocking": -+ try { -+ Thread.sleep(100); -+ } catch (InterruptedException e) { -+ Thread.currentThread().interrupt(); -+ } -+ httpServletResponse.setStatus(200); -+ httpServletResponse.setContentType("text/plain"); -+ httpServletResponse.getWriter().write("some content from the blocking request\n"); -+ callback.succeeded(); -+ return true; -+ case "/async": -+ servletContextRequest.getState().handling(); -+ final AsyncContext context = httpServletRequest.startAsync(); -+ Thread t = -+ new Thread( -+ () -> { - try { -- Thread.sleep(100); -+ Thread.sleep(100); - } catch (InterruptedException e) { -- Thread.currentThread().interrupt(); -+ Thread.currentThread().interrupt(); - } - httpServletResponse.setStatus(200); - httpServletResponse.setContentType("text/plain"); -- httpServletResponse.getWriter().write("some content from the blocking request\n"); -- callback.succeeded(); -- return true; -- case "/async": -- servletContextRequest.getState().handling(); -- final AsyncContext context = httpServletRequest.startAsync(); -- Thread t = new Thread(() -> { -- try { -- Thread.sleep(100); -- } catch (InterruptedException e) { -- Thread.currentThread().interrupt(); -- } -- httpServletResponse.setStatus(200); -- httpServletResponse.setContentType("text/plain"); -- final ServletOutputStream servletOutputStream; -- try { -- servletOutputStream = httpServletResponse.getOutputStream(); -- servletOutputStream.setWriteListener( -- new WriteListener() { -- @Override -- public void onWritePossible() throws IOException { -- servletOutputStream.write("some content from the async\n" -- .getBytes(StandardCharsets.UTF_8)); -- context.complete(); -- servletContextRequest.getServletChannel().handle(); -- } -- -- @Override -- public void onError(Throwable throwable) { -- context.complete(); -- servletContextRequest.getServletChannel().handle(); -- } -- } -- ); -- servletContextRequest.getHttpOutput().run(); -- } catch (IOException e) { -- context.complete(); -- servletContextRequest.getServletChannel().handle(); -- } -- }); -- t.start(); -- return true; -- default: -- return false; -- } -- } -+ final ServletOutputStream servletOutputStream; -+ try { -+ servletOutputStream = httpServletResponse.getOutputStream(); -+ servletOutputStream.setWriteListener( -+ new WriteListener() { -+ @Override -+ public void onWritePossible() throws IOException { -+ servletOutputStream.write( -+ "some content from the async\n".getBytes(UTF_8)); -+ context.complete(); -+ servletContextRequest.getServletChannel().handle(); -+ } -+ -+ @Override -+ public void onError(Throwable throwable) { -+ context.complete(); -+ servletContextRequest.getServletChannel().handle(); -+ } -+ }); -+ servletContextRequest.getHttpOutput().run(); -+ } catch (IOException e) { -+ context.complete(); -+ servletContextRequest.getServletChannel().handle(); -+ } -+ }); -+ t.start(); -+ return true; -+ default: -+ return false; -+ } + void aReservoirOf100OutOf1000Elements() { + final UniformReservoir reservoir = new UniformReservoir(100); + for (int i = 0; i < 1000; i++) { +@@ -20,7 +20,7 @@ class UniformReservoirTest { + assertThat(snapshot.size()).isEqualTo(100); + + for (double i : snapshot.getValues()) { +- assertThat(i).isLessThan(1000).isGreaterThanOrEqualTo(0); ++ assertThat(i).isLessThan(1000).isNotNegative(); } -+ } + } + } +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java +@@ -2,8 +2,8 @@ package io.dropwizard.metrics5; + + import static java.util.Arrays.asList; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.assertj.core.api.Assertions.offset; +-import static org.junit.jupiter.api.Assertions.assertThrows; + + import java.io.ByteArrayOutputStream; + import java.util.Random; +@@ -12,74 +12,74 @@ import java.util.concurrent.CountDownLatch; + import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + +-class UniformSnapshotTest { ++final class UniformSnapshotTest { + private final Snapshot snapshot = new UniformSnapshot(new long[] {5, 1, 2, 3, 4}); + + @Test + void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)).isEqualTo(1, offset(0.1)); ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1)); + } + + @Test + void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)).isEqualTo(5, offset(0.1)); ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1)); + } + + @Test + void disallowsNotANumberQuantile() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(Double.NaN); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(Double.NaN); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disallowsNegativeQuantile() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(-0.5); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(-0.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disallowsQuantileOverOne() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(1.5); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(1.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); ++ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1)); + } + + @Test + void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1)); + } + + @Test + void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test +@@ -138,7 +138,7 @@ class UniformSnapshotTest { + + snapshot.dump(output); + +- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); + } + + @Test +@@ -158,41 +158,41 @@ class UniformSnapshotTest { + + @Test + void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()).isEqualTo(1.5811, offset(0.0001)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001)); + } + + @Test + void calculatesAMinOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMin()).isZero(); ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); + } + + @Test + void calculatesAMaxOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMax()).isZero(); ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); + } + + @Test + void calculatesAMeanOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMean()).isZero(); ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); + } + + @Test + void calculatesAStdDevOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getStdDev()).isZero(); ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); + } + + @Test + void calculatesAStdDevOfZeroForASingletonSnapshot() { + final Snapshot singleItemSnapshot = new UniformSnapshot(new long[] {1}); + +- assertThat(singleItemSnapshot.getStdDev()).isZero(); ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); + } } ---- a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java -+++ b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java -@@ -1,5 +1,13 @@ - package io.dropwizard.metrics.jetty12; +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java +@@ -1,8 +1,10 @@ + package io.dropwizard.metrics5; -+import static io.dropwizard.metrics5.MetricRegistry.name; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; -+import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; -+ -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -7,335 +15,345 @@ import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.RatioGauge; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; --import org.eclipse.jetty.http.HttpMethod; --import org.eclipse.jetty.server.Handler; --import org.eclipse.jetty.server.Request; --import org.eclipse.jetty.server.Response; -- - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; ++import static com.google.common.base.Preconditions.checkArgument; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.assertj.core.api.Assertions.offset; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.mockito.ArgumentMatchers.any; + import static org.mockito.Mockito.doReturn; + import static org.mockito.Mockito.spy; + import static org.mockito.Mockito.when; +@@ -12,16 +14,16 @@ import java.io.ByteArrayOutputStream; + import java.util.ArrayList; import java.util.List; - import java.util.Map; - import java.util.Set; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.TimeUnit; -- --import static io.dropwizard.metrics5.MetricRegistry.name; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; --import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import org.eclipse.jetty.http.HttpMethod; -+import org.eclipse.jetty.server.Handler; -+import org.eclipse.jetty.server.Request; -+import org.eclipse.jetty.server.Response; + import org.junit.jupiter.api.Test; +-import org.mockito.ArgumentMatchers; - /** -- * An abstract base class of a Jetty {@link Handler} which records various metrics about an underlying {@link Handler} -- * instance. -+ * An abstract base class of a Jetty {@link Handler} which records various metrics about an -+ * underlying {@link Handler} instance. - */ - public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { -- protected static final String NAME_REQUESTS = "requests"; -- protected static final String NAME_DISPATCHES = "dispatches"; -- protected static final String NAME_ACTIVE_REQUESTS = "active-requests"; -- protected static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; -- protected static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; -- protected static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; -- protected static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; -- protected static final String NAME_1XX_RESPONSES = "1xx-responses"; -- protected static final String NAME_2XX_RESPONSES = "2xx-responses"; -- protected static final String NAME_3XX_RESPONSES = "3xx-responses"; -- protected static final String NAME_4XX_RESPONSES = "4xx-responses"; -- protected static final String NAME_5XX_RESPONSES = "5xx-responses"; -- protected static final String NAME_GET_REQUESTS = "get-requests"; -- protected static final String NAME_POST_REQUESTS = "post-requests"; -- protected static final String NAME_HEAD_REQUESTS = "head-requests"; -- protected static final String NAME_PUT_REQUESTS = "put-requests"; -- protected static final String NAME_DELETE_REQUESTS = "delete-requests"; -- protected static final String NAME_OPTIONS_REQUESTS = "options-requests"; -- protected static final String NAME_TRACE_REQUESTS = "trace-requests"; -- protected static final String NAME_CONNECT_REQUESTS = "connect-requests"; -- protected static final String NAME_MOVE_REQUESTS = "move-requests"; -- protected static final String NAME_OTHER_REQUESTS = "other-requests"; -- protected static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; -- protected static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; -- protected static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; -- protected static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; -- protected static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; -- protected static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; -- protected static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -- protected static final Set DETAILED_METER_LEVELS = EnumSet.of(DETAILED, ALL); -- -- protected final MetricRegistry metricRegistry; -- -- private String name; -- protected final String prefix; -- -- // the requests handled by this handler, excluding active -- protected Timer requests; -- -- // the number of dispatches seen by this handler, excluding active -- protected Timer dispatches; -- -- // the number of active requests -- protected Counter activeRequests; -- -- // the number of active dispatches -- protected Counter activeDispatches; -- -- // the number of requests currently suspended. -- protected Counter activeSuspended; -- -- // the number of requests that have been asynchronously dispatched -- protected Meter asyncDispatches; -- -- // the number of requests that expired while suspended -- protected Meter asyncTimeouts; -- -- protected final ResponseMeteredLevel responseMeteredLevel; -- protected List responses; -- protected Map responseCodeMeters; -- -- protected Timer getRequests; -- protected Timer postRequests; -- protected Timer headRequests; -- protected Timer putRequests; -- protected Timer deleteRequests; -- protected Timer optionsRequests; -- protected Timer traceRequests; -- protected Timer connectRequests; -- protected Timer moveRequests; -- protected Timer otherRequests; -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- */ -- protected AbstractInstrumentedHandler(MetricRegistry registry) { -- this(registry, null); -- } -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param prefix the prefix to use for the metrics names -- */ -- protected AbstractInstrumentedHandler(MetricRegistry registry, String prefix) { -- this(registry, prefix, COARSE); -- } -- -- /** -- * Create a new instrumented handler using a given metrics registry. -- * -- * @param registry the registry for the metrics -- * @param prefix the prefix to use for the metrics names -- * @param responseMeteredLevel the level to determine individual/aggregate response codes that are instrumented -- */ -- protected AbstractInstrumentedHandler(MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { -- this.responseMeteredLevel = responseMeteredLevel; -- this.metricRegistry = registry; -- this.prefix = prefix; -- } -- -- public String getName() { -- return name; +-class WeightedSnapshotTest { ++final class WeightedSnapshotTest { + + private static List weightedArray( + long[] values, double[] weights) { +- if (values.length != weights.length) { +- throw new IllegalArgumentException( +- "Mismatched lengths: " + values.length + " vs " + weights.length); - } -- -- public void setName(String name) { -- this.name = name; -+ protected static final String NAME_REQUESTS = "requests"; -+ protected static final String NAME_DISPATCHES = "dispatches"; -+ protected static final String NAME_ACTIVE_REQUESTS = "active-requests"; -+ protected static final String NAME_ACTIVE_DISPATCHES = "active-dispatches"; -+ protected static final String NAME_ACTIVE_SUSPENDED = "active-suspended"; -+ protected static final String NAME_ASYNC_DISPATCHES = "async-dispatches"; -+ protected static final String NAME_ASYNC_TIMEOUTS = "async-timeouts"; -+ protected static final String NAME_1XX_RESPONSES = "1xx-responses"; -+ protected static final String NAME_2XX_RESPONSES = "2xx-responses"; -+ protected static final String NAME_3XX_RESPONSES = "3xx-responses"; -+ protected static final String NAME_4XX_RESPONSES = "4xx-responses"; -+ protected static final String NAME_5XX_RESPONSES = "5xx-responses"; -+ protected static final String NAME_GET_REQUESTS = "get-requests"; -+ protected static final String NAME_POST_REQUESTS = "post-requests"; -+ protected static final String NAME_HEAD_REQUESTS = "head-requests"; -+ protected static final String NAME_PUT_REQUESTS = "put-requests"; -+ protected static final String NAME_DELETE_REQUESTS = "delete-requests"; -+ protected static final String NAME_OPTIONS_REQUESTS = "options-requests"; -+ protected static final String NAME_TRACE_REQUESTS = "trace-requests"; -+ protected static final String NAME_CONNECT_REQUESTS = "connect-requests"; -+ protected static final String NAME_MOVE_REQUESTS = "move-requests"; -+ protected static final String NAME_OTHER_REQUESTS = "other-requests"; -+ protected static final String NAME_PERCENT_4XX_1M = "percent-4xx-1m"; -+ protected static final String NAME_PERCENT_4XX_5M = "percent-4xx-5m"; -+ protected static final String NAME_PERCENT_4XX_15M = "percent-4xx-15m"; -+ protected static final String NAME_PERCENT_5XX_1M = "percent-5xx-1m"; -+ protected static final String NAME_PERCENT_5XX_5M = "percent-5xx-5m"; -+ protected static final String NAME_PERCENT_5XX_15M = "percent-5xx-15m"; -+ protected static final Set COARSE_METER_LEVELS = EnumSet.of(COARSE, ALL); -+ protected static final Set DETAILED_METER_LEVELS = -+ EnumSet.of(DETAILED, ALL); -+ -+ protected final MetricRegistry metricRegistry; -+ -+ private String name; -+ protected final String prefix; -+ -+ // the requests handled by this handler, excluding active -+ protected Timer requests; -+ -+ // the number of dispatches seen by this handler, excluding active -+ protected Timer dispatches; -+ -+ // the number of active requests -+ protected Counter activeRequests; -+ -+ // the number of active dispatches -+ protected Counter activeDispatches; -+ -+ // the number of requests currently suspended. -+ protected Counter activeSuspended; -+ -+ // the number of requests that have been asynchronously dispatched -+ protected Meter asyncDispatches; -+ -+ // the number of requests that expired while suspended -+ protected Meter asyncTimeouts; -+ -+ protected final ResponseMeteredLevel responseMeteredLevel; -+ protected List responses; -+ protected Map responseCodeMeters; -+ -+ protected Timer getRequests; -+ protected Timer postRequests; -+ protected Timer headRequests; -+ protected Timer putRequests; -+ protected Timer deleteRequests; -+ protected Timer optionsRequests; -+ protected Timer traceRequests; -+ protected Timer connectRequests; -+ protected Timer moveRequests; -+ protected Timer otherRequests; -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ */ -+ protected AbstractInstrumentedHandler(MetricRegistry registry) { -+ this(registry, null); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param prefix the prefix to use for the metrics names -+ */ -+ protected AbstractInstrumentedHandler(MetricRegistry registry, String prefix) { -+ this(registry, prefix, COARSE); -+ } -+ -+ /** -+ * Create a new instrumented handler using a given metrics registry. -+ * -+ * @param registry the registry for the metrics -+ * @param prefix the prefix to use for the metrics names -+ * @param responseMeteredLevel the level to determine individual/aggregate response codes that are -+ * instrumented -+ */ -+ protected AbstractInstrumentedHandler( -+ MetricRegistry registry, String prefix, ResponseMeteredLevel responseMeteredLevel) { -+ this.responseMeteredLevel = responseMeteredLevel; -+ this.metricRegistry = registry; -+ this.prefix = prefix; -+ } -+ -+ public String getName() { -+ return name; -+ } -+ -+ public void setName(String name) { -+ this.name = name; -+ } -+ -+ @Override -+ protected void doStart() throws Exception { -+ super.doStart(); -+ -+ final MetricName prefix = getMetricPrefix(); -+ -+ this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); -+ this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); -+ -+ this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); -+ this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -+ this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -+ -+ this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); -+ this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -+ -+ this.responseCodeMeters = -+ DETAILED_METER_LEVELS.contains(responseMeteredLevel) -+ ? new ConcurrentHashMap<>() -+ : ImmutableMap.of(); -+ -+ this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); -+ this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); -+ this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); -+ this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); -+ this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); -+ this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); -+ this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); -+ this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); -+ this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); -+ this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); -+ -+ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -+ this.responses = -+ unmodifiableList( -+ Arrays.asList( -+ metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx -+ metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx -+ metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx -+ metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx -+ metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx -+ )); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_4XX_1M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_4XX_5M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(3).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_4XX_15M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of( -+ responses.get(3).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_5XX_1M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getOneMinuteRate(), requests.getOneMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_5XX_5M), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(responses.get(4).getFiveMinuteRate(), requests.getFiveMinuteRate()); -+ } -+ }); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_PERCENT_5XX_15M), -+ new RatioGauge() { -+ @Override -+ public Ratio getRatio() { -+ return Ratio.of( -+ responses.get(4).getFifteenMinuteRate(), requests.getFifteenMinuteRate()); -+ } -+ }); -+ } else { -+ this.responses = ImmutableList.of(); - } -- -- @Override -- protected void doStart() throws Exception { -- super.doStart(); -- -- final MetricName prefix = getMetricPrefix(); -- -- this.requests = metricRegistry.timer(prefix.resolve(NAME_REQUESTS)); -- this.dispatches = metricRegistry.timer(prefix.resolve(NAME_DISPATCHES)); -- -- this.activeRequests = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_REQUESTS)); -- this.activeDispatches = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -- this.activeSuspended = metricRegistry.counter(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -- -- this.asyncDispatches = metricRegistry.meter(prefix.resolve(NAME_ASYNC_DISPATCHES)); -- this.asyncTimeouts = metricRegistry.meter(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -- -- this.responseCodeMeters = DETAILED_METER_LEVELS.contains(responseMeteredLevel) ? new ConcurrentHashMap<>() : Collections.emptyMap(); -- -- this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); -- this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); -- this.headRequests = metricRegistry.timer(prefix.resolve(NAME_HEAD_REQUESTS)); -- this.putRequests = metricRegistry.timer(prefix.resolve(NAME_PUT_REQUESTS)); -- this.deleteRequests = metricRegistry.timer(prefix.resolve(NAME_DELETE_REQUESTS)); -- this.optionsRequests = metricRegistry.timer(prefix.resolve(NAME_OPTIONS_REQUESTS)); -- this.traceRequests = metricRegistry.timer(prefix.resolve(NAME_TRACE_REQUESTS)); -- this.connectRequests = metricRegistry.timer(prefix.resolve(NAME_CONNECT_REQUESTS)); -- this.moveRequests = metricRegistry.timer(prefix.resolve(NAME_MOVE_REQUESTS)); -- this.otherRequests = metricRegistry.timer(prefix.resolve(NAME_OTHER_REQUESTS)); -- -- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -- this.responses = Collections.unmodifiableList(Arrays.asList( -- metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx -- metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx -- metricRegistry.meter(prefix.resolve(NAME_3XX_RESPONSES)), // 3xx -- metricRegistry.meter(prefix.resolve(NAME_4XX_RESPONSES)), // 4xx -- metricRegistry.meter(prefix.resolve(NAME_5XX_RESPONSES)) // 5xx -- )); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_1M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_5M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_4XX_15M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(3).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_1M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getOneMinuteRate(), -- requests.getOneMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_5M), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(responses.get(4).getFiveMinuteRate(), -- requests.getFiveMinuteRate()); -- } -- }); -- -- metricRegistry.register(prefix.resolve(NAME_PERCENT_5XX_15M), new RatioGauge() { -- @Override -- public Ratio getRatio() { -- return Ratio.of(responses.get(4).getFifteenMinuteRate(), -- requests.getFifteenMinuteRate()); -- } -- }); -- } else { -- this.responses = Collections.emptyList(); -- } -+ } -+ -+ @Override -+ protected void doStop() throws Exception { -+ final MetricName prefix = getMetricPrefix(); -+ -+ metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); -+ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -+ metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -+ metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); -+ metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -+ metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); -+ metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); -+ metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); -+ -+ if (responseCodeMeters != null) { -+ responseCodeMeters.keySet().stream() -+ .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) -+ .forEach(metricRegistry::remove); - } -- -- @Override -- protected void doStop() throws Exception { -- final MetricName prefix = getMetricPrefix(); -- -- metricRegistry.remove(prefix.resolve(NAME_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_DISPATCHES)); -- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_DISPATCHES)); -- metricRegistry.remove(prefix.resolve(NAME_ACTIVE_SUSPENDED)); -- metricRegistry.remove(prefix.resolve(NAME_ASYNC_DISPATCHES)); -- metricRegistry.remove(prefix.resolve(NAME_ASYNC_TIMEOUTS)); -- metricRegistry.remove(prefix.resolve(NAME_1XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_2XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_3XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_4XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_5XX_RESPONSES)); -- metricRegistry.remove(prefix.resolve(NAME_GET_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_POST_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_HEAD_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_PUT_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_DELETE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_OPTIONS_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_TRACE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_CONNECT_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_MOVE_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_OTHER_REQUESTS)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_1M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_5M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_4XX_15M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_1M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_5M)); -- metricRegistry.remove(prefix.resolve(NAME_PERCENT_5XX_15M)); -- -- if (responseCodeMeters != null) { -- responseCodeMeters.keySet().stream() -- .map(sc -> getMetricPrefix().resolve(String.format("%d-responses", sc))) -- .forEach(metricRegistry::remove); -- } -- super.doStop(); -+ super.doStop(); -+ } -+ -+ protected Timer requestTimer(String method) { -+ final HttpMethod m = HttpMethod.fromString(method); -+ if (m == null) { -+ return otherRequests; -+ } else { -+ switch (m) { -+ case GET: -+ return getRequests; -+ case POST: -+ return postRequests; -+ case PUT: -+ return putRequests; -+ case HEAD: -+ return headRequests; -+ case DELETE: -+ return deleteRequests; -+ case OPTIONS: -+ return optionsRequests; -+ case TRACE: -+ return traceRequests; -+ case CONNECT: -+ return connectRequests; -+ case MOVE: -+ return moveRequests; -+ default: -+ return otherRequests; -+ } - } -- -- protected Timer requestTimer(String method) { -- final HttpMethod m = HttpMethod.fromString(method); -- if (m == null) { -- return otherRequests; -- } else { -- switch (m) { -- case GET: -- return getRequests; -- case POST: -- return postRequests; -- case PUT: -- return putRequests; -- case HEAD: -- return headRequests; -- case DELETE: -- return deleteRequests; -- case OPTIONS: -- return optionsRequests; -- case TRACE: -- return traceRequests; -- case CONNECT: -- return connectRequests; -- case MOVE: -- return moveRequests; -- default: -- return otherRequests; -- } -- } -+ } -+ -+ protected void updateResponses( -+ Request request, Response response, long start, boolean isHandled) { -+ if (isHandled) { -+ mark(response.getStatus()); -+ } else { -+ mark(404); // will end up with a 404 response sent by HttpChannel.handle - } -- -- protected void updateResponses(Request request, Response response, long start, boolean isHandled) { -- if (isHandled) { -- mark(response.getStatus()); -- } else { -- mark(404); // will end up with a 404 response sent by HttpChannel.handle -- } -- activeRequests.dec(); -- final long elapsedTime = System.currentTimeMillis() - start; -- requests.update(elapsedTime, TimeUnit.MILLISECONDS); -- requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -+ activeRequests.dec(); -+ final long elapsedTime = System.currentTimeMillis() - start; -+ requests.update(elapsedTime, TimeUnit.MILLISECONDS); -+ requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS); -+ } -+ -+ protected void mark(int statusCode) { -+ if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -+ getResponseCodeMeter(statusCode).mark(); - } ++ checkArgument( ++ values.length == weights.length, ++ "Mismatched lengths: %s vs %s", ++ values.length, ++ weights.length); -- protected void mark(int statusCode) { -- if (DETAILED_METER_LEVELS.contains(responseMeteredLevel)) { -- getResponseCodeMeter(statusCode).mark(); -- } -- -- if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -- final int responseStatus = statusCode / 100; -- if (responseStatus >= 1 && responseStatus <= 5) { -- responses.get(responseStatus - 1).mark(); -- } -- } -+ if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { -+ final int responseStatus = statusCode / 100; -+ if (responseStatus >= 1 && responseStatus <= 5) { -+ responses.get(responseStatus - 1).mark(); -+ } - } -+ } + final List samples = new ArrayList<>(); + for (int i = 0; i < values.length; i++) { +@@ -36,69 +38,69 @@ class WeightedSnapshotTest { -- protected Meter getResponseCodeMeter(int statusCode) { -- return responseCodeMeters -- .computeIfAbsent(statusCode, sc -> metricRegistry -- .meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); -- } -+ protected Meter getResponseCodeMeter(int statusCode) { -+ return responseCodeMeters.computeIfAbsent( -+ statusCode, -+ sc -> metricRegistry.meter(getMetricPrefix().resolve(String.format("%d-responses", sc)))); -+ } - -- protected MetricName getMetricPrefix() { -- return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); -- } -+ protected MetricName getMetricPrefix() { -+ return this.prefix == null ? name(getHandler().getClass(), name) : name(this.prefix, name); -+ } - } ---- a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java -+++ b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java -@@ -2,62 +2,63 @@ package io.dropwizard.metrics.jetty12; + @Test + void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)).isEqualTo(1.0, offset(0.1)); ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1)); + } - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Timer; -+import java.util.List; - import org.eclipse.jetty.io.Connection; - import org.eclipse.jetty.io.EndPoint; - import org.eclipse.jetty.server.ConnectionFactory; - import org.eclipse.jetty.server.Connector; - import org.eclipse.jetty.util.component.ContainerLifeCycle; - --import java.util.List; -- - public class InstrumentedConnectionFactory extends ContainerLifeCycle implements ConnectionFactory { -- private final ConnectionFactory connectionFactory; -- private final Timer timer; -- private final Counter counter; -- -- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { -- this(connectionFactory, timer, null); -- } -- -- public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer, Counter counter) { -- this.connectionFactory = connectionFactory; -- this.timer = timer; -- this.counter = counter; -- addBean(connectionFactory); -- } -- -- @Override -- public String getProtocol() { -- return connectionFactory.getProtocol(); -- } -- -- @Override -- public List getProtocols() { -- return connectionFactory.getProtocols(); -- } -- -- @Override -- public Connection newConnection(Connector connector, EndPoint endPoint) { -- final Connection connection = connectionFactory.newConnection(connector, endPoint); -- connection.addEventListener(new Connection.Listener() { -- private Timer.Context context; -- -- @Override -- public void onOpened(Connection connection) { -- this.context = timer.time(); -- if (counter != null) { -- counter.inc(); -- } -+ private final ConnectionFactory connectionFactory; -+ private final Timer timer; -+ private final Counter counter; -+ -+ public InstrumentedConnectionFactory(ConnectionFactory connectionFactory, Timer timer) { -+ this(connectionFactory, timer, null); -+ } -+ -+ public InstrumentedConnectionFactory( -+ ConnectionFactory connectionFactory, Timer timer, Counter counter) { -+ this.connectionFactory = connectionFactory; -+ this.timer = timer; -+ this.counter = counter; -+ addBean(connectionFactory); -+ } -+ -+ @Override -+ public String getProtocol() { -+ return connectionFactory.getProtocol(); -+ } -+ -+ @Override -+ public List getProtocols() { -+ return connectionFactory.getProtocols(); -+ } -+ -+ @Override -+ public Connection newConnection(Connector connector, EndPoint endPoint) { -+ final Connection connection = connectionFactory.newConnection(connector, endPoint); -+ connection.addEventListener( -+ new Connection.Listener() { -+ private Timer.Context context; -+ -+ @Override -+ public void onOpened(Connection connection) { -+ this.context = timer.time(); -+ if (counter != null) { -+ counter.inc(); - } -+ } - -- @Override -- public void onClosed(Connection connection) { -- context.stop(); -- if (counter != null) { -- counter.dec(); -- } -+ @Override -+ public void onClosed(Connection connection) { -+ context.stop(); -+ if (counter != null) { -+ counter.dec(); - } -+ } - }); -- return connection; -- } -+ return connection; -+ } - } ---- a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPool.java -+++ b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPool.java -@@ -1,164 +1,187 @@ - package io.dropwizard.metrics.jetty12; + @Test + void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1)); + } + + @Test + void disallowsNotANumberQuantile() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(Double.NaN); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(Double.NaN); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disallowsNegativeQuantile() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(-0.5); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(-0.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disallowsQuantileOverOne() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(1.5); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(1.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); ++ assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1)); + } + + @Test + void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1)); + } + + @Test + void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); + } -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.RatioGauge; --import org.eclipse.jetty.util.annotation.Name; --import org.eclipse.jetty.util.thread.QueuedThreadPool; -- - import java.util.concurrent.BlockingQueue; - import java.util.concurrent.ThreadFactory; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -+import org.eclipse.jetty.util.annotation.Name; -+import org.eclipse.jetty.util.thread.QueuedThreadPool; - - public class InstrumentedQueuedThreadPool extends QueuedThreadPool { -- private static final String NAME_UTILIZATION = "utilization"; -- private static final String NAME_UTILIZATION_MAX = "utilization-max"; -- private static final String NAME_SIZE = "size"; -- private static final String NAME_JOBS = "jobs"; -- private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; -- -- private final MetricRegistry metricRegistry; -- private String prefix; -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { -- this(registry, 200); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads) { -- this(registry, maxThreads, 8); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads) { -- this(registry, maxThreads, minThreads, 60000); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("queue") BlockingQueue queue) { -- this(registry, maxThreads, minThreads, 60000, queue); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout) { -- this(registry, maxThreads, minThreads, idleTimeout, null); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("queue") BlockingQueue queue) { -- this(registry, maxThreads, minThreads, idleTimeout, queue, (ThreadGroup) null); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("queue") BlockingQueue queue, -- @Name("threadFactory") ThreadFactory threadFactory) { -- this(registry, maxThreads, minThreads, idleTimeout, -1, queue, null, threadFactory); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("queue") BlockingQueue queue, -- @Name("threadGroup") ThreadGroup threadGroup) { -- this(registry, maxThreads, minThreads, idleTimeout, -1, queue, threadGroup); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("reservedThreads") int reservedThreads, -- @Name("queue") BlockingQueue queue, -- @Name("threadGroup") ThreadGroup threadGroup) { -- this(registry, maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, null); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("reservedThreads") int reservedThreads, -- @Name("queue") BlockingQueue queue, -- @Name("threadGroup") ThreadGroup threadGroup, -- @Name("threadFactory") ThreadFactory threadFactory) { -- this(registry, maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, threadFactory, null); -- } -- -- public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry, -- @Name("maxThreads") int maxThreads, -- @Name("minThreads") int minThreads, -- @Name("idleTimeout") int idleTimeout, -- @Name("reservedThreads") int reservedThreads, -- @Name("queue") BlockingQueue queue, -- @Name("threadGroup") ThreadGroup threadGroup, -- @Name("threadFactory") ThreadFactory threadFactory, -- @Name("prefix") String prefix) { -- super(maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, threadFactory); -- this.metricRegistry = registry; -- this.prefix = prefix; -- } -- -- public String getPrefix() { -- return prefix; -- } -- -- public void setPrefix(String prefix) { -- this.prefix = prefix; -- } -- -- @Override -- protected void doStart() throws Exception { -- super.doStart(); -- -- final MetricName prefix = getMetricPrefix(); -- -- metricRegistry.register(prefix.resolve(NAME_UTILIZATION), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(getUtilizedThreads(), getThreads() - getLeasedThreads()); -- } -+ private static final String NAME_UTILIZATION = "utilization"; -+ private static final String NAME_UTILIZATION_MAX = "utilization-max"; -+ private static final String NAME_SIZE = "size"; -+ private static final String NAME_JOBS = "jobs"; -+ private static final String NAME_JOBS_QUEUE_UTILIZATION = "jobs-queue-utilization"; -+ -+ private final MetricRegistry metricRegistry; -+ private String prefix; -+ -+ public InstrumentedQueuedThreadPool(@Name("registry") MetricRegistry registry) { -+ this(registry, 200); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, @Name("maxThreads") int maxThreads) { -+ this(registry, maxThreads, 8); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads) { -+ this(registry, maxThreads, minThreads, 60000); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("queue") BlockingQueue queue) { -+ this(registry, maxThreads, minThreads, 60000, queue); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout) { -+ this(registry, maxThreads, minThreads, idleTimeout, null); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("queue") BlockingQueue queue) { -+ this(registry, maxThreads, minThreads, idleTimeout, queue, (ThreadGroup) null); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("queue") BlockingQueue queue, -+ @Name("threadFactory") ThreadFactory threadFactory) { -+ this(registry, maxThreads, minThreads, idleTimeout, -1, queue, null, threadFactory); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("queue") BlockingQueue queue, -+ @Name("threadGroup") ThreadGroup threadGroup) { -+ this(registry, maxThreads, minThreads, idleTimeout, -1, queue, threadGroup); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("reservedThreads") int reservedThreads, -+ @Name("queue") BlockingQueue queue, -+ @Name("threadGroup") ThreadGroup threadGroup) { -+ this(registry, maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, null); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("reservedThreads") int reservedThreads, -+ @Name("queue") BlockingQueue queue, -+ @Name("threadGroup") ThreadGroup threadGroup, -+ @Name("threadFactory") ThreadFactory threadFactory) { -+ this( -+ registry, -+ maxThreads, -+ minThreads, -+ idleTimeout, -+ reservedThreads, -+ queue, -+ threadGroup, -+ threadFactory, -+ null); -+ } -+ -+ public InstrumentedQueuedThreadPool( -+ @Name("registry") MetricRegistry registry, -+ @Name("maxThreads") int maxThreads, -+ @Name("minThreads") int minThreads, -+ @Name("idleTimeout") int idleTimeout, -+ @Name("reservedThreads") int reservedThreads, -+ @Name("queue") BlockingQueue queue, -+ @Name("threadGroup") ThreadGroup threadGroup, -+ @Name("threadFactory") ThreadFactory threadFactory, -+ @Name("prefix") String prefix) { -+ super(maxThreads, minThreads, idleTimeout, reservedThreads, queue, threadGroup, threadFactory); -+ this.metricRegistry = registry; -+ this.prefix = prefix; -+ } -+ -+ public String getPrefix() { -+ return prefix; -+ } -+ -+ public void setPrefix(String prefix) { -+ this.prefix = prefix; -+ } -+ -+ @Override -+ protected void doStart() throws Exception { -+ super.doStart(); -+ -+ final MetricName prefix = getMetricPrefix(); -+ -+ metricRegistry.register( -+ prefix.resolve(NAME_UTILIZATION), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(getUtilizedThreads(), getThreads() - getLeasedThreads()); -+ } - }); -- metricRegistry.registerGauge(prefix.resolve(NAME_UTILIZATION_MAX), this::getUtilizationRate); -- metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); -- // This assumes the QueuedThreadPool is using a BlockingArrayQueue or -- // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. -- metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); -- metricRegistry.register(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- BlockingQueue queue = getQueue(); -- return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); -- } -+ metricRegistry.registerGauge(prefix.resolve(NAME_UTILIZATION_MAX), this::getUtilizationRate); -+ metricRegistry.registerGauge(prefix.resolve(NAME_SIZE), this::getThreads); -+ // This assumes the QueuedThreadPool is using a BlockingArrayQueue or -+ // ArrayBlockingQueue for its queue, and is therefore a constant-time operation. -+ metricRegistry.registerGauge(prefix.resolve(NAME_JOBS), () -> getQueue().size()); -+ metricRegistry.register( -+ prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ BlockingQueue queue = getQueue(); -+ return Ratio.of(queue.size(), queue.size() + queue.remainingCapacity()); -+ } - }); -- } -- -- @Override -- protected void doStop() throws Exception { -- final MetricName prefix = getMetricPrefix(); -- -- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); -- metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); -- metricRegistry.remove(prefix.resolve(NAME_SIZE)); -- metricRegistry.remove(prefix.resolve(NAME_JOBS)); -- metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); -- -- super.doStop(); -- } -- -- private MetricName getMetricPrefix() { -- return this.prefix == null ? name(QueuedThreadPool.class, getName()) : name(this.prefix, getName()); -- } -+ } -+ -+ @Override -+ protected void doStop() throws Exception { -+ final MetricName prefix = getMetricPrefix(); -+ -+ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION)); -+ metricRegistry.remove(prefix.resolve(NAME_UTILIZATION_MAX)); -+ metricRegistry.remove(prefix.resolve(NAME_SIZE)); -+ metricRegistry.remove(prefix.resolve(NAME_JOBS)); -+ metricRegistry.remove(prefix.resolve(NAME_JOBS_QUEUE_UTILIZATION)); -+ -+ super.doStop(); -+ } -+ -+ private MetricName getMetricPrefix() { -+ return this.prefix == null -+ ? name(QueuedThreadPool.class, getName()) -+ : name(this.prefix, getName()); -+ } - } ---- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java -+++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics.jetty12; + @Test +@@ -118,7 +120,7 @@ class WeightedSnapshotTest { + final List spyItems = spy(originalItems); + doReturn(originalItems.toArray(new WeightedSample[] {})) + .when(spyItems) +- .toArray(ArgumentMatchers.any(WeightedSample[].class)); ++ .toArray(any(WeightedSample[].class)); + when(spyItems.size()).thenReturn(4, 5); + + final Snapshot other = new WeightedSnapshot(spyItems); +@@ -133,7 +135,7 @@ class WeightedSnapshotTest { + final List spyItems = spy(originalItems); + doReturn(originalItems.toArray(new WeightedSample[] {})) + .when(spyItems) +- .toArray(ArgumentMatchers.any(WeightedSample[].class)); ++ .toArray(any(WeightedSample[].class)); + when(spyItems.size()).thenReturn(6, 5); -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -@@ -17,70 +19,70 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; + final Snapshot other = new WeightedSnapshot(spyItems); +@@ -147,7 +149,7 @@ class WeightedSnapshotTest { --import static org.assertj.core.api.Assertions.assertThat; -- --public class InstrumentedConnectionFactoryTest { -- private final MetricRegistry registry = new MetricRegistry(); -- private final Server server = new Server(); -- private final ServerConnector connector = -- new ServerConnector(server, new InstrumentedConnectionFactory(new HttpConnectionFactory(), -- registry.timer("http.connections"), -- registry.counter("http.active-connections"))); -- private final HttpClient client = new HttpClient(); -- -- @BeforeEach -- public void setUp() throws Exception { -- server.setHandler(new Handler.Abstract() { -- @Override -- public boolean handle(Request request, Response response, Callback callback) throws Exception { -- Content.Sink.write(response, true, "OK", callback); -- return true; -- } -+final class InstrumentedConnectionFactoryTest { -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final Server server = new Server(); -+ private final ServerConnector connector = -+ new ServerConnector( -+ server, -+ new InstrumentedConnectionFactory( -+ new HttpConnectionFactory(), -+ registry.timer("http.connections"), -+ registry.counter("http.active-connections"))); -+ private final HttpClient client = new HttpClient(); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ server.setHandler( -+ new Handler.Abstract() { -+ @Override -+ public boolean handle(Request request, Response response, Callback callback) -+ throws Exception { -+ Content.Sink.write(response, true, "OK", callback); -+ return true; -+ } - }); + snapshot.dump(output); -- server.addConnector(connector); -- server.start(); -+ server.addConnector(connector); -+ server.start(); +- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); + } -- client.start(); -- } -+ client.start(); -+ } + @Test +@@ -167,7 +169,7 @@ class WeightedSnapshotTest { -- @AfterEach -- public void tearDown() throws Exception { -- server.stop(); -- client.stop(); -- } -+ @AfterEach -+ void tearDown() throws Exception { -+ server.stop(); -+ client.stop(); -+ } - -- @Test -- public void instrumentsConnectionTimes() throws Exception { -- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -- assertThat(response.getStatus()) -- .isEqualTo(200); -+ @Test -+ void instrumentsConnectionTimes() throws Exception { -+ final ContentResponse response = -+ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -+ assertThat(response.getStatus()).isEqualTo(200); + @Test + void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()).isEqualTo(1.2688, offset(0.0001)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001)); + } -- client.stop(); // close the connection -+ client.stop(); // close the connection + @Test +@@ -175,7 +177,7 @@ class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); -- Thread.sleep(100); // make sure the connection is closed -+ Thread.sleep(100); // make sure the connection is closed +- assertThat(emptySnapshot.getMin()).isZero(); ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); + } -- final Timer timer = registry.timer(MetricRegistry.name("http.connections")); -- assertThat(timer.getCount()) -- .isEqualTo(1); -- } -+ final Timer timer = registry.timer(MetricRegistry.name("http.connections")); -+ assertThat(timer.getCount()).isEqualTo(1); -+ } + @Test +@@ -183,7 +185,7 @@ class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); -- @Test -- public void instrumentsActiveConnections() throws Exception { -- final Counter counter = registry.counter("http.active-connections"); -+ @Test -+ void instrumentsActiveConnections() throws Exception { -+ final Counter counter = registry.counter("http.active-connections"); +- assertThat(emptySnapshot.getMax()).isZero(); ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); + } + + @Test +@@ -191,7 +193,7 @@ class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); -- final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -- assertThat(response.getStatus()) -- .isEqualTo(200); -+ final ContentResponse response = -+ client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); -+ assertThat(response.getStatus()).isEqualTo(200); +- assertThat(emptySnapshot.getMean()).isZero(); ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); + } -- assertThat(counter.getCount()) -- .isEqualTo(1); -+ assertThat(counter.getCount()).isEqualTo(1); + @Test +@@ -199,7 +201,7 @@ class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); -- client.stop(); // close the connection -+ client.stop(); // close the connection +- assertThat(emptySnapshot.getStdDev()).isZero(); ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); + } -- Thread.sleep(100); // make sure the connection is closed -+ Thread.sleep(100); // make sure the connection is closed + @Test +@@ -207,7 +209,7 @@ class WeightedSnapshotTest { + final Snapshot singleItemSnapshot = + new WeightedSnapshot(weightedArray(new long[] {1}, new double[] {1.0})); -- assertThat(counter.getCount()) -- .isEqualTo(0); -- } -+ assertThat(counter.getCount()).isEqualTo(0); -+ } - } ---- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java -+++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java -@@ -1,49 +1,49 @@ - package io.dropwizard.metrics.jetty12; +- assertThat(singleItemSnapshot.getStdDev()).isZero(); ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); + } -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import org.eclipse.jetty.util.thread.QueuedThreadPool; + @Test +--- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java ++++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java +@@ -12,7 +12,7 @@ import net.sf.ehcache.Element; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; -- --public class InstrumentedQueuedThreadPoolTest { -- private static final String PREFIX = "prefix"; -- -- private MetricRegistry metricRegistry; -- private InstrumentedQueuedThreadPool iqtp; -- -- @BeforeEach -- public void setUp() { -- metricRegistry = new MetricRegistry(); -- iqtp = new InstrumentedQueuedThreadPool(metricRegistry); -- } -- -- @Test -- public void customMetricsPrefix() throws Exception { -- iqtp.setPrefix(PREFIX); -- iqtp.start(); -- -- assertThat(metricRegistry.getNames()) -- .overridingErrorMessage("Custom metrics prefix doesn't match") -- .allSatisfy(name -> assertThat(name.getKey()).startsWith(PREFIX)); -- -- iqtp.stop(); -- assertThat(metricRegistry.getMetrics()) -- .overridingErrorMessage("The default metrics prefix was changed") -- .isEmpty(); -- } -- -- @Test -- public void metricsPrefixBackwardCompatible() throws Exception { -- iqtp.start(); -- assertThat(metricRegistry.getNames()) -- .overridingErrorMessage("The default metrics prefix was changed") -- .allSatisfy(name -> assertThat(name.getKey()).startsWith(QueuedThreadPool.class.getName())); -- -- iqtp.stop(); -- assertThat(metricRegistry.getMetrics()) -- .overridingErrorMessage("The default metrics prefix was changed") -- .isEmpty(); -- } -+final class InstrumentedQueuedThreadPoolTest { -+ private static final String PREFIX = "prefix"; -+ -+ private MetricRegistry metricRegistry; -+ private InstrumentedQueuedThreadPool iqtp; -+ -+ @BeforeEach -+ void setUp() { -+ metricRegistry = new MetricRegistry(); -+ iqtp = new InstrumentedQueuedThreadPool(metricRegistry); -+ } -+ -+ @Test -+ void customMetricsPrefix() throws Exception { -+ iqtp.setPrefix(PREFIX); -+ iqtp.start(); -+ -+ assertThat(metricRegistry.getNames()) -+ .overridingErrorMessage("Custom metrics prefix doesn't match") -+ .allSatisfy(name -> assertThat(name.getKey()).startsWith(PREFIX)); -+ -+ iqtp.stop(); -+ assertThat(metricRegistry.getMetrics()) -+ .overridingErrorMessage("The default metrics prefix was changed") -+ .isEmpty(); -+ } -+ -+ @Test -+ void metricsPrefixBackwardCompatible() throws Exception { -+ iqtp.start(); -+ assertThat(metricRegistry.getNames()) -+ .overridingErrorMessage("The default metrics prefix was changed") -+ .allSatisfy(name -> assertThat(name.getKey()).startsWith(QueuedThreadPool.class.getName())); -+ -+ iqtp.stop(); -+ assertThat(metricRegistry.getMetrics()) -+ .overridingErrorMessage("The default metrics prefix was changed") -+ .isEmpty(); -+ } - } ---- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java -+++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java -@@ -2,70 +2,68 @@ package io.dropwizard.metrics5.jmx; +-class InstrumentedCacheDecoratorFactoryTest { ++final class InstrumentedCacheDecoratorFactoryTest { + private static final CacheManager MANAGER = CacheManager.create(); - import io.dropwizard.metrics5.MetricName; - import java.util.Hashtable; -- - import javax.management.MalformedObjectNameException; - import javax.management.ObjectName; -- - import org.slf4j.Logger; - import org.slf4j.LoggerFactory; + private MetricRegistry registry; +--- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java ++++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java +@@ -13,7 +13,7 @@ import net.sf.ehcache.config.CacheConfiguration; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; - public class DefaultObjectNameFactory implements ObjectNameFactory { +-class InstrumentedEhcacheTest { ++final class InstrumentedEhcacheTest { + private static final CacheManager MANAGER = CacheManager.create(); -- private static final char[] QUOTABLE_CHARS = new char[] {',', '=', ':', '"'}; -- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); -+ private static final char[] QUOTABLE_CHARS = new char[] {',', '=', ':', '"'}; -+ private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectNameFactory.class); + private final MetricRegistry registry = new MetricRegistry(); +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java +@@ -1,8 +1,11 @@ + package io.dropwizard.metrics5.graphite; -- @Override -- public ObjectName createName(String type, String domain, MetricName name) { -- try { -- ObjectName objectName; -- Hashtable properties = new Hashtable<>(); -+ @Override -+ public ObjectName createName(String type, String domain, MetricName name) { -+ try { -+ ObjectName objectName; -+ Hashtable properties = new Hashtable<>(); - -- properties.put("name", name.getKey()); -- properties.put("type", type); -- properties.putAll(name.getTags()); -- objectName = new ObjectName(domain, properties); -+ properties.put("name", name.getKey()); -+ properties.put("type", type); -+ properties.putAll(name.getTags()); -+ objectName = new ObjectName(domain, properties); - -- /* -- * The only way we can find out if we need to quote the properties is by -- * checking an ObjectName that we've constructed. -- */ -- if (objectName.isDomainPattern()) { -- domain = ObjectName.quote(domain); -- } -- if (objectName.isPropertyValuePattern("name") || shouldQuote(objectName.getKeyProperty("name"))) { -- properties.put("name", ObjectName.quote(name.getKey())); -- } -- if (objectName.isPropertyValuePattern("type") || shouldQuote(objectName.getKeyProperty("type"))) { -- properties.put("type", ObjectName.quote(type)); -- } -- objectName = new ObjectName(domain, properties); -+ /* -+ * The only way we can find out if we need to quote the properties is by -+ * checking an ObjectName that we've constructed. -+ */ -+ if (objectName.isDomainPattern()) { -+ domain = ObjectName.quote(domain); -+ } -+ if (objectName.isPropertyValuePattern("name") -+ || shouldQuote(objectName.getKeyProperty("name"))) { -+ properties.put("name", ObjectName.quote(name.getKey())); -+ } -+ if (objectName.isPropertyValuePattern("type") -+ || shouldQuote(objectName.getKeyProperty("type"))) { -+ properties.put("type", ObjectName.quote(type)); -+ } -+ return new ObjectName(domain, properties); ++import static com.google.common.base.Preconditions.checkArgument; ++import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.UTF_8; + import static java.util.Objects.requireNonNull; -- return objectName; -- } catch (MalformedObjectNameException e) { -- try { -- return new ObjectName(domain, "name", ObjectName.quote(name.getKey())); -- } catch (MalformedObjectNameException e1) { -- LOGGER.warn("Unable to register {} {}", type, name, e1); -- throw new RuntimeException(e1); -- } -- } -+ } catch (MalformedObjectNameException e) { -+ try { -+ return new ObjectName(domain, "name", ObjectName.quote(name.getKey())); -+ } catch (MalformedObjectNameException e1) { -+ LOG.warn("Unable to register {} {}", type, name, e1); -+ throw new RuntimeException(e1); -+ } - } -+ } - -- /** -- * Determines whether the value requires quoting. -- * According to the {@link ObjectName} documentation, values can be quoted or unquoted. Unquoted -- * values may not contain any of the characters comma, equals, colon, or quote. -- * -- * @param value a value to test -- * @return true when it requires quoting, false otherwise -- */ -- private boolean shouldQuote(final String value) { -- for (char quotableChar : QUOTABLE_CHARS) { -- if (value.indexOf(quotableChar) != -1) { -- return true; -- } -- } -- return false; -+ /** -+ * Determines whether the value requires quoting. According to the {@link ObjectName} -+ * documentation, values can be quoted or unquoted. Unquoted values may not contain any of the -+ * characters comma, equals, colon, or quote. -+ * -+ * @param value a value to test -+ * @return true when it requires quoting, false otherwise -+ */ -+ private boolean shouldQuote(final String value) { -+ for (char quotableChar : QUOTABLE_CHARS) { -+ if (value.indexOf(quotableChar) != -1) { -+ return true; -+ } - } -- -+ return false; -+ } - } ---- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java -+++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.jmx; ++import com.google.common.base.Strings; + import java.io.BufferedWriter; + import java.io.IOException; + import java.io.OutputStreamWriter; +@@ -29,7 +32,7 @@ public class Graphite implements GraphiteSender { + private Writer writer; + private int failures; -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.util.Collections.unmodifiableMap; -+ -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Histogram; -@@ -11,9 +15,12 @@ import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricRegistryListener; - import io.dropwizard.metrics5.Reporter; - import io.dropwizard.metrics5.Timer; --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -- -+import java.io.Closeable; -+import java.lang.management.ManagementFactory; -+import java.util.Locale; -+import java.util.Map; -+import java.util.concurrent.ConcurrentHashMap; -+import java.util.concurrent.TimeUnit; - import javax.management.InstanceAlreadyExistsException; - import javax.management.InstanceNotFoundException; - import javax.management.JMException; -@@ -21,758 +28,755 @@ import javax.management.MBeanRegistrationException; - import javax.management.MBeanServer; - import javax.management.ObjectInstance; - import javax.management.ObjectName; --import java.io.Closeable; --import java.lang.management.ManagementFactory; --import java.util.Collections; --import java.util.Locale; --import java.util.Map; --import java.util.concurrent.ConcurrentHashMap; --import java.util.concurrent.TimeUnit; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; - --/** -- * A reporter which listens for new metrics and exposes them as namespaced MBeans. -- */ -+/** A reporter which listens for new metrics and exposes them as namespaced MBeans. */ - public class JmxReporter implements Reporter, Closeable { -+ /** -+ * Returns a new {@link Builder} for {@link JmxReporter}. -+ * -+ * @param registry the registry to report -+ * @return a {@link Builder} instance for a {@link JmxReporter} -+ */ -+ public static Builder forRegistry(MetricRegistry registry) { -+ return new Builder(registry); -+ } -+ -+ /** -+ * A builder for {@link JmxReporter} instances. Defaults to using the default MBean server and not -+ * filtering metrics. -+ */ -+ public static class Builder { -+ private final MetricRegistry registry; -+ private MBeanServer mBeanServer; -+ private TimeUnit rateUnit; -+ private TimeUnit durationUnit; -+ private ObjectNameFactory objectNameFactory; -+ private MetricFilter filter = MetricFilter.ALL; -+ private String domain; -+ private Map specificDurationUnits; -+ private Map specificRateUnits; -+ -+ private Builder(MetricRegistry registry) { -+ this.registry = registry; -+ this.rateUnit = TimeUnit.SECONDS; -+ this.durationUnit = TimeUnit.MILLISECONDS; -+ this.domain = "metrics"; -+ this.objectNameFactory = new DefaultObjectNameFactory(); -+ this.specificDurationUnits = ImmutableMap.of(); -+ this.specificRateUnits = ImmutableMap.of(); -+ } -+ - /** -- * Returns a new {@link Builder} for {@link JmxReporter}. -+ * Register MBeans with the given {@link MBeanServer}. - * -- * @param registry the registry to report -- * @return a {@link Builder} instance for a {@link JmxReporter} -+ * @param mBeanServer an {@link MBeanServer} -+ * @return {@code this} - */ -- public static Builder forRegistry(MetricRegistry registry) { -- return new Builder(registry); -+ public Builder registerWith(MBeanServer mBeanServer) { -+ this.mBeanServer = mBeanServer; -+ return this; - } +- private static final Logger LOGGER = LoggerFactory.getLogger(Graphite.class); ++ private static final Logger LOG = LoggerFactory.getLogger(Graphite.class); - /** -- * A builder for {@link JmxReporter} instances. Defaults to using the default MBean server and -- * not filtering metrics. -+ * Convert rates to the given time unit. -+ * -+ * @param rateUnit a unit of time -+ * @return {@code this} - */ -- public static class Builder { -- private final MetricRegistry registry; -- private MBeanServer mBeanServer; -- private TimeUnit rateUnit; -- private TimeUnit durationUnit; -- private ObjectNameFactory objectNameFactory; -- private MetricFilter filter = MetricFilter.ALL; -- private String domain; -- private Map specificDurationUnits; -- private Map specificRateUnits; -- -- private Builder(MetricRegistry registry) { -- this.registry = registry; -- this.rateUnit = TimeUnit.SECONDS; -- this.durationUnit = TimeUnit.MILLISECONDS; -- this.domain = "metrics"; -- this.objectNameFactory = new DefaultObjectNameFactory(); -- this.specificDurationUnits = Collections.emptyMap(); -- this.specificRateUnits = Collections.emptyMap(); -- } -- -- /** -- * Register MBeans with the given {@link MBeanServer}. -- * -- * @param mBeanServer an {@link MBeanServer} -- * @return {@code this} -- */ -- public Builder registerWith(MBeanServer mBeanServer) { -- this.mBeanServer = mBeanServer; -- return this; -- } -- -- /** -- * Convert rates to the given time unit. -- * -- * @param rateUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertRatesTo(TimeUnit rateUnit) { -- this.rateUnit = rateUnit; -- return this; -- } -- -- public Builder createsObjectNamesWith(ObjectNameFactory onFactory) { -- if (onFactory == null) { -- throw new IllegalArgumentException("null objectNameFactory"); -- } -- this.objectNameFactory = onFactory; -- return this; -- } -- -- /** -- * Convert durations to the given time unit. -- * -- * @param durationUnit a unit of time -- * @return {@code this} -- */ -- public Builder convertDurationsTo(TimeUnit durationUnit) { -- this.durationUnit = durationUnit; -- return this; -- } -- -- /** -- * Only report metrics which match the given filter. -- * -- * @param filter a {@link MetricFilter} -- * @return {@code this} -- */ -- public Builder filter(MetricFilter filter) { -- this.filter = filter; -- return this; -- } -- -- public Builder inDomain(String domain) { -- this.domain = domain; -- return this; -- } -- -- /** -- * Use specific {@link TimeUnit}s for the duration of the metrics with these names. -- * -- * @param specificDurationUnits a map of metric names and specific {@link TimeUnit}s -- * @return {@code this} -- */ -- public Builder specificDurationUnits(Map specificDurationUnits) { -- this.specificDurationUnits = Collections.unmodifiableMap(specificDurationUnits); -- return this; -- } -- -- -- /** -- * Use specific {@link TimeUnit}s for the rate of the metrics with these names. -- * -- * @param specificRateUnits a map of metric names and specific {@link TimeUnit}s -- * @return {@code this} -- */ -- public Builder specificRateUnits(Map specificRateUnits) { -- this.specificRateUnits = Collections.unmodifiableMap(specificRateUnits); -- return this; -- } -+ public Builder convertRatesTo(TimeUnit rateUnit) { -+ this.rateUnit = rateUnit; -+ return this; -+ } - -- /** -- * Builds a {@link JmxReporter} with the given properties. -- * -- * @return a {@link JmxReporter} -- */ -- public JmxReporter build() { -- final MetricTimeUnits timeUnits = new MetricTimeUnits(rateUnit, durationUnit, specificRateUnits, specificDurationUnits); -- if (mBeanServer == null) { -- mBeanServer = ManagementFactory.getPlatformMBeanServer(); -- } -- return new JmxReporter(mBeanServer, domain, registry, filter, timeUnits, objectNameFactory); -- } -+ public Builder createsObjectNamesWith(ObjectNameFactory onFactory) { -+ checkArgument(onFactory != null, "null objectNameFactory"); -+ this.objectNameFactory = onFactory; -+ return this; - } + /** + * Creates a new client which connects to the given address using the default {@link +@@ -63,13 +66,9 @@ public class Graphite implements GraphiteSender { + * @param charset the character set used by the server + */ + public Graphite(String hostname, int port, SocketFactory socketFactory, Charset charset) { +- if (hostname == null || hostname.isEmpty()) { +- throw new IllegalArgumentException("hostname must not be null or empty"); +- } ++ checkArgument(!Strings.isNullOrEmpty(hostname), "hostname must not be null or empty"); -- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); -+ /** -+ * Convert durations to the given time unit. -+ * -+ * @param durationUnit a unit of time -+ * @return {@code this} -+ */ -+ public Builder convertDurationsTo(TimeUnit durationUnit) { -+ this.durationUnit = durationUnit; -+ return this; -+ } - -- @SuppressWarnings("UnusedDeclaration") -- public interface MetricMBean { -- ObjectName objectName(); -+ /** -+ * Only report metrics which match the given filter. -+ * -+ * @param filter a {@link MetricFilter} -+ * @return {@code this} -+ */ -+ public Builder filter(MetricFilter filter) { -+ this.filter = filter; -+ return this; - } +- if (port < 0 || port > 65535) { +- throw new IllegalArgumentException("port must be a valid IP port (0-65535)"); +- } ++ checkArgument(port >= 0 && port <= 65535, "port must be a valid IP port (0-65535)"); -- private abstract static class AbstractBean implements MetricMBean { -- private final ObjectName objectName; -+ public Builder inDomain(String domain) { -+ this.domain = domain; -+ return this; -+ } + this.hostname = hostname; + this.port = port; +@@ -116,9 +115,7 @@ public class Graphite implements GraphiteSender { + + @Override + public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); + InetSocketAddress address = this.address; + // the previous dns retry logic did not work, as address.getAddress would always return the + // cached value +@@ -178,7 +175,7 @@ public class Graphite implements GraphiteSender { + writer.close(); + } + } catch (IOException ex) { +- LOGGER.debug("Error closing writer", ex); ++ LOG.debug("Error closing writer", ex); + } finally { + this.writer = null; + } +@@ -188,7 +185,7 @@ public class Graphite implements GraphiteSender { + socket.close(); + } + } catch (IOException ex) { +- LOGGER.debug("Error closing socket", ex); ++ LOG.debug("Error closing socket", ex); + } finally { + this.socket = null; + } +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.graphite; -- AbstractBean(ObjectName objectName) { -- this.objectName = objectName; -- } -+ /** -+ * Use specific {@link TimeUnit}s for the duration of the metrics with these names. -+ * -+ * @param specificDurationUnits a map of metric names and specific {@link TimeUnit}s -+ * @return {@code this} -+ */ -+ public Builder specificDurationUnits(Map specificDurationUnits) { -+ this.specificDurationUnits = unmodifiableMap(specificDurationUnits); -+ return this; -+ } ++import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.UTF_8; -- @Override -- public ObjectName objectName() { -- return objectName; -- } -+ /** -+ * Use specific {@link TimeUnit}s for the rate of the metrics with these names. -+ * -+ * @param specificRateUnits a map of metric names and specific {@link TimeUnit}s -+ * @return {@code this} -+ */ -+ public Builder specificRateUnits(Map specificRateUnits) { -+ this.specificRateUnits = unmodifiableMap(specificRateUnits); -+ return this; - } + import com.rabbitmq.client.Channel; +@@ -109,9 +110,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { -- @SuppressWarnings("UnusedDeclaration") -- public interface JmxGaugeMBean extends MetricMBean { -- Object getValue(); -- Number getNumber(); -+ /** -+ * Builds a {@link JmxReporter} with the given properties. -+ * -+ * @return a {@link JmxReporter} -+ */ -+ public JmxReporter build() { -+ final MetricTimeUnits timeUnits = -+ new MetricTimeUnits(rateUnit, durationUnit, specificRateUnits, specificDurationUnits); -+ if (mBeanServer == null) { -+ mBeanServer = ManagementFactory.getPlatformMBeanServer(); -+ } -+ return new JmxReporter(mBeanServer, domain, registry, filter, timeUnits, objectNameFactory); - } -+ } + @Override + public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); -- private static class JmxGauge extends AbstractBean implements JmxGaugeMBean { -- private final Gauge metric; -+ private static final Logger LOG = LoggerFactory.getLogger(JmxReporter.class); + try { + connection = connectionFactory.newConnection(); +@@ -132,8 +131,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { + final String sanitizedName = sanitize(name); + final String sanitizedValue = sanitize(value); -- private JmxGauge(Gauge metric, ObjectName objectName) { -- super(objectName); -- this.metric = metric; -- } -+ @SuppressWarnings("UnusedDeclaration") -+ public interface MetricMBean { -+ ObjectName objectName(); -+ } - -- @Override -- public Object getValue() { -- return metric.getValue(); -- } -+ private abstract static class AbstractBean implements MetricMBean { -+ private final ObjectName objectName; +- final String message = +- sanitizedName + ' ' + sanitizedValue + ' ' + Long.toString(timestamp) + '\n'; ++ final String message = sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n'; + channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); + } catch (IOException e) { + failures++; +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java +@@ -4,10 +4,8 @@ import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MAX; + import static io.dropwizard.metrics5.MetricAttribute.MEAN; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P75; + import static io.dropwizard.metrics5.MetricAttribute.P95; +@@ -17,6 +15,7 @@ import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; + import static io.dropwizard.metrics5.MetricAttribute.SUM; -- @Override -- public Number getNumber() { -- Object value = metric.getValue(); -- return value instanceof Number ? (Number) value : 0; -- } -+ AbstractBean(ObjectName objectName) { -+ this.objectName = objectName; ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -31,7 +30,6 @@ import io.dropwizard.metrics5.ScheduledReporter; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; + import java.io.IOException; +-import java.util.Collections; + import java.util.Locale; + import java.util.Map; + import java.util.Set; +@@ -85,7 +83,7 @@ public class GraphiteReporter extends ScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = ImmutableSet.of(); + this.addMetricAttributesAsTags = false; + this.floatingPointFormatter = DEFAULT_FP_FORMATTER; } - -- @SuppressWarnings("UnusedDeclaration") -- public interface JmxCounterMBean extends MetricMBean { -- long getCount(); -+ @Override -+ public ObjectName objectName() { -+ return objectName; +@@ -249,7 +247,7 @@ public class GraphiteReporter extends ScheduledReporter { } -+ } + } -- private static class JmxCounter extends AbstractBean implements JmxCounterMBean { -- private final Counter metric; -+ @SuppressWarnings("UnusedDeclaration") -+ public interface JmxGaugeMBean extends MetricMBean { -+ Object getValue(); +- private static final Logger LOGGER = LoggerFactory.getLogger(GraphiteReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(GraphiteReporter.class); + // the Carbon plaintext format is pretty underspecified, but it seems like it just wants + // US-formatted digits + private static final DoubleFunction DEFAULT_FP_FORMATTER = +@@ -430,12 +428,12 @@ public class GraphiteReporter extends ScheduledReporter { + } + graphite.flush(); + } catch (IOException e) { +- LOGGER.warn("Unable to report to Graphite", graphite, e); ++ LOG.warn("Unable to report to Graphite", graphite, e); + } finally { + try { + graphite.close(); + } catch (IOException e1) { +- LOGGER.warn("Error closing Graphite", graphite, e1); ++ LOG.warn("Error closing Graphite", graphite, e1); + } + } + } +@@ -448,16 +446,16 @@ public class GraphiteReporter extends ScheduledReporter { + try { + graphite.close(); + } catch (IOException e) { +- LOGGER.debug("Error disconnecting from Graphite", graphite, e); ++ LOG.debug("Error disconnecting from Graphite", graphite, e); + } + } + } -- private JmxCounter(Counter metric, ObjectName objectName) { -- super(objectName); -- this.metric = metric; -- } -+ Number getNumber(); -+ } + private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { + final Snapshot snapshot = timer.getSnapshot(); +- sendIfEnabled(MAX, name, convertDuration(snapshot.getMax()), timestamp); ++ sendIfEnabled(MetricAttribute.MAX, name, convertDuration(snapshot.getMax()), timestamp); + sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); +- sendIfEnabled(MIN, name, convertDuration(snapshot.getMin()), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, convertDuration(snapshot.getMin()), timestamp); + sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); + sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); + sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); +@@ -484,9 +482,9 @@ public class GraphiteReporter extends ScheduledReporter { + final Snapshot snapshot = histogram.getSnapshot(); + sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); + sendIfEnabled(SUM, name, histogram.getSum(), timestamp); +- sendIfEnabled(MAX, name, snapshot.getMax(), timestamp); ++ sendIfEnabled(MetricAttribute.MAX, name, snapshot.getMax(), timestamp); + sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); +- sendIfEnabled(MIN, name, snapshot.getMin(), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, snapshot.getMin(), timestamp); + sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); + sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); + sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.graphite; -- @Override -- public long getCount() { -- return metric.getCount(); -- } -- } -- -- @SuppressWarnings("UnusedDeclaration") -- public interface JmxHistogramMBean extends MetricMBean { -- long getCount(); -+ private static class JmxGauge extends AbstractBean implements JmxGaugeMBean { -+ private final Gauge metric; - -- long getSum(); -+ private JmxGauge(Gauge metric, ObjectName objectName) { -+ super(objectName); -+ this.metric = metric; -+ } - -- long getMin(); -+ @Override -+ public Object getValue() { -+ return metric.getValue(); -+ } - -- long getMax(); -+ @Override -+ public Number getNumber() { -+ Object value = metric.getValue(); -+ return value instanceof Number ? (Number) value : 0; -+ } -+ } - -- double getMean(); -+ @SuppressWarnings("UnusedDeclaration") -+ public interface JmxCounterMBean extends MetricMBean { -+ long getCount(); -+ } - -- double getStdDev(); -+ private static class JmxCounter extends AbstractBean implements JmxCounterMBean { -+ private final Counter metric; - -- double get50thPercentile(); -+ private JmxCounter(Counter metric, ObjectName objectName) { -+ super(objectName); -+ this.metric = metric; -+ } - -- double get75thPercentile(); -+ @Override -+ public long getCount() { -+ return metric.getCount(); -+ } -+ } - -- double get95thPercentile(); -+ @SuppressWarnings("UnusedDeclaration") -+ public interface JmxHistogramMBean extends MetricMBean { -+ long getCount(); - -- double get98thPercentile(); -+ long getSum(); - -- double get99thPercentile(); -+ long getMin(); - -- double get999thPercentile(); -+ long getMax(); - -- long[] values(); -+ double getMean(); - -- long getSnapshotSize(); -- } -+ double getStdDev(); ++import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.UTF_8; -- private static class JmxHistogram implements JmxHistogramMBean { -- private final ObjectName objectName; -- private final Histogram metric; -+ double get50thPercentile(); + import java.io.IOException; +@@ -43,9 +44,7 @@ public class GraphiteUDP implements GraphiteSender { -- private JmxHistogram(Histogram metric, ObjectName objectName) { -- this.metric = metric; -- this.objectName = objectName; -- } -+ double get75thPercentile(); + @Override + public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); -- @Override -- public ObjectName objectName() { -- return objectName; -- } -+ double get95thPercentile(); + // Resolve hostname + if (hostname != null) { +@@ -63,7 +62,7 @@ public class GraphiteUDP implements GraphiteSender { + @Override + public void send(String name, String value, long timestamp) throws IOException { + try { +- String str = sanitize(name) + ' ' + sanitize(value) + ' ' + Long.toString(timestamp) + '\n'; ++ String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n'; + ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); + datagramChannel.send(byteBuffer, address); + this.failures = 0; +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.graphite; -- @Override -- public double get50thPercentile() { -- return metric.getSnapshot().getMedian(); -- } -+ double get98thPercentile(); ++import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.UTF_8; -- @Override -- public long getCount() { -- return metric.getCount(); -- } -+ double get99thPercentile(); + import java.io.BufferedWriter; +@@ -48,7 +49,7 @@ public class PickledGraphite implements GraphiteSender { + QUOTE = '\'', + LF = '\n'; -- @Override -- public long getSum() { -- return metric.getSum(); -- } -+ double get999thPercentile(); +- private static final Logger LOGGER = LoggerFactory.getLogger(PickledGraphite.class); ++ private static final Logger LOG = LoggerFactory.getLogger(PickledGraphite.class); + private static final int DEFAULT_BATCH_SIZE = 100; -- @Override -- public long getMin() { -- return metric.getSnapshot().getMin(); -- } -+ long[] values(); + private int batchSize; +@@ -173,9 +174,7 @@ public class PickledGraphite implements GraphiteSender { -- @Override -- public long getMax() { -- return metric.getSnapshot().getMax(); -- } -+ long getSnapshotSize(); -+ } + @Override + public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); + InetSocketAddress address = this.address; + if (address == null) { + address = new InetSocketAddress(hostname, port); +@@ -249,7 +248,7 @@ public class PickledGraphite implements GraphiteSender { + * message to graphite 3. Clear out the list of metrics + */ + private void writeMetrics() throws IOException { +- if (metrics.size() > 0) { ++ if (!metrics.isEmpty()) { + try { + byte[] payload = pickleMetrics(metrics); + byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); +@@ -260,8 +259,8 @@ public class PickledGraphite implements GraphiteSender { + outputStream.write(payload); + outputStream.flush(); + +- if (LOGGER.isDebugEnabled()) { +- LOGGER.debug("Wrote {} metrics", metrics.size()); ++ if (LOG.isDebugEnabled()) { ++ LOG.debug("Wrote {} metrics", metrics.size()); + } + } catch (IOException e) { + this.failures++; +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java +@@ -8,7 +8,6 @@ import static org.mockito.Mockito.anyString; + import static org.mockito.Mockito.atMost; + import static org.mockito.Mockito.doThrow; + import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; -- @Override -- public double getMean() { -- return metric.getSnapshot().getMean(); -- } -+ private static class JmxHistogram implements JmxHistogramMBean { -+ private final ObjectName objectName; -+ private final Histogram metric; +@@ -20,14 +19,14 @@ import java.net.UnknownHostException; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- @Override -- public double getStdDev() { -- return metric.getSnapshot().getStdDev(); -- } -+ private JmxHistogram(Histogram metric, ObjectName objectName) { -+ this.metric = metric; -+ this.objectName = objectName; -+ } - -- @Override -- public double get75thPercentile() { -- return metric.getSnapshot().get75thPercentile(); -- } -+ @Override -+ public ObjectName objectName() { -+ return objectName; -+ } - -- @Override -- public double get95thPercentile() { -- return metric.getSnapshot().get95thPercentile(); -- } -+ @Override -+ public double get50thPercentile() { -+ return metric.getSnapshot().getMedian(); -+ } - -- @Override -- public double get98thPercentile() { -- return metric.getSnapshot().get98thPercentile(); -- } -+ @Override -+ public long getCount() { -+ return metric.getCount(); -+ } - -- @Override -- public double get99thPercentile() { -- return metric.getSnapshot().get99thPercentile(); -- } -+ @Override -+ public long getSum() { -+ return metric.getSum(); -+ } - -- @Override -- public double get999thPercentile() { -- return metric.getSnapshot().get999thPercentile(); -- } -+ @Override -+ public long getMin() { -+ return metric.getSnapshot().getMin(); -+ } - -- @Override -- public long[] values() { -- return metric.getSnapshot().getValues(); -- } -+ @Override -+ public long getMax() { -+ return metric.getSnapshot().getMax(); -+ } - -- @Override -- public long getSnapshotSize() { -- return metric.getSnapshot().size(); -- } -+ @Override -+ public double getMean() { -+ return metric.getSnapshot().getMean(); - } +-class GraphiteRabbitMQTest { +- private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); +- private final Connection connection = mock(Connection.class); +- private final Channel channel = mock(Channel.class); ++final class GraphiteRabbitMQTest { ++ private final ConnectionFactory connectionFactory = mock(); ++ private final Connection connection = mock(); ++ private final Channel channel = mock(); -- @SuppressWarnings("UnusedDeclaration") -- public interface JmxMeterMBean extends MetricMBean { -- long getCount(); -+ @Override -+ public double getStdDev() { -+ return metric.getSnapshot().getStdDev(); -+ } - -- double getSum(); -+ @Override -+ public double get75thPercentile() { -+ return metric.getSnapshot().get75thPercentile(); -+ } - -- double getMeanRate(); -+ @Override -+ public double get95thPercentile() { -+ return metric.getSnapshot().get95thPercentile(); -+ } - -- double getOneMinuteRate(); -+ @Override -+ public double get98thPercentile() { -+ return metric.getSnapshot().get98thPercentile(); -+ } - -- double getFiveMinuteRate(); -+ @Override -+ public double get99thPercentile() { -+ return metric.getSnapshot().get99thPercentile(); -+ } - -- double getFifteenMinuteRate(); -+ @Override -+ public double get999thPercentile() { -+ return metric.getSnapshot().get999thPercentile(); -+ } - -- String getRateUnit(); -+ @Override -+ public long[] values() { -+ return metric.getSnapshot().getValues(); - } +- private final ConnectionFactory bogusConnectionFactory = mock(ConnectionFactory.class); +- private final Connection bogusConnection = mock(Connection.class); +- private final Channel bogusChannel = mock(Channel.class); ++ private final ConnectionFactory bogusConnectionFactory = mock(); ++ private final Connection bogusConnection = mock(); ++ private final Channel bogusChannel = mock(); -- private static class JmxMeter extends AbstractBean implements JmxMeterMBean { -- private final Metered metric; -- private final double rateFactor; -- private final String rateUnit; -+ @Override -+ public long getSnapshotSize() { -+ return metric.getSnapshot().size(); -+ } -+ } - -- private JmxMeter(Metered metric, ObjectName objectName, TimeUnit rateUnit) { -- super(objectName); -- this.metric = metric; -- this.rateFactor = rateUnit.toSeconds(1); -- this.rateUnit = ("events/" + calculateRateUnit(rateUnit)).intern(); -- } -+ @SuppressWarnings("UnusedDeclaration") -+ public interface JmxMeterMBean extends MetricMBean { -+ long getCount(); + private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); -- @Override -- public long getCount() { -- return metric.getCount(); -- } -+ double getSum(); +@@ -92,10 +91,9 @@ class GraphiteRabbitMQTest { -- @Override -- public double getSum() { -- return metric.getSum(); -- } -+ double getMeanRate(); + String expectedMessage = "name value 100\n"; -- @Override -- public double getMeanRate() { -- return metric.getMeanRate() * rateFactor; -- } -+ double getOneMinuteRate(); +- verify(channel, times(1)) +- .basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); ++ verify(channel).basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); -- @Override -- public double getOneMinuteRate() { -- return metric.getOneMinuteRate() * rateFactor; -- } -+ double getFiveMinuteRate(); +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } -- @Override -- public double getFiveMinuteRate() { -- return metric.getFiveMinuteRate() * rateFactor; -- } -+ double getFifteenMinuteRate(); + @Test +@@ -105,10 +103,10 @@ class GraphiteRabbitMQTest { -- @Override -- public double getFifteenMinuteRate() { -- return metric.getFifteenMinuteRate() * rateFactor; -- } -+ String getRateUnit(); -+ } + String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; -- @Override -- public String getRateUnit() { -- return rateUnit; -- } -+ private static class JmxMeter extends AbstractBean implements JmxMeterMBean { -+ private final Metered metric; -+ private final double rateFactor; -+ private final String rateUnit; - -- private String calculateRateUnit(TimeUnit unit) { -- final String s = unit.toString().toLowerCase(Locale.US); -- return s.substring(0, s.length() - 1); -- } -+ private JmxMeter(Metered metric, ObjectName objectName, TimeUnit rateUnit) { -+ super(objectName); -+ this.metric = metric; -+ this.rateFactor = rateUnit.toSeconds(1); -+ this.rateUnit = ("events/" + calculateRateUnit(rateUnit)).intern(); - } +- verify(channel, times(1)) ++ verify(channel) + .basicPublish("graphite", "name-to-sanitize", null, expectedMessage.getBytes(UTF_8)); -- @SuppressWarnings("UnusedDeclaration") -- public interface JmxTimerMBean extends JmxMeterMBean { -- double getMin(); -+ @Override -+ public long getCount() { -+ return metric.getCount(); -+ } - -- double getMax(); -+ @Override -+ public double getSum() { -+ return metric.getSum(); -+ } - -- double getMean(); -+ @Override -+ public double getMeanRate() { -+ return metric.getMeanRate() * rateFactor; -+ } - -- double getStdDev(); -+ @Override -+ public double getOneMinuteRate() { -+ return metric.getOneMinuteRate() * rateFactor; -+ } - -- double get50thPercentile(); -+ @Override -+ public double getFiveMinuteRate() { -+ return metric.getFiveMinuteRate() * rateFactor; -+ } - -- double get75thPercentile(); -+ @Override -+ public double getFifteenMinuteRate() { -+ return metric.getFifteenMinuteRate() * rateFactor; -+ } - -- double get95thPercentile(); -+ @Override -+ public String getRateUnit() { -+ return rateUnit; -+ } - -- double get98thPercentile(); -+ private String calculateRateUnit(TimeUnit unit) { -+ final String s = unit.toString().toLowerCase(Locale.US); -+ return s.substring(0, s.length() - 1); -+ } -+ } - -- double get99thPercentile(); -+ @SuppressWarnings("UnusedDeclaration") -+ public interface JmxTimerMBean extends JmxMeterMBean { -+ double getMin(); - -- double get999thPercentile(); -+ double getMax(); - -- long[] values(); -+ double getMean(); - -- String getDurationUnit(); -- } -+ double getStdDev(); - -- static class JmxTimer extends JmxMeter implements JmxTimerMBean { -- private final Timer metric; -- private final double durationFactor; -- private final String durationUnit; -+ double get50thPercentile(); - -- private JmxTimer(Timer metric, -- ObjectName objectName, -- TimeUnit rateUnit, -- TimeUnit durationUnit) { -- super(metric, objectName, rateUnit); -- this.metric = metric; -- this.durationFactor = 1.0 / durationUnit.toNanos(1); -- this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); -- } -+ double get75thPercentile(); +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } -- @Override -- public double get50thPercentile() { -- return metric.getSnapshot().getMedian() * durationFactor; -- } -+ double get95thPercentile(); + @Test +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java +@@ -8,6 +8,7 @@ import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verifyNoMoreInteractions; + import static org.mockito.Mockito.when; -- @Override -- public double getMin() { -- return metric.getSnapshot().getMin() * durationFactor; -- } -+ double get98thPercentile(); ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -22,7 +23,6 @@ import io.dropwizard.metrics5.Timer; + import java.net.UnknownHostException; + import java.text.DecimalFormat; + import java.text.DecimalFormatSymbols; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.Locale; + import java.util.Set; +@@ -33,15 +33,15 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.mockito.InOrder; -- @Override -- public double getMax() { -- return metric.getSnapshot().getMax() * durationFactor; -- } -+ double get99thPercentile(); +-class GraphiteReporterTest { ++final class GraphiteReporterTest { + private static final MetricName GAUGE = MetricName.build("gauge"); + private static final MetricName METER = MetricName.build("meter"); + private static final MetricName COUNTER = MetricName.build("counter"); + + private final long timestamp = 1000198; +- private final Clock clock = mock(Clock.class); +- private final Graphite graphite = mock(Graphite.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final Clock clock = mock(); ++ private final Graphite graphite = mock(); ++ private final MetricRegistry registry = mock(); + private final GraphiteReporter reporter = + GraphiteReporter.forRegistry(registry) + .withClock(clock) +@@ -49,7 +49,7 @@ class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .build(graphite); + + private final GraphiteReporter minuteRateReporter = +@@ -59,7 +59,7 @@ class GraphiteReporterTest { + .convertRatesTo(TimeUnit.MINUTES) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .build(graphite); -- @Override -- public double getMean() { -- return metric.getSnapshot().getMean() * durationFactor; -- } -+ double get999thPercentile(); + @BeforeEach +@@ -179,7 +179,7 @@ class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .withFloatingPointFormatter(formatter::format) + .build(graphite)) { + reportGaugeValue(graphiteReporter, 0.000045322); +@@ -222,7 +222,7 @@ class GraphiteReporterTest { -- @Override -- public double getStdDev() { -- return metric.getSnapshot().getStdDev() * durationFactor; -- } -+ long[] values(); + @Test + void reportsCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); -- @Override -- public double get75thPercentile() { -- return metric.getSnapshot().get75thPercentile() * durationFactor; -- } -+ String getDurationUnit(); -+ } + reporter.report(map(), map(COUNTER, counter), map(), map(), map()); +@@ -238,11 +238,11 @@ class GraphiteReporterTest { -- @Override -- public double get95thPercentile() { -- return metric.getSnapshot().get95thPercentile() * durationFactor; -- } -+ static class JmxTimer extends JmxMeter implements JmxTimerMBean { -+ private final Timer metric; -+ private final double durationFactor; -+ private final String durationUnit; - -- @Override -- public double get98thPercentile() { -- return metric.getSnapshot().get98thPercentile() * durationFactor; -- } -+ private JmxTimer( -+ Timer metric, ObjectName objectName, TimeUnit rateUnit, TimeUnit durationUnit) { -+ super(metric, objectName, rateUnit); -+ this.metric = metric; -+ this.durationFactor = 1.0 / durationUnit.toNanos(1); -+ this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); -+ } - -- @Override -- public double get99thPercentile() { -- return metric.getSnapshot().get99thPercentile() * durationFactor; -- } -+ @Override -+ public double get50thPercentile() { -+ return metric.getSnapshot().getMedian() * durationFactor; -+ } - -- @Override -- public double get999thPercentile() { -- return metric.getSnapshot().get999thPercentile() * durationFactor; -- } -- -- @Override -- public double getSum() { -- return super.getSum() * durationFactor; -- } -+ @Override -+ public double getMin() { -+ return metric.getSnapshot().getMin() * durationFactor; -+ } - -- @Override -- public long[] values() { -- return metric.getSnapshot().getValues(); -- } -+ @Override -+ public double getMax() { -+ return metric.getSnapshot().getMax() * durationFactor; -+ } - -- @Override -- public String getDurationUnit() { -- return durationUnit; -- } -+ @Override -+ public double getMean() { -+ return metric.getSnapshot().getMean() * durationFactor; - } + @Test + void reportsHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(12L); -- private static class JmxListener implements MetricRegistryListener { -- private final String name; -- private final MBeanServer mBeanServer; -- private final MetricFilter filter; -- private final MetricTimeUnits timeUnits; -- private final Map registered; -- private final ObjectNameFactory objectNameFactory; -- -- private JmxListener(MBeanServer mBeanServer, String name, MetricFilter filter, MetricTimeUnits timeUnits, ObjectNameFactory objectNameFactory) { -- this.mBeanServer = mBeanServer; -- this.name = name; -- this.filter = filter; -- this.timeUnits = timeUnits; -- this.registered = new ConcurrentHashMap<>(); -- this.objectNameFactory = objectNameFactory; -- } -+ @Override -+ public double getStdDev() { -+ return metric.getSnapshot().getStdDev() * durationFactor; -+ } - -- private void registerMBean(Object mBean, ObjectName objectName) throws InstanceAlreadyExistsException, JMException { -- ObjectInstance objectInstance = mBeanServer.registerMBean(mBean, objectName); -- if (objectInstance != null) { -- // the websphere mbeanserver rewrites the objectname to include -- // cell, node & server info -- // make sure we capture the new objectName for unregistration -- registered.put(objectName, objectInstance.getObjectName()); -- } else { -- registered.put(objectName, objectName); -- } -- } -+ @Override -+ public double get75thPercentile() { -+ return metric.getSnapshot().get75thPercentile() * durationFactor; -+ } - -- private void unregisterMBean(ObjectName originalObjectName) throws InstanceNotFoundException, MBeanRegistrationException { -- ObjectName storedObjectName = registered.remove(originalObjectName); -- if (storedObjectName != null) { -- mBeanServer.unregisterMBean(storedObjectName); -- } else { -- mBeanServer.unregisterMBean(originalObjectName); -- } -- } -+ @Override -+ public double get95thPercentile() { -+ return metric.getSnapshot().get95thPercentile() * durationFactor; -+ } - -- @Override -- public void onGaugeAdded(MetricName name, Gauge gauge) { -- try { -- if (filter.matches(name, gauge)) { -- final ObjectName objectName = createName("gauges", name); -- registerMBean(new JmxGauge(gauge, objectName), objectName); -- } -- } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register gauge", e); -- } catch (JMException e) { -- LOGGER.warn("Unable to register gauge", e); -- } -- } -+ @Override -+ public double get98thPercentile() { -+ return metric.getSnapshot().get98thPercentile() * durationFactor; -+ } - -- @Override -- public void onGaugeRemoved(MetricName name) { -- try { -- final ObjectName objectName = createName("gauges", name); -- unregisterMBean(objectName); -- } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister gauge", e); -- } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister gauge", e); -- } -- } -+ @Override -+ public double get99thPercentile() { -+ return metric.getSnapshot().get99thPercentile() * durationFactor; -+ } - -- @Override -- public void onCounterAdded(MetricName name, Counter counter) { -- try { -- if (filter.matches(name, counter)) { -- final ObjectName objectName = createName("counters", name); -- registerMBean(new JmxCounter(counter, objectName), objectName); -- } -- } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register counter", e); -- } catch (JMException e) { -- LOGGER.warn("Unable to register counter", e); -- } -- } -+ @Override -+ public double get999thPercentile() { -+ return metric.getSnapshot().get999thPercentile() * durationFactor; -+ } - -- @Override -- public void onCounterRemoved(MetricName name) { -- try { -- final ObjectName objectName = createName("counters", name); -- unregisterMBean(objectName); -- } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister counter", e); -- } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister counter", e); -- } -- } -+ @Override -+ public double getSum() { -+ return super.getSum() * durationFactor; -+ } - -- @Override -- public void onHistogramAdded(MetricName name, Histogram histogram) { -- try { -- if (filter.matches(name, histogram)) { -- final ObjectName objectName = createName("histograms", name); -- registerMBean(new JmxHistogram(histogram, objectName), objectName); -- } -- } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register histogram", e); -- } catch (JMException e) { -- LOGGER.warn("Unable to register histogram", e); -- } -- } -+ @Override -+ public long[] values() { -+ return metric.getSnapshot().getValues(); -+ } - -- @Override -- public void onHistogramRemoved(MetricName name) { -- try { -- final ObjectName objectName = createName("histograms", name); -- unregisterMBean(objectName); -- } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister histogram", e); -- } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister histogram", e); -- } -- } -+ @Override -+ public String getDurationUnit() { -+ return durationUnit; -+ } -+ } -+ -+ private static class JmxListener implements MetricRegistryListener { -+ private final String name; -+ private final MBeanServer mBeanServer; -+ private final MetricFilter filter; -+ private final MetricTimeUnits timeUnits; -+ private final Map registered; -+ private final ObjectNameFactory objectNameFactory; -+ -+ private JmxListener( -+ MBeanServer mBeanServer, -+ String name, -+ MetricFilter filter, -+ MetricTimeUnits timeUnits, -+ ObjectNameFactory objectNameFactory) { -+ this.mBeanServer = mBeanServer; -+ this.name = name; -+ this.filter = filter; -+ this.timeUnits = timeUnits; -+ this.registered = new ConcurrentHashMap<>(); -+ this.objectNameFactory = objectNameFactory; -+ } - -- @Override -- public void onMeterAdded(MetricName name, Meter meter) { -- try { -- if (filter.matches(name, meter)) { -- final ObjectName objectName = createName("meters", name); -- registerMBean(new JmxMeter(meter, objectName, timeUnits.rateFor(name.getKey())), objectName); -- } -- } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register meter", e); -- } catch (JMException e) { -- LOGGER.warn("Unable to register meter", e); -- } -- } -+ private void registerMBean(Object mBean, ObjectName objectName) -+ throws InstanceAlreadyExistsException, JMException { -+ ObjectInstance objectInstance = mBeanServer.registerMBean(mBean, objectName); -+ if (objectInstance != null) { -+ // the websphere mbeanserver rewrites the objectname to include -+ // cell, node & server info -+ // make sure we capture the new objectName for unregistration -+ registered.put(objectName, objectInstance.getObjectName()); -+ } else { -+ registered.put(objectName, objectName); -+ } -+ } - -- @Override -- public void onMeterRemoved(MetricName name) { -- try { -- final ObjectName objectName = createName("meters", name); -- unregisterMBean(objectName); -- } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister meter", e); -- } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister meter", e); -- } -- } -+ private void unregisterMBean(ObjectName originalObjectName) -+ throws InstanceNotFoundException, MBeanRegistrationException { -+ ObjectName storedObjectName = registered.remove(originalObjectName); -+ if (storedObjectName != null) { -+ mBeanServer.unregisterMBean(storedObjectName); -+ } else { -+ mBeanServer.unregisterMBean(originalObjectName); -+ } -+ } - -- @Override -- public void onTimerAdded(MetricName name, Timer timer) { -- try { -- if (filter.matches(name, timer)) { -- final ObjectName objectName = createName("timers", name); -- registerMBean(new JmxTimer(timer, objectName, timeUnits.rateFor(name.getKey()), timeUnits.durationFor(name.getKey())), objectName); -- } -- } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register timer", e); -- } catch (JMException e) { -- LOGGER.warn("Unable to register timer", e); -- } -- } -+ @Override -+ public void onGaugeAdded(MetricName name, Gauge gauge) { -+ try { -+ if (filter.matches(name, gauge)) { -+ final ObjectName objectName = createName("gauges", name); -+ registerMBean(new JmxGauge(gauge, objectName), objectName); -+ } -+ } catch (InstanceAlreadyExistsException e) { -+ LOG.debug("Unable to register gauge", e); -+ } catch (JMException e) { -+ LOG.warn("Unable to register gauge", e); -+ } -+ } - -- @Override -- public void onTimerRemoved(MetricName name) { -- try { -- final ObjectName objectName = createName("timers", name); -- unregisterMBean(objectName); -- } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister timer", e); -- } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister timer", e); -- } -- } -+ @Override -+ public void onGaugeRemoved(MetricName name) { -+ try { -+ final ObjectName objectName = createName("gauges", name); -+ unregisterMBean(objectName); -+ } catch (InstanceNotFoundException e) { -+ LOG.debug("Unable to unregister gauge", e); -+ } catch (MBeanRegistrationException e) { -+ LOG.warn("Unable to unregister gauge", e); -+ } -+ } +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -280,7 +280,7 @@ class GraphiteReporterTest { -- private ObjectName createName(String type, MetricName name) { -- return objectNameFactory.createName(type, this.name, name); -- } -+ @Override -+ public void onCounterAdded(MetricName name, Counter counter) { -+ try { -+ if (filter.matches(name, counter)) { -+ final ObjectName objectName = createName("counters", name); -+ registerMBean(new JmxCounter(counter, objectName), objectName); -+ } -+ } catch (InstanceAlreadyExistsException e) { -+ LOG.debug("Unable to register counter", e); -+ } catch (JMException e) { -+ LOG.warn("Unable to register counter", e); -+ } -+ } - -- void unregisterAll() { -- for (ObjectName name : registered.keySet()) { -- try { -- unregisterMBean(name); -- } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister metric", e); -- } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister metric", e); -- } -- } -- registered.clear(); -- } -+ @Override -+ public void onCounterRemoved(MetricName name) { -+ try { -+ final ObjectName objectName = createName("counters", name); -+ unregisterMBean(objectName); -+ } catch (InstanceNotFoundException e) { -+ LOG.debug("Unable to unregister counter", e); -+ } catch (MBeanRegistrationException e) { -+ LOG.warn("Unable to unregister counter", e); -+ } - } + @Test + void reportsMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -306,7 +306,7 @@ class GraphiteReporterTest { -- private static class MetricTimeUnits { -- private final TimeUnit defaultRate; -- private final TimeUnit defaultDuration; -- private final Map rateOverrides; -- private final Map durationOverrides; -- -- MetricTimeUnits(TimeUnit defaultRate, -- TimeUnit defaultDuration, -- Map rateOverrides, -- Map durationOverrides) { -- this.defaultRate = defaultRate; -- this.defaultDuration = defaultDuration; -- this.rateOverrides = rateOverrides; -- this.durationOverrides = durationOverrides; -- } -+ @Override -+ public void onHistogramAdded(MetricName name, Histogram histogram) { -+ try { -+ if (filter.matches(name, histogram)) { -+ final ObjectName objectName = createName("histograms", name); -+ registerMBean(new JmxHistogram(histogram, objectName), objectName); -+ } -+ } catch (InstanceAlreadyExistsException e) { -+ LOG.debug("Unable to register histogram", e); -+ } catch (JMException e) { -+ LOG.warn("Unable to register histogram", e); -+ } -+ } + @Test + void reportsMetersInMinutes() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -333,7 +333,7 @@ class GraphiteReporterTest { -- public TimeUnit durationFor(String name) { -- return durationOverrides.getOrDefault(name, defaultDuration); -- } -+ @Override -+ public void onHistogramRemoved(MetricName name) { -+ try { -+ final ObjectName objectName = createName("histograms", name); -+ unregisterMBean(objectName); -+ } catch (InstanceNotFoundException e) { -+ LOG.debug("Unable to unregister histogram", e); -+ } catch (MBeanRegistrationException e) { -+ LOG.warn("Unable to unregister histogram", e); -+ } -+ } + @Test + void reportsTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -341,7 +341,7 @@ class GraphiteReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -410,7 +410,7 @@ class GraphiteReporterTest { -- public TimeUnit rateFor(String name) { -- return rateOverrides.getOrDefault(name, defaultRate); -- } -+ @Override -+ public void onMeterAdded(MetricName name, Meter meter) { -+ try { -+ if (filter.matches(name, meter)) { -+ final ObjectName objectName = createName("meters", name); -+ registerMBean( -+ new JmxMeter(meter, objectName, timeUnits.rateFor(name.getKey())), objectName); -+ } -+ } catch (InstanceAlreadyExistsException e) { -+ LOG.debug("Unable to register meter", e); -+ } catch (JMException e) { -+ LOG.warn("Unable to register meter", e); -+ } - } + @Test + void disabledMetricsAttribute() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -418,7 +418,7 @@ class GraphiteReporterTest { + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(11L); -- private final MetricRegistry registry; -- private final JmxListener listener; -+ @Override -+ public void onMeterRemoved(MetricName name) { -+ try { -+ final ObjectName objectName = createName("meters", name); -+ unregisterMBean(objectName); -+ } catch (InstanceNotFoundException e) { -+ LOG.debug("Unable to unregister meter", e); -+ } catch (MBeanRegistrationException e) { -+ LOG.warn("Unable to unregister meter", e); -+ } -+ } - -- private JmxReporter(MBeanServer mBeanServer, -- String domain, -- MetricRegistry registry, -- MetricFilter filter, -- MetricTimeUnits timeUnits, -- ObjectNameFactory objectNameFactory) { -- this.registry = registry; -- this.listener = new JmxListener(mBeanServer, domain, filter, timeUnits, objectNameFactory); -+ @Override -+ public void onTimerAdded(MetricName name, Timer timer) { -+ try { -+ if (filter.matches(name, timer)) { -+ final ObjectName objectName = createName("timers", name); -+ registerMBean( -+ new JmxTimer( -+ timer, -+ objectName, -+ timeUnits.rateFor(name.getKey()), -+ timeUnits.durationFor(name.getKey())), -+ objectName); -+ } -+ } catch (InstanceAlreadyExistsException e) { -+ LOG.debug("Unable to register timer", e); -+ } catch (JMException e) { -+ LOG.warn("Unable to register timer", e); -+ } - } + Set disabledMetricAttributes = +@@ -450,7 +450,7 @@ class GraphiteReporterTest { -- /** -- * Starts the reporter. -- */ -- public void start() { -- registry.addListener(listener); -+ @Override -+ public void onTimerRemoved(MetricName name) { -+ try { -+ final ObjectName objectName = createName("timers", name); -+ unregisterMBean(objectName); -+ } catch (InstanceNotFoundException e) { -+ LOG.debug("Unable to unregister timer", e); -+ } catch (MBeanRegistrationException e) { -+ LOG.warn("Unable to unregister timer", e); -+ } - } + @Test + void sendsMetricAttributesAsTagsIfEnabled() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + getReporterThatSendsMetricAttributesAsTags() +@@ -476,7 +476,7 @@ class GraphiteReporterTest { + MetricFilter.ALL, + null, + false, +- Collections.emptySet(), ++ ImmutableSet.of(), + false) { + @Override + protected String format(double v) { +@@ -492,7 +492,7 @@ class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .addMetricAttributesAsTags(true) + .build(graphite); + } +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java +@@ -3,7 +3,7 @@ package io.dropwizard.metrics5.graphite; + import org.assertj.core.api.SoftAssertions; + import org.junit.jupiter.api.Test; -- /** -- * Stops the reporter. -- */ -- public void stop() { -- registry.removeListener(listener); -- listener.unregisterAll(); -+ private ObjectName createName(String type, MetricName name) { -+ return objectNameFactory.createName(type, this.name, name); - } +-class GraphiteSanitizeTest { ++final class GraphiteSanitizeTest { + @Test + void sanitizeGraphiteValues() { + SoftAssertions softly = new SoftAssertions(); +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java +@@ -23,14 +23,14 @@ import javax.net.SocketFactory; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- /** -- * Stops the reporter. -- */ -- @Override -- public void close() { -- stop(); -+ void unregisterAll() { -+ for (ObjectName name : registered.keySet()) { -+ try { -+ unregisterMBean(name); -+ } catch (InstanceNotFoundException e) { -+ LOG.debug("Unable to unregister metric", e); -+ } catch (MBeanRegistrationException e) { -+ LOG.warn("Unable to unregister metric", e); -+ } -+ } -+ registered.clear(); -+ } -+ } -+ -+ private static class MetricTimeUnits { -+ private final TimeUnit defaultRate; -+ private final TimeUnit defaultDuration; -+ private final Map rateOverrides; -+ private final Map durationOverrides; -+ -+ MetricTimeUnits( -+ TimeUnit defaultRate, -+ TimeUnit defaultDuration, -+ Map rateOverrides, -+ Map durationOverrides) { -+ this.defaultRate = defaultRate; -+ this.defaultDuration = defaultDuration; -+ this.rateOverrides = rateOverrides; -+ this.durationOverrides = durationOverrides; - } +-class GraphiteTest { ++final class GraphiteTest { + private final String host = "example.com"; + private final int port = 1234; +- private final SocketFactory socketFactory = mock(SocketFactory.class); ++ private final SocketFactory socketFactory = mock(); + private final InetSocketAddress address = new InetSocketAddress(host, port); -- /** -- * Visible for testing -- */ -- ObjectNameFactory getObjectNameFactory() { -- return listener.objectNameFactory; -+ public TimeUnit durationFor(String name) { -+ return durationOverrides.getOrDefault(name, defaultDuration); +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); + + @BeforeEach + void setUp() throws Exception { +@@ -84,7 +84,7 @@ class GraphiteTest { + @Test + void measuresFailures() throws IOException { + try (Graphite graphite = new Graphite(address, socketFactory)) { +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); } + } -+ public TimeUnit rateFor(String name) { -+ return rateOverrides.getOrDefault(name, defaultRate); -+ } -+ } -+ -+ private final MetricRegistry registry; -+ private final JmxListener listener; -+ -+ private JmxReporter( -+ MBeanServer mBeanServer, -+ String domain, -+ MetricRegistry registry, -+ MetricFilter filter, -+ MetricTimeUnits timeUnits, -+ ObjectNameFactory objectNameFactory) { -+ this.registry = registry; -+ this.listener = new JmxListener(mBeanServer, domain, filter, timeUnits, objectNameFactory); -+ } -+ -+ /** Starts the reporter. */ -+ public void start() { -+ registry.addListener(listener); -+ } -+ -+ /** Stops the reporter. */ -+ public void stop() { -+ registry.removeListener(listener); -+ listener.unregisterAll(); -+ } -+ -+ /** Stops the reporter. */ -+ @Override -+ public void close() { -+ stop(); -+ } -+ -+ /** Visible for testing */ -+ ObjectNameFactory getObjectNameFactory() { -+ return listener.objectNameFactory; -+ } - } ---- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/ObjectNameFactory.java -+++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/ObjectNameFactory.java -@@ -1,10 +1,9 @@ - package io.dropwizard.metrics5.jmx; +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java +@@ -1,15 +1,15 @@ + package io.dropwizard.metrics5.graphite; - import io.dropwizard.metrics5.MetricName; -- - import javax.management.ObjectName; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; - public interface ObjectNameFactory { + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; + import java.nio.channels.DatagramChannel; + import org.junit.jupiter.api.Test; +-import org.mockito.Mockito; -- ObjectName createName(String type, String domain, MetricName name); -+ ObjectName createName(String type, String domain, MetricName name); - } ---- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java -+++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java -@@ -1,41 +1,51 @@ - package io.dropwizard.metrics5.jmx; +-class GraphiteUDPTest { ++final class GraphiteUDPTest { --import io.dropwizard.metrics5.MetricName; --import org.junit.jupiter.api.Test; -- --import javax.management.ObjectName; -- --import static org.assertj.core.api.Assertions.assertThatCode; - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatCode; + private final String host = "example.com"; + private final int port = 1234; +@@ -30,7 +30,7 @@ class GraphiteUDPTest { + @Test + void writesValue() throws Exception { + graphiteUDP = new GraphiteUDP(host, port); +- DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); ++ DatagramChannel mockDatagramChannel = mock(); + graphiteUDP.setDatagramChannel(mockDatagramChannel); + graphiteUDP.setAddress(new InetSocketAddress(host, port)); --class DefaultObjectNameFactoryTest { -- -- @Test -- void createsObjectNameWithDomainInInput() { -- DefaultObjectNameFactory f = new DefaultObjectNameFactory(); -- ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); -- assertThat(on.getDomain()).isEqualTo("com.domain"); -- assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); -- assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); -- } -- -- @Test -- void createsObjectNameWithNameAsKeyPropertyName() { -- DefaultObjectNameFactory f = new DefaultObjectNameFactory(); -- ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); -- assertThat(on.getKeyProperty("name")).isEqualTo("something.with.dots"); -- assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); -- assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); -- -- } -+import io.dropwizard.metrics5.MetricName; -+import javax.management.ObjectName; -+import org.junit.jupiter.api.Test; - -- @Test -- void createsObjectNameWithNameWithDisallowedUnquotedCharacters() { -- DefaultObjectNameFactory f = new DefaultObjectNameFactory(); -- ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.quotes(\"ABcd\")").tagged("foo", "bar", "baz", "biz")); -- assertThatCode(() -> new ObjectName(on.toString())).doesNotThrowAnyException(); -- assertThat(on.getKeyProperty("name")).isEqualTo("\"something.with.quotes(\\\"ABcd\\\")\""); -- assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); -- assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); -- } -+final class DefaultObjectNameFactoryTest { -+ -+ @Test -+ void createsObjectNameWithDomainInInput() { -+ DefaultObjectNameFactory f = new DefaultObjectNameFactory(); -+ ObjectName on = -+ f.createName( -+ "type", -+ "com.domain", -+ MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); -+ assertThat(on.getDomain()).isEqualTo("com.domain"); -+ assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); -+ assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); -+ } -+ -+ @Test -+ void createsObjectNameWithNameAsKeyPropertyName() { -+ DefaultObjectNameFactory f = new DefaultObjectNameFactory(); -+ ObjectName on = -+ f.createName( -+ "type", -+ "com.domain", -+ MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); -+ assertThat(on.getKeyProperty("name")).isEqualTo("something.with.dots"); -+ assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); -+ assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); -+ } -+ -+ @Test -+ void createsObjectNameWithNameWithDisallowedUnquotedCharacters() { -+ DefaultObjectNameFactory f = new DefaultObjectNameFactory(); -+ ObjectName on = -+ f.createName( -+ "type", -+ "com.domain", -+ MetricName.build("something.with.quotes(\"ABcd\")").tagged("foo", "bar", "baz", "biz")); -+ assertThatCode(() -> new ObjectName(on.toString())).doesNotThrowAnyException(); -+ assertThat(on.getKeyProperty("name")).isEqualTo("\"something.with.quotes(\\\"ABcd\\\")\""); -+ assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); -+ assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); -+ } - } ---- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java -+++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java -@@ -1,5 +1,15 @@ - package io.dropwizard.metrics5.jmx; +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java +@@ -31,13 +31,13 @@ import org.junit.jupiter.api.Test; + import org.python.core.PyList; + import org.python.core.PyTuple; -+import static java.util.UUID.randomUUID; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.entry; -+import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -+import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.ArgumentMatchers.eq; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Histogram; -@@ -9,10 +19,10 @@ import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- -+import java.lang.management.ManagementFactory; -+import java.util.SortedMap; -+import java.util.TreeMap; -+import java.util.concurrent.TimeUnit; - import javax.management.Attribute; - import javax.management.AttributeList; - import javax.management.InstanceNotFoundException; -@@ -20,301 +30,304 @@ import javax.management.JMException; - import javax.management.MBeanServer; - import javax.management.ObjectInstance; - import javax.management.ObjectName; --import java.lang.management.ManagementFactory; --import java.util.SortedMap; --import java.util.TreeMap; --import java.util.UUID; --import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.entry; --import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; --import static org.mockito.ArgumentMatchers.any; --import static org.mockito.ArgumentMatchers.eq; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; +-class PickledGraphiteTest { +- private final SocketFactory socketFactory = mock(SocketFactory.class); ++final class PickledGraphiteTest { ++ private final SocketFactory socketFactory = mock(); + private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); + private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); - @SuppressWarnings("rawtypes") --class JmxReporterTest { -- private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); -- private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); -- private final MetricRegistry registry = new MetricRegistry(); -- -- private final JmxReporter reporter = JmxReporter.forRegistry(registry) -- .registerWith(mBeanServer) -- .inDomain(name) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .convertRatesTo(TimeUnit.SECONDS) -- .filter(MetricFilter.ALL) -- .build(); -- -- private final Gauge gauge = mock(Gauge.class); -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -- private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); -- private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); -- -- @BeforeEach -- void setUp() throws Exception { -- when(gauge.getValue()).thenReturn(1); -- -- when(counter.getCount()).thenReturn(100L); -- -- when(histogram.getCount()).thenReturn(1L); -- when(histogram.getSum()).thenReturn(12L); -- -- final Snapshot hSnapshot = mock(Snapshot.class); -- when(hSnapshot.getMax()).thenReturn(2L); -- when(hSnapshot.getMean()).thenReturn(3.0); -- when(hSnapshot.getMin()).thenReturn(4L); -- when(hSnapshot.getStdDev()).thenReturn(5.0); -- when(hSnapshot.getMedian()).thenReturn(6.0); -- when(hSnapshot.get75thPercentile()).thenReturn(7.0); -- when(hSnapshot.get95thPercentile()).thenReturn(8.0); -- when(hSnapshot.get98thPercentile()).thenReturn(9.0); -- when(hSnapshot.get99thPercentile()).thenReturn(10.0); -- when(hSnapshot.get999thPercentile()).thenReturn(11.0); -- when(hSnapshot.size()).thenReturn(1); -- -- when(histogram.getSnapshot()).thenReturn(hSnapshot); -- -- when(meter.getCount()).thenReturn(1L); -- when(meter.getSum()).thenReturn(6L); -- when(meter.getMeanRate()).thenReturn(2.0); -- when(meter.getOneMinuteRate()).thenReturn(3.0); -- when(meter.getFiveMinuteRate()).thenReturn(4.0); -- when(meter.getFifteenMinuteRate()).thenReturn(5.0); -- -- when(timer.getCount()).thenReturn(1L); -- when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); -- when(timer.getMeanRate()).thenReturn(2.0); -- when(timer.getOneMinuteRate()).thenReturn(3.0); -- when(timer.getFiveMinuteRate()).thenReturn(4.0); -- when(timer.getFifteenMinuteRate()).thenReturn(5.0); -- -- final Snapshot tSnapshot = mock(Snapshot.class); -- when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -- when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -- when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -- when(tSnapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -- when(tSnapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -- when(tSnapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -- when(tSnapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -- when(tSnapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -- when(tSnapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -- when(tSnapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -- when(tSnapshot.size()).thenReturn(1); -- -- when(timer.getSnapshot()).thenReturn(tSnapshot); -- -- registry.register(MetricName.build("gauge"), gauge); -- registry.register(MetricName.build("test", "counter"), counter); -- registry.register(MetricName.build("test", "histogram"), histogram); -- registry.register(MetricName.build("test", "meter"), meter); -- registry.register(MetricName.build("test", "another", "timer"), timer); -- -- reporter.start(); -- } -- -- @AfterEach -- void tearDown() { -- reporter.stop(); -- } -- -- @Test -- void registersMBeansForMetricObjectsUsingProvidedObjectNameFactory() throws Exception { -- ObjectName n = new ObjectName(name + ":name=dummy"); -- try { -- String widgetName = "something"; -- when(mockObjectNameFactory.createName(any(String.class), any(String.class), any(MetricName.class))).thenReturn(n); -- JmxReporter reporter = JmxReporter.forRegistry(registry) -- .registerWith(mBeanServer) -- .inDomain(name) -- .createsObjectNamesWith(mockObjectNameFactory) -- .build(); -- registry.registerGauge(widgetName, () -> 1); -- reporter.start(); -- verify(mockObjectNameFactory).createName(eq("gauges"), any(String.class), eq(MetricName.build("something"))); -- //verifyNoMoreInteractions(mockObjectNameFactory); -- } finally { -- reporter.stop(); -- if (mBeanServer.isRegistered(n)) { -- mBeanServer.unregisterMBean(n); -- } -- } -- } -- -- @Test -- void registersMBeansForGauges() throws Exception { -- final AttributeList attributes = getAttributes("gauges", "gauge", "Value", "Number"); -- -- assertThat(values(attributes)) -- .contains(entry("Value", 1), entry("Number", 1)); -- } -- -- @Test -- void registersMBeansForCounters() throws Exception { -- final AttributeList attributes = getAttributes("counters", "test.counter", "Count"); -- -- assertThat(values(attributes)) -- .contains(entry("Count", 100L)); -- } -- -- @Test -- void registersMBeansForHistograms() throws Exception { -- final AttributeList attributes = getAttributes("histograms", "test.histogram", -- "Count", -- "Sum", -- "Max", -- "Mean", -- "Min", -- "StdDev", -- "50thPercentile", -- "75thPercentile", -- "95thPercentile", -- "98thPercentile", -- "99thPercentile", -- "999thPercentile", -- "SnapshotSize"); -- -- assertThat(values(attributes)) -- .contains(entry("Count", 1L)) -- .contains(entry("Sum", 12L)) -- .contains(entry("Max", 2L)) -- .contains(entry("Mean", 3.0)) -- .contains(entry("Min", 4L)) -- .contains(entry("StdDev", 5.0)) -- .contains(entry("50thPercentile", 6.0)) -- .contains(entry("75thPercentile", 7.0)) -- .contains(entry("95thPercentile", 8.0)) -- .contains(entry("98thPercentile", 9.0)) -- .contains(entry("99thPercentile", 10.0)) -- .contains(entry("999thPercentile", 11.0)) -- .contains(entry("SnapshotSize", 1L)); -- } -- -- @Test -- void registersMBeansForMeters() throws Exception { -- final AttributeList attributes = getAttributes("meters", "test.meter", -- "Count", -- "Sum", -- "MeanRate", -- "OneMinuteRate", -- "FiveMinuteRate", -- "FifteenMinuteRate", -- "RateUnit"); -- -- assertThat(values(attributes)) -- .contains(entry("Count", 1L)) -- .contains(entry("Sum", 6.0)) -- .contains(entry("MeanRate", 2.0)) -- .contains(entry("OneMinuteRate", 3.0)) -- .contains(entry("FiveMinuteRate", 4.0)) -- .contains(entry("FifteenMinuteRate", 5.0)) -- .contains(entry("RateUnit", "events/second")); -+final class JmxReporterTest { -+ private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); -+ private final String name = randomUUID().toString().replaceAll("[{\\-}]", ""); -+ private final MetricRegistry registry = new MetricRegistry(); -+ -+ private final JmxReporter reporter = -+ JmxReporter.forRegistry(registry) -+ .registerWith(mBeanServer) -+ .inDomain(name) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .convertRatesTo(TimeUnit.SECONDS) -+ .filter(MetricFilter.ALL) -+ .build(); -+ -+ private final Gauge gauge = mock(); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); -+ private final ObjectNameFactory mockObjectNameFactory = mock(); -+ private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ when(gauge.getValue()).thenReturn(1); -+ -+ when(counter.getCount()).thenReturn(100L); -+ -+ when(histogram.getCount()).thenReturn(1L); -+ when(histogram.getSum()).thenReturn(12L); -+ -+ final Snapshot hSnapshot = mock(); -+ when(hSnapshot.getMax()).thenReturn(2L); -+ when(hSnapshot.getMean()).thenReturn(3.0); -+ when(hSnapshot.getMin()).thenReturn(4L); -+ when(hSnapshot.getStdDev()).thenReturn(5.0); -+ when(hSnapshot.getMedian()).thenReturn(6.0); -+ when(hSnapshot.get75thPercentile()).thenReturn(7.0); -+ when(hSnapshot.get95thPercentile()).thenReturn(8.0); -+ when(hSnapshot.get98thPercentile()).thenReturn(9.0); -+ when(hSnapshot.get99thPercentile()).thenReturn(10.0); -+ when(hSnapshot.get999thPercentile()).thenReturn(11.0); -+ when(hSnapshot.size()).thenReturn(1); -+ -+ when(histogram.getSnapshot()).thenReturn(hSnapshot); -+ -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getSum()).thenReturn(6L); -+ when(meter.getMeanRate()).thenReturn(2.0); -+ when(meter.getOneMinuteRate()).thenReturn(3.0); -+ when(meter.getFiveMinuteRate()).thenReturn(4.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ when(timer.getCount()).thenReturn(1L); -+ when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); -+ when(timer.getMeanRate()).thenReturn(2.0); -+ when(timer.getOneMinuteRate()).thenReturn(3.0); -+ when(timer.getFiveMinuteRate()).thenReturn(4.0); -+ when(timer.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ final Snapshot tSnapshot = mock(); -+ when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -+ when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -+ when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -+ when(tSnapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -+ when(tSnapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -+ when(tSnapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -+ when(tSnapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -+ when(tSnapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -+ when(tSnapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -+ when(tSnapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -+ when(tSnapshot.size()).thenReturn(1); -+ -+ when(timer.getSnapshot()).thenReturn(tSnapshot); -+ -+ registry.register(MetricName.build("gauge"), gauge); -+ registry.register(MetricName.build("test", "counter"), counter); -+ registry.register(MetricName.build("test", "histogram"), histogram); -+ registry.register(MetricName.build("test", "meter"), meter); -+ registry.register(MetricName.build("test", "another", "timer"), timer); -+ -+ reporter.start(); -+ } -+ -+ @AfterEach -+ void tearDown() { -+ reporter.stop(); -+ } -+ -+ @Test -+ void registersMBeansForMetricObjectsUsingProvidedObjectNameFactory() throws Exception { -+ ObjectName n = new ObjectName(name + ":name=dummy"); -+ try { -+ String widgetName = "something"; -+ when(mockObjectNameFactory.createName( -+ any(String.class), any(String.class), any(MetricName.class))) -+ .thenReturn(n); -+ JmxReporter reporter = -+ JmxReporter.forRegistry(registry) -+ .registerWith(mBeanServer) -+ .inDomain(name) -+ .createsObjectNamesWith(mockObjectNameFactory) -+ .build(); -+ registry.registerGauge(widgetName, () -> 1); -+ reporter.start(); -+ verify(mockObjectNameFactory) -+ .createName(eq("gauges"), any(String.class), eq(MetricName.build("something"))); -+ // verifyNoMoreInteractions(mockObjectNameFactory); -+ } finally { -+ reporter.stop(); -+ if (mBeanServer.isRegistered(n)) { -+ mBeanServer.unregisterMBean(n); -+ } - } -+ } -+ -+ @Test -+ void registersMBeansForGauges() throws Exception { -+ final AttributeList attributes = getAttributes("gauges", "gauge", "Value", "Number"); -+ -+ assertThat(values(attributes)).contains(entry("Value", 1), entry("Number", 1)); -+ } -+ -+ @Test -+ void registersMBeansForCounters() throws Exception { -+ final AttributeList attributes = getAttributes("counters", "test.counter", "Count"); -+ -+ assertThat(values(attributes)).contains(entry("Count", 100L)); -+ } -+ -+ @Test -+ void registersMBeansForHistograms() throws Exception { -+ final AttributeList attributes = -+ getAttributes( -+ "histograms", -+ "test.histogram", -+ "Count", -+ "Sum", -+ "Max", -+ "Mean", -+ "Min", -+ "StdDev", -+ "50thPercentile", -+ "75thPercentile", -+ "95thPercentile", -+ "98thPercentile", -+ "99thPercentile", -+ "999thPercentile", -+ "SnapshotSize"); -+ -+ assertThat(values(attributes)) -+ .contains(entry("Count", 1L)) -+ .contains(entry("Sum", 12L)) -+ .contains(entry("Max", 2L)) -+ .contains(entry("Mean", 3.0)) -+ .contains(entry("Min", 4L)) -+ .contains(entry("StdDev", 5.0)) -+ .contains(entry("50thPercentile", 6.0)) -+ .contains(entry("75thPercentile", 7.0)) -+ .contains(entry("95thPercentile", 8.0)) -+ .contains(entry("98thPercentile", 9.0)) -+ .contains(entry("99thPercentile", 10.0)) -+ .contains(entry("999thPercentile", 11.0)) -+ .contains(entry("SnapshotSize", 1L)); -+ } -+ -+ @Test -+ void registersMBeansForMeters() throws Exception { -+ final AttributeList attributes = -+ getAttributes( -+ "meters", -+ "test.meter", -+ "Count", -+ "Sum", -+ "MeanRate", -+ "OneMinuteRate", -+ "FiveMinuteRate", -+ "FifteenMinuteRate", -+ "RateUnit"); -+ -+ assertThat(values(attributes)) -+ .contains(entry("Count", 1L)) -+ .contains(entry("Sum", 6.0)) -+ .contains(entry("MeanRate", 2.0)) -+ .contains(entry("OneMinuteRate", 3.0)) -+ .contains(entry("FiveMinuteRate", 4.0)) -+ .contains(entry("FifteenMinuteRate", 5.0)) -+ .contains(entry("RateUnit", "events/second")); -+ } -+ -+ @Test -+ void registersMBeansForTimers() throws Exception { -+ final AttributeList attributes = -+ getAttributes( -+ "timers", -+ "test.another.timer", -+ "Count", -+ "Sum", -+ "MeanRate", -+ "OneMinuteRate", -+ "FiveMinuteRate", -+ "FifteenMinuteRate", -+ "Max", -+ "Mean", -+ "Min", -+ "StdDev", -+ "50thPercentile", -+ "75thPercentile", -+ "95thPercentile", -+ "98thPercentile", -+ "99thPercentile", -+ "999thPercentile", -+ "RateUnit", -+ "DurationUnit"); -+ -+ assertThat(values(attributes)) -+ .contains(entry("Count", 1L)) -+ .contains(entry("Sum", 6.0)) -+ .contains(entry("MeanRate", 2.0)) -+ .contains(entry("OneMinuteRate", 3.0)) -+ .contains(entry("FiveMinuteRate", 4.0)) -+ .contains(entry("FifteenMinuteRate", 5.0)) -+ .contains(entry("Max", 100.0)) -+ .contains(entry("Mean", 200.0)) -+ .contains(entry("Min", 300.0)) -+ .contains(entry("StdDev", 400.0)) -+ .contains(entry("50thPercentile", 500.0)) -+ .contains(entry("75thPercentile", 600.0)) -+ .contains(entry("95thPercentile", 700.0)) -+ .contains(entry("98thPercentile", 800.0)) -+ .contains(entry("99thPercentile", 900.0)) -+ .contains(entry("999thPercentile", 1000.0)) -+ .contains(entry("RateUnit", "events/second")) -+ .contains(entry("DurationUnit", "milliseconds")); -+ } -+ -+ @Test -+ void cleansUpAfterItselfWhenStopped() throws Exception { -+ reporter.stop(); -+ -+ try { -+ getAttributes("gauges", "gauge", "Value", "Number"); -+ failBecauseExceptionWasNotThrown(InstanceNotFoundException.class); -+ } catch (InstanceNotFoundException e) { - -- @Test -- void registersMBeansForTimers() throws Exception { -- final AttributeList attributes = getAttributes("timers", "test.another.timer", -- "Count", -- "Sum", -- "MeanRate", -- "OneMinuteRate", -- "FiveMinuteRate", -- "FifteenMinuteRate", -- "Max", -- "Mean", -- "Min", -- "StdDev", -- "50thPercentile", -- "75thPercentile", -- "95thPercentile", -- "98thPercentile", -- "99thPercentile", -- "999thPercentile", -- "RateUnit", -- "DurationUnit"); -- -- assertThat(values(attributes)) -- .contains(entry("Count", 1L)) -- .contains(entry("Sum", 6.0)) -- .contains(entry("MeanRate", 2.0)) -- .contains(entry("OneMinuteRate", 3.0)) -- .contains(entry("FiveMinuteRate", 4.0)) -- .contains(entry("FifteenMinuteRate", 5.0)) -- .contains(entry("Max", 100.0)) -- .contains(entry("Mean", 200.0)) -- .contains(entry("Min", 300.0)) -- .contains(entry("StdDev", 400.0)) -- .contains(entry("50thPercentile", 500.0)) -- .contains(entry("75thPercentile", 600.0)) -- .contains(entry("95thPercentile", 700.0)) -- .contains(entry("98thPercentile", 800.0)) -- .contains(entry("99thPercentile", 900.0)) -- .contains(entry("999thPercentile", 1000.0)) -- .contains(entry("RateUnit", "events/second")) -- .contains(entry("DurationUnit", "milliseconds")); - } -+ } +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); -- @Test -- void cleansUpAfterItselfWhenStopped() throws Exception { -- reporter.stop(); -- -- try { -- getAttributes("gauges", "gauge", "Value", "Number"); -- failBecauseExceptionWasNotThrown(InstanceNotFoundException.class); -- } catch (InstanceNotFoundException e) { -- -- } -- } -+ @Test -+ void objectNameModifyingMBeanServer() throws Exception { -+ MBeanServer mockedMBeanServer = mock(); + private CompiledScript unpickleScript; -- @Test -- void objectNameModifyingMBeanServer() throws Exception { -- MBeanServer mockedMBeanServer = mock(MBeanServer.class); -+ // overwrite the objectName -+ when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))) -+ .thenReturn(new ObjectInstance("DOMAIN:key=value", "className")); +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.health; -- // overwrite the objectName -- when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))).thenReturn(new ObjectInstance("DOMAIN:key=value", "className")); -- -- MetricRegistry testRegistry = new MetricRegistry(); -- JmxReporter testJmxReporter = JmxReporter.forRegistry(testRegistry) -- .registerWith(mockedMBeanServer) -- .inDomain(name) -- .build(); -+ MetricRegistry testRegistry = new MetricRegistry(); -+ JmxReporter testJmxReporter = -+ JmxReporter.forRegistry(testRegistry) -+ .registerWith(mockedMBeanServer) -+ .inDomain(name) -+ .build(); - -- testJmxReporter.start(); -+ testJmxReporter.start(); - -- // should trigger a registerMBean -- testRegistry.timer("test"); -+ // should trigger a registerMBean -+ testRegistry.timer("test"); - -- // should trigger an unregisterMBean with the overwritten objectName = "DOMAIN:key=value" -- testJmxReporter.stop(); -+ // should trigger an unregisterMBean with the overwritten objectName = "DOMAIN:key=value" -+ testJmxReporter.stop(); - -- verify(mockedMBeanServer).unregisterMBean(new ObjectName("DOMAIN:key=value")); -+ verify(mockedMBeanServer).unregisterMBean(new ObjectName("DOMAIN:key=value")); -+ } ++import static com.google.common.base.Preconditions.checkArgument; ++ + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.health.annotation.Async; + import java.util.concurrent.ScheduledExecutorService; +@@ -29,10 +31,10 @@ public class AsyncHealthCheckDecorator implements HealthCheck, Runnable { + this.healthyTtl = + async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); + result = +- Async.InitialState.HEALTHY.equals(async.initialState()) ++ Async.InitialState.HEALTHY == async.initialState() + ? Result.healthy(NO_RESULT_YET_MESSAGE) + : Result.unhealthy(NO_RESULT_YET_MESSAGE); +- if (Async.ScheduleType.FIXED_RATE.equals(async.scheduleType())) { ++ if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) { + future = + executorService.scheduleAtFixedRate( + this, async.initialDelay(), async.period(), async.unit()); +@@ -77,8 +79,6 @@ public class AsyncHealthCheckDecorator implements HealthCheck, Runnable { + } + private static void check(boolean expression, String message) { +- if (!expression) { +- throw new IllegalArgumentException(message); - } -+ @Test -+ void jmxMetricNameWithAsterisk() { -+ MetricRegistry metricRegistry = new MetricRegistry(); -+ JmxReporter.forRegistry(metricRegistry).build().start(); -+ metricRegistry.counter("test*"); -+ } - -- @Test -- void testJmxMetricNameWithAsterisk() { -- MetricRegistry metricRegistry = new MetricRegistry(); -- JmxReporter.forRegistry(metricRegistry).build().start(); -- metricRegistry.counter("test*"); -- } -- -- private AttributeList getAttributes(String type, String name, String... attributeNames) throws JMException { -- ObjectName n = concreteObjectNameFactory.createName(type, this.name, MetricName.build(name)); -- return mBeanServer.getAttributes(n, attributeNames); -- } -+ private AttributeList getAttributes(String type, String name, String... attributeNames) -+ throws JMException { -+ ObjectName n = concreteObjectNameFactory.createName(type, this.name, MetricName.build(name)); -+ return mBeanServer.getAttributes(n, attributeNames); -+ } - -- private SortedMap values(AttributeList attributes) { -- final SortedMap values = new TreeMap<>(); -- for (Object o : attributes) { -- final Attribute attribute = (Attribute) o; -- values.put(attribute.getName(), attribute.getValue()); -- } -- return values; -+ private SortedMap values(AttributeList attributes) { -+ final SortedMap values = new TreeMap<>(); -+ for (Object o : attributes) { -+ final Attribute attribute = (Attribute) o; -+ values.put(attribute.getName(), attribute.getValue()); - } -+ return values; -+ } ++ checkArgument(expression, message); + } } ---- a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java -+++ b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java -@@ -6,79 +6,80 @@ import com.fasterxml.jackson.databind.Module; - import com.fasterxml.jackson.databind.SerializerProvider; - import com.fasterxml.jackson.databind.module.SimpleSerializers; - import com.fasterxml.jackson.databind.ser.std.StdSerializer; -+import com.google.common.collect.ImmutableList; - import io.dropwizard.metrics5.health.HealthCheck; -- - import java.io.IOException; --import java.util.Collections; - import java.util.Map; - - public class HealthCheckModule extends Module { -- private static class HealthCheckResultSerializer extends StdSerializer { -- -- private static final long serialVersionUID = 1L; -- -- private HealthCheckResultSerializer() { -- super(HealthCheck.Result.class); -- } -- -- @Override -- public void serialize(HealthCheck.Result result, -- JsonGenerator json, -- SerializerProvider provider) throws IOException { -- json.writeStartObject(); -- json.writeBooleanField("healthy", result.isHealthy()); -+ private static class HealthCheckResultSerializer extends StdSerializer { - -- final String message = result.getMessage(); -- if (message != null) { -- json.writeStringField("message", message); -- } -+ private static final long serialVersionUID = 1L; - -- serializeThrowable(json, result.getError(), "error"); -- json.writeNumberField("duration", result.getDuration()); -- -- Map details = result.getDetails(); -- if (details != null && !details.isEmpty()) { -- for (Map.Entry e : details.entrySet()) { -- json.writeObjectField(e.getKey(), e.getValue()); -- } -- } -+ private HealthCheckResultSerializer() { -+ super(HealthCheck.Result.class); -+ } - -- json.writeStringField("timestamp", result.getTimestamp()); -- json.writeEndObject(); -+ @Override -+ public void serialize( -+ HealthCheck.Result result, JsonGenerator json, SerializerProvider provider) -+ throws IOException { -+ json.writeStartObject(); -+ json.writeBooleanField("healthy", result.isHealthy()); -+ -+ final String message = result.getMessage(); -+ if (message != null) { -+ json.writeStringField("message", message); -+ } -+ -+ serializeThrowable(json, result.getError(), "error"); -+ json.writeNumberField("duration", result.getDuration()); -+ -+ Map details = result.getDetails(); -+ if (details != null && !details.isEmpty()) { -+ for (Map.Entry e : details.entrySet()) { -+ json.writeObjectField(e.getKey(), e.getValue()); - } -+ } - -- private void serializeThrowable(JsonGenerator json, Throwable error, String name) throws IOException { -- if (error != null) { -- json.writeObjectFieldStart(name); -- json.writeStringField("type", error.getClass().getTypeName()); -- json.writeStringField("message", error.getMessage()); -- json.writeArrayFieldStart("stack"); -- for (StackTraceElement element : error.getStackTrace()) { -- json.writeString(element.toString()); -- } -- json.writeEndArray(); -- -- if (error.getCause() != null) { -- serializeThrowable(json, error.getCause(), "cause"); -- } -- -- json.writeEndObject(); -- } -- } -+ json.writeStringField("timestamp", result.getTimestamp()); -+ json.writeEndObject(); - } +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java +@@ -1,11 +1,12 @@ + package io.dropwizard.metrics5.health; -- @Override -- public String getModuleName() { -- return "healthchecks"; -- } -+ private void serializeThrowable(JsonGenerator json, Throwable error, String name) -+ throws IOException { -+ if (error != null) { -+ json.writeObjectFieldStart(name); -+ json.writeStringField("type", error.getClass().getTypeName()); -+ json.writeStringField("message", error.getMessage()); -+ json.writeArrayFieldStart("stack"); -+ for (StackTraceElement element : error.getStackTrace()) { -+ json.writeString(element.toString()); -+ } -+ json.writeEndArray(); - -- @Override -- public Version version() { -- return MetricsModule.VERSION; -- } -+ if (error.getCause() != null) { -+ serializeThrowable(json, error.getCause(), "cause"); -+ } - -- @Override -- public void setupModule(SetupContext context) { -- context.addSerializers(new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer()))); -+ json.writeEndObject(); -+ } - } -+ } -+ -+ @Override -+ public String getModuleName() { -+ return "healthchecks"; -+ } -+ -+ @Override -+ public Version version() { -+ return MetricsModule.VERSION; -+ } ++import static java.util.Collections.unmodifiableMap; + -+ @Override -+ public void setupModule(SetupContext context) { -+ context.addSerializers( -+ new SimpleSerializers(ImmutableList.of(new HealthCheckResultSerializer()))); -+ } - } ---- a/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java -+++ b/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java -@@ -14,248 +14,241 @@ import io.dropwizard.metrics5.MetricFilter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; -- - import java.io.IOException; - import java.util.Arrays; - import java.util.Locale; + import io.dropwizard.metrics5.Clock; + import java.time.Instant; + import java.time.ZoneId; + import java.time.ZonedDateTime; + import java.time.format.DateTimeFormatter; +-import java.util.Collections; + import java.util.LinkedHashMap; + import java.util.Map; import java.util.concurrent.TimeUnit; - - public class MetricsModule extends Module { -- static final Version VERSION = new Version(5, 0, 0, "", "io.dropwizard.metrics5", "metrics-json"); -- -- @SuppressWarnings("rawtypes") -- private static class GaugeSerializer extends StdSerializer { -+ static final Version VERSION = new Version(5, 0, 0, "", "io.dropwizard.metrics5", "metrics-json"); - -- private static final long serialVersionUID = 1L; -+ @SuppressWarnings("rawtypes") -+ private static class GaugeSerializer extends StdSerializer { - -- private GaugeSerializer() { -- super(Gauge.class); -- } -+ private static final long serialVersionUID = 1L; - -- @Override -- public void serialize(Gauge gauge, -- JsonGenerator json, -- SerializerProvider provider) throws IOException { -- json.writeStartObject(); -- final Object value; -- try { -- value = gauge.getValue(); -- json.writeObjectField("value", value); -- } catch (RuntimeException e) { -- json.writeObjectField("error", e.toString()); -- } -- json.writeEndObject(); -- } -+ private GaugeSerializer() { -+ super(Gauge.class); +@@ -123,7 +124,7 @@ public interface HealthCheck { + this.healthy = isHealthy; + this.message = message; + this.error = error; +- this.details = details == null ? null : Collections.unmodifiableMap(details); ++ this.details = details == null ? null : unmodifiableMap(details); + this.time = clock.getTime(); } -- private static class CounterSerializer extends StdSerializer { -+ @Override -+ public void serialize(Gauge gauge, JsonGenerator json, SerializerProvider provider) -+ throws IOException { -+ json.writeStartObject(); -+ final Object value; -+ try { -+ value = gauge.getValue(); -+ json.writeObjectField("value", value); -+ } catch (RuntimeException e) { -+ json.writeObjectField("error", e.toString()); -+ } -+ json.writeEndObject(); -+ } -+ } - -- private static final long serialVersionUID = 1L; -+ private static class CounterSerializer extends StdSerializer { - -- private CounterSerializer() { -- super(Counter.class); -- } -+ private static final long serialVersionUID = 1L; - -- @Override -- public void serialize(Counter counter, -- JsonGenerator json, -- SerializerProvider provider) throws IOException { -- json.writeStartObject(); -- json.writeNumberField("count", counter.getCount()); -- json.writeEndObject(); -- } -+ private CounterSerializer() { -+ super(Counter.class); +@@ -162,7 +163,7 @@ public interface HealthCheck { + */ + public String getTimestamp() { + Instant currentInstant = Instant.ofEpochMilli(time); +- ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(currentInstant, ZoneId.systemDefault()); ++ ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault()); + return DATE_FORMAT_PATTERN.format(zonedDateTime); } -- private static class HistogramSerializer extends StdSerializer { -+ @Override -+ public void serialize(Counter counter, JsonGenerator json, SerializerProvider provider) -+ throws IOException { -+ json.writeStartObject(); -+ json.writeNumberField("count", counter.getCount()); -+ json.writeEndObject(); -+ } -+ } - -- private static final long serialVersionUID = 1L; -+ private static class HistogramSerializer extends StdSerializer { - -- private final boolean showSamples; -+ private static final long serialVersionUID = 1L; - -- private HistogramSerializer(boolean showSamples) { -- super(Histogram.class); -- this.showSamples = showSamples; -- } -+ private final boolean showSamples; - -- @Override -- public void serialize(Histogram histogram, -- JsonGenerator json, -- SerializerProvider provider) throws IOException { -- json.writeStartObject(); -- final Snapshot snapshot = histogram.getSnapshot(); -- json.writeNumberField("count", histogram.getCount()); -- json.writeNumberField("max", snapshot.getMax()); -- json.writeNumberField("mean", snapshot.getMean()); -- json.writeNumberField("min", snapshot.getMin()); -- json.writeNumberField("p50", snapshot.getMedian()); -- json.writeNumberField("p75", snapshot.get75thPercentile()); -- json.writeNumberField("p95", snapshot.get95thPercentile()); -- json.writeNumberField("p98", snapshot.get98thPercentile()); -- json.writeNumberField("p99", snapshot.get99thPercentile()); -- json.writeNumberField("p999", snapshot.get999thPercentile()); -- -- if (showSamples) { -- json.writeObjectField("values", snapshot.getValues()); -- } -- -- json.writeNumberField("stddev", snapshot.getStdDev()); -- json.writeEndObject(); -- } -+ private HistogramSerializer(boolean showSamples) { -+ super(Histogram.class); -+ this.showSamples = showSamples; +@@ -218,8 +219,7 @@ public interface HealthCheck { + int result = healthy ? 1 : 0; + result = PRIME * result + (message != null ? message.hashCode() : 0); + result = PRIME * result + (error != null ? error.hashCode() : 0); +- result = PRIME * result + (Long.hashCode(time)); +- return result; ++ return PRIME * result + (Long.hashCode(time)); } -- private static class MeterSerializer extends StdSerializer { -+ @Override -+ public void serialize(Histogram histogram, JsonGenerator json, SerializerProvider provider) -+ throws IOException { -+ json.writeStartObject(); -+ final Snapshot snapshot = histogram.getSnapshot(); -+ json.writeNumberField("count", histogram.getCount()); -+ json.writeNumberField("max", snapshot.getMax()); -+ json.writeNumberField("mean", snapshot.getMean()); -+ json.writeNumberField("min", snapshot.getMin()); -+ json.writeNumberField("p50", snapshot.getMedian()); -+ json.writeNumberField("p75", snapshot.get75thPercentile()); -+ json.writeNumberField("p95", snapshot.get95thPercentile()); -+ json.writeNumberField("p98", snapshot.get98thPercentile()); -+ json.writeNumberField("p99", snapshot.get99thPercentile()); -+ json.writeNumberField("p999", snapshot.get999thPercentile()); -+ -+ if (showSamples) { -+ json.writeObjectField("values", snapshot.getValues()); -+ } -+ -+ json.writeNumberField("stddev", snapshot.getStdDev()); -+ json.writeEndObject(); -+ } -+ } - -- private static final long serialVersionUID = 1L; -+ private static class MeterSerializer extends StdSerializer { - -- private final String rateUnit; -- private final double rateFactor; -+ private static final long serialVersionUID = 1L; - -- public MeterSerializer(TimeUnit rateUnit) { -- super(Meter.class); -- this.rateFactor = rateUnit.toSeconds(1); -- this.rateUnit = calculateRateUnit(rateUnit, "events"); -- } -+ private final String rateUnit; -+ private final double rateFactor; - -- @Override -- public void serialize(Meter meter, -- JsonGenerator json, -- SerializerProvider provider) throws IOException { -- json.writeStartObject(); -- json.writeNumberField("count", meter.getCount()); -- json.writeNumberField("m15_rate", meter.getFifteenMinuteRate() * rateFactor); -- json.writeNumberField("m1_rate", meter.getOneMinuteRate() * rateFactor); -- json.writeNumberField("m5_rate", meter.getFiveMinuteRate() * rateFactor); -- json.writeNumberField("mean_rate", meter.getMeanRate() * rateFactor); -- json.writeStringField("units", rateUnit); -- json.writeEndObject(); -- } -+ public MeterSerializer(TimeUnit rateUnit) { -+ super(Meter.class); -+ this.rateFactor = rateUnit.toSeconds(1); -+ this.rateUnit = calculateRateUnit(rateUnit, "events"); - } + @Override +@@ -237,7 +237,7 @@ public interface HealthCheck { + if (details != null) { + for (Map.Entry e : details.entrySet()) { + builder.append(", "); +- builder.append(e.getKey()).append("=").append(String.valueOf(e.getValue())); ++ builder.append(e.getKey()).append("=").append(e.getValue()); + } + } + builder.append('}'); +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java +@@ -1,9 +1,11 @@ + package io.dropwizard.metrics5.health; -- private static class TimerSerializer extends StdSerializer { -- -- private static final long serialVersionUID = 1L; -- -- private final String rateUnit; -- private final double rateFactor; -- private final String durationUnit; -- private final double durationFactor; -- private final boolean showSamples; -- -- private TimerSerializer(TimeUnit rateUnit, -- TimeUnit durationUnit, -- boolean showSamples) { -- super(Timer.class); -- this.rateUnit = calculateRateUnit(rateUnit, "calls"); -- this.rateFactor = rateUnit.toSeconds(1); -- this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); -- this.durationFactor = 1.0 / durationUnit.toNanos(1); -- this.showSamples = showSamples; -- } -- -- @Override -- public void serialize(Timer timer, -- JsonGenerator json, -- SerializerProvider provider) throws IOException { -- json.writeStartObject(); -- final Snapshot snapshot = timer.getSnapshot(); -- json.writeNumberField("count", timer.getCount()); -- json.writeNumberField("max", snapshot.getMax() * durationFactor); -- json.writeNumberField("mean", snapshot.getMean() * durationFactor); -- json.writeNumberField("min", snapshot.getMin() * durationFactor); -- -- json.writeNumberField("p50", snapshot.getMedian() * durationFactor); -- json.writeNumberField("p75", snapshot.get75thPercentile() * durationFactor); -- json.writeNumberField("p95", snapshot.get95thPercentile() * durationFactor); -- json.writeNumberField("p98", snapshot.get98thPercentile() * durationFactor); -- json.writeNumberField("p99", snapshot.get99thPercentile() * durationFactor); -- json.writeNumberField("p999", snapshot.get999thPercentile() * durationFactor); -- -- if (showSamples) { -- final long[] values = snapshot.getValues(); -- final double[] scaledValues = new double[values.length]; -- for (int i = 0; i < values.length; i++) { -- scaledValues[i] = values[i] * durationFactor; -- } -- json.writeObjectField("values", scaledValues); -- } -- -- json.writeNumberField("stddev", snapshot.getStdDev() * durationFactor); -- json.writeNumberField("m15_rate", timer.getFifteenMinuteRate() * rateFactor); -- json.writeNumberField("m1_rate", timer.getOneMinuteRate() * rateFactor); -- json.writeNumberField("m5_rate", timer.getFiveMinuteRate() * rateFactor); -- json.writeNumberField("mean_rate", timer.getMeanRate() * rateFactor); -- json.writeStringField("duration_units", durationUnit); -- json.writeStringField("rate_units", rateUnit); -- json.writeEndObject(); -- } -+ @Override -+ public void serialize(Meter meter, JsonGenerator json, SerializerProvider provider) -+ throws IOException { -+ json.writeStartObject(); -+ json.writeNumberField("count", meter.getCount()); -+ json.writeNumberField("m15_rate", meter.getFifteenMinuteRate() * rateFactor); -+ json.writeNumberField("m1_rate", meter.getOneMinuteRate() * rateFactor); -+ json.writeNumberField("m5_rate", meter.getFiveMinuteRate() * rateFactor); -+ json.writeNumberField("mean_rate", meter.getMeanRate() * rateFactor); -+ json.writeStringField("units", rateUnit); -+ json.writeEndObject(); - } -+ } ++import static com.google.common.base.Preconditions.checkArgument; + import static io.dropwizard.metrics5.health.HealthCheck.Result; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; -- private static class MetricRegistrySerializer extends StdSerializer { -+ private static class TimerSerializer extends StdSerializer { + import io.dropwizard.metrics5.health.annotation.Async; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -27,7 +29,7 @@ import org.slf4j.LoggerFactory; -- private static final long serialVersionUID = 1L; -+ private static final long serialVersionUID = 1L; + /** A registry for health checks. */ + public class HealthCheckRegistry { +- private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckRegistry.class); ++ private static final Logger LOG = LoggerFactory.getLogger(HealthCheckRegistry.class); + private static final int ASYNC_EXECUTOR_POOL_SIZE = 2; + + private final ConcurrentMap healthChecks; +@@ -92,9 +94,8 @@ public class HealthCheckRegistry { + public void register(String name, HealthCheck healthCheck) { + HealthCheck registered; + synchronized (lock) { +- if (healthChecks.containsKey(name)) { +- throw new IllegalArgumentException("A health check named " + name + " already exists"); +- } ++ checkArgument( ++ !healthChecks.containsKey(name), "A health check named %s already exists", name); + registered = healthCheck; + if (healthCheck.getClass().isAnnotationPresent(Async.class)) { + registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); +@@ -128,7 +129,7 @@ public class HealthCheckRegistry { + * @return the names of all registered health checks + */ + public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); ++ return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); + } -- private final MetricFilter filter; -+ private final String rateUnit; -+ private final double rateFactor; -+ private final String durationUnit; -+ private final double durationFactor; -+ private final boolean showSamples; + /** +@@ -180,7 +181,7 @@ public class HealthCheckRegistry { + results.put(entry.getKey(), result); + } + } +- return Collections.unmodifiableSortedMap(results); ++ return unmodifiableSortedMap(results); + } -- private MetricRegistrySerializer(MetricFilter filter) { -- super(MetricRegistry.class); -- this.filter = filter; -- } -+ private TimerSerializer(TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples) { -+ super(Timer.class); -+ this.rateUnit = calculateRateUnit(rateUnit, "calls"); -+ this.rateFactor = rateUnit.toSeconds(1); -+ this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); -+ this.durationFactor = 1.0 / durationUnit.toNanos(1); -+ this.showSamples = showSamples; -+ } - -- @Override -- public void serialize(MetricRegistry registry, -- JsonGenerator json, -- SerializerProvider provider) throws IOException { -- json.writeStartObject(); -- json.writeStringField("version", VERSION.toString()); -- json.writeObjectField("gauges", registry.getGauges(filter)); -- json.writeObjectField("counters", registry.getCounters(filter)); -- json.writeObjectField("histograms", registry.getHistograms(filter)); -- json.writeObjectField("meters", registry.getMeters(filter)); -- json.writeObjectField("timers", registry.getTimers(filter)); -- json.writeEndObject(); -+ @Override -+ public void serialize(Timer timer, JsonGenerator json, SerializerProvider provider) -+ throws IOException { -+ json.writeStartObject(); -+ final Snapshot snapshot = timer.getSnapshot(); -+ json.writeNumberField("count", timer.getCount()); -+ json.writeNumberField("max", snapshot.getMax() * durationFactor); -+ json.writeNumberField("mean", snapshot.getMean() * durationFactor); -+ json.writeNumberField("min", snapshot.getMin() * durationFactor); -+ -+ json.writeNumberField("p50", snapshot.getMedian() * durationFactor); -+ json.writeNumberField("p75", snapshot.get75thPercentile() * durationFactor); -+ json.writeNumberField("p95", snapshot.get95thPercentile() * durationFactor); -+ json.writeNumberField("p98", snapshot.get98thPercentile() * durationFactor); -+ json.writeNumberField("p99", snapshot.get99thPercentile() * durationFactor); -+ json.writeNumberField("p999", snapshot.get999thPercentile() * durationFactor); -+ -+ if (showSamples) { -+ final long[] values = snapshot.getValues(); -+ final double[] scaledValues = new double[values.length]; -+ for (int i = 0; i < values.length; i++) { -+ scaledValues[i] = values[i] * durationFactor; - } -+ json.writeObjectField("values", scaledValues); -+ } -+ -+ json.writeNumberField("stddev", snapshot.getStdDev() * durationFactor); -+ json.writeNumberField("m15_rate", timer.getFifteenMinuteRate() * rateFactor); -+ json.writeNumberField("m1_rate", timer.getOneMinuteRate() * rateFactor); -+ json.writeNumberField("m5_rate", timer.getFiveMinuteRate() * rateFactor); -+ json.writeNumberField("mean_rate", timer.getMeanRate() * rateFactor); -+ json.writeStringField("duration_units", durationUnit); -+ json.writeStringField("rate_units", rateUnit); -+ json.writeEndObject(); + /** +@@ -217,12 +218,12 @@ public class HealthCheckRegistry { + try { + results.put(entry.getKey(), entry.getValue().get()); + } catch (Exception e) { +- LOGGER.warn("Error executing health check {}", entry.getKey(), e); ++ LOG.warn("Error executing health check {}", entry.getKey(), e); + results.put(entry.getKey(), HealthCheck.Result.unhealthy(e)); + } } -+ } -- protected final TimeUnit rateUnit; -- protected final TimeUnit durationUnit; -- protected final boolean showSamples; -- protected final MetricFilter filter; -+ private static class MetricRegistrySerializer extends StdSerializer { +- return Collections.unmodifiableSortedMap(results); ++ return unmodifiableSortedMap(results); + } + + private void onHealthCheckAdded(String name, HealthCheck healthCheck) { +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java +@@ -1,11 +1,12 @@ + package io.dropwizard.metrics5.health; -- public MetricsModule(TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples) { -- this(rateUnit, durationUnit, showSamples, MetricFilter.ALL); -- } -+ private static final long serialVersionUID = 1L; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.ArgumentCaptor.forClass; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.*; ++import static org.mockito.Mockito.verify; -- public MetricsModule(TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples, MetricFilter filter) { -- this.rateUnit = rateUnit; -- this.durationUnit = durationUnit; -- this.showSamples = showSamples; -- this.filter = filter; -- } -+ private final MetricFilter filter; - -- @Override -- public String getModuleName() { -- return "metrics"; -+ private MetricRegistrySerializer(MetricFilter filter) { -+ super(MetricRegistry.class); -+ this.filter = filter; - } + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.health.annotation.Async; +@@ -16,7 +17,7 @@ import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; - @Override -- public Version version() { -- return VERSION; -+ public void serialize(MetricRegistry registry, JsonGenerator json, SerializerProvider provider) -+ throws IOException { -+ json.writeStartObject(); -+ json.writeStringField("version", VERSION.toString()); -+ json.writeObjectField("gauges", registry.getGauges(filter)); -+ json.writeObjectField("counters", registry.getCounters(filter)); -+ json.writeObjectField("histograms", registry.getHistograms(filter)); -+ json.writeObjectField("meters", registry.getMeters(filter)); -+ json.writeObjectField("timers", registry.getTimers(filter)); -+ json.writeEndObject(); - } -- -- @Override -- public void setupModule(SetupContext context) { -- context.addSerializers(new SimpleSerializers(Arrays.asList( -+ } -+ -+ protected final TimeUnit rateUnit; -+ protected final TimeUnit durationUnit; -+ protected final boolean showSamples; -+ protected final MetricFilter filter; -+ -+ public MetricsModule(TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples) { -+ this(rateUnit, durationUnit, showSamples, MetricFilter.ALL); -+ } -+ -+ public MetricsModule( -+ TimeUnit rateUnit, TimeUnit durationUnit, boolean showSamples, MetricFilter filter) { -+ this.rateUnit = rateUnit; -+ this.durationUnit = durationUnit; -+ this.showSamples = showSamples; -+ this.filter = filter; -+ } -+ -+ @Override -+ public String getModuleName() { -+ return "metrics"; -+ } -+ -+ @Override -+ public Version version() { -+ return VERSION; -+ } -+ -+ @Override -+ public void setupModule(SetupContext context) { -+ context.addSerializers( -+ new SimpleSerializers( -+ Arrays.asList( - new GaugeSerializer(), - new CounterSerializer(), - new HistogramSerializer(showSamples), - new MeterSerializer(rateUnit), - new TimerSerializer(rateUnit, durationUnit, showSamples), -- new MetricRegistrySerializer(filter) -- ))); -- } -+ new MetricRegistrySerializer(filter)))); -+ } + /** Unit tests for {@link AsyncHealthCheckDecorator}. */ +-class AsyncHealthCheckDecoratorTest { ++final class AsyncHealthCheckDecoratorTest { -- private static String calculateRateUnit(TimeUnit unit, String name) { -- final String s = unit.toString().toLowerCase(Locale.US); -- return name + '/' + s.substring(0, s.length() - 1); -- } -+ private static String calculateRateUnit(TimeUnit unit, String name) { -+ final String s = unit.toString().toLowerCase(Locale.US); -+ return name + '/' + s.substring(0, s.length() - 1); -+ } - } ---- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java -+++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java -@@ -1,138 +1,95 @@ - package io.dropwizard.metrics5.json; + private static final long CURRENT_TIME = 1551002401000L; -+import static org.assertj.core.api.Assertions.assertThat; -+ - import com.fasterxml.jackson.databind.ObjectMapper; - import io.dropwizard.metrics5.health.HealthCheck; --import org.junit.jupiter.api.Test; -- - import java.math.BigDecimal; - import java.math.BigInteger; - import java.util.LinkedHashMap; - import java.util.Map; -+import org.junit.jupiter.api.Test; +@@ -29,65 +30,66 @@ class AsyncHealthCheckDecoratorTest { + .withMessage("Result was healthy but it expired 1 milliseconds ago") + .build(); --import static org.assertj.core.api.Assertions.assertThat; -- --class HealthCheckModuleTest { -- private final ObjectMapper mapper = new ObjectMapper().registerModule(new HealthCheckModule()); -+final class HealthCheckModuleTest { -+ private final ObjectMapper mapper = new ObjectMapper().registerModule(new HealthCheckModule()); +- private final HealthCheck mockHealthCheck = mock(HealthCheck.class); +- private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); ++ private final HealthCheck mockHealthCheck = mock(); ++ private final ScheduledExecutorService mockExecutorService = mock(); -- @Test -- void serializesAHealthyResult() throws Exception { -- HealthCheck.Result result = HealthCheck.Result.healthy(); -- assertThat(mapper.writeValueAsString(result)) -- .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); -- } -+ @Test -+ void serializesAHealthyResult() throws Exception { -+ HealthCheck.Result result = HealthCheck.Result.healthy(); -+ assertThat(mapper.writeValueAsString(result)) -+ .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp()); -+ } - -- @Test -- void serializesAHealthyResultWithAMessage() throws Exception { -- HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); -- assertThat(mapper.writeValueAsString(result)) -- .isEqualTo("{" + -- "\"healthy\":true," + -- "\"message\":\"yay for me\"," + -- "\"duration\":0," + -- "\"timestamp\":\"" + result.getTimestamp() + "\"" + -- "}"); -- } -+ @Test -+ void serializesAHealthyResultWithAMessage() throws Exception { -+ HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); -+ assertThat(mapper.writeValueAsString(result)) -+ .isEqualTo( -+ "{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); -+ } - -- @Test -- void serializesAnUnhealthyResult() throws Exception { -- HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); -- assertThat(mapper.writeValueAsString(result)) -- .isEqualTo("{" + -- "\"healthy\":false," + -- "\"message\":\"boo\"," + -- "\"duration\":0," + -- "\"timestamp\":\"" + result.getTimestamp() + "\"" + -- "}"); -- } -+ @Test -+ void serializesAnUnhealthyResult() throws Exception { -+ HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); -+ assertThat(mapper.writeValueAsString(result)) -+ .isEqualTo( -+ "{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); -+ } + @SuppressWarnings("rawtypes") +- private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); ++ private final ScheduledFuture mockFuture = mock(); -- @Test -- void serializesAnUnhealthyResultWithAnException() throws Exception { -- final RuntimeException e = new RuntimeException("oh no"); -- e.setStackTrace(new StackTraceElement[]{ -- new StackTraceElement("Blah", "bloo", "Blah.java", 100) + @Test + void nullHealthCheckTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(null, mockExecutorService); - }); -+ @Test -+ void serializesAnUnhealthyResultWithAnException() throws Exception { -+ final RuntimeException e = new RuntimeException("oh no"); -+ e.setStackTrace( -+ new StackTraceElement[] {new StackTraceElement("Blah", "bloo", "Blah.java", 100)}); - -- HealthCheck.Result result = HealthCheck.Result.unhealthy(e); -- assertThat(mapper.writeValueAsString(result)) -- .isEqualTo("{" + -- "\"healthy\":false," + -- "\"message\":\"oh no\"," + -- "\"error\":{" + -- "\"type\":\"java.lang.RuntimeException\"," + -- "\"message\":\"oh no\"," + -- "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" + -- "}," + -- "\"duration\":0," + -- "\"timestamp\":\"" + result.getTimestamp() + "\"" + -- "}"); -- } -+ HealthCheck.Result result = HealthCheck.Result.unhealthy(e); -+ assertThat(mapper.writeValueAsString(result)) -+ .isEqualTo( -+ "{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); -+ } ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(null, mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } -- @Test -- void serializesAnUnhealthyResultWithNestedExceptions() throws Exception { -- final RuntimeException a = new RuntimeException("oh no"); -- a.setStackTrace(new StackTraceElement[]{ -- new StackTraceElement("Blah", "bloo", "Blah.java", 100) + @Test + void nullExecutorServiceTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(mockHealthCheck, null); - }); -+ @Test -+ void serializesAnUnhealthyResultWithNestedExceptions() throws Exception { -+ final RuntimeException a = new RuntimeException("oh no"); -+ a.setStackTrace( -+ new StackTraceElement[] {new StackTraceElement("Blah", "bloo", "Blah.java", 100)}); - -- final RuntimeException b = new RuntimeException("oh well", a); -- b.setStackTrace(new StackTraceElement[]{ -- new StackTraceElement("Blah", "blee", "Blah.java", 150) ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(mockHealthCheck, null); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void nonAsyncHealthCheckTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); - }); -+ final RuntimeException b = new RuntimeException("oh well", a); -+ b.setStackTrace( -+ new StackTraceElement[] {new StackTraceElement("Blah", "blee", "Blah.java", 150)}); - -- HealthCheck.Result result = HealthCheck.Result.unhealthy(b); -- assertThat(mapper.writeValueAsString(result)) -- .isEqualTo("{" + -- "\"healthy\":false," + -- "\"message\":\"oh well\"," + -- "\"error\":{" + -- "\"type\":\"java.lang.RuntimeException\"," + -- "\"message\":\"oh well\"," + -- "\"stack\":[\"Blah.blee(Blah.java:150)\"]," + -- "\"cause\":{" + -- "\"type\":\"java.lang.RuntimeException\"," + -- "\"message\":\"oh no\"," + -- "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" + -- "}" + -- "}," + -- "\"duration\":0," + -- "\"timestamp\":\"" + result.getTimestamp() + "\"" + -- "}"); -- } -+ HealthCheck.Result result = HealthCheck.Result.unhealthy(b); -+ assertThat(mapper.writeValueAsString(result)) -+ .isEqualTo( -+ "{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); -+ } ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } -- @Test -- void serializeResultWithDetail() throws Exception { -- Map complex = new LinkedHashMap<>(); -- complex.put("field", "value"); -+ @Test -+ void serializeResultWithDetail() throws Exception { -+ Map complex = new LinkedHashMap<>(); -+ complex.put("field", "value"); - -- HealthCheck.Result result = HealthCheck.Result.builder() -- .healthy() -- .withDetail("boolean", true) -- .withDetail("integer", 1) -- .withDetail("long", 2L) -- .withDetail("float", 3.546F) -- .withDetail("double", 4.567D) -- .withDetail("BigInteger", new BigInteger("12345")) -- .withDetail("BigDecimal", new BigDecimal("12345.56789")) -- .withDetail("String", "string") -- .withDetail("complex", complex) -- .build(); -+ HealthCheck.Result result = -+ HealthCheck.Result.builder() -+ .healthy() -+ .withDetail("boolean", true) -+ .withDetail("integer", 1) -+ .withDetail("long", 2L) -+ .withDetail("float", 3.546F) -+ .withDetail("double", 4.567D) -+ .withDetail("BigInteger", new BigInteger("12345")) -+ .withDetail("BigDecimal", new BigDecimal("12345.56789")) -+ .withDetail("String", "string") -+ .withDetail("complex", complex) -+ .build(); - -- assertThat(mapper.writeValueAsString(result)) -- .isEqualTo("{" + -- "\"healthy\":true," + -- "\"duration\":0," + -- "\"boolean\":true," + -- "\"integer\":1," + -- "\"long\":2," + -- "\"float\":3.546," + -- "\"double\":4.567," + -- "\"BigInteger\":12345," + -- "\"BigDecimal\":12345.56789," + -- "\"String\":\"string\"," + -- "\"complex\":{" + -- "\"field\":\"value\"" + -- "}," + -- "\"timestamp\":\"" + result.getTimestamp() + "\"" + -- "}"); -- } -+ assertThat(mapper.writeValueAsString(result)) -+ .isEqualTo( -+ "{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", -+ result.getTimestamp()); -+ } - } ---- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java -+++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.json; + @Test + void negativePeriodTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(new NegativePeriodAsyncHealthCheck(), mockExecutorService); +- }); ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator( ++ new NegativePeriodAsyncHealthCheck(), mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import com.fasterxml.jackson.databind.ObjectMapper; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -9,202 +13,210 @@ import io.dropwizard.metrics5.MetricFilter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; --import org.junit.jupiter.api.Test; -- - import java.util.concurrent.TimeUnit; -+import org.junit.jupiter.api.Test; + @Test + void zeroPeriodTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); +- }); ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- --class MetricsModuleTest { -- private final ObjectMapper mapper = new ObjectMapper().registerModule( -- new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, false, MetricFilter.ALL)); -+final class MetricsModuleTest { -+ private final ObjectMapper mapper = -+ new ObjectMapper() -+ .registerModule( -+ new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, false, MetricFilter.ALL)); - -- @Test -- void serializesGauges() throws Exception { -- final Gauge gauge = () -> 100; -+ @Test -+ void serializesGauges() throws Exception { -+ final Gauge gauge = () -> 100; + @Test + void negativeInitialValueTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator( +- new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); +- }); ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator( ++ new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } -- assertThat(mapper.writeValueAsString(gauge)) -- .isEqualTo("{\"value\":100}"); -- } -+ assertThat(mapper.writeValueAsString(gauge)).isEqualTo("{\"value\":100}"); -+ } + @Test +@@ -97,7 +99,7 @@ class AsyncHealthCheckDecoratorTest { + AsyncHealthCheckDecorator asyncDecorator = + new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); -- @Test -- void serializesGaugesThatThrowExceptions() throws Exception { -- final Gauge gauge = () -> { -- throw new IllegalArgumentException("poops"); -+ @Test -+ void serializesGaugesThatThrowExceptions() throws Exception { -+ final Gauge gauge = -+ () -> { -+ throw new IllegalArgumentException("poops"); - }; +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); + assertThat(asyncDecorator.check().isHealthy()).isTrue(); +@@ -109,7 +111,7 @@ class AsyncHealthCheckDecoratorTest { + AsyncHealthCheckDecorator asyncDecorator = + new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); + } +@@ -124,8 +126,8 @@ class AsyncHealthCheckDecoratorTest { + assertThat(asyncDecorator.check().isHealthy()).isFalse(); + } -- assertThat(mapper.writeValueAsString(gauge)) -- .isEqualTo("{\"error\":\"java.lang.IllegalArgumentException: poops\"}"); -- } -- -- @Test -- void serializesCounters() throws Exception { -- final Counter counter = mock(Counter.class); -- when(counter.getCount()).thenReturn(100L); -- -- assertThat(mapper.writeValueAsString(counter)) -- .isEqualTo("{\"count\":100}"); -- } -- -- @Test -- void serializesHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -- when(histogram.getCount()).thenReturn(1L); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(2L); -- when(snapshot.getMean()).thenReturn(3.0); -- when(snapshot.getMin()).thenReturn(4L); -- when(snapshot.getStdDev()).thenReturn(5.0); -- when(snapshot.getMedian()).thenReturn(6.0); -- when(snapshot.get75thPercentile()).thenReturn(7.0); -- when(snapshot.get95thPercentile()).thenReturn(8.0); -- when(snapshot.get98thPercentile()).thenReturn(9.0); -- when(snapshot.get99thPercentile()).thenReturn(10.0); -- when(snapshot.get999thPercentile()).thenReturn(11.0); -- when(snapshot.getValues()).thenReturn(new long[]{1, 2, 3}); -- -- when(histogram.getSnapshot()).thenReturn(snapshot); -- -- assertThat(mapper.writeValueAsString(histogram)) -- .isEqualTo("{" + -- "\"count\":1," + -- "\"max\":2," + -- "\"mean\":3.0," + -- "\"min\":4," + -- "\"p50\":6.0," + -- "\"p75\":7.0," + -- "\"p95\":8.0," + -- "\"p98\":9.0," + -- "\"p99\":10.0," + -- "\"p999\":11.0," + -- "\"stddev\":5.0}"); -- -- final ObjectMapper fullMapper = new ObjectMapper().registerModule( -+ assertThat(mapper.writeValueAsString(gauge)) -+ .isEqualTo("{\"error\":\"java.lang.IllegalArgumentException: poops\"}"); -+ } -+ -+ @Test -+ void serializesCounters() throws Exception { -+ final Counter counter = mock(); -+ when(counter.getCount()).thenReturn(100L); -+ -+ assertThat(mapper.writeValueAsString(counter)).isEqualTo("{\"count\":100}"); -+ } -+ -+ @Test -+ void serializesHistograms() throws Exception { -+ final Histogram histogram = mock(); -+ when(histogram.getCount()).thenReturn(1L); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(2L); -+ when(snapshot.getMean()).thenReturn(3.0); -+ when(snapshot.getMin()).thenReturn(4L); -+ when(snapshot.getStdDev()).thenReturn(5.0); -+ when(snapshot.getMedian()).thenReturn(6.0); -+ when(snapshot.get75thPercentile()).thenReturn(7.0); -+ when(snapshot.get95thPercentile()).thenReturn(8.0); -+ when(snapshot.get98thPercentile()).thenReturn(9.0); -+ when(snapshot.get99thPercentile()).thenReturn(10.0); -+ when(snapshot.get999thPercentile()).thenReturn(11.0); -+ when(snapshot.getValues()).thenReturn(new long[] {1, 2, 3}); -+ -+ when(histogram.getSnapshot()).thenReturn(snapshot); -+ -+ assertThat(mapper.writeValueAsString(histogram)) -+ .isEqualTo( -+ "{" -+ + "\"count\":1," -+ + "\"max\":2," -+ + "\"mean\":3.0," -+ + "\"min\":4," -+ + "\"p50\":6.0," -+ + "\"p75\":7.0," -+ + "\"p95\":8.0," -+ + "\"p98\":9.0," -+ + "\"p99\":10.0," -+ + "\"p999\":11.0," -+ + "\"stddev\":5.0}"); -+ -+ final ObjectMapper fullMapper = -+ new ObjectMapper() -+ .registerModule( - new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true, MetricFilter.ALL)); - -- assertThat(fullMapper.writeValueAsString(histogram)) -- .isEqualTo("{" + -- "\"count\":1," + -- "\"max\":2," + -- "\"mean\":3.0," + -- "\"min\":4," + -- "\"p50\":6.0," + -- "\"p75\":7.0," + -- "\"p95\":8.0," + -- "\"p98\":9.0," + -- "\"p99\":10.0," + -- "\"p999\":11.0," + -- "\"values\":[1,2,3]," + -- "\"stddev\":5.0}"); -- } -- -- @Test -- void serializesMeters() throws Exception { -- final Meter meter = mock(Meter.class); -- when(meter.getCount()).thenReturn(1L); -- when(meter.getMeanRate()).thenReturn(2.0); -- when(meter.getOneMinuteRate()).thenReturn(5.0); -- when(meter.getFiveMinuteRate()).thenReturn(4.0); -- when(meter.getFifteenMinuteRate()).thenReturn(3.0); -- -- assertThat(mapper.writeValueAsString(meter)) -- .isEqualTo("{" + -- "\"count\":1," + -- "\"m15_rate\":3.0," + -- "\"m1_rate\":5.0," + -- "\"m5_rate\":4.0," + -- "\"mean_rate\":2.0," + -- "\"units\":\"events/second\"}"); -- } -- -- @Test -- void serializesTimers() throws Exception { -- final Timer timer = mock(Timer.class); -- when(timer.getCount()).thenReturn(1L); -- when(timer.getMeanRate()).thenReturn(2.0); -- when(timer.getOneMinuteRate()).thenReturn(3.0); -- when(timer.getFiveMinuteRate()).thenReturn(4.0); -- when(timer.getFifteenMinuteRate()).thenReturn(5.0); -- -- final Snapshot snapshot = mock(Snapshot.class); -- when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -- when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -- when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -- when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -- when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -- when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -- when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -- when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -- when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -- when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -- -- when(snapshot.getValues()).thenReturn(new long[]{ -- TimeUnit.MILLISECONDS.toNanos(1), -- TimeUnit.MILLISECONDS.toNanos(2), -- TimeUnit.MILLISECONDS.toNanos(3) -- }); -- -- when(timer.getSnapshot()).thenReturn(snapshot); -- -- assertThat(mapper.writeValueAsString(timer)) -- .isEqualTo("{" + -- "\"count\":1," + -- "\"max\":100.0," + -- "\"mean\":200.0," + -- "\"min\":300.0," + -- "\"p50\":500.0," + -- "\"p75\":600.0," + -- "\"p95\":700.0," + -- "\"p98\":800.0," + -- "\"p99\":900.0," + -- "\"p999\":1000.0," + -- "\"stddev\":400.0," + -- "\"m15_rate\":5.0," + -- "\"m1_rate\":3.0," + -- "\"m5_rate\":4.0," + -- "\"mean_rate\":2.0," + -- "\"duration_units\":\"milliseconds\"," + -- "\"rate_units\":\"calls/second\"}"); -- -- final ObjectMapper fullMapper = new ObjectMapper().registerModule( -+ assertThat(fullMapper.writeValueAsString(histogram)) -+ .isEqualTo( -+ "{" -+ + "\"count\":1," -+ + "\"max\":2," -+ + "\"mean\":3.0," -+ + "\"min\":4," -+ + "\"p50\":6.0," -+ + "\"p75\":7.0," -+ + "\"p95\":8.0," -+ + "\"p98\":9.0," -+ + "\"p99\":10.0," -+ + "\"p999\":11.0," -+ + "\"values\":[1,2,3]," -+ + "\"stddev\":5.0}"); -+ } -+ -+ @Test -+ void serializesMeters() throws Exception { -+ final Meter meter = mock(); -+ when(meter.getCount()).thenReturn(1L); -+ when(meter.getMeanRate()).thenReturn(2.0); -+ when(meter.getOneMinuteRate()).thenReturn(5.0); -+ when(meter.getFiveMinuteRate()).thenReturn(4.0); -+ when(meter.getFifteenMinuteRate()).thenReturn(3.0); -+ -+ assertThat(mapper.writeValueAsString(meter)) -+ .isEqualTo( -+ "{" -+ + "\"count\":1," -+ + "\"m15_rate\":3.0," -+ + "\"m1_rate\":5.0," -+ + "\"m5_rate\":4.0," -+ + "\"mean_rate\":2.0," -+ + "\"units\":\"events/second\"}"); -+ } -+ +- @Test + @SuppressWarnings("unchecked") + @Test -+ void serializesTimers() throws Exception { -+ final Timer timer = mock(); -+ when(timer.getCount()).thenReturn(1L); -+ when(timer.getMeanRate()).thenReturn(2.0); -+ when(timer.getOneMinuteRate()).thenReturn(3.0); -+ when(timer.getFiveMinuteRate()).thenReturn(4.0); -+ when(timer.getFifteenMinuteRate()).thenReturn(5.0); -+ -+ final Snapshot snapshot = mock(); -+ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); -+ when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); -+ when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -+ when(snapshot.getStdDev()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(400)); -+ when(snapshot.getMedian()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(500)); -+ when(snapshot.get75thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(600)); -+ when(snapshot.get95thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(700)); -+ when(snapshot.get98thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(800)); -+ when(snapshot.get99thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(900)); -+ when(snapshot.get999thPercentile()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(1000)); -+ -+ when(snapshot.getValues()) -+ .thenReturn( -+ new long[] { -+ TimeUnit.MILLISECONDS.toNanos(1), -+ TimeUnit.MILLISECONDS.toNanos(2), -+ TimeUnit.MILLISECONDS.toNanos(3) -+ }); -+ -+ when(timer.getSnapshot()).thenReturn(snapshot); -+ -+ assertThat(mapper.writeValueAsString(timer)) -+ .isEqualTo( -+ "{" -+ + "\"count\":1," -+ + "\"max\":100.0," -+ + "\"mean\":200.0," -+ + "\"min\":300.0," -+ + "\"p50\":500.0," -+ + "\"p75\":600.0," -+ + "\"p95\":700.0," -+ + "\"p98\":800.0," -+ + "\"p99\":900.0," -+ + "\"p999\":1000.0," -+ + "\"stddev\":400.0," -+ + "\"m15_rate\":5.0," -+ + "\"m1_rate\":3.0," -+ + "\"m5_rate\":4.0," -+ + "\"mean_rate\":2.0," -+ + "\"duration_units\":\"milliseconds\"," -+ + "\"rate_units\":\"calls/second\"}"); -+ -+ final ObjectMapper fullMapper = -+ new ObjectMapper() -+ .registerModule( - new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true, MetricFilter.ALL)); - -- assertThat(fullMapper.writeValueAsString(timer)) -- .isEqualTo("{" + -- "\"count\":1," + -- "\"max\":100.0," + -- "\"mean\":200.0," + -- "\"min\":300.0," + -- "\"p50\":500.0," + -- "\"p75\":600.0," + -- "\"p95\":700.0," + -- "\"p98\":800.0," + -- "\"p99\":900.0," + -- "\"p999\":1000.0," + -- "\"values\":[1.0,2.0,3.0]," + -- "\"stddev\":400.0," + -- "\"m15_rate\":5.0," + -- "\"m1_rate\":3.0," + -- "\"m5_rate\":4.0," + -- "\"mean_rate\":2.0," + -- "\"duration_units\":\"milliseconds\"," + -- "\"rate_units\":\"calls/second\"}"); -- } -- -- @Test -- void serializesMetricRegistries() throws Exception { -- final MetricRegistry registry = new MetricRegistry(); -- -- assertThat(mapper.writeValueAsString(registry)) -- .isEqualTo("{" + -- "\"version\":\"5.0.0\"," + -- "\"gauges\":{}," + -- "\"counters\":{}," + -- "\"histograms\":{}," + -- "\"meters\":{}," + -- "\"timers\":{}}"); -- } -+ assertThat(fullMapper.writeValueAsString(timer)) -+ .isEqualTo( -+ "{" -+ + "\"count\":1," -+ + "\"max\":100.0," -+ + "\"mean\":200.0," -+ + "\"min\":300.0," -+ + "\"p50\":500.0," -+ + "\"p75\":600.0," -+ + "\"p95\":700.0," -+ + "\"p98\":800.0," -+ + "\"p99\":900.0," -+ + "\"p999\":1000.0," -+ + "\"values\":[1.0,2.0,3.0]," -+ + "\"stddev\":400.0," -+ + "\"m15_rate\":5.0," -+ + "\"m1_rate\":3.0," -+ + "\"m5_rate\":4.0," -+ + "\"mean_rate\":2.0," -+ + "\"duration_units\":\"milliseconds\"," -+ + "\"rate_units\":\"calls/second\"}"); -+ } -+ + void tearDownTriggersCancellation() throws Exception { + when(mockExecutorService.scheduleAtFixedRate( + any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) +@@ -136,13 +138,13 @@ class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); + asyncDecorator.tearDown(); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); +- verify(mockFuture, times(1)).cancel(eq(true)); ++ verify(mockFuture).cancel(true); + } + +- @Test + @SuppressWarnings("unchecked") + @Test -+ void serializesMetricRegistries() throws Exception { -+ final MetricRegistry registry = new MetricRegistry(); -+ -+ assertThat(mapper.writeValueAsString(registry)) -+ .isEqualTo( -+ "{" -+ + "\"version\":\"5.0.0\"," -+ + "\"gauges\":{}," -+ + "\"counters\":{}," -+ + "\"histograms\":{}," -+ + "\"meters\":{}," -+ + "\"timers\":{}}"); -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java -@@ -1,52 +1,53 @@ - package io.dropwizard.metrics5.jvm; + void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { + HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); + when(mockExecutorService.scheduleAtFixedRate( +@@ -155,7 +157,7 @@ class AsyncHealthCheckDecoratorTest { + HealthCheck.Result initialResult = asyncDecorator.check(); -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricSet; --import org.slf4j.Logger; --import org.slf4j.LoggerFactory; -- -+import java.util.HashMap; -+import java.util.Map; - import javax.management.JMException; - import javax.management.MBeanServer; - import javax.management.ObjectName; --import java.util.Collections; --import java.util.HashMap; --import java.util.Map; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +@@ -165,8 +167,8 @@ class AsyncHealthCheckDecoratorTest { + assertThat(actualResult).isNotEqualTo(initialResult); + } - /** - * A set of gauges for the count, usage, and capacity of the JVM's direct and mapped buffer pools. -- *

    -- * These JMX objects are only available on Java 7 and above. -+ * -+ *

    These JMX objects are only available on Java 7 and above. - */ - public class BufferPoolMetricSet implements MetricSet { -- private static final Logger LOGGER = LoggerFactory.getLogger(BufferPoolMetricSet.class); -- private static final String[] ATTRIBUTES = {"Count", "MemoryUsed", "TotalCapacity"}; -- private static final String[] NAMES = {"count", "used", "capacity"}; -- private static final String[] POOLS = {"direct", "mapped"}; -+ private static final Logger LOG = LoggerFactory.getLogger(BufferPoolMetricSet.class); -+ private static final String[] ATTRIBUTES = {"Count", "MemoryUsed", "TotalCapacity"}; -+ private static final String[] NAMES = {"count", "used", "capacity"}; -+ private static final String[] POOLS = {"direct", "mapped"}; +- @Test + @SuppressWarnings("unchecked") ++ @Test + void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { + Exception exception = new Exception("TestException"); + when(mockExecutorService.scheduleAtFixedRate( +@@ -178,7 +180,7 @@ class AsyncHealthCheckDecoratorTest { + new ConfigurableAsyncHealthCheck(exception), mockExecutorService); -- private final MBeanServer mBeanServer; -+ private final MBeanServer mBeanServer; + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +@@ -195,7 +197,7 @@ class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate( + runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); +@@ -214,7 +216,7 @@ class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate( + runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); +@@ -232,7 +234,7 @@ class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java +@@ -5,7 +5,7 @@ import static org.mockito.Mockito.mock; -- public BufferPoolMetricSet(MBeanServer mBeanServer) { -- this.mBeanServer = mBeanServer; -- } -+ public BufferPoolMetricSet(MBeanServer mBeanServer) { -+ this.mBeanServer = mBeanServer; -+ } - -- @Override -- public Map getMetrics() { -- final Map gauges = new HashMap<>(); -- for (String pool : POOLS) { -- for (int i = 0; i < ATTRIBUTES.length; i++) { -- final String attribute = ATTRIBUTES[i]; -- final String name = NAMES[i]; -- try { -- final ObjectName on = new ObjectName("java.nio:type=BufferPool,name=" + pool); -- mBeanServer.getMBeanInfo(on); -- gauges.put(MetricRegistry.name(pool, name), new JmxAttributeGauge(mBeanServer, on, attribute)); -- } catch (JMException ignored) { -- LOGGER.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); -- } -- } -+ @Override -+ public Map getMetrics() { -+ final Map gauges = new HashMap<>(); -+ for (String pool : POOLS) { -+ for (int i = 0; i < ATTRIBUTES.length; i++) { -+ final String attribute = ATTRIBUTES[i]; -+ final String name = NAMES[i]; -+ try { -+ final ObjectName on = new ObjectName("java.nio:type=BufferPool,name=" + pool); -+ mBeanServer.getMBeanInfo(on); -+ gauges.put( -+ MetricRegistry.name(pool, name), new JmxAttributeGauge(mBeanServer, on, attribute)); -+ } catch (JMException ignored) { -+ LOG.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); - } -- return Collections.unmodifiableMap(gauges); -+ } - } -+ return unmodifiableMap(gauges); -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/CachedThreadStatesGaugeSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/CachedThreadStatesGaugeSet.java -@@ -1,54 +1,55 @@ - package io.dropwizard.metrics5.jvm; + import org.junit.jupiter.api.Test; - import io.dropwizard.metrics5.CachedGauge; -- - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; - import java.util.concurrent.TimeUnit; +-class HealthCheckFilterTest { ++final class HealthCheckFilterTest { - /** -- * A variation of ThreadStatesGaugeSet that caches the ThreadInfo[] objects for -- * a given interval. -+ * A variation of ThreadStatesGaugeSet that caches the ThreadInfo[] objects for a given interval. - */ - public class CachedThreadStatesGaugeSet extends ThreadStatesGaugeSet { + @Test + void theAllFilterMatchesAllHealthChecks() { +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java +@@ -1,9 +1,9 @@ + package io.dropwizard.metrics5.health; -- private final CachedGauge threadInfo; -- -- /** -- * Creates a new set of gauges using the given MXBean and detector. -- * Caches the information for the given interval and time unit. -- * -- * @param threadMXBean a thread MXBean -- * @param deadlockDetector a deadlock detector -- * @param interval cache interval -- * @param unit cache interval time unit -- */ -- public CachedThreadStatesGaugeSet(final ThreadMXBean threadMXBean, ThreadDeadlockDetector deadlockDetector, -- long interval, TimeUnit unit) { -- super(threadMXBean, deadlockDetector); -- threadInfo = new CachedGauge(interval, unit) { -- @Override -- protected ThreadInfo[] loadValue() { -- return CachedThreadStatesGaugeSet.super.getThreadInfo(); -- } -+ private final CachedGauge threadInfo; -+ -+ /** -+ * Creates a new set of gauges using the given MXBean and detector. Caches the information for the -+ * given interval and time unit. -+ * -+ * @param threadMXBean a thread MXBean -+ * @param deadlockDetector a deadlock detector -+ * @param interval cache interval -+ * @param unit cache interval time unit -+ */ -+ public CachedThreadStatesGaugeSet( -+ final ThreadMXBean threadMXBean, -+ ThreadDeadlockDetector deadlockDetector, -+ long interval, -+ TimeUnit unit) { -+ super(threadMXBean, deadlockDetector); -+ threadInfo = -+ new CachedGauge(interval, unit) { -+ @Override -+ protected ThreadInfo[] loadValue() { -+ return CachedThreadStatesGaugeSet.super.getThreadInfo(); -+ } - }; -- } -- -- /** -- * Creates a new set of gauges using the default MXBeans. -- * Caches the information for the given interval and time unit. -- * -- * @param interval cache interval -- * @param unit cache interval time unit -- */ -- public CachedThreadStatesGaugeSet(long interval, TimeUnit unit) { -- this(ManagementFactory.getThreadMXBean(), new ThreadDeadlockDetector(), interval, unit); -- } -- -- @Override -- ThreadInfo[] getThreadInfo() { -- return threadInfo.getValue(); -- } -- -+ } -+ -+ /** -+ * Creates a new set of gauges using the default MXBeans. Caches the information for the given -+ * interval and time unit. -+ * -+ * @param interval cache interval -+ * @param unit cache interval time unit -+ */ -+ public CachedThreadStatesGaugeSet(long interval, TimeUnit unit) { -+ this(ManagementFactory.getThreadMXBean(), new ThreadDeadlockDetector(), interval, unit); -+ } -+ -+ @Override -+ ThreadInfo[] getThreadInfo() { -+ return threadInfo.getValue(); -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSet.java -@@ -4,33 +4,30 @@ import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricSet; -- - import java.lang.management.ClassLoadingMXBean; - import java.lang.management.ManagementFactory; - import java.util.HashMap; - import java.util.Map; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.assertj.core.api.Assertions.entry; + import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +-import static org.junit.jupiter.api.Assertions.assertThrows; + import static org.mockito.ArgumentCaptor.forClass; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; +@@ -23,22 +23,22 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; --/** -- * A set of gauges for JVM classloader usage. -- */ -+/** A set of gauges for JVM classloader usage. */ - public class ClassLoadingGaugeSet implements MetricSet { +-class HealthCheckRegistryTest { +- private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); ++final class HealthCheckRegistryTest { ++ private final ScheduledExecutorService executorService = mock(); + private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); +- private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ private final HealthCheckRegistryListener listener = mock(); -- private final ClassLoadingMXBean mxBean; -+ private final ClassLoadingMXBean mxBean; +- private final HealthCheck hc1 = mock(HealthCheck.class); +- private final HealthCheck hc2 = mock(HealthCheck.class); ++ private final HealthCheck hc1 = mock(); ++ private final HealthCheck hc2 = mock(); -- public ClassLoadingGaugeSet() { -- this(ManagementFactory.getClassLoadingMXBean()); -- } -+ public ClassLoadingGaugeSet() { -+ this(ManagementFactory.getClassLoadingMXBean()); -+ } +- private final HealthCheck.Result r1 = mock(HealthCheck.Result.class); +- private final HealthCheck.Result r2 = mock(HealthCheck.Result.class); ++ private final HealthCheck.Result r1 = mock(); ++ private final HealthCheck.Result r2 = mock(); -- public ClassLoadingGaugeSet(ClassLoadingMXBean mxBean) { -- this.mxBean = mxBean; -- } -+ public ClassLoadingGaugeSet(ClassLoadingMXBean mxBean) { -+ this.mxBean = mxBean; -+ } - -- @Override -- public Map getMetrics() { -- final Map gauges = new HashMap<>(); -- gauges.put(MetricName.build("loaded"), (Gauge) mxBean::getTotalLoadedClassCount); -- gauges.put(MetricName.build("unloaded"), (Gauge) mxBean::getUnloadedClassCount); -+ @Override -+ public Map getMetrics() { -+ final Map gauges = new HashMap<>(); -+ gauges.put(MetricName.build("loaded"), (Gauge) mxBean::getTotalLoadedClassCount); -+ gauges.put(MetricName.build("unloaded"), (Gauge) mxBean::getUnloadedClassCount); - -- return gauges; -- } -+ return gauges; -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/CpuTimeClock.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/CpuTimeClock.java -@@ -1,19 +1,16 @@ - package io.dropwizard.metrics5.jvm; +- private final HealthCheck.Result ar = mock(HealthCheck.Result.class); ++ private final HealthCheck.Result ar = mock(); + private final HealthCheck ahc = new TestAsyncHealthCheck(ar); - import io.dropwizard.metrics5.Clock; -- - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadMXBean; + @SuppressWarnings("rawtypes") +- private final ScheduledFuture af = mock(ScheduledFuture.class); ++ private final ScheduledFuture af = mock(); --/** -- * A clock implementation which returns the current thread's CPU time. -- */ -+/** A clock implementation which returns the current thread's CPU time. */ - public class CpuTimeClock extends Clock { + @BeforeEach + @SuppressWarnings("unchecked") +@@ -74,11 +74,11 @@ class HealthCheckRegistryTest { -- private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); -+ private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean(); + @Test + void registeringHealthCheckTwiceThrowsException() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- registry.register("hc1", hc1); +- }); ++ assertThatThrownBy( ++ () -> { ++ registry.register("hc1", hc1); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } -- @Override -- public long getTick() { -- return THREAD_MX_BEAN.getCurrentThreadCpuTime(); -- } -+ @Override -+ public long getTick() { -+ return THREAD_MX_BEAN.getCurrentThreadCpuTime(); -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGauge.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGauge.java -@@ -1,50 +1,47 @@ - package io.dropwizard.metrics5.jvm; + @Test +@@ -101,7 +101,7 @@ class HealthCheckRegistryTest { - import io.dropwizard.metrics5.RatioGauge; -- - import java.lang.management.ManagementFactory; - import java.lang.management.OperatingSystemMXBean; + @Test + void addingListenerCatchesExistingHealthChecks() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ HealthCheckRegistryListener listener = mock(); + HealthCheckRegistry registry = new HealthCheckRegistry(); + registry.register("hc1", hc1); + registry.register("hc2", hc2); +@@ -115,7 +115,7 @@ class HealthCheckRegistryTest { --/** -- * A gauge for the ratio of used to total file descriptors. -- */ -+/** A gauge for the ratio of used to total file descriptors. */ - public class FileDescriptorRatioGauge extends RatioGauge { -- private static boolean unixOperatingSystemMXBeanExists = false; -- -- private final OperatingSystemMXBean os; -- -- static { -- try { -- Class.forName("com.sun.management.UnixOperatingSystemMXBean"); -- unixOperatingSystemMXBeanExists = true; -- } catch (ClassNotFoundException e) { -- // do nothing -- } -- } -+ private static boolean unixOperatingSystemMXBeanExists = false; + @Test + void removedListenerDoesNotReceiveUpdates() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ HealthCheckRegistryListener listener = mock(); + HealthCheckRegistry registry = new HealthCheckRegistry(); + registry.addListener(listener); + registry.register("hc1", hc1); +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java +@@ -11,7 +11,7 @@ import java.time.ZonedDateTime; + import java.time.format.DateTimeFormatter; + import org.junit.jupiter.api.Test; -- /** -- * Creates a new gauge using the platform OS bean. -- */ -- public FileDescriptorRatioGauge() { -- this(ManagementFactory.getOperatingSystemMXBean()); -- } -+ private final OperatingSystemMXBean os; - -- /** -- * Creates a new gauge using the given OS bean. -- * -- * @param os an {@link OperatingSystemMXBean} -- */ -- public FileDescriptorRatioGauge(OperatingSystemMXBean os) { -- this.os = os; -+ static { -+ try { -+ Class.forName("com.sun.management.UnixOperatingSystemMXBean"); -+ unixOperatingSystemMXBeanExists = true; -+ } catch (ClassNotFoundException e) { -+ // do nothing - } -- -- @Override -- protected Ratio getRatio() { -- if (unixOperatingSystemMXBeanExists && os instanceof com.sun.management.UnixOperatingSystemMXBean) { -- final com.sun.management.UnixOperatingSystemMXBean unixOs = (com.sun.management.UnixOperatingSystemMXBean) os; -- return Ratio.of(unixOs.getOpenFileDescriptorCount(), unixOs.getMaxFileDescriptorCount()); -- } else { -- return Ratio.of(Double.NaN, Double.NaN); -- } -+ } -+ -+ /** Creates a new gauge using the platform OS bean. */ -+ public FileDescriptorRatioGauge() { -+ this(ManagementFactory.getOperatingSystemMXBean()); -+ } -+ -+ /** -+ * Creates a new gauge using the given OS bean. -+ * -+ * @param os an {@link OperatingSystemMXBean} -+ */ -+ public FileDescriptorRatioGauge(OperatingSystemMXBean os) { -+ this.os = os; -+ } -+ -+ @Override -+ protected Ratio getRatio() { -+ if (unixOperatingSystemMXBeanExists -+ && os instanceof com.sun.management.UnixOperatingSystemMXBean) { -+ final com.sun.management.UnixOperatingSystemMXBean unixOs = -+ (com.sun.management.UnixOperatingSystemMXBean) os; -+ return Ratio.of(unixOs.getOpenFileDescriptorCount(), unixOs.getMaxFileDescriptorCount()); -+ } else { -+ return Ratio.of(Double.NaN, Double.NaN); - } -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java -@@ -1,53 +1,49 @@ - package io.dropwizard.metrics5.jvm; +-class HealthCheckTest { ++final class HealthCheckTest { -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricSet; -- - import java.lang.management.GarbageCollectorMXBean; - import java.lang.management.ManagementFactory; - import java.util.ArrayList; - import java.util.Collection; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; - import java.util.regex.Pattern; - --/** -- * A set of gauges for the counts and elapsed times of garbage collections. -- */ -+/** A set of gauges for the counts and elapsed times of garbage collections. */ - public class GarbageCollectorMetricSet implements MetricSet { -- private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); -+ private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); - -- private final List garbageCollectors; -+ private final List garbageCollectors; - -- /** -- * Creates a new set of gauges for all discoverable garbage collectors. -- */ -- public GarbageCollectorMetricSet() { -- this(ManagementFactory.getGarbageCollectorMXBeans()); -- } -+ /** Creates a new set of gauges for all discoverable garbage collectors. */ -+ public GarbageCollectorMetricSet() { -+ this(ManagementFactory.getGarbageCollectorMXBeans()); -+ } - -- /** -- * Creates a new set of gauges for the given collection of garbage collectors. -- * -- * @param garbageCollectors the garbage collectors -- */ -- public GarbageCollectorMetricSet(Collection garbageCollectors) { -- this.garbageCollectors = new ArrayList<>(garbageCollectors); -- } -+ /** -+ * Creates a new set of gauges for the given collection of garbage collectors. -+ * -+ * @param garbageCollectors the garbage collectors -+ */ -+ public GarbageCollectorMetricSet(Collection garbageCollectors) { -+ this.garbageCollectors = new ArrayList<>(garbageCollectors); -+ } - -- @Override -- public Map getMetrics() { -- final Map gauges = new HashMap<>(); -- for (final GarbageCollectorMXBean gc : garbageCollectors) { -- final String name = WHITESPACE.matcher(gc.getName()).replaceAll("-"); -- gauges.put(MetricRegistry.name(name, "count"), (Gauge) gc::getCollectionCount); -- gauges.put(MetricRegistry.name(name, "time"), (Gauge) gc::getCollectionTime); -- } -- return Collections.unmodifiableMap(gauges); -+ @Override -+ public Map getMetrics() { -+ final Map gauges = new HashMap<>(); -+ for (final GarbageCollectorMXBean gc : garbageCollectors) { -+ final String name = WHITESPACE.matcher(gc.getName()).replaceAll("-"); -+ gauges.put(MetricRegistry.name(name, "count"), (Gauge) gc::getCollectionCount); -+ gauges.put(MetricRegistry.name(name, "time"), (Gauge) gc::getCollectionTime); + private static final DateTimeFormatter DATE_TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); +@@ -29,7 +29,7 @@ class HealthCheckTest { } -+ return unmodifiableMap(gauges); -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JmxAttributeGauge.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JmxAttributeGauge.java -@@ -1,61 +1,62 @@ - package io.dropwizard.metrics5.jvm; + } - import io.dropwizard.metrics5.Gauge; -- --import javax.management.JMException; --import javax.management.MBeanServerConnection; --import javax.management.ObjectName; - import java.io.IOException; - import java.lang.management.ManagementFactory; - import java.util.Set; -+import javax.management.JMException; -+import javax.management.MBeanServerConnection; -+import javax.management.ObjectName; +- private final HealthCheck underlying = mock(HealthCheck.class); ++ private final HealthCheck underlying = mock(); + private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); - /** -- * A {@link Gauge} implementation which queries an {@link MBeanServerConnection} for an attribute of an object. -+ * A {@link Gauge} implementation which queries an {@link MBeanServerConnection} for an attribute of -+ * an object. - */ - public class JmxAttributeGauge implements Gauge { -- private final MBeanServerConnection mBeanServerConn; -- private final ObjectName objectName; -- private final String attributeName; -+ private final MBeanServerConnection mBeanServerConn; -+ private final ObjectName objectName; -+ private final String attributeName; - -- /** -- * Creates a new JmxAttributeGauge. -- * -- * @param objectName the name of the object -- * @param attributeName the name of the object's attribute -- */ -- public JmxAttributeGauge(ObjectName objectName, String attributeName) { -- this(ManagementFactory.getPlatformMBeanServer(), objectName, attributeName); -- } -+ /** -+ * Creates a new JmxAttributeGauge. -+ * -+ * @param objectName the name of the object -+ * @param attributeName the name of the object's attribute -+ */ -+ public JmxAttributeGauge(ObjectName objectName, String attributeName) { -+ this(ManagementFactory.getPlatformMBeanServer(), objectName, attributeName); -+ } - -- /** -- * Creates a new JmxAttributeGauge. -- * -- * @param mBeanServerConn the {@link MBeanServerConnection} -- * @param objectName the name of the object -- * @param attributeName the name of the object's attribute -- */ -- public JmxAttributeGauge(MBeanServerConnection mBeanServerConn, ObjectName objectName, String attributeName) { -- this.mBeanServerConn = mBeanServerConn; -- this.objectName = objectName; -- this.attributeName = attributeName; -- } -+ /** -+ * Creates a new JmxAttributeGauge. -+ * -+ * @param mBeanServerConn the {@link MBeanServerConnection} -+ * @param objectName the name of the object -+ * @param attributeName the name of the object's attribute -+ */ -+ public JmxAttributeGauge( -+ MBeanServerConnection mBeanServerConn, ObjectName objectName, String attributeName) { -+ this.mBeanServerConn = mBeanServerConn; -+ this.objectName = objectName; -+ this.attributeName = attributeName; -+ } - -- @Override -- public Object getValue() { -- try { -- return mBeanServerConn.getAttribute(getObjectName(), attributeName); -- } catch (IOException | JMException e) { -- return null; -- } -+ @Override -+ public Object getValue() { -+ try { -+ return mBeanServerConn.getAttribute(getObjectName(), attributeName); -+ } catch (IOException | JMException e) { -+ return null; - } -+ } - -- private ObjectName getObjectName() throws IOException { -- if (objectName.isPattern()) { -- Set foundNames = mBeanServerConn.queryNames(objectName, null); -- if (foundNames.size() == 1) { -- return foundNames.iterator().next(); -- } -- } -- return objectName; -+ private ObjectName getObjectName() throws IOException { -+ if (objectName.isPattern()) { -+ Set foundNames = mBeanServerConn.queryNames(objectName, null); -+ if (foundNames.size() == 1) { -+ return foundNames.iterator().next(); -+ } - } -+ return objectName; -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java -@@ -1,52 +1,53 @@ - package io.dropwizard.metrics5.jvm; + @Test +@@ -89,7 +89,7 @@ class HealthCheckTest { -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricSet; -- - import java.lang.management.ManagementFactory; - import java.lang.management.RuntimeMXBean; --import java.util.Collections; - import java.util.HashMap; - import java.util.Locale; - import java.util.Map; + @Test + void canHaveUnhealthyResultsWithExceptions() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); --/** -- * A set of gauges for the JVM name, vendor, and uptime. -- */ -+/** A set of gauges for the JVM name, vendor, and uptime. */ - public class JvmAttributeGaugeSet implements MetricSet { -- private final RuntimeMXBean runtime; -- -- /** -- * Creates a new set of gauges. -- */ -- public JvmAttributeGaugeSet() { -- this(ManagementFactory.getRuntimeMXBean()); -- } -- -- /** -- * Creates a new set of gauges with the given {@link RuntimeMXBean}. -- * -- * @param runtime JVM management interface with access to system properties -- */ -- public JvmAttributeGaugeSet(RuntimeMXBean runtime) { -- this.runtime = runtime; -- } -- -- @Override -- public Map getMetrics() { -- final Map gauges = new HashMap<>(); -- -- gauges.put(MetricName.build("name"), (Gauge) runtime::getName); -- gauges.put(MetricName.build("vendor"), (Gauge) () -> String.format(Locale.US, -- "%s %s %s (%s)", -- runtime.getVmVendor(), -- runtime.getVmName(), -- runtime.getVmVersion(), -- runtime.getSpecVersion())); -- gauges.put(MetricName.build("uptime"), (Gauge) runtime::getUptime); -- -- return Collections.unmodifiableMap(gauges); -- } -+ private final RuntimeMXBean runtime; -+ -+ /** Creates a new set of gauges. */ -+ public JvmAttributeGaugeSet() { -+ this(ManagementFactory.getRuntimeMXBean()); -+ } -+ -+ /** -+ * Creates a new set of gauges with the given {@link RuntimeMXBean}. -+ * -+ * @param runtime JVM management interface with access to system properties -+ */ -+ public JvmAttributeGaugeSet(RuntimeMXBean runtime) { -+ this.runtime = runtime; -+ } -+ -+ @Override -+ public Map getMetrics() { -+ final Map gauges = new HashMap<>(); -+ -+ gauges.put(MetricName.build("name"), (Gauge) runtime::getName); -+ gauges.put( -+ MetricName.build("vendor"), -+ (Gauge) -+ () -> -+ String.format( -+ Locale.US, -+ "%s %s %s (%s)", -+ runtime.getVmVendor(), -+ runtime.getVmName(), -+ runtime.getVmVersion(), -+ runtime.getSpecVersion())); -+ gauges.put(MetricName.build("uptime"), (Gauge) runtime::getUptime); -+ -+ return unmodifiableMap(gauges); -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java -@@ -1,19 +1,19 @@ - package io.dropwizard.metrics5.jvm; + final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); +@@ -144,7 +144,7 @@ class HealthCheckTest { -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricSet; - import io.dropwizard.metrics5.RatioGauge; -- - import java.lang.management.ManagementFactory; - import java.lang.management.MemoryMXBean; - import java.lang.management.MemoryPoolMXBean; - import java.lang.management.MemoryUsage; - import java.util.ArrayList; - import java.util.Collection; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -24,83 +24,122 @@ import java.util.regex.Pattern; - * GC-specific memory pools. - */ - public class MemoryUsageGaugeSet implements MetricSet { -- private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); -- -- private final MemoryMXBean mxBean; -- private final List memoryPools; -- -- public MemoryUsageGaugeSet() { -- this(ManagementFactory.getMemoryMXBean(), ManagementFactory.getMemoryPoolMXBeans()); -- } -- -- public MemoryUsageGaugeSet(MemoryMXBean mxBean, -- Collection memoryPools) { -- this.mxBean = mxBean; -- this.memoryPools = new ArrayList<>(memoryPools); -- } -+ private static final Pattern WHITESPACE = Pattern.compile("[\\s]+"); -+ -+ private final MemoryMXBean mxBean; -+ private final List memoryPools; -+ -+ public MemoryUsageGaugeSet() { -+ this(ManagementFactory.getMemoryMXBean(), ManagementFactory.getMemoryPoolMXBeans()); -+ } -+ -+ public MemoryUsageGaugeSet(MemoryMXBean mxBean, Collection memoryPools) { -+ this.mxBean = mxBean; -+ this.memoryPools = new ArrayList<>(memoryPools); -+ } -+ -+ @Override -+ public Map getMetrics() { -+ final Map gauges = new HashMap<>(); -+ -+ gauges.put( -+ MetricName.build("total.init"), -+ (Gauge) -+ () -> mxBean.getHeapMemoryUsage().getInit() + mxBean.getNonHeapMemoryUsage().getInit()); -+ gauges.put( -+ MetricName.build("total.used"), -+ (Gauge) -+ () -> mxBean.getHeapMemoryUsage().getUsed() + mxBean.getNonHeapMemoryUsage().getUsed()); -+ gauges.put( -+ MetricName.build("total.max"), -+ (Gauge) -+ () -> -+ mxBean.getNonHeapMemoryUsage().getMax() == -1 -+ ? -1 -+ : mxBean.getHeapMemoryUsage().getMax() -+ + mxBean.getNonHeapMemoryUsage().getMax()); -+ gauges.put( -+ MetricName.build("total.committed"), -+ (Gauge) -+ () -> -+ mxBean.getHeapMemoryUsage().getCommitted() -+ + mxBean.getNonHeapMemoryUsage().getCommitted()); -+ -+ gauges.put( -+ MetricName.build("heap.init"), (Gauge) () -> mxBean.getHeapMemoryUsage().getInit()); -+ gauges.put( -+ MetricName.build("heap.used"), (Gauge) () -> mxBean.getHeapMemoryUsage().getUsed()); -+ gauges.put( -+ MetricName.build("heap.max"), (Gauge) () -> mxBean.getHeapMemoryUsage().getMax()); -+ gauges.put( -+ MetricName.build("heap.committed"), -+ (Gauge) () -> mxBean.getHeapMemoryUsage().getCommitted()); -+ gauges.put( -+ MetricName.build("heap.usage"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ final MemoryUsage usage = mxBean.getHeapMemoryUsage(); -+ return Ratio.of(usage.getUsed(), usage.getMax()); -+ } -+ }); - -- @Override -- public Map getMetrics() { -- final Map gauges = new HashMap<>(); -- -- gauges.put(MetricName.build("total.init"), (Gauge) () -> mxBean.getHeapMemoryUsage().getInit() + -- mxBean.getNonHeapMemoryUsage().getInit()); -- gauges.put(MetricName.build("total.used"), (Gauge) () -> mxBean.getHeapMemoryUsage().getUsed() + -- mxBean.getNonHeapMemoryUsage().getUsed()); -- gauges.put(MetricName.build("total.max"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getMax() == -1 ? -- -1 : mxBean.getHeapMemoryUsage().getMax() + mxBean.getNonHeapMemoryUsage().getMax()); -- gauges.put(MetricName.build("total.committed"), (Gauge) () -> mxBean.getHeapMemoryUsage().getCommitted() + -- mxBean.getNonHeapMemoryUsage().getCommitted()); -- -- gauges.put(MetricName.build("heap.init"), (Gauge) () -> mxBean.getHeapMemoryUsage().getInit()); -- gauges.put(MetricName.build("heap.used"), (Gauge) () -> mxBean.getHeapMemoryUsage().getUsed()); -- gauges.put(MetricName.build("heap.max"), (Gauge) () -> mxBean.getHeapMemoryUsage().getMax()); -- gauges.put(MetricName.build("heap.committed"), (Gauge) () -> mxBean.getHeapMemoryUsage().getCommitted()); -- gauges.put(MetricName.build("heap.usage"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- final MemoryUsage usage = mxBean.getHeapMemoryUsage(); -- return Ratio.of(usage.getUsed(), usage.getMax()); -- } -+ gauges.put( -+ MetricName.build("non-heap.init"), -+ (Gauge) () -> mxBean.getNonHeapMemoryUsage().getInit()); -+ gauges.put( -+ MetricName.build("non-heap.used"), -+ (Gauge) () -> mxBean.getNonHeapMemoryUsage().getUsed()); -+ gauges.put( -+ MetricName.build("non-heap.max"), -+ (Gauge) () -> mxBean.getNonHeapMemoryUsage().getMax()); -+ gauges.put( -+ MetricName.build("non-heap.committed"), -+ (Gauge) () -> mxBean.getNonHeapMemoryUsage().getCommitted()); -+ gauges.put( -+ MetricName.build("non-heap.usage"), -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ final MemoryUsage usage = mxBean.getNonHeapMemoryUsage(); -+ return Ratio.of( -+ usage.getUsed(), usage.getMax() == -1 ? usage.getCommitted() : usage.getMax()); -+ } - }); + @Test + void canHaveUnHealthyBuilderWithDetailAndError() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + final HealthCheck.Result result = +@@ -161,7 +161,7 @@ class HealthCheckTest { + + @Test + void returnsResultsWhenExecuted() { +- final HealthCheck.Result result = mock(HealthCheck.Result.class); ++ final HealthCheck.Result result = mock(); + when(underlying.execute()).thenReturn(result); + + assertThat(healthCheck.execute()).isEqualTo(result); +@@ -171,7 +171,7 @@ class HealthCheckTest { + + @Test + void wrapsExceptionsWhenExecuted() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + when(underlying.execute()).thenThrow(e); +@@ -181,7 +181,7 @@ class HealthCheckTest { + assertThat(actual.getMessage()).isEqualTo("oh noes"); + assertThat(actual.getError()).isEqualTo(e); + assertThat(actual.getDetails()).isNull(); +- assertThat(actual.getDuration()).isGreaterThanOrEqualTo(0); ++ assertThat(actual.getDuration()).isNotNegative(); + } -- gauges.put(MetricName.build("non-heap.init"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getInit()); -- gauges.put(MetricName.build("non-heap.used"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getUsed()); -- gauges.put(MetricName.build("non-heap.max"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getMax()); -- gauges.put(MetricName.build("non-heap.committed"), (Gauge) () -> mxBean.getNonHeapMemoryUsage().getCommitted()); -- gauges.put(MetricName.build("non-heap.usage"), new RatioGauge() { -+ for (final MemoryPoolMXBean pool : memoryPools) { -+ final String poolName = "pools." + WHITESPACE.matcher(pool.getName()).replaceAll("-"); -+ -+ gauges.put( -+ MetricRegistry.name(poolName, "usage"), -+ new RatioGauge() { - @Override - protected Ratio getRatio() { -- final MemoryUsage usage = mxBean.getNonHeapMemoryUsage(); -- return Ratio.of(usage.getUsed(), usage.getMax() == -1 ? usage.getCommitted() : usage.getMax()); -+ MemoryUsage usage = pool.getUsage(); -+ return Ratio.of( -+ usage.getUsed(), usage.getMax() == -1 ? usage.getCommitted() : usage.getMax()); - } -- }); -- -- for (final MemoryPoolMXBean pool : memoryPools) { -- final String poolName = "pools." + WHITESPACE.matcher(pool.getName()).replaceAll("-"); -- -- gauges.put(MetricRegistry.name(poolName, "usage"), new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- MemoryUsage usage = pool.getUsage(); -- return Ratio.of(usage.getUsed(), -- usage.getMax() == -1 ? usage.getCommitted() : usage.getMax()); -- } -- }); -- -- gauges.put(MetricRegistry.name(poolName, "max"), (Gauge) () -> pool.getUsage().getMax()); -- gauges.put(MetricRegistry.name(poolName, "used"), (Gauge) () -> pool.getUsage().getUsed()); -- gauges.put(MetricRegistry.name(poolName, "committed"), (Gauge) () -> pool.getUsage().getCommitted()); -- -- // Only register GC usage metrics if the memory pool supports usage statistics. -- if (pool.getCollectionUsage() != null) { -- gauges.put(MetricRegistry.name(poolName, "used-after-gc"), (Gauge) () -> -- pool.getCollectionUsage().getUsed()); -- } -- -- gauges.put(MetricRegistry.name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); -- } -- -- return Collections.unmodifiableMap(gauges); -+ }); -+ -+ gauges.put( -+ MetricRegistry.name(poolName, "max"), (Gauge) () -> pool.getUsage().getMax()); -+ gauges.put( -+ MetricRegistry.name(poolName, "used"), (Gauge) () -> pool.getUsage().getUsed()); -+ gauges.put( -+ MetricRegistry.name(poolName, "committed"), -+ (Gauge) () -> pool.getUsage().getCommitted()); -+ -+ // Only register GC usage metrics if the memory pool supports usage statistics. -+ if (pool.getCollectionUsage() != null) { -+ gauges.put( -+ MetricRegistry.name(poolName, "used-after-gc"), -+ (Gauge) () -> pool.getCollectionUsage().getUsed()); -+ } -+ -+ gauges.put( -+ MetricRegistry.name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); - } -+ -+ return unmodifiableMap(gauges); -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java -@@ -1,65 +1,57 @@ - package io.dropwizard.metrics5.jvm; + @Test +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java +@@ -2,13 +2,12 @@ package io.dropwizard.metrics5.health; -+import static java.util.Collections.unmodifiableSet; -+ -+import com.google.common.collect.ImmutableSet; - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; --import java.util.Collections; - import java.util.HashSet; - import java.util.Set; + import static org.assertj.core.api.Assertions.assertThat; + import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.junit.jupiter.api.Assertions.assertTrue; --/** -- * A utility class for detecting deadlocked threads. -- */ -+/** A utility class for detecting deadlocked threads. */ - public class ThreadDeadlockDetector { -- private static final int MAX_STACK_TRACE_DEPTH = 100; -+ private static final int MAX_STACK_TRACE_DEPTH = 100; - -- private final ThreadMXBean threads; -+ private final ThreadMXBean threads; - -- /** -- * Creates a new detector. -- */ -- public ThreadDeadlockDetector() { -- this(ManagementFactory.getThreadMXBean()); -- } -+ /** Creates a new detector. */ -+ public ThreadDeadlockDetector() { -+ this(ManagementFactory.getThreadMXBean()); -+ } - -- /** -- * Creates a new detector using the given {@link ThreadMXBean}. -- * -- * @param threads a {@link ThreadMXBean} -- */ -- public ThreadDeadlockDetector(ThreadMXBean threads) { -- this.threads = threads; -- } -+ /** -+ * Creates a new detector using the given {@link ThreadMXBean}. -+ * -+ * @param threads a {@link ThreadMXBean} -+ */ -+ public ThreadDeadlockDetector(ThreadMXBean threads) { -+ this.threads = threads; -+ } - -- /** -- * Returns a set of diagnostic stack traces for any deadlocked threads. If no threads are -- * deadlocked, returns an empty set. -- * -- * @return stack traces for deadlocked threads or an empty set -- */ -- public Set getDeadlockedThreads() { -- final long[] ids = threads.findDeadlockedThreads(); -- if (ids != null) { -- final Set deadlocks = new HashSet<>(); -- for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { -- final StringBuilder stackTrace = new StringBuilder(); -- for (StackTraceElement element : info.getStackTrace()) { -- stackTrace.append("\t at ") -- .append(element.toString()) -- .append(String.format("%n")); -- } -- -- deadlocks.add( -- String.format("%s locked on %s (owned by %s):%n%s", -- info.getThreadName(), -- info.getLockName(), -- info.getLockOwnerName(), -- stackTrace.toString() -- ) -- ); -- } -- return Collections.unmodifiableSet(deadlocks); -+ /** -+ * Returns a set of diagnostic stack traces for any deadlocked threads. If no threads are -+ * deadlocked, returns an empty set. -+ * -+ * @return stack traces for deadlocked threads or an empty set -+ */ -+ public Set getDeadlockedThreads() { -+ final long[] ids = threads.findDeadlockedThreads(); -+ if (ids != null) { -+ final Set deadlocks = new HashSet<>(); -+ for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { -+ final StringBuilder stackTrace = new StringBuilder(); -+ for (StackTraceElement element : info.getStackTrace()) { -+ stackTrace.append("\t at ").append(element).append(String.format("%n")); - } -- return Collections.emptySet(); -+ -+ deadlocks.add( -+ String.format( -+ "%s locked on %s (owned by %s):%n%s", -+ info.getThreadName(), info.getLockName(), info.getLockOwnerName(), stackTrace)); -+ } -+ return unmodifiableSet(deadlocks); - } -+ return ImmutableSet.of(); -+ } - } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDump.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDump.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.jvm; + import java.util.concurrent.atomic.AtomicReference; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -+import static java.nio.charset.StandardCharsets.UTF_8; -+ - import java.io.OutputStream; - import java.io.OutputStreamWriter; - import java.io.PrintWriter; -@@ -8,106 +10,98 @@ import java.lang.management.MonitorInfo; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; +-class SharedHealthCheckRegistriesTest { ++final class SharedHealthCheckRegistriesTest { --import static java.nio.charset.StandardCharsets.UTF_8; -- -- --/** -- * A convenience class for getting a thread dump. -- */ -+/** A convenience class for getting a thread dump. */ - public class ThreadDump { + @BeforeEach + void setUp() { +@@ -28,7 +27,7 @@ class SharedHealthCheckRegistriesTest { + void returnsSetOfCreatedRegistries() { + SharedHealthCheckRegistries.getOrCreate("db"); -- private final ThreadMXBean threadMXBean; -- -- public ThreadDump(ThreadMXBean threadMXBean) { -- this.threadMXBean = threadMXBean; -- } -- -- /** -- * Dumps all of the threads' current information, including synchronization, to an output stream. -- * -- * @param out an output stream -- */ -- public void dump(OutputStream out) { -- dump(true, true, out); -- } -- -- /** -- * Dumps all of the threads' current information, optionally including synchronization, to an output stream. -- * -- * Having control over including synchronization info allows using this method (and its wrappers, i.e. -- * ThreadDumpServlet) in environments where getting object monitor and/or ownable synchronizer usage is not -- * supported. It can also speed things up. -- * -- * See {@link ThreadMXBean#dumpAllThreads(boolean, boolean)} -- * -- * @param lockedMonitors dump all locked monitors if true -- * @param lockedSynchronizers dump all locked ownable synchronizers if true -- * @param out an output stream -- */ -- public void dump(boolean lockedMonitors, boolean lockedSynchronizers, OutputStream out) { -- final ThreadInfo[] threads = this.threadMXBean.dumpAllThreads(lockedMonitors, lockedSynchronizers); -- final PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, UTF_8)); -- -- for (int ti = threads.length - 1; ti >= 0; ti--) { -- final ThreadInfo t = threads[ti]; -- writer.printf("\"%s\" id=%d state=%s", -- t.getThreadName(), -- t.getThreadId(), -- t.getThreadState()); -- final LockInfo lock = t.getLockInfo(); -- if (lock != null && t.getThreadState() != Thread.State.BLOCKED) { -- writer.printf("%n - waiting on <0x%08x> (a %s)", -- lock.getIdentityHashCode(), -- lock.getClassName()); -- writer.printf("%n - locked <0x%08x> (a %s)", -- lock.getIdentityHashCode(), -- lock.getClassName()); -- } else if (lock != null && t.getThreadState() == Thread.State.BLOCKED) { -- writer.printf("%n - waiting to lock <0x%08x> (a %s)", -- lock.getIdentityHashCode(), -- lock.getClassName()); -- } -- -- if (t.isSuspended()) { -- writer.print(" (suspended)"); -- } -- -- if (t.isInNative()) { -- writer.print(" (running in native)"); -- } -- -- writer.println(); -- if (t.getLockOwnerName() != null) { -- writer.printf(" owned by %s id=%d%n", t.getLockOwnerName(), t.getLockOwnerId()); -- } -- -- final StackTraceElement[] elements = t.getStackTrace(); -- final MonitorInfo[] monitors = t.getLockedMonitors(); -- -- for (int i = 0; i < elements.length; i++) { -- final StackTraceElement element = elements[i]; -- writer.printf(" at %s%n", element); -- for (int j = 1; j < monitors.length; j++) { -- final MonitorInfo monitor = monitors[j]; -- if (monitor.getLockedStackDepth() == i) { -- writer.printf(" - locked %s%n", monitor); -- } -- } -- } -- writer.println(); -- -- final LockInfo[] locks = t.getLockedSynchronizers(); -- if (locks.length > 0) { -- writer.printf(" Locked synchronizers: count = %d%n", locks.length); -- for (LockInfo l : locks) { -- writer.printf(" - %s%n", l); -- } -- writer.println(); -- } -+ private final ThreadMXBean threadMXBean; -+ -+ public ThreadDump(ThreadMXBean threadMXBean) { -+ this.threadMXBean = threadMXBean; -+ } -+ -+ /** -+ * Dumps all of the threads' current information, including synchronization, to an output stream. -+ * -+ * @param out an output stream -+ */ -+ public void dump(OutputStream out) { -+ dump(true, true, out); -+ } -+ -+ /** -+ * Dumps all of the threads' current information, optionally including synchronization, to an -+ * output stream. -+ * -+ *

    Having control over including synchronization info allows using this method (and its -+ * wrappers, i.e. ThreadDumpServlet) in environments where getting object monitor and/or ownable -+ * synchronizer usage is not supported. It can also speed things up. -+ * -+ *

    See {@link ThreadMXBean#dumpAllThreads(boolean, boolean)} -+ * -+ * @param lockedMonitors dump all locked monitors if true -+ * @param lockedSynchronizers dump all locked ownable synchronizers if true -+ * @param out an output stream -+ */ -+ public void dump(boolean lockedMonitors, boolean lockedSynchronizers, OutputStream out) { -+ final ThreadInfo[] threads = -+ this.threadMXBean.dumpAllThreads(lockedMonitors, lockedSynchronizers); -+ final PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, UTF_8)); -+ -+ for (int ti = threads.length - 1; ti >= 0; ti--) { -+ final ThreadInfo t = threads[ti]; -+ writer.printf( -+ "\"%s\" id=%d state=%s", t.getThreadName(), t.getThreadId(), t.getThreadState()); -+ final LockInfo lock = t.getLockInfo(); -+ if (lock != null && t.getThreadState() != Thread.State.BLOCKED) { -+ writer.printf( -+ "%n - waiting on <0x%08x> (a %s)", lock.getIdentityHashCode(), lock.getClassName()); -+ writer.printf( -+ "%n - locked <0x%08x> (a %s)", lock.getIdentityHashCode(), lock.getClassName()); -+ } else if (lock != null && t.getThreadState() == Thread.State.BLOCKED) { -+ writer.printf( -+ "%n - waiting to lock <0x%08x> (a %s)", -+ lock.getIdentityHashCode(), lock.getClassName()); -+ } -+ -+ if (t.isSuspended()) { -+ writer.print(" (suspended)"); -+ } -+ -+ if (t.isInNative()) { -+ writer.print(" (running in native)"); -+ } -+ -+ writer.println(); -+ if (t.getLockOwnerName() != null) { -+ writer.printf(" owned by %s id=%d%n", t.getLockOwnerName(), t.getLockOwnerId()); -+ } -+ -+ final StackTraceElement[] elements = t.getStackTrace(); -+ final MonitorInfo[] monitors = t.getLockedMonitors(); -+ -+ for (int i = 0; i < elements.length; i++) { -+ final StackTraceElement element = elements[i]; -+ writer.printf(" at %s%n", element); -+ for (int j = 1; j < monitors.length; j++) { -+ final MonitorInfo monitor = monitors[j]; -+ if (monitor.getLockedStackDepth() == i) { -+ writer.printf(" - locked %s%n", monitor); -+ } -+ } -+ } -+ writer.println(); -+ -+ final LockInfo[] locks = t.getLockedSynchronizers(); -+ if (locks.length > 0) { -+ writer.printf(" Locked synchronizers: count = %d%n", locks.length); -+ for (LockInfo l : locks) { -+ writer.printf(" - %s%n", l); - } -- - writer.println(); -- writer.flush(); -+ } - } +- assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); ++ assertThat(SharedHealthCheckRegistries.names()).containsExactly("db"); + } + + @Test +@@ -58,7 +57,7 @@ class SharedHealthCheckRegistriesTest { + () -> { + SharedHealthCheckRegistries.getDefault(); + }); +- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); ++ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); + } + + @Test +@@ -85,7 +84,8 @@ class SharedHealthCheckRegistriesTest { + SharedHealthCheckRegistries.setDefault("default"); + SharedHealthCheckRegistries.setDefault("default"); + }); +- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); ++ assertThat(exception.getMessage().contains("Default health check registry is already set.")) ++ .isTrue(); + } -+ writer.println(); -+ writer.flush(); -+ } + @Test +@@ -97,6 +97,7 @@ class SharedHealthCheckRegistriesTest { + SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); + SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); + }); +- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); ++ assertThat(exception.getMessage().contains("Default health check registry is already set.")) ++ .isTrue(); + } } ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java -@@ -1,81 +1,80 @@ - package io.dropwizard.metrics5.jvm; +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java +@@ -4,23 +4,22 @@ import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricSet; -- - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.health.HealthCheck; + import io.dropwizard.metrics5.jvm.ThreadDeadlockDetector; -import java.util.Collections; - import java.util.HashMap; - import java.util.Map; import java.util.Set; + import java.util.TreeSet; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.Test; --/** -- * A set of gauges for the number of threads in their various states and deadlock detection. -- */ -+/** A set of gauges for the number of threads in their various states and deadlock detection. */ - public class ThreadStatesGaugeSet implements MetricSet { +-class ThreadDeadlockHealthCheckTest { ++final class ThreadDeadlockHealthCheckTest { + @Test + void isHealthyIfNoThreadsAreDeadlocked() { +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ final ThreadDeadlockDetector detector = mock(); + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); -- // do not compute stack traces. -- private final static int STACK_TRACE_DEPTH = 0; -- -- private final ThreadMXBean threads; -- private final ThreadDeadlockDetector deadlockDetector; -- -- /** -- * Creates a new set of gauges using the default MXBeans. -- */ -- public ThreadStatesGaugeSet() { -- this(ManagementFactory.getThreadMXBean(), new ThreadDeadlockDetector()); -- } -+ // do not compute stack traces. -+ private static final int STACK_TRACE_DEPTH = 0; - -- /** -- * Creates a new set of gauges using the given MXBean and detector. -- * -- * @param threads a thread MXBean -- * @param deadlockDetector a deadlock detector -- */ -- public ThreadStatesGaugeSet(ThreadMXBean threads, -- ThreadDeadlockDetector deadlockDetector) { -- this.threads = threads; -- this.deadlockDetector = deadlockDetector; -- } -+ private final ThreadMXBean threads; -+ private final ThreadDeadlockDetector deadlockDetector; - -- @Override -- public Map getMetrics() { -- final Map gauges = new HashMap<>(); -+ /** Creates a new set of gauges using the default MXBeans. */ -+ public ThreadStatesGaugeSet() { -+ this(ManagementFactory.getThreadMXBean(), new ThreadDeadlockDetector()); -+ } - -- for (final Thread.State state : Thread.State.values()) { -- gauges.put(MetricRegistry.name(state.toString().toLowerCase(), "count"), -- (Gauge) () -> getThreadCount(state)); -- } -+ /** -+ * Creates a new set of gauges using the given MXBean and detector. -+ * -+ * @param threads a thread MXBean -+ * @param deadlockDetector a deadlock detector -+ */ -+ public ThreadStatesGaugeSet(ThreadMXBean threads, ThreadDeadlockDetector deadlockDetector) { -+ this.threads = threads; -+ this.deadlockDetector = deadlockDetector; -+ } - -- gauges.put(MetricName.build("count"), (Gauge) threads::getThreadCount); -- gauges.put(MetricName.build("daemon.count"), (Gauge) threads::getDaemonThreadCount); -- gauges.put(MetricName.build("peak.count"), (Gauge) threads::getPeakThreadCount); -- gauges.put(MetricName.build("total_started.count"), (Gauge) threads::getTotalStartedThreadCount); -- gauges.put(MetricName.build("deadlock.count"), (Gauge) () -> deadlockDetector.getDeadlockedThreads().size()); -- gauges.put(MetricName.build("deadlocks"), (Gauge>) deadlockDetector::getDeadlockedThreads); -+ @Override -+ public Map getMetrics() { -+ final Map gauges = new HashMap<>(); - -- return Collections.unmodifiableMap(gauges); -+ for (final Thread.State state : Thread.State.values()) { -+ gauges.put( -+ MetricRegistry.name(state.toString().toLowerCase(), "count"), -+ (Gauge) () -> getThreadCount(state)); - } +- when(detector.getDeadlockedThreads()).thenReturn(Collections.emptySet()); ++ when(detector.getDeadlockedThreads()).thenReturn(ImmutableSet.of()); -- private int getThreadCount(Thread.State state) { -- final ThreadInfo[] allThreads = getThreadInfo(); -- int count = 0; -- for (ThreadInfo info : allThreads) { -- if (info != null && info.getThreadState() == state) { -- count++; -- } -- } -- return count; -- } -+ gauges.put(MetricName.build("count"), (Gauge) threads::getThreadCount); -+ gauges.put(MetricName.build("daemon.count"), (Gauge) threads::getDaemonThreadCount); -+ gauges.put(MetricName.build("peak.count"), (Gauge) threads::getPeakThreadCount); -+ gauges.put( -+ MetricName.build("total_started.count"), (Gauge) threads::getTotalStartedThreadCount); -+ gauges.put( -+ MetricName.build("deadlock.count"), -+ (Gauge) () -> deadlockDetector.getDeadlockedThreads().size()); -+ gauges.put( -+ MetricName.build("deadlocks"), (Gauge>) deadlockDetector::getDeadlockedThreads); -+ -+ return unmodifiableMap(gauges); -+ } - -- ThreadInfo[] getThreadInfo() { -- return threads.getThreadInfo(threads.getAllThreadIds(), STACK_TRACE_DEPTH); -+ private int getThreadCount(Thread.State state) { -+ final ThreadInfo[] allThreads = getThreadInfo(); -+ int count = 0; -+ for (ThreadInfo info : allThreads) { -+ if (info != null && info.getThreadState() == state) { -+ count++; -+ } - } -+ return count; -+ } +- Assertions.assertThat(healthCheck.execute().isHealthy()).isTrue(); ++ assertThat(healthCheck.execute().isHealthy()).isTrue(); + } -+ ThreadInfo[] getThreadInfo() { -+ return threads.getThreadInfo(threads.getAllThreadIds(), STACK_TRACE_DEPTH); -+ } - } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java -@@ -1,121 +1,107 @@ - package io.dropwizard.metrics5.jvm; + @Test +@@ -29,7 +28,7 @@ class ThreadDeadlockHealthCheckTest { + threads.add("one"); + threads.add("two"); -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.MetricName; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- - import javax.management.InstanceNotFoundException; - import javax.management.MBeanServer; - import javax.management.ObjectName; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ final ThreadDeadlockDetector detector = mock(); + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); - @SuppressWarnings("rawtypes") --class BufferPoolMetricSetTest { -- -- private static final MetricName DIRECT = MetricName.build("direct"); -- private static final MetricName MAPPED = MetricName.build("mapped"); -- private static final MetricName DIRECT_COUNT = DIRECT.resolve("count"); -- private static final MetricName DIRECT_CAPACITY = DIRECT.resolve("capacity"); -- private static final MetricName DIRECT_USED = DIRECT.resolve("used"); -- private static final MetricName MAPPED_COUNT = MAPPED.resolve("count"); -- private static final MetricName MAPPED_CAPACITY = MAPPED.resolve("capacity"); -- private static final MetricName MAPPED_USED = MAPPED.resolve("used"); -+final class BufferPoolMetricSetTest { + when(detector.getDeadlockedThreads()).thenReturn(threads); +@@ -44,6 +43,6 @@ class ThreadDeadlockHealthCheckTest { + @Test + void automaticallyUsesThePlatformThreadBeans() { + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(); +- Assertions.assertThat(healthCheck.execute().isHealthy()).isTrue(); ++ assertThat(healthCheck.execute().isHealthy()).isTrue(); + } + } +--- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java ++++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java +@@ -22,7 +22,7 @@ import org.mockito.Mock; + import org.mockito.junit.jupiter.MockitoExtension; -- private final MBeanServer mBeanServer = mock(MBeanServer.class); -- private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); -+ private static final MetricName DIRECT = MetricName.build("direct"); -+ private static final MetricName MAPPED = MetricName.build("mapped"); -+ private static final MetricName DIRECT_COUNT = DIRECT.resolve("count"); -+ private static final MetricName DIRECT_CAPACITY = DIRECT.resolve("capacity"); -+ private static final MetricName DIRECT_USED = DIRECT.resolve("used"); -+ private static final MetricName MAPPED_COUNT = MAPPED.resolve("count"); -+ private static final MetricName MAPPED_CAPACITY = MAPPED.resolve("capacity"); -+ private static final MetricName MAPPED_USED = MAPPED.resolve("used"); - -- private ObjectName mapped; -- private ObjectName direct; -+ private final MBeanServer mBeanServer = mock(); -+ private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); + @ExtendWith(MockitoExtension.class) +-class InstrumentedHttpClientsTest extends HttpClientTestBase { ++final class InstrumentedHttpClientsTest extends HttpClientTestBase { -- @BeforeEach -- void setUp() throws Exception { -- this.mapped = new ObjectName("java.nio:type=BufferPool,name=mapped"); -- this.direct = new ObjectName("java.nio:type=BufferPool,name=direct"); -+ private ObjectName mapped; -+ private ObjectName direct; + private final MetricRegistry metricRegistry = new MetricRegistry(); -- } -+ @BeforeEach -+ void setUp() throws Exception { -+ this.mapped = new ObjectName("java.nio:type=BufferPool,name=mapped"); -+ this.direct = new ObjectName("java.nio:type=BufferPool,name=direct"); -+ } - -- @Test -- void includesGaugesForDirectAndMappedPools() { -- assertThat(buffers.getMetrics().keySet()) -- .containsOnly(DIRECT_COUNT, -- DIRECT_USED, -- DIRECT_CAPACITY, -- MAPPED_COUNT, -- MAPPED_USED, -- MAPPED_CAPACITY); -- } -+ @Test -+ void includesGaugesForDirectAndMappedPools() { -+ assertThat(buffers.getMetrics().keySet()) -+ .containsOnly( -+ DIRECT_COUNT, DIRECT_USED, DIRECT_CAPACITY, MAPPED_COUNT, MAPPED_USED, MAPPED_CAPACITY); -+ } - -- @Test -- void ignoresGaugesForObjectsWhichCannotBeFound() throws Exception { -- when(mBeanServer.getMBeanInfo(mapped)).thenThrow(new InstanceNotFoundException()); -+ @Test -+ void ignoresGaugesForObjectsWhichCannotBeFound() throws Exception { -+ when(mBeanServer.getMBeanInfo(mapped)).thenThrow(new InstanceNotFoundException()); +--- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java ++++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java +@@ -1,7 +1,7 @@ + package io.dropwizard.metrics5.httpasyncclient; -- assertThat(buffers.getMetrics().keySet()) -- .containsOnly(DIRECT_COUNT, -- DIRECT_USED, -- DIRECT_CAPACITY); -- } -+ assertThat(buffers.getMetrics().keySet()) -+ .containsOnly(DIRECT_COUNT, DIRECT_USED, DIRECT_CAPACITY); -+ } + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; ++import static org.assertj.core.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +@@ -29,7 +29,7 @@ import org.mockito.junit.jupiter.MockitoExtension; -- @Test -- void includesAGaugeForDirectCount() throws Exception { -- final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_COUNT); -+ @Test -+ void includesAGaugeForDirectCount() throws Exception { -+ final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_COUNT); + @ExtendWith(MockitoExtension.class) + @Disabled("The tests are flaky") +-class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { ++final class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { -- when(mBeanServer.getAttribute(direct, "Count")).thenReturn(100); -+ when(mBeanServer.getAttribute(direct, "Count")).thenReturn(100); + private HttpAsyncClient asyncHttpClient; -- assertThat(gauge.getValue()) -- .isEqualTo(100); -- } -+ assertThat(gauge.getValue()).isEqualTo(100); -+ } +@@ -46,7 +46,7 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + chac.start(); + asyncHttpClient = chac; -- @Test -- void includesAGaugeForDirectMemoryUsed() throws Exception { -- final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_USED); +- Timer timer = mock(Timer.class); ++ Timer timer = mock(); + when(timer.time()).thenReturn(context); + when(metricRegistry.timer(MetricName.build("test"))).thenReturn(timer); + } +@@ -72,13 +72,13 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + verify(context, timeout(200).times(1)).stop(); + } + +- @Test + @SuppressWarnings("unchecked") + @Test -+ void includesAGaugeForDirectMemoryUsed() throws Exception { -+ final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_USED); + void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { + HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); + HttpGet get = new HttpGet("/?q=something"); -- when(mBeanServer.getAttribute(direct, "MemoryUsed")).thenReturn(100); -+ when(mBeanServer.getAttribute(direct, "MemoryUsed")).thenReturn(100); +- FutureCallback futureCallback = mock(FutureCallback.class); ++ FutureCallback futureCallback = mock(); -- assertThat(gauge.getValue()) -- .isEqualTo(100); -- } -+ assertThat(gauge.getValue()).isEqualTo(100); -+ } + // Timer hasn't been stopped prior to executing the request + verify(context, never()).stop(); +@@ -99,14 +99,14 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + verify(context, timeout(200).times(1)).stop(); + } -- @Test -- void includesAGaugeForDirectCapacity() throws Exception { -- final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_CAPACITY); +- @Test + @SuppressWarnings("unchecked") + @Test -+ void includesAGaugeForDirectCapacity() throws Exception { -+ final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_CAPACITY); + void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { + // There should be nothing listening on this port + HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); + HttpGet get = new HttpGet("/?q=something"); + +- FutureCallback futureCallback = mock(FutureCallback.class); ++ FutureCallback futureCallback = mock(); -- when(mBeanServer.getAttribute(direct, "TotalCapacity")).thenReturn(100); -+ when(mBeanServer.getAttribute(direct, "TotalCapacity")).thenReturn(100); + // Timer hasn't been stopped prior to executing the request + verify(context, never()).stop(); +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java +@@ -17,7 +17,7 @@ import org.apache.http.client.methods.HttpRequestWrapper; + import org.apache.http.client.utils.URIUtils; + import org.junit.jupiter.api.Test; -- assertThat(gauge.getValue()) -- .isEqualTo(100); -- } -+ assertThat(gauge.getValue()).isEqualTo(100); -+ } +-class HttpClientMetricNameStrategiesTest { ++final class HttpClientMetricNameStrategiesTest { -- @Test -- void includesAGaugeForMappedCount() throws Exception { -- final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_COUNT); -+ @Test -+ void includesAGaugeForMappedCount() throws Exception { -+ final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_COUNT); + @Test + void methodOnlyWithName() { +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java +@@ -3,16 +3,17 @@ package io.dropwizard.metrics5.httpclient; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertTrue; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; -- when(mBeanServer.getAttribute(mapped, "Count")).thenReturn(100); -+ when(mBeanServer.getAttribute(mapped, "Count")).thenReturn(100); + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; -- assertThat(gauge.getValue()) -- .isEqualTo(100); -- } -+ assertThat(gauge.getValue()).isEqualTo(100); -+ } +-class InstrumentedHttpClientConnectionManagerTest { ++final class InstrumentedHttpClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); -- @Test -- void includesAGaugeForMappedMemoryUsed() throws Exception { -- final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_USED); -+ @Test -+ void includesAGaugeForMappedMemoryUsed() throws Exception { -+ final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_USED); + @Test +@@ -37,7 +38,7 @@ class InstrumentedHttpClientConnectionManagerTest { -- when(mBeanServer.getAttribute(mapped, "MemoryUsed")).thenReturn(100); -+ when(mBeanServer.getAttribute(mapped, "MemoryUsed")).thenReturn(100); + @Test + void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); -- assertThat(gauge.getValue()) -- .isEqualTo(100); -- } -+ assertThat(gauge.getValue()).isEqualTo(100); -+ } + InstrumentedHttpClientConnectionManager.builder(registry) + .name("some-name") +@@ -46,7 +47,7 @@ class InstrumentedHttpClientConnectionManagerTest { + .close(); -- @Test -- void includesAGaugeForMappedCapacity() throws Exception { -- final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_CAPACITY); -+ @Test -+ void includesAGaugeForMappedCapacity() throws Exception { -+ final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_CAPACITY); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); +- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); + } + } +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java +@@ -1,7 +1,7 @@ + package io.dropwizard.metrics5.httpclient; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; ++import static org.assertj.core.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; +@@ -22,10 +22,9 @@ import org.apache.http.client.methods.HttpGet; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- when(mBeanServer.getAttribute(mapped, "TotalCapacity")).thenReturn(100); -+ when(mBeanServer.getAttribute(mapped, "TotalCapacity")).thenReturn(100); +-class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); ++final class InstrumentedHttpClientsTest { ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); + private final MetricRegistry metricRegistry = new MetricRegistry(); + private final HttpClient client = + InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java +@@ -16,7 +16,7 @@ import org.apache.hc.core5.http.message.HttpRequestWrapper; + import org.apache.hc.core5.net.URIBuilder; + import org.junit.jupiter.api.Test; -- assertThat(gauge.getValue()) -- .isEqualTo(100); -- } -+ assertThat(gauge.getValue()).isEqualTo(100); -+ } - } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java -@@ -1,38 +1,36 @@ - package io.dropwizard.metrics5.jvm; +-class HttpClientMetricNameStrategiesTest { ++final class HttpClientMetricNameStrategiesTest { -+import static org.assertj.core.api.Assertions.assertThat; + @Test + void methodOnlyWithName() { +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java +@@ -3,16 +3,17 @@ package io.dropwizard.metrics5.httpclient5; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertTrue; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.Gauge; ++import static org.mockito.Mockito.verify; + import io.dropwizard.metrics5.MetricName; -+import java.lang.management.ClassLoadingMXBean; - import org.junit.jupiter.api.BeforeEach; + import io.dropwizard.metrics5.MetricRegistry; import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; --import java.lang.management.ClassLoadingMXBean; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- - @SuppressWarnings("rawtypes") --class ClassLoadingGaugeSetTest { -- -- private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); -- private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); -- -- @BeforeEach -- void setUp() { -- when(cl.getTotalLoadedClassCount()).thenReturn(2L); -- when(cl.getUnloadedClassCount()).thenReturn(1L); -- } -- -- @Test -- void loadedGauge() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("loaded")); -- assertThat(gauge.getValue()).isEqualTo(2L); -- } -- -- @Test -- void unLoadedGauge() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("unloaded")); -- assertThat(gauge.getValue()).isEqualTo(1L); -- } -- -+final class ClassLoadingGaugeSetTest { -+ -+ private final ClassLoadingMXBean cl = mock(); -+ private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); -+ -+ @BeforeEach -+ void setUp() { -+ when(cl.getTotalLoadedClassCount()).thenReturn(2L); -+ when(cl.getUnloadedClassCount()).thenReturn(1L); -+ } -+ -+ @Test -+ void loadedGauge() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("loaded")); -+ assertThat(gauge.getValue()).isEqualTo(2L); -+ } -+ -+ @Test -+ void unLoadedGauge() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("unloaded")); -+ assertThat(gauge.getValue()).isEqualTo(1L); -+ } - } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java -@@ -1,24 +1,23 @@ - package io.dropwizard.metrics5.jvm; +-class InstrumentedAsyncClientConnectionManagerTest { ++final class InstrumentedAsyncClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); --import org.junit.jupiter.api.Test; -- --import java.lang.management.ManagementFactory; -- - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.offset; + @Test +@@ -44,7 +45,7 @@ class InstrumentedAsyncClientConnectionManagerTest { --class CpuTimeClockTest { -+import java.lang.management.ManagementFactory; -+import org.junit.jupiter.api.Test; -+ -+final class CpuTimeClockTest { + @Test + void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); -- @Test -- void cpuTimeClock() { -- final CpuTimeClock clock = new CpuTimeClock(); -+ @Test -+ void cpuTimeClock() { -+ final CpuTimeClock clock = new CpuTimeClock(); - -- final long clockTime = clock.getTime(); -- final long systemTime = System.currentTimeMillis(); -- assertThat((double) clockTime).isEqualTo(systemTime, offset(200.0)); -+ final long clockTime = clock.getTime(); -+ final long systemTime = System.currentTimeMillis(); -+ assertThat((double) clockTime).isCloseTo(systemTime, offset(200.0)); + InstrumentedAsyncClientConnectionManager.builder(registry) + .name("some-name") +@@ -53,7 +54,7 @@ class InstrumentedAsyncClientConnectionManagerTest { + .close(); -- final long clockTick = clock.getTick(); -- final long systemTick = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(); -- assertThat((double) clockTick).isEqualTo(systemTick, offset(1000000.0)); -- } --} -\ No newline at end of file -+ final long clockTick = clock.getTick(); -+ final long systemTick = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(); -+ assertThat((double) clockTick).isCloseTo(systemTick, offset(1000000.0)); -+ } -+} ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java -@@ -1,48 +1,43 @@ - package io.dropwizard.metrics5.jvm; + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); +- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); + } + } +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java +@@ -1,8 +1,9 @@ + package io.dropwizard.metrics5.httpclient5; --import com.sun.management.UnixOperatingSystemMXBean; --import org.assertj.core.api.Assertions; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import java.lang.management.ManagementFactory; --import java.lang.management.OperatingSystemMXBean; -- -+import static org.assertj.core.api.Assertions.assertThat; - import static org.junit.jupiter.api.Assumptions.assumeTrue; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; ++import static java.nio.charset.StandardCharsets.US_ASCII; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; + import static org.awaitility.Awaitility.await; +-import static org.junit.jupiter.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.atLeastOnce; +@@ -18,7 +19,6 @@ import io.dropwizard.metrics5.MetricRegistryListener; + import io.dropwizard.metrics5.Timer; + import java.io.IOException; + import java.net.InetSocketAddress; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.ExecutionException; + import java.util.concurrent.Future; +@@ -39,7 +39,7 @@ import org.mockito.Mock; + import org.mockito.junit.jupiter.MockitoExtension; -+import com.sun.management.UnixOperatingSystemMXBean; -+import java.lang.management.ManagementFactory; -+import java.lang.management.OperatingSystemMXBean; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; -+ - @SuppressWarnings("UnusedDeclaration") --class FileDescriptorRatioGaugeTest { -- private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); -- -- private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); -- -- @BeforeEach -- void setUp() throws Exception { -- when(os.getOpenFileDescriptorCount()).thenReturn(10L); -- when(os.getMaxFileDescriptorCount()).thenReturn(100L); -- } -- -- @Test -- void calculatesTheRatioOfUsedToTotalFileDescriptors() { -- Assertions.assertThat(gauge.getValue()) -- .isEqualTo(0.1); -- } -- -- @Test -- void validateFileDescriptorRatioPresenceOnNixPlatforms() { -- OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); -- assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); -- -- Assertions.assertThat(new FileDescriptorRatioGauge().getValue()) -- .isGreaterThanOrEqualTo(0.0) -- .isLessThanOrEqualTo(1.0); -- } -- -- @Test -- void returnsNaNWhenTheInformationIsUnavailable() { -- Assertions.assertThat(new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()) -- .isNaN(); -- } -+final class FileDescriptorRatioGaugeTest { -+ private final UnixOperatingSystemMXBean os = mock(); -+ -+ private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ when(os.getOpenFileDescriptorCount()).thenReturn(10L); -+ when(os.getMaxFileDescriptorCount()).thenReturn(100L); -+ } -+ -+ @Test -+ void calculatesTheRatioOfUsedToTotalFileDescriptors() { -+ assertThat(gauge.getValue()).isEqualTo(0.1); -+ } -+ -+ @Test -+ void validateFileDescriptorRatioPresenceOnNixPlatforms() { -+ OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); -+ assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); -+ -+ assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative().isLessThanOrEqualTo(1.0); -+ } -+ -+ @Test -+ void returnsNaNWhenTheInformationIsUnavailable() { -+ assertThat(new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()).isNaN(); -+ } - } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java -@@ -1,55 +1,51 @@ - package io.dropwizard.metrics5.jvm; + @ExtendWith(MockitoExtension.class) +-class InstrumentedHttpAsyncClientsTest { ++final class InstrumentedHttpAsyncClientsTest { -+import static org.assertj.core.api.Assertions.assertThat; + @Mock private HttpClientMetricNameStrategy metricNameStrategy; + @Mock private MetricRegistryListener registryListener; +@@ -83,7 +83,7 @@ class InstrumentedHttpAsyncClientsTest { + exchange -> { + exchange.sendResponseHeaders(200, 0L); + exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); + exchange.close(); + }); + httpServer.start(); +@@ -193,7 +193,7 @@ class InstrumentedHttpAsyncClientsTest { + exchange -> { + exchange.sendResponseHeaders(200, 0L); + exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); + exchange.close(); + }); + httpServer.start(); +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java +@@ -3,16 +3,17 @@ package io.dropwizard.metrics5.httpclient5; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertTrue; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ -+import com.google.common.collect.ImmutableList; - import io.dropwizard.metrics5.Gauge; ++import static org.mockito.Mockito.verify; + import io.dropwizard.metrics5.MetricName; -+import java.lang.management.GarbageCollectorMXBean; - import org.junit.jupiter.api.BeforeEach; + import io.dropwizard.metrics5.MetricRegistry; import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; --import java.lang.management.GarbageCollectorMXBean; --import java.util.Collections; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- - @SuppressWarnings("unchecked") --class GarbageCollectorMetricSetTest { -- private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); -- private final GarbageCollectorMetricSet metrics = new GarbageCollectorMetricSet(Collections.singletonList(gc)); -- -- private static final MetricName PS_OLDGEN_TIME = MetricName.build("PS-OldGen.time"); -- private static final MetricName PS_OLDGEN_COUNT = MetricName.build("PS-OldGen.count"); -- -- @BeforeEach -- void setUp() { -- when(gc.getName()).thenReturn("PS OldGen"); -- when(gc.getCollectionCount()).thenReturn(1L); -- when(gc.getCollectionTime()).thenReturn(2L); -- } -- -- @Test -- void hasGaugesForGcCountsAndElapsedTimes() { -- assertThat(metrics.getMetrics().keySet()) -- .containsOnly(PS_OLDGEN_TIME, PS_OLDGEN_COUNT); -- } -- -- @Test -- void hasAGaugeForGcCounts() { -- final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_COUNT); -- assertThat(gauge.getValue()) -- .isEqualTo(1L); -- } -- -- @Test -- void hasAGaugeForGcTimes() { -- final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_TIME); -- assertThat(gauge.getValue()) -- .isEqualTo(2L); -- } -- -- @Test -- void autoDiscoversGCs() { -- assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()) -- .isNotEmpty(); -- } -+final class GarbageCollectorMetricSetTest { -+ private final GarbageCollectorMXBean gc = mock(); -+ private final GarbageCollectorMetricSet metrics = -+ new GarbageCollectorMetricSet(ImmutableList.of(gc)); -+ -+ private static final MetricName PS_OLDGEN_TIME = MetricName.build("PS-OldGen.time"); -+ private static final MetricName PS_OLDGEN_COUNT = MetricName.build("PS-OldGen.count"); -+ -+ @BeforeEach -+ void setUp() { -+ when(gc.getName()).thenReturn("PS OldGen"); -+ when(gc.getCollectionCount()).thenReturn(1L); -+ when(gc.getCollectionTime()).thenReturn(2L); -+ } -+ -+ @Test -+ void hasGaugesForGcCountsAndElapsedTimes() { -+ assertThat(metrics.getMetrics().keySet()).containsOnly(PS_OLDGEN_TIME, PS_OLDGEN_COUNT); -+ } -+ -+ @Test -+ void hasAGaugeForGcCounts() { -+ final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_COUNT); -+ assertThat(gauge.getValue()).isEqualTo(1L); -+ } -+ -+ @Test -+ void hasAGaugeForGcTimes() { -+ final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_TIME); -+ assertThat(gauge.getValue()).isEqualTo(2L); -+ } -+ -+ @Test -+ void autoDiscoversGCs() { -+ assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty(); -+ } - } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java -@@ -5,95 +5,92 @@ import static org.assertj.core.api.Assertions.assertThat; - import java.lang.management.ManagementFactory; - import java.util.ArrayList; - import java.util.List; -- - import javax.management.JMException; - import javax.management.MBeanServer; - import javax.management.ObjectInstance; - import javax.management.ObjectName; -- - import org.junit.jupiter.api.AfterAll; - import org.junit.jupiter.api.BeforeAll; - import org.junit.jupiter.api.Test; +-class InstrumentedHttpClientConnectionManagerTest { ++final class InstrumentedHttpClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); --class JmxAttributeGaugeTest { -- -- private static MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); -- -- private static List registeredMBeans = new ArrayList<>(); -- -- public interface JmxTestMBean { -- Long getValue(); -- } -- -- private static class JmxTest implements JmxTestMBean { -- @Override -- public Long getValue() { -- return Long.MAX_VALUE; -- } -- } -- -- @BeforeAll -- static void setUp() throws Exception { -- registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test1")); -- registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test2")); -- } -- -- @AfterAll -- static void tearDown() { -- for (ObjectName objectName : registeredMBeans) { -- try { -- mBeanServer.unregisterMBean(objectName); -- } catch (Exception e) { -- // ignore -- } -- } -- } -- -- @Test -- void returnsJmxAttribute() throws Exception { -- ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); -- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); -- -- assertThat(gauge.getValue()).isInstanceOf(Integer.class); -- assertThat((Integer) gauge.getValue()).isGreaterThan(0); -- } -- -- @Test -- void returnsNullIfAttributeDoesNotExist() throws Exception { -- ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); -- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "DoesNotExist"); -- -- assertThat(gauge.getValue()).isNull(); -- } -- -- @Test -- void returnsNullIfMBeanNotFound() throws Exception { -- ObjectName objectName = new ObjectName("foo.bar:type=NoSuchMBean"); -- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); -- -- assertThat(gauge.getValue()).isNull(); -- } -+final class JmxAttributeGaugeTest { + @Test +@@ -42,7 +43,7 @@ class InstrumentedHttpClientConnectionManagerTest { -- @Test -- void returnsAttributeForObjectNamePattern() throws Exception { -- ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:name=test1,*"); -- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); -+ private static MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + @Test + void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); -- assertThat(gauge.getValue()).isInstanceOf(Long.class); -- assertThat((Long) gauge.getValue()).isEqualTo(Long.MAX_VALUE); -- } -+ private static List registeredMBeans = new ArrayList<>(); - -- @Test -- void returnsNullIfObjectNamePatternAmbiguous() throws Exception { -- ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:type=test,*"); -- JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); -+ public interface JmxTestMBean { -+ Long getValue(); -+ } - -- assertThat(gauge.getValue()).isNull(); -+ private static class JmxTest implements JmxTestMBean { -+ @Override -+ public Long getValue() { -+ return Long.MAX_VALUE; - } -- -- private static void registerMBean(ObjectName objectName) throws JMException { -- ObjectInstance objectInstance = mBeanServer.registerMBean(new JmxTest(), objectName); -- registeredMBeans.add(objectInstance.getObjectName()); -+ } -+ -+ @BeforeAll -+ static void setUp() throws Exception { -+ registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test1")); -+ registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test2")); -+ } -+ -+ @AfterAll -+ static void tearDown() { -+ for (ObjectName objectName : registeredMBeans) { -+ try { -+ mBeanServer.unregisterMBean(objectName); -+ } catch (Exception e) { -+ // ignore -+ } - } -- -+ } -+ -+ @Test -+ void returnsJmxAttribute() throws Exception { -+ ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); -+ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); -+ -+ assertThat(gauge.getValue()).isInstanceOf(Integer.class); -+ assertThat((Integer) gauge.getValue()).isPositive(); -+ } -+ -+ @Test -+ void returnsNullIfAttributeDoesNotExist() throws Exception { -+ ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); -+ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "DoesNotExist"); -+ -+ assertThat(gauge.getValue()).isNull(); -+ } -+ -+ @Test -+ void returnsNullIfMBeanNotFound() throws Exception { -+ ObjectName objectName = new ObjectName("foo.bar:type=NoSuchMBean"); -+ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); -+ -+ assertThat(gauge.getValue()).isNull(); -+ } -+ -+ @Test -+ void returnsAttributeForObjectNamePattern() throws Exception { -+ ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:name=test1,*"); -+ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); -+ -+ assertThat(gauge.getValue()).isInstanceOf(Long.class); -+ assertThat((Long) gauge.getValue()).isEqualTo(Long.MAX_VALUE); -+ } -+ -+ @Test -+ void returnsNullIfObjectNamePatternAmbiguous() throws Exception { -+ ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:type=test,*"); -+ JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); -+ -+ assertThat(gauge.getValue()).isNull(); -+ } -+ -+ private static void registerMBean(ObjectName objectName) throws JMException { -+ ObjectInstance objectInstance = mBeanServer.registerMBean(new JmxTest(), objectName); -+ registeredMBeans.add(objectInstance.getObjectName()); -+ } + InstrumentedHttpClientConnectionManager.builder(registry) + .name("some-name") +@@ -51,7 +52,7 @@ class InstrumentedHttpClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); +- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); + } } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java -@@ -1,68 +1,65 @@ - package io.dropwizard.metrics5.jvm; +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java +@@ -1,7 +1,7 @@ + package io.dropwizard.metrics5.httpclient5; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.MetricName; -+import java.lang.management.RuntimeMXBean; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; ++import static org.assertj.core.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; +@@ -22,10 +22,9 @@ import org.apache.hc.core5.http.NoHttpResponseException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import java.lang.management.RuntimeMXBean; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- - @SuppressWarnings("unchecked") --class JvmAttributeGaugeSetTest { -- private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); -- private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); -+final class JvmAttributeGaugeSetTest { -+ private final RuntimeMXBean runtime = mock(); -+ private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); +-class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); ++final class InstrumentedHttpClientsTest { ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); + private final MetricRegistry metricRegistry = new MetricRegistry(); + private final HttpClient client = + InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) +--- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java ++++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.influxdb; -- @BeforeEach -- void setUp() { -- when(runtime.getName()).thenReturn("9928@example.com"); -+ @BeforeEach -+ void setUp() { -+ when(runtime.getName()).thenReturn("9928@example.com"); + import static io.dropwizard.metrics5.MetricAttribute.*; -- when(runtime.getVmVendor()).thenReturn("Oracle Corporation"); -- when(runtime.getVmName()).thenReturn("Java HotSpot(TM) 64-Bit Server VM"); -- when(runtime.getVmVersion()).thenReturn("23.7-b01"); -- when(runtime.getSpecVersion()).thenReturn("1.7"); -- when(runtime.getUptime()).thenReturn(100L); -- } -+ when(runtime.getVmVendor()).thenReturn("Oracle Corporation"); -+ when(runtime.getVmName()).thenReturn("Java HotSpot(TM) 64-Bit Server VM"); -+ when(runtime.getVmVersion()).thenReturn("23.7-b01"); -+ when(runtime.getSpecVersion()).thenReturn("1.7"); -+ when(runtime.getUptime()).thenReturn(100L); -+ } - -- @Test -- void hasASetOfGauges() { -- assertThat(gauges.getMetrics().keySet()) -- .containsOnly(MetricName.build("vendor"), -- MetricName.build("name"), -- MetricName.build("uptime")); -- } -+ @Test -+ void hasASetOfGauges() { -+ assertThat(gauges.getMetrics().keySet()) -+ .containsOnly( -+ MetricName.build("vendor"), MetricName.build("name"), MetricName.build("uptime")); -+ } - -- @Test -- void hasAGaugeForTheJVMName() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("name")); -+ @Test -+ void hasAGaugeForTheJVMName() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("name")); ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -15,7 +16,6 @@ import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; + import java.io.IOException; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -78,7 +78,7 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = ImmutableSet.of(); + } -- assertThat(gauge.getValue()) -- .isEqualTo("9928@example.com"); -- } -+ assertThat(gauge.getValue()).isEqualTo("9928@example.com"); -+ } + /** +@@ -196,7 +196,7 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { + } + } -- @Test -- void hasAGaugeForTheJVMVendor() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("vendor")); -+ @Test -+ void hasAGaugeForTheJVMVendor() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("vendor")); +- private static final Logger LOGGER = LoggerFactory.getLogger(InfluxDbReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(InfluxDbReporter.class); + private static final String VALUE = "value"; + + private final Clock clock; +@@ -279,12 +279,12 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { + } + sender.flush(); + } catch (IOException e) { +- LOGGER.warn("Unable to report to InfluxDb", sender, e); ++ LOG.warn("Unable to report to InfluxDb", sender, e); + } finally { + try { + sender.disconnect(); + } catch (IOException e) { +- LOGGER.warn("Error disconnecting InfluxDb", sender, e); ++ LOG.warn("Error disconnecting InfluxDb", sender, e); + } + } + } +@@ -297,7 +297,7 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { + try { + sender.close(); + } catch (IOException e) { +- LOGGER.debug("Error disconnecting from InfluxDb", e); ++ LOG.debug("Error disconnecting from InfluxDb", e); + } + } + } +--- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java ++++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.influxdb; -- assertThat(gauge.getValue()) -- .isEqualTo("Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 23.7-b01 (1.7)"); -- } -+ assertThat(gauge.getValue()) -+ .isEqualTo("Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 23.7-b01 (1.7)"); -+ } ++import static java.util.Objects.requireNonNull; ++ + import java.io.IOException; + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; +@@ -9,7 +11,6 @@ import java.nio.charset.Charset; + import java.nio.charset.CharsetEncoder; + import java.nio.charset.CoderResult; + import java.nio.charset.CodingErrorAction; +-import java.util.Objects; -- @Test -- void hasAGaugeForTheJVMUptime() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("uptime")); -+ @Test -+ void hasAGaugeForTheJVMUptime() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("uptime")); + public class InfluxDbUdpSender implements InfluxDbSender { -- assertThat(gauge.getValue()) -- .isEqualTo(100L); -- } -+ assertThat(gauge.getValue()).isEqualTo(100L); -+ } +@@ -42,7 +43,7 @@ public class InfluxDbUdpSender implements InfluxDbSender { + * @param address the address of the InfluxDb server + */ + public InfluxDbUdpSender(InetSocketAddress address) { +- this.address = Objects.requireNonNull(address); ++ this.address = requireNonNull(address); + charBuf = CharBuffer.allocate(mtu * 2); + byteBuf = ByteBuffer.allocate(mtu * 2); + } +--- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java ++++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java +@@ -5,7 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; + import io.dropwizard.metrics5.MetricAttribute; + import org.junit.jupiter.api.Test; -- @Test -- void autoDiscoversTheRuntimeBean() { -- final Gauge gauge = (Gauge) new JvmAttributeGaugeSet().getMetrics().get(MetricName.build("uptime")); -+ @Test -+ void autoDiscoversTheRuntimeBean() { -+ final Gauge gauge = -+ (Gauge) new JvmAttributeGaugeSet().getMetrics().get(MetricName.build("uptime")); +-class InfluxDbLineBuilderAssumptionsTest { ++final class InfluxDbLineBuilderAssumptionsTest { -- assertThat(gauge.getValue()).isPositive(); -- } -+ assertThat(gauge.getValue()).isPositive(); -+ } - } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java -@@ -1,325 +1,301 @@ - package io.dropwizard.metrics5.jvm; + @Test + void ensureMetricAttributeCodesAreSafeFieldKeys() { +--- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java ++++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java +@@ -11,6 +11,7 @@ import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.verifyNoMoreInteractions; + import static org.mockito.Mockito.when; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.MetricName; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- - import java.lang.management.MemoryMXBean; - import java.lang.management.MemoryPoolMXBean; - import java.lang.management.MemoryUsage; - import java.util.Arrays; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; +@@ -25,7 +26,6 @@ import io.dropwizard.metrics5.Timer; + import java.io.IOException; + import java.net.UnknownHostException; + import java.util.ArrayList; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Set; +@@ -36,16 +36,16 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.mockito.InOrder; - @SuppressWarnings("rawtypes") --class MemoryUsageGaugeSetTest { -- private final MemoryUsage heap = mock(MemoryUsage.class); -- private final MemoryUsage nonHeap = mock(MemoryUsage.class); -- private final MemoryUsage pool = mock(MemoryUsage.class); -- private final MemoryUsage weirdPool = mock(MemoryUsage.class); -- private final MemoryUsage weirdCollection = mock(MemoryUsage.class); -- private final MemoryMXBean mxBean = mock(MemoryMXBean.class); -- private final MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); -- private final MemoryPoolMXBean weirdMemoryPool = mock(MemoryPoolMXBean.class); -- -- private final MemoryUsageGaugeSet gauges = new MemoryUsageGaugeSet(mxBean, -- Arrays.asList(memoryPool, -- weirdMemoryPool)); -- -- private static final MetricName TOTAL = MetricName.build("total"); -- private static final MetricName HEAP = MetricName.build("heap"); -- private static final MetricName NON_HEAP = MetricName.build("non-heap"); -- private static final MetricName POOLS = MetricName.build("pools"); -- -- private static final MetricName TOTAL_MAX = TOTAL.resolve("max"); -- private static final MetricName TOTAL_INIT = TOTAL.resolve("init"); -- private static final MetricName TOTAL_USED = TOTAL.resolve("used"); -- private static final MetricName TOTAL_COMMITTED = TOTAL.resolve("committed"); -- private static final MetricName POOLS_BIG_POOL_USAGE = POOLS.resolve("Big-Pool.usage"); -- private static final MetricName POOLS_BIG_POOL_USED = POOLS.resolve("Big-Pool.used"); -- private static final MetricName POOLS_BIG_POOL_INIT = POOLS.resolve("Big-Pool.init"); -- private static final MetricName POOLS_BIG_POOL_COMMITED = POOLS.resolve("Big-Pool.committed"); -- private static final MetricName POOLS_BIG_POOL_MAX = POOLS.resolve("Big-Pool.max"); -- private static final MetricName POOLS_WEIRD_POOL_USAGE = POOLS.resolve("Weird-Pool.usage"); -- private static final MetricName POOLS_WEIRD_POOL_INIT = POOLS.resolve("Weird-Pool.init"); -- private static final MetricName POOLS_WEIRD_POOL_MAX = POOLS.resolve("Weird-Pool.max"); -- private static final MetricName POOLS_WEIRD_POOL_USED = POOLS.resolve("Weird-Pool.used"); -- private static final MetricName POOLS_WEIRD_POOL_USED_AFTER_GC = POOLS.resolve("Weird-Pool.used-after-gc"); -- private static final MetricName POOLS_WEIRD_POOL_COMMITTED = POOLS.resolve("Weird-Pool.committed"); -- private static final MetricName HEAP_INIT = HEAP.resolve("init"); -- private static final MetricName HEAP_COMMITTED = HEAP.resolve("committed"); -- private static final MetricName HEAP_USAGE = HEAP.resolve("usage"); -- private static final MetricName HEAP_USED = HEAP.resolve("used"); -- private static final MetricName HEAP_MAX = HEAP.resolve("max"); -- private static final MetricName NON_HEAP_USAGE = NON_HEAP.resolve("usage"); -- private static final MetricName NON_HEAP_MAX = NON_HEAP.resolve("max"); -- private static final MetricName NON_HEAP_USED = NON_HEAP.resolve("used"); -- private static final MetricName NON_HEAP_INIT = NON_HEAP.resolve("init"); -- private static final MetricName NON_HEAP_COMMITTED = NON_HEAP.resolve("committed"); -- -- @BeforeEach -- void setUp() { -- when(heap.getCommitted()).thenReturn(10L); -- when(heap.getInit()).thenReturn(20L); -- when(heap.getUsed()).thenReturn(30L); -- when(heap.getMax()).thenReturn(40L); -- -- when(nonHeap.getCommitted()).thenReturn(1L); -- when(nonHeap.getInit()).thenReturn(2L); -- when(nonHeap.getUsed()).thenReturn(3L); -- when(nonHeap.getMax()).thenReturn(4L); -- -- when(pool.getCommitted()).thenReturn(100L); -- when(pool.getInit()).thenReturn(200L); -- when(pool.getUsed()).thenReturn(300L); -- when(pool.getMax()).thenReturn(400L); -- -- when(weirdPool.getCommitted()).thenReturn(100L); -- when(weirdPool.getInit()).thenReturn(200L); -- when(weirdPool.getUsed()).thenReturn(300L); -- when(weirdPool.getMax()).thenReturn(-1L); -- -- when(weirdCollection.getUsed()).thenReturn(290L); -- -- when(mxBean.getHeapMemoryUsage()).thenReturn(heap); -- when(mxBean.getNonHeapMemoryUsage()).thenReturn(nonHeap); -- -- when(memoryPool.getUsage()).thenReturn(pool); -- // Mock that "Big Pool" is a non-collected pool therefore doesn't -- // have collection usage statistics. -- when(memoryPool.getCollectionUsage()).thenReturn(null); -- when(memoryPool.getName()).thenReturn("Big Pool"); -- -- when(weirdMemoryPool.getUsage()).thenReturn(weirdPool); -- when(weirdMemoryPool.getCollectionUsage()).thenReturn(weirdCollection); -- when(weirdMemoryPool.getName()).thenReturn("Weird Pool"); -- } -- -- @Test -- void hasASetOfGauges() { -- assertThat(gauges.getMetrics().keySet()) -- .containsOnly( -- TOTAL_MAX, -- TOTAL_INIT, -- TOTAL_USED, -- TOTAL_COMMITTED, -- HEAP_INIT, -- HEAP_COMMITTED, -- HEAP_USAGE, -- HEAP_USED, -- HEAP_MAX, -- NON_HEAP_USAGE, -- NON_HEAP_MAX, -- NON_HEAP_USED, -- NON_HEAP_INIT, -- NON_HEAP_COMMITTED, -- POOLS_BIG_POOL_INIT, -- POOLS_BIG_POOL_COMMITED, -- POOLS_BIG_POOL_USED, -- POOLS_BIG_POOL_USAGE, -- POOLS_BIG_POOL_MAX, -- // skip in non-collected pools - "pools.Big-Pool.used-after-gc", -- POOLS_WEIRD_POOL_USAGE, -- POOLS_WEIRD_POOL_USED, -- POOLS_WEIRD_POOL_INIT, -- POOLS_WEIRD_POOL_MAX, -- POOLS_WEIRD_POOL_COMMITTED, -- POOLS_WEIRD_POOL_USED_AFTER_GC); -- } -- -- @Test -- void hasAGaugeForTotalCommitted() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_COMMITTED); -- -- assertThat(gauge.getValue()) -- .isEqualTo(11L); -- } -- -- @Test -- void hasAGaugeForTotalInit() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_INIT); -- -- assertThat(gauge.getValue()) -- .isEqualTo(22L); -- } -- -- @Test -- void hasAGaugeForTotalUsed() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_USED); -- -- assertThat(gauge.getValue()) -- .isEqualTo(33L); -- } -- -- @Test -- void hasAGaugeForTotalMax() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); -- -- assertThat(gauge.getValue()) -- .isEqualTo(44L); -- } -- -- @Test -- public void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { -- when(nonHeap.getMax()).thenReturn(-1L); -- -- final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); -- -- assertThat(gauge.getValue()) -- .isEqualTo(-1L); -- } -- -- @Test -- void hasAGaugeForHeapCommitted() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_COMMITTED); -- -- assertThat(gauge.getValue()) -- .isEqualTo(10L); -- } -- -- @Test -- void hasAGaugeForHeapInit() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_INIT); -- -- assertThat(gauge.getValue()) -- .isEqualTo(20L); -- } -- -- @Test -- void hasAGaugeForHeapUsed() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USED); -- -- assertThat(gauge.getValue()) -- .isEqualTo(30L); -- } -- -- @Test -- void hasAGaugeForHeapMax() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_MAX); -- -- assertThat(gauge.getValue()) -- .isEqualTo(40L); -- } -- -- @Test -- void hasAGaugeForHeapUsage() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USAGE); -- -- assertThat(gauge.getValue()) -- .isEqualTo(0.75); -- } -- -- @Test -- void hasAGaugeForNonHeapCommitted() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_COMMITTED); -- -- assertThat(gauge.getValue()) -- .isEqualTo(1L); -- } -- -- @Test -- void hasAGaugeForNonHeapInit() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_INIT); -- -- assertThat(gauge.getValue()) -- .isEqualTo(2L); -- } -+final class MemoryUsageGaugeSetTest { -+ private final MemoryUsage heap = mock(); -+ private final MemoryUsage nonHeap = mock(); -+ private final MemoryUsage pool = mock(); -+ private final MemoryUsage weirdPool = mock(); -+ private final MemoryUsage weirdCollection = mock(); -+ private final MemoryMXBean mxBean = mock(); -+ private final MemoryPoolMXBean memoryPool = mock(); -+ private final MemoryPoolMXBean weirdMemoryPool = mock(); -+ -+ private final MemoryUsageGaugeSet gauges = -+ new MemoryUsageGaugeSet(mxBean, Arrays.asList(memoryPool, weirdMemoryPool)); -+ -+ private static final MetricName TOTAL = MetricName.build("total"); -+ private static final MetricName HEAP = MetricName.build("heap"); -+ private static final MetricName NON_HEAP = MetricName.build("non-heap"); -+ private static final MetricName POOLS = MetricName.build("pools"); -+ -+ private static final MetricName TOTAL_MAX = TOTAL.resolve("max"); -+ private static final MetricName TOTAL_INIT = TOTAL.resolve("init"); -+ private static final MetricName TOTAL_USED = TOTAL.resolve("used"); -+ private static final MetricName TOTAL_COMMITTED = TOTAL.resolve("committed"); -+ private static final MetricName POOLS_BIG_POOL_USAGE = POOLS.resolve("Big-Pool.usage"); -+ private static final MetricName POOLS_BIG_POOL_USED = POOLS.resolve("Big-Pool.used"); -+ private static final MetricName POOLS_BIG_POOL_INIT = POOLS.resolve("Big-Pool.init"); -+ private static final MetricName POOLS_BIG_POOL_COMMITED = POOLS.resolve("Big-Pool.committed"); -+ private static final MetricName POOLS_BIG_POOL_MAX = POOLS.resolve("Big-Pool.max"); -+ private static final MetricName POOLS_WEIRD_POOL_USAGE = POOLS.resolve("Weird-Pool.usage"); -+ private static final MetricName POOLS_WEIRD_POOL_INIT = POOLS.resolve("Weird-Pool.init"); -+ private static final MetricName POOLS_WEIRD_POOL_MAX = POOLS.resolve("Weird-Pool.max"); -+ private static final MetricName POOLS_WEIRD_POOL_USED = POOLS.resolve("Weird-Pool.used"); -+ private static final MetricName POOLS_WEIRD_POOL_USED_AFTER_GC = -+ POOLS.resolve("Weird-Pool.used-after-gc"); -+ private static final MetricName POOLS_WEIRD_POOL_COMMITTED = -+ POOLS.resolve("Weird-Pool.committed"); -+ private static final MetricName HEAP_INIT = HEAP.resolve("init"); -+ private static final MetricName HEAP_COMMITTED = HEAP.resolve("committed"); -+ private static final MetricName HEAP_USAGE = HEAP.resolve("usage"); -+ private static final MetricName HEAP_USED = HEAP.resolve("used"); -+ private static final MetricName HEAP_MAX = HEAP.resolve("max"); -+ private static final MetricName NON_HEAP_USAGE = NON_HEAP.resolve("usage"); -+ private static final MetricName NON_HEAP_MAX = NON_HEAP.resolve("max"); -+ private static final MetricName NON_HEAP_USED = NON_HEAP.resolve("used"); -+ private static final MetricName NON_HEAP_INIT = NON_HEAP.resolve("init"); -+ private static final MetricName NON_HEAP_COMMITTED = NON_HEAP.resolve("committed"); -+ -+ @BeforeEach -+ void setUp() { -+ when(heap.getCommitted()).thenReturn(10L); -+ when(heap.getInit()).thenReturn(20L); -+ when(heap.getUsed()).thenReturn(30L); -+ when(heap.getMax()).thenReturn(40L); -+ -+ when(nonHeap.getCommitted()).thenReturn(1L); -+ when(nonHeap.getInit()).thenReturn(2L); -+ when(nonHeap.getUsed()).thenReturn(3L); -+ when(nonHeap.getMax()).thenReturn(4L); -+ -+ when(pool.getCommitted()).thenReturn(100L); -+ when(pool.getInit()).thenReturn(200L); -+ when(pool.getUsed()).thenReturn(300L); -+ when(pool.getMax()).thenReturn(400L); -+ -+ when(weirdPool.getCommitted()).thenReturn(100L); -+ when(weirdPool.getInit()).thenReturn(200L); -+ when(weirdPool.getUsed()).thenReturn(300L); -+ when(weirdPool.getMax()).thenReturn(-1L); -+ -+ when(weirdCollection.getUsed()).thenReturn(290L); -+ -+ when(mxBean.getHeapMemoryUsage()).thenReturn(heap); -+ when(mxBean.getNonHeapMemoryUsage()).thenReturn(nonHeap); -+ -+ when(memoryPool.getUsage()).thenReturn(pool); -+ // Mock that "Big Pool" is a non-collected pool therefore doesn't -+ // have collection usage statistics. -+ when(memoryPool.getCollectionUsage()).thenReturn(null); -+ when(memoryPool.getName()).thenReturn("Big Pool"); -+ -+ when(weirdMemoryPool.getUsage()).thenReturn(weirdPool); -+ when(weirdMemoryPool.getCollectionUsage()).thenReturn(weirdCollection); -+ when(weirdMemoryPool.getName()).thenReturn("Weird Pool"); -+ } -+ -+ @Test -+ void hasASetOfGauges() { -+ assertThat(gauges.getMetrics().keySet()) -+ .containsOnly( -+ TOTAL_MAX, -+ TOTAL_INIT, -+ TOTAL_USED, -+ TOTAL_COMMITTED, -+ HEAP_INIT, -+ HEAP_COMMITTED, -+ HEAP_USAGE, -+ HEAP_USED, -+ HEAP_MAX, -+ NON_HEAP_USAGE, -+ NON_HEAP_MAX, -+ NON_HEAP_USED, -+ NON_HEAP_INIT, -+ NON_HEAP_COMMITTED, -+ POOLS_BIG_POOL_INIT, -+ POOLS_BIG_POOL_COMMITED, -+ POOLS_BIG_POOL_USED, -+ POOLS_BIG_POOL_USAGE, -+ POOLS_BIG_POOL_MAX, -+ // skip in non-collected pools - "pools.Big-Pool.used-after-gc", -+ POOLS_WEIRD_POOL_USAGE, -+ POOLS_WEIRD_POOL_USED, -+ POOLS_WEIRD_POOL_INIT, -+ POOLS_WEIRD_POOL_MAX, -+ POOLS_WEIRD_POOL_COMMITTED, -+ POOLS_WEIRD_POOL_USED_AFTER_GC); -+ } -+ -+ @Test -+ void hasAGaugeForTotalCommitted() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_COMMITTED); -+ -+ assertThat(gauge.getValue()).isEqualTo(11L); -+ } -+ -+ @Test -+ void hasAGaugeForTotalInit() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_INIT); -+ -+ assertThat(gauge.getValue()).isEqualTo(22L); -+ } -+ -+ @Test -+ void hasAGaugeForTotalUsed() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_USED); -+ -+ assertThat(gauge.getValue()).isEqualTo(33L); -+ } -+ -+ @Test -+ void hasAGaugeForTotalMax() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); -+ -+ assertThat(gauge.getValue()).isEqualTo(44L); -+ } -+ -+ @Test -+ void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { -+ when(nonHeap.getMax()).thenReturn(-1L); -+ -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); -+ -+ assertThat(gauge.getValue()).isEqualTo(-1L); -+ } -+ -+ @Test -+ void hasAGaugeForHeapCommitted() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_COMMITTED); -+ -+ assertThat(gauge.getValue()).isEqualTo(10L); -+ } -+ -+ @Test -+ void hasAGaugeForHeapInit() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_INIT); -+ -+ assertThat(gauge.getValue()).isEqualTo(20L); -+ } -+ -+ @Test -+ void hasAGaugeForHeapUsed() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USED); -+ -+ assertThat(gauge.getValue()).isEqualTo(30L); -+ } -+ -+ @Test -+ void hasAGaugeForHeapMax() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_MAX); -+ -+ assertThat(gauge.getValue()).isEqualTo(40L); -+ } -+ -+ @Test -+ void hasAGaugeForHeapUsage() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USAGE); -+ -+ assertThat(gauge.getValue()).isEqualTo(0.75); -+ } -+ -+ @Test -+ void hasAGaugeForNonHeapCommitted() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_COMMITTED); -+ -+ assertThat(gauge.getValue()).isEqualTo(1L); -+ } -+ -+ @Test -+ void hasAGaugeForNonHeapInit() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_INIT); -+ -+ assertThat(gauge.getValue()).isEqualTo(2L); -+ } -+ -+ @Test -+ void hasAGaugeForNonHeapUsed() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USED); -+ -+ assertThat(gauge.getValue()).isEqualTo(3L); -+ } -+ -+ @Test -+ void hasAGaugeForNonHeapMax() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_MAX); -+ -+ assertThat(gauge.getValue()).isEqualTo(4L); -+ } -+ -+ @Test -+ void hasAGaugeForNonHeapUsage() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); -+ -+ assertThat(gauge.getValue()).isEqualTo(0.75); -+ } -+ -+ @Test -+ void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { -+ when(nonHeap.getMax()).thenReturn(-1L); -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); -+ -+ assertThat(gauge.getValue()).isEqualTo(3.0); -+ } -+ -+ @Test -+ void hasAGaugeForMemoryPoolUsage() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_BIG_POOL_USAGE); -+ -+ assertThat(gauge.getValue()).isEqualTo(0.75); -+ } -+ -+ @Test -+ void hasAGaugeForWeirdMemoryPoolInit() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_INIT); -+ -+ assertThat(gauge.getValue()).isEqualTo(200L); -+ } -+ -+ @Test -+ void hasAGaugeForWeirdMemoryPoolCommitted() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_COMMITTED); +-class InfluxDbReporterTest { ++final class InfluxDbReporterTest { + private static final MetricName GAUGE = MetricName.build("gauge"); + private static final MetricName METER = MetricName.build("meter"); + private static final MetricName COUNTER = MetricName.build("counter"); + + private final long timestamp = 1000198; +- private final Clock clock = mock(Clock.class); +- private final InfluxDbSender sender = mock(InfluxDbSender.class); ++ private final Clock clock = mock(); ++ private final InfluxDbSender sender = mock(); + private final List send = new ArrayList<>(); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final MetricRegistry registry = mock(); + private final InfluxDbReporter reporter = + InfluxDbReporter.forRegistry(registry) + .withClock(clock) +@@ -53,7 +53,7 @@ class InfluxDbReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .build(sender); + + private final InfluxDbReporter minuteRateReporter = +@@ -63,7 +63,7 @@ class InfluxDbReporterTest { + .convertRatesTo(TimeUnit.MINUTES) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .build(sender); -- @Test -- void hasAGaugeForNonHeapUsed() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USED); -+ assertThat(gauge.getValue()).isEqualTo(100L); -+ } + @BeforeEach +@@ -197,7 +197,7 @@ class InfluxDbReporterTest { -- assertThat(gauge.getValue()) -- .isEqualTo(3L); -- } -+ @Test -+ void hasAGaugeForWeirdMemoryPoolUsed() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED); + @Test + void reportsCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); -- @Test -- void hasAGaugeForNonHeapMax() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_MAX); -+ assertThat(gauge.getValue()).isEqualTo(300L); -+ } + reporter.report(map(), map(COUNTER, counter), map(), map(), map()); +@@ -214,11 +214,11 @@ class InfluxDbReporterTest { -- assertThat(gauge.getValue()) -- .isEqualTo(4L); -- } -+ @Test -+ void hasAGaugeForWeirdMemoryPoolUsage() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USAGE); + @Test + void reportsHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(12L); -- @Test -- void hasAGaugeForNonHeapUsage() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); -+ assertThat(gauge.getValue()).isEqualTo(3.0); -+ } +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -249,7 +249,7 @@ class InfluxDbReporterTest { -- assertThat(gauge.getValue()) -- .isEqualTo(0.75); -- } -+ @Test -+ void hasAGaugeForWeirdMemoryPoolMax() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_MAX); - -- @Test -- public void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { -- when(nonHeap.getMax()).thenReturn(-1L); -- final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); -+ assertThat(gauge.getValue()).isEqualTo(-1L); -+ } - -- assertThat(gauge.getValue()) -- .isEqualTo(3.0); -- } -+ @Test -+ void hasAGaugeForWeirdCollectionPoolUsed() { -+ final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED_AFTER_GC); + @Test + void reportsMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -274,7 +274,7 @@ class InfluxDbReporterTest { -- @Test -- void hasAGaugeForMemoryPoolUsage() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_BIG_POOL_USAGE); -+ assertThat(gauge.getValue()).isEqualTo(290L); -+ } + @Test + void reportsMetersInMinutes() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -300,7 +300,7 @@ class InfluxDbReporterTest { -- assertThat(gauge.getValue()) -- .isEqualTo(0.75); -- } -- -- @Test -- void hasAGaugeForWeirdMemoryPoolInit() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_INIT); -- -- assertThat(gauge.getValue()) -- .isEqualTo(200L); -- } -- -- @Test -- void hasAGaugeForWeirdMemoryPoolCommitted() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_COMMITTED); -- -- assertThat(gauge.getValue()) -- .isEqualTo(100L); -- } -- -- @Test -- void hasAGaugeForWeirdMemoryPoolUsed() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED); -- -- assertThat(gauge.getValue()) -- .isEqualTo(300L); -- } -- -- @Test -- void hasAGaugeForWeirdMemoryPoolUsage() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USAGE); -- -- assertThat(gauge.getValue()) -- .isEqualTo(3.0); -- } -- -- @Test -- void hasAGaugeForWeirdMemoryPoolMax() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_MAX); -- -- assertThat(gauge.getValue()) -- .isEqualTo(-1L); -- } -- -- @Test -- void hasAGaugeForWeirdCollectionPoolUsed() { -- final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED_AFTER_GC); -- -- assertThat(gauge.getValue()) -- .isEqualTo(290L); -- } -- -- @Test -- void autoDetectsMemoryUsageBeanAndMemoryPools() { -- assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()) -- .isNotEmpty(); -- } -+ @Test -+ void autoDetectsMemoryUsageBeanAndMemoryPools() { -+ assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty(); -+ } - } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java -@@ -1,68 +1,71 @@ - package io.dropwizard.metrics5.jvm; + @Test + void reportsTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(6L); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -308,7 +308,7 @@ class InfluxDbReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -360,7 +360,7 @@ class InfluxDbReporterTest { --import org.junit.jupiter.api.Test; -- --import java.lang.management.ThreadInfo; --import java.lang.management.ThreadMXBean; --import java.util.Locale; -- + @Test + void disabledMetricsAttribute() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -368,7 +368,7 @@ class InfluxDbReporterTest { + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(11L); + + Set disabledMetricAttributes = +--- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java ++++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java +@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.influxdb; import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.ArgumentMatchers.anyInt; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; + import static org.mockito.Mockito.any; + import static org.mockito.Mockito.doAnswer; ++import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; --class ThreadDeadlockDetectorTest { -- private final ThreadMXBean threads = mock(ThreadMXBean.class); -- private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); -+import java.lang.management.ThreadInfo; -+import java.lang.management.ThreadMXBean; -+import java.util.Locale; -+import org.junit.jupiter.api.Test; -+ -+final class ThreadDeadlockDetectorTest { -+ private final ThreadMXBean threads = mock(); -+ private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); +@@ -14,15 +15,14 @@ import java.util.ArrayList; + import java.util.List; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; +-import org.mockito.Mockito; -- @Test -- void returnsAnEmptySetIfNoThreadsAreDeadlocked() { -- when(threads.findDeadlockedThreads()).thenReturn(null); -+ @Test -+ void returnsAnEmptySetIfNoThreadsAreDeadlocked() { -+ when(threads.findDeadlockedThreads()).thenReturn(null); +-class InfluxDbUdpTest { ++final class InfluxDbUdpTest { -- assertThat(detector.getDeadlockedThreads()) -- .isEmpty(); -- } -+ assertThat(detector.getDeadlockedThreads()).isEmpty(); -+ } - -- @Test -- void returnsASetOfThreadsIfAnyAreDeadlocked() { -- final ThreadInfo thread1 = mock(ThreadInfo.class); -- when(thread1.getThreadName()).thenReturn("thread1"); -- when(thread1.getLockName()).thenReturn("lock2"); -- when(thread1.getLockOwnerName()).thenReturn("thread2"); -- when(thread1.getStackTrace()).thenReturn(new StackTraceElement[]{ -- new StackTraceElement("Blah", "bloo", "Blah.java", 150), -- new StackTraceElement("Blah", "blee", "Blah.java", 100) -- }); -+ @Test -+ void returnsASetOfThreadsIfAnyAreDeadlocked() { -+ final ThreadInfo thread1 = mock(); -+ when(thread1.getThreadName()).thenReturn("thread1"); -+ when(thread1.getLockName()).thenReturn("lock2"); -+ when(thread1.getLockOwnerName()).thenReturn("thread2"); -+ when(thread1.getStackTrace()) -+ .thenReturn( -+ new StackTraceElement[] { -+ new StackTraceElement("Blah", "bloo", "Blah.java", 150), -+ new StackTraceElement("Blah", "blee", "Blah.java", 100) -+ }); - -- final ThreadInfo thread2 = mock(ThreadInfo.class); -- when(thread2.getThreadName()).thenReturn("thread2"); -- when(thread2.getLockName()).thenReturn("lock1"); -- when(thread2.getLockOwnerName()).thenReturn("thread1"); -- when(thread2.getStackTrace()).thenReturn(new StackTraceElement[]{ -- new StackTraceElement("Blah", "blee", "Blah.java", 100), -- new StackTraceElement("Blah", "bloo", "Blah.java", 150) -- }); -+ final ThreadInfo thread2 = mock(); -+ when(thread2.getThreadName()).thenReturn("thread2"); -+ when(thread2.getLockName()).thenReturn("lock1"); -+ when(thread2.getLockOwnerName()).thenReturn("thread1"); -+ when(thread2.getStackTrace()) -+ .thenReturn( -+ new StackTraceElement[] { -+ new StackTraceElement("Blah", "blee", "Blah.java", 100), -+ new StackTraceElement("Blah", "bloo", "Blah.java", 150) -+ }); - -- final long[] ids = {1, 2}; -- when(threads.findDeadlockedThreads()).thenReturn(ids); -- when(threads.getThreadInfo(eq(ids), anyInt())) -- .thenReturn(new ThreadInfo[]{thread1, thread2}); -+ final long[] ids = {1, 2}; -+ when(threads.findDeadlockedThreads()).thenReturn(ids); -+ when(threads.getThreadInfo(eq(ids), anyInt())).thenReturn(new ThreadInfo[] {thread1, thread2}); - -- assertThat(detector.getDeadlockedThreads()) -- .containsOnly(String.format(Locale.US, -- "thread1 locked on lock2 (owned by thread2):%n" + -- "\t at Blah.bloo(Blah.java:150)%n" + -- "\t at Blah.blee(Blah.java:100)%n"), -- String.format(Locale.US, -- "thread2 locked on lock1 (owned by thread1):%n" + -- "\t at Blah.blee(Blah.java:100)%n" + -- "\t at Blah.bloo(Blah.java:150)%n")); -- } -+ assertThat(detector.getDeadlockedThreads()) -+ .containsOnly( -+ String.format( -+ Locale.US, -+ "thread1 locked on lock2 (owned by thread2):%n" -+ + "\t at Blah.bloo(Blah.java:150)%n" -+ + "\t at Blah.blee(Blah.java:100)%n"), -+ String.format( -+ Locale.US, -+ "thread2 locked on lock1 (owned by thread1):%n" -+ + "\t at Blah.blee(Blah.java:100)%n" -+ + "\t at Blah.bloo(Blah.java:150)%n")); -+ } - -- @Test -- void autoDiscoversTheThreadMXBean() { -- assertThat(new ThreadDeadlockDetector().getDeadlockedThreads()) -- .isNotNull(); -- } -+ @Test -+ void autoDiscoversTheThreadMXBean() { -+ assertThat(new ThreadDeadlockDetector().getDeadlockedThreads()).isNotNull(); -+ } - } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java -@@ -1,51 +1,50 @@ - package io.dropwizard.metrics5.jvm; + private final String host = "example.com"; + private final int port = 1234; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; + private InfluxDbUdpSender influxdbUdp; +- private final DatagramChannel datagramChannel = Mockito.mock(DatagramChannel.class); ++ private final DatagramChannel datagramChannel = mock(); + private final List sent = new ArrayList<>(); - import java.io.ByteArrayOutputStream; - import java.lang.management.LockInfo; - import java.lang.management.MonitorInfo; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; + @BeforeEach +--- a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java ++++ b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.servlet; - // TODO: 3/12/13 -- improve test coverage for ThreadDump + import static io.dropwizard.metrics5.MetricRegistry.name; --class ThreadDumpTest { -- private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); -- private final ThreadDump threadDump = new ThreadDump(threadMXBean); -- -- private final ThreadInfo runnable = mock(ThreadInfo.class); -- -- @BeforeEach -- void setUp() { -- final StackTraceElement rLine1 = new StackTraceElement("Blah", "blee", "Blah.java", 100); -- -- when(runnable.getThreadName()).thenReturn("runnable"); -- when(runnable.getThreadId()).thenReturn(100L); -- when(runnable.getThreadState()).thenReturn(Thread.State.RUNNABLE); -- when(runnable.getStackTrace()).thenReturn(new StackTraceElement[]{rLine1}); -- when(runnable.getLockedMonitors()).thenReturn(new MonitorInfo[]{}); -- when(runnable.getLockedSynchronizers()).thenReturn(new LockInfo[]{}); -- -- when(threadMXBean.dumpAllThreads(true, true)).thenReturn(new ThreadInfo[]{ -- runnable -- }); -- } -- -- @Test -- void dumpsAllThreads() { -- final ByteArrayOutputStream output = new ByteArrayOutputStream(); -- threadDump.dump(output); -- -- assertThat(output.toString()) -- .isEqualTo(String.format("\"runnable\" id=100 state=RUNNABLE%n" + -- " at Blah.blee(Blah.java:100)%n" + -- "%n" + -- "%n")); -- } -+final class ThreadDumpTest { -+ private final ThreadMXBean threadMXBean = mock(); -+ private final ThreadDump threadDump = new ThreadDump(threadMXBean); -+ -+ private final ThreadInfo runnable = mock(); -+ -+ @BeforeEach -+ void setUp() { -+ final StackTraceElement rLine1 = new StackTraceElement("Blah", "blee", "Blah.java", 100); -+ -+ when(runnable.getThreadName()).thenReturn("runnable"); -+ when(runnable.getThreadId()).thenReturn(100L); -+ when(runnable.getThreadState()).thenReturn(Thread.State.RUNNABLE); -+ when(runnable.getStackTrace()).thenReturn(new StackTraceElement[] {rLine1}); -+ when(runnable.getLockedMonitors()).thenReturn(new MonitorInfo[] {}); -+ when(runnable.getLockedSynchronizers()).thenReturn(new LockInfo[] {}); -+ -+ when(threadMXBean.dumpAllThreads(true, true)).thenReturn(new ThreadInfo[] {runnable}); -+ } -+ -+ @Test -+ void dumpsAllThreads() { -+ final ByteArrayOutputStream output = new ByteArrayOutputStream(); -+ threadDump.dump(output); -+ -+ assertThat(output) -+ .hasToString( -+ String.format( -+ "\"runnable\" id=100 state=RUNNABLE%n" -+ + " at Blah.blee(Blah.java:100)%n" -+ + "%n" -+ + "%n")); -+ } - } ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java -@@ -1,151 +1,142 @@ - package io.dropwizard.metrics5.jvm; ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -64,7 +65,7 @@ public abstract class AbstractInstrumentedFilter implements Filter { + final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.MetricName; --import org.assertj.core.api.Assertions; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; - import java.util.HashSet; - import java.util.Set; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; + String metricName = filterConfig.getInitParameter(METRIC_PREFIX); +- if (metricName == null || metricName.isEmpty()) { ++ if (Strings.isNullOrEmpty(metricName)) { + metricName = getClass().getName(); + } --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- --class ThreadStatesGaugeSetTest { -- private final ThreadMXBean threads = mock(ThreadMXBean.class); -- private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -- private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); -- private final long[] ids = new long[]{1, 2, 3}; -- -- private final ThreadInfo newThread = mock(ThreadInfo.class); -- private final ThreadInfo runnableThread = mock(ThreadInfo.class); -- private final ThreadInfo blockedThread = mock(ThreadInfo.class); -- private final ThreadInfo waitingThread = mock(ThreadInfo.class); -- private final ThreadInfo timedWaitingThread = mock(ThreadInfo.class); -- private final ThreadInfo terminatedThread = mock(ThreadInfo.class); -- -- private final Set deadlocks = new HashSet<>(); -- -- private static final MetricName TERMINATED_COUNT = MetricName.build("terminated.count"); -- private static final MetricName NEW_COUNT = MetricName.build("new.count"); -- private static final MetricName COUNT = MetricName.build("count"); -- private static final MetricName TIMED_WAITING_COUNT = MetricName.build("timed_waiting.count"); -- private static final MetricName DEADLOCKS = MetricName.build("deadlocks"); -- private static final MetricName BLOCKED_COUNT = MetricName.build("blocked.count"); -- private static final MetricName WAITING_COUNT = MetricName.build("waiting.count"); -- private static final MetricName DAEMON_COUNT = MetricName.build("daemon.count"); -- private static final MetricName RUNNABLE_COUNT = MetricName.build("runnable.count"); -- private static final MetricName DEADLOCK_COUNT = MetricName.build("deadlock.count"); -- -- @BeforeEach -- void setUp() { -- deadlocks.add("yay"); -- -- when(newThread.getThreadState()).thenReturn(Thread.State.NEW); -- when(runnableThread.getThreadState()).thenReturn(Thread.State.RUNNABLE); -- when(blockedThread.getThreadState()).thenReturn(Thread.State.BLOCKED); -- when(waitingThread.getThreadState()).thenReturn(Thread.State.WAITING); -- when(timedWaitingThread.getThreadState()).thenReturn(Thread.State.TIMED_WAITING); -- when(terminatedThread.getThreadState()).thenReturn(Thread.State.TERMINATED); -- -- when(threads.getAllThreadIds()).thenReturn(ids); -- when(threads.getThreadInfo(ids, 0)).thenReturn(new ThreadInfo[]{ -- newThread, runnableThread, blockedThread, -- waitingThread, timedWaitingThread, terminatedThread -- }); -- -- when(threads.getThreadCount()).thenReturn(12); -- when(threads.getDaemonThreadCount()).thenReturn(10); -- when(threads.getPeakThreadCount()).thenReturn(30); -- when(threads.getTotalStartedThreadCount()).thenReturn(42L); -- -- when(detector.getDeadlockedThreads()).thenReturn(deadlocks); -- } -- -- @Test -- void hasASetOfGauges() { -- assertThat(gauges.getMetrics().keySet()) -- .containsOnly(TERMINATED_COUNT, -- NEW_COUNT, -- COUNT, -- TIMED_WAITING_COUNT, -- DEADLOCKS, -- BLOCKED_COUNT, -- WAITING_COUNT, -- DAEMON_COUNT, -- RUNNABLE_COUNT, -- DEADLOCK_COUNT, -- MetricName.build("total_started.count"), -- MetricName.build("peak.count")); -- } -- -- @Test -- void hasAGaugeForEachThreadState() { -- Assertions.assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()) -- .isEqualTo(1); -- -- assertThat(((Gauge) gauges.getMetrics().get(RUNNABLE_COUNT)).getValue()) -- .isEqualTo(1); -- -- assertThat(((Gauge) gauges.getMetrics().get(BLOCKED_COUNT)).getValue()) -- .isEqualTo(1); -- -- assertThat(((Gauge) gauges.getMetrics().get(WAITING_COUNT)).getValue()) -- .isEqualTo(1); -- -- assertThat(((Gauge) gauges.getMetrics().get(TIMED_WAITING_COUNT)).getValue()) -- .isEqualTo(1); -- -- assertThat(((Gauge) gauges.getMetrics().get(TERMINATED_COUNT)).getValue()) -- .isEqualTo(1); -- } -- -- @Test -- void hasAGaugeForTheNumberOfThreads() { -- assertThat(((Gauge) gauges.getMetrics().get(COUNT)).getValue()) -- .isEqualTo(12); -- } -- -- @Test -- void hasAGaugeForTheNumberOfDaemonThreads() { -- assertThat(((Gauge) gauges.getMetrics().get(DAEMON_COUNT)).getValue()) -- .isEqualTo(10); -- } -- -- @Test -- void hasAGaugeForAnyDeadlocks() { -- assertThat(((Gauge) gauges.getMetrics().get(DEADLOCKS)).getValue()) -- .isEqualTo(deadlocks); -- } -- -- @Test -- void hasAGaugeForAnyDeadlockCount() { -- assertThat(((Gauge) gauges.getMetrics().get(DEADLOCK_COUNT)).getValue()) -- .isEqualTo(1); -- } -- -- @Test -- void hasAGaugeForPeakThreadCount() { -- assertThat(((Gauge) gauges.getMetrics().get(MetricName.build("peak.count"))).getValue()) -- .isEqualTo(30); -- } -- -- @Test -- void hasAGaugeForTotalStartedThreadsCount() { -- assertThat(((Gauge) gauges.getMetrics().get(MetricName.build("total_started.count"))).getValue()) -- .isEqualTo(42L); -- } -- -- @Test -- void autoDiscoversTheMXBeans() { -- final ThreadStatesGaugeSet set = new ThreadStatesGaugeSet(); -- assertThat(((Gauge) set.getMetrics().get(COUNT)).getValue()) -- .isNotNull(); -- assertThat(((Gauge) set.getMetrics().get(DEADLOCKS)).getValue()) -- .isNotNull(); -- } -+final class ThreadStatesGaugeSetTest { -+ private final ThreadMXBean threads = mock(); -+ private final ThreadDeadlockDetector detector = mock(); -+ private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); -+ private final long[] ids = new long[] {1, 2, 3}; -+ -+ private final ThreadInfo newThread = mock(); -+ private final ThreadInfo runnableThread = mock(); -+ private final ThreadInfo blockedThread = mock(); -+ private final ThreadInfo waitingThread = mock(); -+ private final ThreadInfo timedWaitingThread = mock(); -+ private final ThreadInfo terminatedThread = mock(); -+ -+ private final Set deadlocks = new HashSet<>(); -+ -+ private static final MetricName TERMINATED_COUNT = MetricName.build("terminated.count"); -+ private static final MetricName NEW_COUNT = MetricName.build("new.count"); -+ private static final MetricName COUNT = MetricName.build("count"); -+ private static final MetricName TIMED_WAITING_COUNT = MetricName.build("timed_waiting.count"); -+ private static final MetricName DEADLOCKS = MetricName.build("deadlocks"); -+ private static final MetricName BLOCKED_COUNT = MetricName.build("blocked.count"); -+ private static final MetricName WAITING_COUNT = MetricName.build("waiting.count"); -+ private static final MetricName DAEMON_COUNT = MetricName.build("daemon.count"); -+ private static final MetricName RUNNABLE_COUNT = MetricName.build("runnable.count"); -+ private static final MetricName DEADLOCK_COUNT = MetricName.build("deadlock.count"); -+ -+ @BeforeEach -+ void setUp() { -+ deadlocks.add("yay"); -+ -+ when(newThread.getThreadState()).thenReturn(Thread.State.NEW); -+ when(runnableThread.getThreadState()).thenReturn(Thread.State.RUNNABLE); -+ when(blockedThread.getThreadState()).thenReturn(Thread.State.BLOCKED); -+ when(waitingThread.getThreadState()).thenReturn(Thread.State.WAITING); -+ when(timedWaitingThread.getThreadState()).thenReturn(Thread.State.TIMED_WAITING); -+ when(terminatedThread.getThreadState()).thenReturn(Thread.State.TERMINATED); -+ -+ when(threads.getAllThreadIds()).thenReturn(ids); -+ when(threads.getThreadInfo(ids, 0)) -+ .thenReturn( -+ new ThreadInfo[] { -+ newThread, runnableThread, blockedThread, -+ waitingThread, timedWaitingThread, terminatedThread -+ }); -+ -+ when(threads.getThreadCount()).thenReturn(12); -+ when(threads.getDaemonThreadCount()).thenReturn(10); -+ when(threads.getPeakThreadCount()).thenReturn(30); -+ when(threads.getTotalStartedThreadCount()).thenReturn(42L); -+ -+ when(detector.getDeadlockedThreads()).thenReturn(deadlocks); -+ } -+ -+ @Test -+ void hasASetOfGauges() { -+ assertThat(gauges.getMetrics().keySet()) -+ .containsOnly( -+ TERMINATED_COUNT, -+ NEW_COUNT, -+ COUNT, -+ TIMED_WAITING_COUNT, -+ DEADLOCKS, -+ BLOCKED_COUNT, -+ WAITING_COUNT, -+ DAEMON_COUNT, -+ RUNNABLE_COUNT, -+ DEADLOCK_COUNT, -+ MetricName.build("total_started.count"), -+ MetricName.build("peak.count")); -+ } -+ -+ @Test -+ void hasAGaugeForEachThreadState() { -+ assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1); -+ -+ assertThat(((Gauge) gauges.getMetrics().get(RUNNABLE_COUNT)).getValue()).isEqualTo(1); -+ -+ assertThat(((Gauge) gauges.getMetrics().get(BLOCKED_COUNT)).getValue()).isEqualTo(1); -+ -+ assertThat(((Gauge) gauges.getMetrics().get(WAITING_COUNT)).getValue()).isEqualTo(1); -+ -+ assertThat(((Gauge) gauges.getMetrics().get(TIMED_WAITING_COUNT)).getValue()).isEqualTo(1); -+ -+ assertThat(((Gauge) gauges.getMetrics().get(TERMINATED_COUNT)).getValue()).isEqualTo(1); -+ } -+ -+ @Test -+ void hasAGaugeForTheNumberOfThreads() { -+ assertThat(((Gauge) gauges.getMetrics().get(COUNT)).getValue()).isEqualTo(12); -+ } -+ -+ @Test -+ void hasAGaugeForTheNumberOfDaemonThreads() { -+ assertThat(((Gauge) gauges.getMetrics().get(DAEMON_COUNT)).getValue()).isEqualTo(10); -+ } -+ -+ @Test -+ void hasAGaugeForAnyDeadlocks() { -+ assertThat(((Gauge) gauges.getMetrics().get(DEADLOCKS)).getValue()).isEqualTo(deadlocks); -+ } -+ -+ @Test -+ void hasAGaugeForAnyDeadlockCount() { -+ assertThat(((Gauge) gauges.getMetrics().get(DEADLOCK_COUNT)).getValue()).isEqualTo(1); -+ } -+ -+ @Test -+ void hasAGaugeForPeakThreadCount() { -+ assertThat(((Gauge) gauges.getMetrics().get(MetricName.build("peak.count"))).getValue()) -+ .isEqualTo(30); -+ } -+ -+ @Test -+ void hasAGaugeForTotalStartedThreadsCount() { -+ assertThat( -+ ((Gauge) gauges.getMetrics().get(MetricName.build("total_started.count"))) -+ .getValue()) -+ .isEqualTo(42L); -+ } -+ -+ @Test -+ void autoDiscoversTheMXBeans() { -+ final ThreadStatesGaugeSet set = new ThreadStatesGaugeSet(); -+ assertThat(((Gauge) set.getMetrics().get(COUNT)).getValue()).isNotNull(); -+ assertThat(((Gauge) set.getMetrics().get(DEADLOCKS)).getValue()).isNotNull(); -+ } - } ---- a/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java -+++ b/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheck.java -@@ -6,158 +6,158 @@ import java.util.Objects; - @Deprecated - public abstract class HealthCheck { +--- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +@@ -9,8 +9,8 @@ import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletContextEvent; + import org.junit.jupiter.api.Test; + +-class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++final class InstrumentedFilterContextListenerTest { ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ class InstrumentedFilterContextListenerTest { + + @Test + void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); + + listener.contextInitialized(event); +--- a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java ++++ b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.servlet6; + + import static io.dropwizard.metrics5.MetricRegistry.name; + ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -64,7 +65,7 @@ public abstract class AbstractInstrumentedFilter implements Filter { + final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); + + String metricName = filterConfig.getInitParameter(METRIC_PREFIX); +- if (metricName == null || metricName.isEmpty()) { ++ if (Strings.isNullOrEmpty(metricName)) { + metricName = getClass().getName(); + } + +--- a/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java ++++ b/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java +@@ -9,8 +9,8 @@ import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletContextEvent; + import org.junit.jupiter.api.Test; + +-class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++final class InstrumentedFilterContextListenerTest { ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ class InstrumentedFilterContextListenerTest { -- public static class Result { -+ public static class Result { + @Test + void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); -- public static HealthCheck.Result healthy() { -- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy()); -- } -- -- public static HealthCheck.Result healthy(String message) { -- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy(message)); -- } -- -- public static HealthCheck.Result healthy(String message, Object... args) { -- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy(message, args)); -- } -- -- public static HealthCheck.Result unhealthy(String message) { -- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(message)); -- } -+ public static HealthCheck.Result healthy() { -+ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy()); -+ } +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); -- public static HealthCheck.Result unhealthy(String message, Object... args) { -- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(message, args)); -- } -+ public static HealthCheck.Result healthy(String message) { -+ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy(message)); -+ } + listener.contextInitialized(event); +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java +@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { + super.init(config); -- public static HealthCheck.Result unhealthy(Throwable error) { -- return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(error)); -- } -+ public static HealthCheck.Result healthy(String message, Object... args) { -+ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.healthy(message, args)); -+ } + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); + if (registryAttr instanceof HealthCheckRegistry) { + this.registry = (HealthCheckRegistry) registryAttr; +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { + super.init(config); -- public static HealthCheck.Result of(io.dropwizard.metrics5.health.HealthCheck.Result delegate) { -- return new Result(delegate); -- } -+ public static HealthCheck.Result unhealthy(String message) { -+ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(message)); -+ } + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(METRICS_REGISTRY); + if (registryAttr instanceof MetricRegistry) { + this.registry = (MetricRegistry) registryAttr; +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- public static HealthCheck.ResultBuilder builder() { -- return new HealthCheck.ResultBuilder(); -- } -+ public static HealthCheck.Result unhealthy(String message, Object... args) { -+ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(message, args)); -+ } +-class AdminServletExclusionTest extends AbstractServletTest { ++final class AdminServletExclusionTest extends AbstractServletTest { + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -- private final io.dropwizard.metrics5.health.HealthCheck.Result delegate; -+ public static HealthCheck.Result unhealthy(Throwable error) { -+ return new Result(io.dropwizard.metrics5.health.HealthCheck.Result.unhealthy(error)); -+ } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- private Result(io.dropwizard.metrics5.health.HealthCheck.Result delegate) { -- this.delegate = delegate; -- } -+ public static HealthCheck.Result of(io.dropwizard.metrics5.health.HealthCheck.Result delegate) { -+ return new Result(delegate); -+ } +-class AdminServletTest extends AbstractServletTest { ++final class AdminServletTest extends AbstractServletTest { + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -- private Result(io.dropwizard.metrics5.health.HealthCheck.ResultBuilder builder) { -- this.delegate = builder.build(); -- } -+ public static HealthCheck.ResultBuilder builder() { -+ return new HealthCheck.ResultBuilder(); -+ } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- public boolean isHealthy() { -- return delegate.isHealthy(); -- } -+ private final io.dropwizard.metrics5.health.HealthCheck.Result delegate; +-class AdminServletUriTest extends AbstractServletTest { ++final class AdminServletUriTest extends AbstractServletTest { + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -- public String getMessage() { -- return delegate.getMessage(); -- } -+ private Result(io.dropwizard.metrics5.health.HealthCheck.Result delegate) { -+ this.delegate = delegate; -+ } +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- public Throwable getError() { -- return delegate.getError(); -- } -+ private Result(io.dropwizard.metrics5.health.HealthCheck.ResultBuilder builder) { -+ this.delegate = builder.build(); -+ } +-class CpuProfileServletTest extends AbstractServletTest { ++final class CpuProfileServletTest extends AbstractServletTest { -- public String getTimestamp() { -- return delegate.getTimestamp(); -- } -+ public boolean isHealthy() { -+ return delegate.isHealthy(); -+ } + @Override + protected void setUp(ServletTester tester) { +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +@@ -1,10 +1,9 @@ + package io.dropwizard.metrics5.servlets; -- public Map getDetails() { -- return delegate.getDetails(); -- } -+ public String getMessage() { -+ return delegate.getMessage(); -+ } + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; -- public io.dropwizard.metrics5.health.HealthCheck.Result getDelegate() { -- return delegate; -- } -+ public Throwable getError() { -+ return delegate.getError(); -+ } - -- @Override -- public boolean equals(Object o) { -- if (o instanceof Result) { -- final Result that = (Result) o; -- return Objects.equals(delegate, that.delegate); -- } -- return false; -- } -+ public String getTimestamp() { -+ return delegate.getTimestamp(); -+ } +@@ -27,7 +26,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- @Override -- public int hashCode() { -- return Objects.hash(delegate); -- } -+ public Map getDetails() { -+ return delegate.getDetails(); -+ } +-class HealthCheckServletTest extends AbstractServletTest { ++final class HealthCheckServletTest extends AbstractServletTest { -- @Override -- public String toString() { -- return delegate.toString(); -- } -+ public io.dropwizard.metrics5.health.HealthCheck.Result getDelegate() { -+ return delegate; - } + private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); -- public static class ResultBuilder { -+ @Override -+ public boolean equals(Object o) { -+ if (o instanceof Result) { -+ final Result that = (Result) o; -+ return Objects.equals(delegate, that.delegate); -+ } -+ return false; -+ } - -- private io.dropwizard.metrics5.health.HealthCheck.ResultBuilder delegate; -+ @Override -+ public int hashCode() { -+ return Objects.hash(delegate); -+ } - -- protected ResultBuilder() { -- delegate = io.dropwizard.metrics5.health.HealthCheck.Result.builder(); -- } -+ @Override -+ public String toString() { -+ return delegate.toString(); -+ } -+ } - -- public HealthCheck.ResultBuilder healthy() { -- delegate.healthy(); -- return this; -- } -+ public static class ResultBuilder { +@@ -95,9 +94,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } -- public HealthCheck.ResultBuilder unhealthy() { -- delegate.unhealthy(); -- return this; -- } -+ private io.dropwizard.metrics5.health.HealthCheck.ResultBuilder delegate; + @Test +@@ -111,9 +109,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } -- public HealthCheck.ResultBuilder unhealthy(Throwable error) { -- delegate.unhealthy(error); -- return this; -- } -+ protected ResultBuilder() { -+ delegate = io.dropwizard.metrics5.health.HealthCheck.Result.builder(); -+ } + @Test +@@ -168,15 +165,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getContent()) + .isEqualTo( + String.format( +- "{%n" +- + " \"fun\" : {%n" +- + " \"healthy\" : true,%n" +- + " \"message\" : \"foo bar 123\",%n" +- + " \"duration\" : 0,%n" +- + " \"timestamp\" : \"" +- + EXPECTED_TIMESTAMP +- + "\"" +- + "%n }%n}")); ++ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", ++ EXPECTED_TIMESTAMP)); + } -- public HealthCheck.ResultBuilder withMessage(String message) { -- delegate.withMessage(message); -- return this; -- } -+ public HealthCheck.ResultBuilder healthy() { -+ delegate.healthy(); -+ return this; -+ } - -- public HealthCheck.ResultBuilder withMessage(String message, Object... args) { -- delegate.withMessage(message, args); -- return this; -- } -+ public HealthCheck.ResultBuilder unhealthy() { -+ delegate.unhealthy(); -+ return this; -+ } - -- public HealthCheck.ResultBuilder withDetail(String key, Object data) { -- delegate.withDetail(key, data); -- return this; -- } -+ public HealthCheck.ResultBuilder unhealthy(Throwable error) { -+ delegate.unhealthy(error); -+ return this; -+ } + private static HealthCheck.Result healthyResultWithMessage(String message) { +@@ -197,23 +187,23 @@ class HealthCheckServletTest extends AbstractServletTest { -- public HealthCheck.Result build() { -- return new HealthCheck.Result(delegate); -- } -+ public HealthCheck.ResultBuilder withMessage(String message) { -+ delegate.withMessage(message); -+ return this; - } + @Test + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); -- protected abstract HealthCheck.Result check() throws Exception; -+ public HealthCheck.ResultBuilder withMessage(String message, Object... args) { -+ delegate.withMessage(message, args); -+ return this; -+ } - -- public HealthCheck.Result execute() { -- try { -- return check(); -- } catch (Exception e) { -- return HealthCheck.Result.unhealthy(e); -- } -+ public HealthCheck.ResultBuilder withDetail(String key, Object data) { -+ delegate.withDetail(key, data); -+ return this; - } + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); + healthCheckServlet.init(servletConfig); -- public io.dropwizard.metrics5.health.HealthCheck transform() { -- final HealthCheck original = this; -- return () -> original.check().delegate; -+ public HealthCheck.Result build() { -+ return new HealthCheck.Result(delegate); - } -+ } -+ -+ protected abstract HealthCheck.Result check() throws Exception; - -- public static HealthCheck of(io.dropwizard.metrics5.health.HealthCheck delegate) { -- return new HealthCheck() { -- @Override -- protected Result check() throws Exception { -- return new Result(delegate.execute()); -- } -- }; -+ public HealthCheck.Result execute() { -+ try { -+ return check(); -+ } catch (Exception e) { -+ return HealthCheck.Result.unhealthy(e); - } -+ } -+ -+ public io.dropwizard.metrics5.health.HealthCheck transform() { -+ final HealthCheck original = this; -+ return () -> original.check().delegate; -+ } +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(healthCheckRegistry); +@@ -221,32 +211,32 @@ class HealthCheckServletTest extends AbstractServletTest { + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- assertThrows( +- ServletException.class, +- () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) +- .thenReturn("IRELLEVANT_STRING"); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); +- }); ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn("IRELLEVANT_STRING"); + -+ public static HealthCheck of(io.dropwizard.metrics5.health.HealthCheck delegate) { -+ return new HealthCheck() { -+ @Override -+ protected Result check() throws Exception { -+ return new Result(delegate.execute()); -+ } -+ }; -+ } - } ---- a/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckFilter.java -+++ b/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckFilter.java -@@ -3,12 +3,12 @@ package com.codahale.metrics.health; - @Deprecated - public interface HealthCheckFilter { ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); + } -- HealthCheckFilter ALL = (name, healthCheck) -> true; -+ HealthCheckFilter ALL = (name, healthCheck) -> true; + @Test + void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(registry); +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +@@ -17,8 +17,8 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- boolean matches(String name, HealthCheck healthCheck); -+ boolean matches(String name, HealthCheck healthCheck); +-class MetricsServletContextListenerTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++final class MetricsServletContextListenerTest extends AbstractServletTest { ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final String allowedOrigin = "some.other.origin"; -- default io.dropwizard.metrics5.health.HealthCheckFilter transform() { -- final HealthCheckFilter origin = this; -- return (name, healthCheck) -> origin.matches(name, HealthCheck.of(healthCheck)); -- } -+ default io.dropwizard.metrics5.health.HealthCheckFilter transform() { -+ final HealthCheckFilter origin = this; -+ return (name, healthCheck) -> origin.matches(name, HealthCheck.of(healthCheck)); -+ } - } ---- a/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java -+++ b/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistry.java -@@ -11,79 +11,80 @@ import java.util.concurrent.ScheduledExecutorService; - @Deprecated - public class HealthCheckRegistry { +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +@@ -1,11 +1,9 @@ + package io.dropwizard.metrics5.servlets; -- private final io.dropwizard.metrics5.health.HealthCheckRegistry delegate; -- -- public HealthCheckRegistry() { -- this(new io.dropwizard.metrics5.health.HealthCheckRegistry()); -- } -- -- public HealthCheckRegistry(int asyncExecutorPoolSize) { -- this(new io.dropwizard.metrics5.health.HealthCheckRegistry(asyncExecutorPoolSize)); -- } -- -- public HealthCheckRegistry(ScheduledExecutorService asyncExecutorService) { -- this(new io.dropwizard.metrics5.health.HealthCheckRegistry(asyncExecutorService)); -- } -- -- private HealthCheckRegistry(io.dropwizard.metrics5.health.HealthCheckRegistry delegate) { -- this.delegate = delegate; -- } -- -- public static HealthCheckRegistry of(io.dropwizard.metrics5.health.HealthCheckRegistry reg) { -- return new HealthCheckRegistry(reg); -- } -- -- public void addListener(HealthCheckRegistryListener listener) { -- delegate.addListener(listener.transform()); -- } -- -- public void removeListener(HealthCheckRegistryListener listener) { -- delegate.removeListener(listener.transform()); -- } -- -- public void register(String name, HealthCheck healthCheck) { -- delegate.register(name, healthCheck.transform()); -- } -- -- public void unregister(String name) { -- delegate.unregister(name); -- } -- -- public SortedSet getNames() { -- return delegate.getNames(); -- } -- -- public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException { -- return HealthCheck.Result.of(delegate.runHealthCheck(name)); -- } -- -- public SortedMap runHealthChecks() { -- return convertHealthChecks(delegate.runHealthChecks()); -- } -- -- public SortedMap runHealthChecks(HealthCheckFilter filter) { -- return convertHealthChecks(delegate.runHealthChecks(filter.transform())); -- } -- -- public SortedMap runHealthChecks(ExecutorService executor) { -- return convertHealthChecks(delegate.runHealthChecks(executor)); -- } -- -- public SortedMap runHealthChecks(ExecutorService executor, -- HealthCheckFilter filter) { -- return convertHealthChecks(delegate.runHealthChecks(executor, filter.transform())); -- } -- -- private SortedMap convertHealthChecks( -- SortedMap originResults) { -- final SortedMap results = new TreeMap<>(); -- for (Map.Entry entry : originResults.entrySet()) { -- results.put(entry.getKey(), HealthCheck.Result.of(entry.getValue())); -- } -- return results; -- } -- -- public void shutdown() { -- delegate.shutdown(); -- } -+ private final io.dropwizard.metrics5.health.HealthCheckRegistry delegate; -+ -+ public HealthCheckRegistry() { -+ this(new io.dropwizard.metrics5.health.HealthCheckRegistry()); -+ } -+ -+ public HealthCheckRegistry(int asyncExecutorPoolSize) { -+ this(new io.dropwizard.metrics5.health.HealthCheckRegistry(asyncExecutorPoolSize)); -+ } -+ -+ public HealthCheckRegistry(ScheduledExecutorService asyncExecutorService) { -+ this(new io.dropwizard.metrics5.health.HealthCheckRegistry(asyncExecutorService)); -+ } -+ -+ private HealthCheckRegistry(io.dropwizard.metrics5.health.HealthCheckRegistry delegate) { -+ this.delegate = delegate; -+ } -+ -+ public static HealthCheckRegistry of(io.dropwizard.metrics5.health.HealthCheckRegistry reg) { -+ return new HealthCheckRegistry(reg); -+ } -+ -+ public void addListener(HealthCheckRegistryListener listener) { -+ delegate.addListener(listener.transform()); -+ } -+ -+ public void removeListener(HealthCheckRegistryListener listener) { -+ delegate.removeListener(listener.transform()); -+ } -+ -+ public void register(String name, HealthCheck healthCheck) { -+ delegate.register(name, healthCheck.transform()); -+ } -+ -+ public void unregister(String name) { -+ delegate.unregister(name); -+ } -+ -+ public SortedSet getNames() { -+ return delegate.getNames(); -+ } -+ -+ public HealthCheck.Result runHealthCheck(String name) throws NoSuchElementException { -+ return HealthCheck.Result.of(delegate.runHealthCheck(name)); -+ } -+ -+ public SortedMap runHealthChecks() { -+ return convertHealthChecks(delegate.runHealthChecks()); -+ } -+ -+ public SortedMap runHealthChecks(HealthCheckFilter filter) { -+ return convertHealthChecks(delegate.runHealthChecks(filter.transform())); -+ } -+ -+ public SortedMap runHealthChecks(ExecutorService executor) { -+ return convertHealthChecks(delegate.runHealthChecks(executor)); -+ } -+ -+ public SortedMap runHealthChecks( -+ ExecutorService executor, HealthCheckFilter filter) { -+ return convertHealthChecks(delegate.runHealthChecks(executor, filter.transform())); -+ } -+ -+ private SortedMap convertHealthChecks( -+ SortedMap originResults) { -+ final SortedMap results = new TreeMap<>(); -+ for (Map.Entry entry : -+ originResults.entrySet()) { -+ results.put(entry.getKey(), HealthCheck.Result.of(entry.getValue())); -+ } -+ return results; -+ } -+ -+ public void shutdown() { -+ delegate.shutdown(); -+ } - } ---- a/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistryListener.java -+++ b/metrics-legacy-adapter-healthchecks/src/main/java/com/codahale/metrics/health/HealthCheckRegistryListener.java -@@ -6,44 +6,46 @@ import java.util.Objects; - @Deprecated - public interface HealthCheckRegistryListener extends EventListener { + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.mockito.ArgumentMatchers.eq; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; -- void onHealthCheckAdded(String name, HealthCheck healthCheck); -+ void onHealthCheckAdded(String name, HealthCheck healthCheck); +@@ -25,8 +23,8 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- void onHealthCheckRemoved(String name, HealthCheck healthCheck); -+ void onHealthCheckRemoved(String name, HealthCheck healthCheck); +-class MetricsServletTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++final class MetricsServletTest extends AbstractServletTest { ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private ServletTester tester; + +@@ -130,22 +128,8 @@ class MetricsServletTest extends AbstractServletTest { + assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); + assertThat(response.getContent()) + .isEqualTo( +- callbackParamVal +- + "({" +- + "\"version\":\"5.0.0\"," +- + "\"gauges\":{" +- + "\"g1\":{\"value\":100}" +- + "}," +- + "\"counters\":{" +- + "\"c\":{\"count\":1}" +- + "}," +- + "\"histograms\":{" +- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" +- + "}," +- + "\"meters\":{" +- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" +- + "}" +- + "})"); ++ "%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", ++ callbackParamVal); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } -- default io.dropwizard.metrics5.health.HealthCheckRegistryListener transform() { -- return new Adapter(this); -+ default io.dropwizard.metrics5.health.HealthCheckRegistryListener transform() { -+ return new Adapter(this); -+ } -+ -+ class Adapter implements io.dropwizard.metrics5.health.HealthCheckRegistryListener { -+ -+ private final HealthCheckRegistryListener delegate; -+ -+ public Adapter(HealthCheckRegistryListener delegate) { -+ this.delegate = delegate; -+ } -+ -+ @Override -+ public void onHealthCheckAdded( -+ String name, io.dropwizard.metrics5.health.HealthCheck healthCheck) { -+ delegate.onHealthCheckAdded(name, HealthCheck.of(healthCheck)); -+ } -+ -+ @Override -+ public void onHealthCheckRemoved( -+ String name, io.dropwizard.metrics5.health.HealthCheck healthCheck) { -+ delegate.onHealthCheckRemoved(name, HealthCheck.of(healthCheck)); -+ } -+ -+ @Override -+ public boolean equals(Object o) { -+ if (o instanceof Adapter) { -+ final Adapter that = (Adapter) o; -+ return Objects.equals(delegate, that.delegate); -+ } -+ return false; - } +@@ -224,48 +208,47 @@ class MetricsServletTest extends AbstractServletTest { -- class Adapter implements io.dropwizard.metrics5.health.HealthCheckRegistryListener { -- -- private final HealthCheckRegistryListener delegate; -- -- public Adapter(HealthCheckRegistryListener delegate) { -- this.delegate = delegate; -- } -- -- @Override -- public void onHealthCheckAdded(String name, io.dropwizard.metrics5.health.HealthCheck healthCheck) { -- delegate.onHealthCheckAdded(name, HealthCheck.of(healthCheck)); -- } -- -- @Override -- public void onHealthCheckRemoved(String name, io.dropwizard.metrics5.health.HealthCheck healthCheck) { -- delegate.onHealthCheckRemoved(name, HealthCheck.of(healthCheck)); -- } -- -- @Override -- public boolean equals(Object o) { -- if (o instanceof Adapter) { -- final Adapter that = (Adapter) o; -- return Objects.equals(delegate, that.delegate); -- } -- return false; -- } -- -- @Override -- public int hashCode() { -- return Objects.hash(delegate); -- } -+ @Override -+ public int hashCode() { -+ return Objects.hash(delegate); - } -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CachedGauge.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CachedGauge.java -@@ -1,42 +1,43 @@ - package com.codahale.metrics; + @Test + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); --import java.util.concurrent.TimeUnit; -- - import static java.util.Objects.requireNonNull; + final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn(metricRegistry); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); -+import java.util.concurrent.TimeUnit; -+ - @Deprecated - public abstract class CachedGauge implements Gauge { + final MetricsServlet metricsServlet = new MetricsServlet(null); + metricsServlet.init(servletConfig); -- private final io.dropwizard.metrics5.CachedGauge gauge; -+ private final io.dropwizard.metrics5.CachedGauge gauge; +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); + } -- public CachedGauge(io.dropwizard.metrics5.CachedGauge gauge) { -- this.gauge = requireNonNull(gauge); -- } -+ public CachedGauge(io.dropwizard.metrics5.CachedGauge gauge) { -+ this.gauge = requireNonNull(gauge); -+ } - -- protected CachedGauge(long timeout, TimeUnit timeoutUnit) { -- final CachedGauge original = this; -- gauge = new io.dropwizard.metrics5.CachedGauge(timeout, timeoutUnit) { -- @Override -- protected T loadValue() { -- return original.loadValue(); -- } -+ protected CachedGauge(long timeout, TimeUnit timeoutUnit) { -+ final CachedGauge original = this; -+ gauge = -+ new io.dropwizard.metrics5.CachedGauge(timeout, timeoutUnit) { -+ @Override -+ protected T loadValue() { -+ return original.loadValue(); -+ } - }; -- } -- -- protected CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit) { -- final CachedGauge original = this; -- gauge = new io.dropwizard.metrics5.CachedGauge(clock.getDelegate(), timeout, timeoutUnit) { -- @Override -- protected T loadValue() { -- return original.loadValue(); -- } -+ } + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- assertThrows( +- ServletException.class, +- () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn("IRELLEVANT_STRING"); +- +- final MetricsServlet metricsServlet = new MetricsServlet(null); +- metricsServlet.init(servletConfig); +- }); ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) ++ .thenReturn("IRELLEVANT_STRING"); + -+ protected CachedGauge(Clock clock, long timeout, TimeUnit timeoutUnit) { -+ final CachedGauge original = this; -+ gauge = -+ new io.dropwizard.metrics5.CachedGauge(clock.getDelegate(), timeout, timeoutUnit) { -+ @Override -+ protected T loadValue() { -+ return original.loadValue(); -+ } - }; -- } -- -- protected abstract T loadValue(); -+ } - -- public T getValue() { -- return gauge.getValue(); -- } -+ protected abstract T loadValue(); - -+ public T getValue() { -+ return gauge.getValue(); -+ } ++ final MetricsServlet metricsServlet = new MetricsServlet(null); ++ metricsServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); + } } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Clock.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Clock.java -@@ -3,64 +3,65 @@ package com.codahale.metrics; - @Deprecated - public abstract class Clock { +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- public abstract long getTick(); -+ public abstract long getTick(); +-class PingServletTest extends AbstractServletTest { ++final class PingServletTest extends AbstractServletTest { + @Override + protected void setUp(ServletTester tester) { + tester.addServlet(PingServlet.class, "/ping"); +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- public long getTime() { -- return System.currentTimeMillis(); -- } -- -- public io.dropwizard.metrics5.Clock getDelegate() { -- if (this instanceof DelegateClock) { -- return ((DelegateClock) this).delegate; -- } -- final Clock original = this; -- return new io.dropwizard.metrics5.Clock() { -- @Override -- public long getTick() { -- return original.getTick(); -- } -+ public long getTime() { -+ return System.currentTimeMillis(); -+ } - -- @Override -- public long getTime() { -- return original.getTime(); -- } -- }; -+ public io.dropwizard.metrics5.Clock getDelegate() { -+ if (this instanceof DelegateClock) { -+ return ((DelegateClock) this).delegate; - } -+ final Clock original = this; -+ return new io.dropwizard.metrics5.Clock() { -+ @Override -+ public long getTick() { -+ return original.getTick(); -+ } - -- public static Clock of(io.dropwizard.metrics5.Clock delegate) { -- return new DelegateClock(delegate); -- } -+ @Override -+ public long getTime() { -+ return original.getTime(); -+ } -+ }; -+ } - -- public static Clock defaultClock() { -- return of(io.dropwizard.metrics5.Clock.defaultClock()); -- } -+ public static Clock of(io.dropwizard.metrics5.Clock delegate) { -+ return new DelegateClock(delegate); -+ } +-class ThreadDumpServletTest extends AbstractServletTest { ++final class ThreadDumpServletTest extends AbstractServletTest { + @Override + protected void setUp(ServletTester tester) { + tester.addServlet(ThreadDumpServlet.class, "/threads"); +--- a/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java ++++ b/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics5.jcache; -- public static class UserTimeClock extends Clock { -+ public static Clock defaultClock() { -+ return of(io.dropwizard.metrics5.Clock.defaultClock()); -+ } + import static io.dropwizard.metrics5.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; -- private final io.dropwizard.metrics5.Clock delegate = new io.dropwizard.metrics5.Clock.UserTimeClock(); -+ public static class UserTimeClock extends Clock { + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; +@@ -9,7 +10,6 @@ import io.dropwizard.metrics5.jvm.JmxAttributeGauge; + import java.lang.management.ManagementFactory; + import java.lang.reflect.Method; + import java.util.ArrayList; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Locale; +@@ -33,7 +33,7 @@ public class JCacheGaugeSet implements MetricSet { + private static final String M_BEAN_COORDINATES = + "javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"; -- @Override -- public long getTick() { -- return delegate.getTick(); -- } -+ private final io.dropwizard.metrics5.Clock delegate = -+ new io.dropwizard.metrics5.Clock.UserTimeClock(); +- private static final Logger LOGGER = LoggerFactory.getLogger(JCacheGaugeSet.class); ++ private static final Logger LOG = LoggerFactory.getLogger(JCacheGaugeSet.class); -- @Override -- public long getTime() { -- return delegate.getTime(); -- } -+ @Override -+ public long getTick() { -+ return delegate.getTick(); + @Override + public Map getMetrics() { +@@ -52,7 +52,7 @@ public class JCacheGaugeSet implements MetricSet { + } } -- private static class DelegateClock extends Clock { -+ @Override -+ public long getTime() { -+ return delegate.getTime(); -+ } -+ } - -- private final io.dropwizard.metrics5.Clock delegate; -+ private static class DelegateClock extends Clock { - -- private DelegateClock(io.dropwizard.metrics5.Clock delegate) { -- this.delegate = delegate; -- } -+ private final io.dropwizard.metrics5.Clock delegate; -+ -+ private DelegateClock(io.dropwizard.metrics5.Clock delegate) { -+ this.delegate = delegate; -+ } +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } -- @Override -- public long getTick() { -- return delegate.getTick(); -- } -+ @Override -+ public long getTick() { -+ return delegate.getTick(); + private Set getCacheBeans() { +@@ -60,7 +60,7 @@ public class JCacheGaugeSet implements MetricSet { + return ManagementFactory.getPlatformMBeanServer() + .queryMBeans(ObjectName.getInstance(M_BEAN_COORDINATES), null); + } catch (MalformedObjectNameException e) { +- LOGGER.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); ++ LOG.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); + throw new RuntimeException(e); } -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ConsoleReporter.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ConsoleReporter.java -@@ -11,83 +11,91 @@ import java.util.concurrent.TimeUnit; - @Deprecated - public class ConsoleReporter extends ScheduledReporter { + } +--- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java ++++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java +@@ -11,7 +11,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- public static Builder forRegistry(MetricRegistry registry) { -- return new Builder(registry); -+ public static Builder forRegistry(MetricRegistry registry) { -+ return new Builder(registry); -+ } -+ -+ public static class Builder { -+ -+ private io.dropwizard.metrics5.ConsoleReporter.Builder delegate; -+ -+ private Builder(MetricRegistry metricRegistry) { -+ delegate = io.dropwizard.metrics5.ConsoleReporter.forRegistry(metricRegistry.getDelegate()); -+ } -+ -+ public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -+ delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); -+ return this; -+ } -+ -+ public Builder scheduleOn(ScheduledExecutorService executor) { -+ delegate.scheduleOn(executor); -+ return this; -+ } -+ -+ public Builder outputTo(PrintStream output) { -+ delegate.outputTo(output); -+ return this; -+ } -+ -+ public Builder formattedFor(Locale locale) { -+ delegate.formattedFor(locale); -+ return this; -+ } -+ -+ public Builder withClock(Clock clock) { -+ delegate.withClock(clock.getDelegate()); -+ return this; -+ } -+ -+ public Builder formattedFor(TimeZone timeZone) { -+ delegate.formattedFor(timeZone); -+ return this; -+ } -+ -+ public Builder convertRatesTo(TimeUnit rateUnit) { -+ delegate.convertRatesTo(rateUnit); -+ return this; -+ } -+ -+ public Builder convertDurationsTo(TimeUnit durationUnit) { -+ delegate.convertDurationsTo(durationUnit); -+ return this; - } +-class JCacheGaugeSetTest { ++final class JCacheGaugeSetTest { -- public static class Builder { -- -- private io.dropwizard.metrics5.ConsoleReporter.Builder delegate; -- -- private Builder(MetricRegistry metricRegistry) { -- delegate = io.dropwizard.metrics5.ConsoleReporter.forRegistry(metricRegistry.getDelegate()); -- } -- -- public Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -- delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); -- return this; -- } -- -- public Builder scheduleOn(ScheduledExecutorService executor) { -- delegate.scheduleOn(executor); -- return this; -- } -- -- public Builder outputTo(PrintStream output) { -- delegate.outputTo(output); -- return this; -- } -- -- public Builder formattedFor(Locale locale) { -- delegate.formattedFor(locale); -- return this; -- } -- -- public Builder withClock(Clock clock) { -- delegate.withClock(clock.getDelegate()); -- return this; -- } -- -- public Builder formattedFor(TimeZone timeZone) { -- delegate.formattedFor(timeZone); -- return this; -- } -- -- public Builder convertRatesTo(TimeUnit rateUnit) { -- delegate.convertRatesTo(rateUnit); -- return this; -- } -- -- public Builder convertDurationsTo(TimeUnit durationUnit) { -- delegate.convertDurationsTo(durationUnit); -- return this; -- } -- -- public Builder filter(MetricFilter filter) { -- delegate.filter(filter.transform()); -- return this; -- } -- -- public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -- delegate.disabledMetricAttributes(MetricAttribute.transform(disabledMetricAttributes)); -- return this; -- } -- -- public ConsoleReporter build() { -- return new ConsoleReporter(delegate.build()); -- } -+ public Builder filter(MetricFilter filter) { -+ delegate.filter(filter.transform()); -+ return this; - } + private MetricRegistry registry; + private Cache myCache; +@@ -67,11 +67,11 @@ class JCacheGaugeSetTest { -- private ConsoleReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { -- super(delegate); -+ public Builder disabledMetricAttributes(Set disabledMetricAttributes) { -+ delegate.disabledMetricAttributes(MetricAttribute.transform(disabledMetricAttributes)); -+ return this; - } + this.myCache.remove("woo2"); + assertThat((Float) registry.getGauges().get(myCache.resolve("average-get-time")).getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + assertThat((Float) registry.getGauges().get(myCache.resolve("average-put-time")).getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + assertThat((Float) registry.getGauges().get(myCache.resolve("average-remove-time")).getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + } + + @AfterEach +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.jdbi3.strategies; -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap gauges, SortedMap counters, -- SortedMap histograms, SortedMap meters, -- SortedMap timers) { -- getDelegate().report(transform(gauges), transform(counters), transform(histograms), transform(meters), -- transform(timers)); -+ public ConsoleReporter build() { -+ return new ConsoleReporter(delegate.build()); ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.jdbi.v3.core.extension.ExtensionMethod; +@@ -13,7 +14,7 @@ public enum DefaultNameStrategy implements StatementNameStrategy { + @Override + public MetricName getStatementName(StatementContext statementContext) { + final String rawSql = statementContext.getRawSql(); +- return rawSql == null || rawSql.isEmpty() ? MetricName.build("sql.empty") : null; ++ return Strings.isNullOrEmpty(rawSql) ? MetricName.build("sql.empty") : null; } -+ } -+ -+ private ConsoleReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { -+ super(delegate); -+ } -+ -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ getDelegate() -+ .report( -+ transform(gauges), -+ transform(counters), -+ transform(histograms), -+ transform(meters), -+ transform(timers)); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Counter.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Counter.java -@@ -5,40 +5,39 @@ import static java.util.Objects.requireNonNull; - @Deprecated - public class Counter implements Metric, Counting { + }, -- private final io.dropwizard.metrics5.Counter counter; -+ private final io.dropwizard.metrics5.Counter counter; +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java +@@ -8,7 +8,7 @@ import io.dropwizard.metrics5.MetricName; + import org.jdbi.v3.core.extension.ExtensionMethod; + import org.junit.jupiter.api.Test; -- public Counter() { -- this(new io.dropwizard.metrics5.Counter()); -- } -+ public Counter() { -+ this(new io.dropwizard.metrics5.Counter()); -+ } +-class BasicSqlNameStrategyTest extends AbstractStrategyTest { ++final class BasicSqlNameStrategyTest extends AbstractStrategyTest { -- public Counter(io.dropwizard.metrics5.Counter counter) { -- this.counter = requireNonNull(counter); -- } -+ public Counter(io.dropwizard.metrics5.Counter counter) { -+ this.counter = requireNonNull(counter); -+ } + private final BasicSqlNameStrategy basicSqlNameStrategy = new BasicSqlNameStrategy(); -- public void inc() { -- counter.inc(); -- } -+ public void inc() { -+ counter.inc(); -+ } +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java +@@ -12,15 +12,15 @@ import java.util.concurrent.TimeUnit; + import org.jdbi.v3.core.statement.StatementContext; + import org.junit.jupiter.api.Test; -- public void inc(long n) { -- counter.inc(n); -- } -+ public void inc(long n) { -+ counter.inc(n); -+ } +-class InstrumentedSqlLoggerTest { ++final class InstrumentedSqlLoggerTest { + @Test + void logsExecutionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); + final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); -- public void dec() { -- counter.dec(); -- } -+ public void dec() { -+ counter.dec(); -+ } +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); -- public void dec(long n) { -- counter.dec(n); -- } -+ public void dec(long n) { -+ counter.dec(n); -+ } + final MetricName statementName = MetricName.build("my-fake-name"); + final long fakeElapsed = 1234L; +@@ -37,12 +37,12 @@ class InstrumentedSqlLoggerTest { -- @Override -- public long getCount() { -- return counter.getCount(); -- } -- -- @Override -- public io.dropwizard.metrics5.Counter getDelegate() { -- return counter; -- } -+ @Override -+ public long getCount() { -+ return counter.getCount(); -+ } - -+ @Override -+ public io.dropwizard.metrics5.Counter getDelegate() { -+ return counter; -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Counting.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Counting.java -@@ -3,5 +3,5 @@ package com.codahale.metrics; - @Deprecated - public interface Counting { + @Test + void logsExceptionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); + final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); -- long getCount(); -+ long getCount(); - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CsvFileProvider.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CsvFileProvider.java -@@ -5,5 +5,5 @@ import java.io.File; - @Deprecated - public interface CsvFileProvider { +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); -- File getFile(File directory, String metricName); -+ File getFile(File directory, String metricName); - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CsvReporter.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/CsvReporter.java -@@ -9,80 +9,86 @@ import java.util.concurrent.TimeUnit; - @Deprecated - public class CsvReporter extends ScheduledReporter { + final MetricName statementName = MetricName.build("my-fake-name"); + final long fakeElapsed = 1234L; +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java +@@ -5,7 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; + import io.dropwizard.metrics5.MetricName; + import org.junit.jupiter.api.Test; -- public static Builder forRegistry(MetricRegistry registry) { -- return new Builder(registry); -- } -- -- public static class Builder { -- -- private io.dropwizard.metrics5.CsvReporter.Builder delegate; -- -- private Builder(MetricRegistry metricRegistry) { -- delegate = io.dropwizard.metrics5.CsvReporter.forRegistry(metricRegistry.getDelegate()); -- } -+ public static Builder forRegistry(MetricRegistry registry) { -+ return new Builder(registry); -+ } +-class NaiveNameStrategyTest extends AbstractStrategyTest { ++final class NaiveNameStrategyTest extends AbstractStrategyTest { -- public CsvReporter.Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -- delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); -- return this; -- } -+ public static class Builder { + private final NaiveNameStrategy naiveNameStrategy = new NaiveNameStrategy(); -+ private io.dropwizard.metrics5.CsvReporter.Builder delegate; +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java +@@ -12,7 +12,7 @@ import org.jdbi.v3.core.extension.ExtensionMethod; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- public CsvReporter.Builder scheduleOn(ScheduledExecutorService executor) { -- delegate.scheduleOn(executor); -- return this; -- } -- -- public CsvReporter.Builder formatFor(Locale locale) { -- delegate.formatFor(locale); -- return this; -- } -+ private Builder(MetricRegistry metricRegistry) { -+ delegate = io.dropwizard.metrics5.CsvReporter.forRegistry(metricRegistry.getDelegate()); -+ } - -+ public CsvReporter.Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -+ delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); -+ return this; -+ } - -- public CsvReporter.Builder convertRatesTo(TimeUnit rateUnit) { -- delegate.convertRatesTo(rateUnit); -- return this; -- } -+ public CsvReporter.Builder scheduleOn(ScheduledExecutorService executor) { -+ delegate.scheduleOn(executor); -+ return this; -+ } - -- public CsvReporter.Builder convertDurationsTo(TimeUnit durationUnit) { -- delegate.convertDurationsTo(durationUnit); -- return this; -- } -+ public CsvReporter.Builder formatFor(Locale locale) { -+ delegate.formatFor(locale); -+ return this; -+ } - -- public CsvReporter.Builder withSeparator(String separator) { -- delegate.withSeparator(separator); -- return this; -- } -+ public CsvReporter.Builder convertRatesTo(TimeUnit rateUnit) { -+ delegate.convertRatesTo(rateUnit); -+ return this; -+ } - -- public CsvReporter.Builder withClock(Clock clock) { -- delegate.withClock(clock.getDelegate()); -- return this; -- } -+ public CsvReporter.Builder convertDurationsTo(TimeUnit durationUnit) { -+ delegate.convertDurationsTo(durationUnit); -+ return this; -+ } - -- public CsvReporter.Builder filter(MetricFilter filter) { -- delegate.filter(filter.transform()); -- return this; -- } -+ public CsvReporter.Builder withSeparator(String separator) { -+ delegate.withSeparator(separator); -+ return this; -+ } - -- public Builder withCsvFileProvider(CsvFileProvider csvFileProvider) { -- delegate.withCsvFileProvider(csvFileProvider::getFile); -- return this; -- } -+ public CsvReporter.Builder withClock(Clock clock) { -+ delegate.withClock(clock.getDelegate()); -+ return this; -+ } +-class SmartNameStrategyTest extends AbstractStrategyTest { ++final class SmartNameStrategyTest extends AbstractStrategyTest { -- public CsvReporter build(File directory) { -- return new CsvReporter(delegate.build(directory)); -- } -+ public CsvReporter.Builder filter(MetricFilter filter) { -+ delegate.filter(filter.transform()); -+ return this; - } -- -- public CsvReporter(io.dropwizard.metrics5.CsvReporter delegate) { -- super(delegate); -+ -+ public Builder withCsvFileProvider(CsvFileProvider csvFileProvider) { -+ delegate.withCsvFileProvider(csvFileProvider::getFile); -+ return this; - } + private final StatementNameStrategy smartNameStrategy = new SmartNameStrategy(); + private InstrumentedTimingCollector collector; +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java +@@ -8,7 +8,7 @@ import io.dropwizard.metrics5.annotation.Timed; + import org.jdbi.v3.core.extension.ExtensionMethod; + import org.junit.jupiter.api.Test; -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap gauges, SortedMap counters, -- SortedMap histograms, SortedMap meters, -- SortedMap timers) { -- getDelegate().report(transform(gauges), transform(counters), transform(histograms), transform(meters), -- transform(timers)); -+ public CsvReporter build(File directory) { -+ return new CsvReporter(delegate.build(directory)); - } -+ } -+ -+ public CsvReporter(io.dropwizard.metrics5.CsvReporter delegate) { -+ super(delegate); -+ } -+ -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ getDelegate() -+ .report( -+ transform(gauges), -+ transform(counters), -+ transform(histograms), -+ transform(meters), -+ transform(timers)); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/DerivativeGauge.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/DerivativeGauge.java -@@ -3,22 +3,23 @@ package com.codahale.metrics; - @Deprecated - public abstract class DerivativeGauge implements Gauge { - -- private final io.dropwizard.metrics5.DerivativeGauge delegate; -+ private final io.dropwizard.metrics5.DerivativeGauge delegate; - -- protected DerivativeGauge(Gauge base) { -- DerivativeGauge original = this; -- delegate = new io.dropwizard.metrics5.DerivativeGauge(base.getDelegate()) { -- @Override -- protected T transform(F value) { -- return original.transform(base.getValue()); -- } -+ protected DerivativeGauge(Gauge base) { -+ DerivativeGauge original = this; -+ delegate = -+ new io.dropwizard.metrics5.DerivativeGauge(base.getDelegate()) { -+ @Override -+ protected T transform(F value) { -+ return original.transform(base.getValue()); -+ } - }; -- } -+ } +-class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { ++final class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { -- protected abstract T transform(F value); -+ protected abstract T transform(F value); + private final TimedAnnotationNameStrategy timedAnnotationNameStrategy = + new TimedAnnotationNameStrategy(); +@@ -44,7 +44,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } -- @Override -- public T getValue() { -- return delegate.getValue(); -- } -+ @Override -+ public T getValue() { -+ return delegate.getValue(); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ExponentiallyDecayingReservoir.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ExponentiallyDecayingReservoir.java -@@ -5,41 +5,44 @@ import static java.util.Objects.requireNonNull; - @Deprecated - public class ExponentiallyDecayingReservoir implements Reservoir { + @Test +- void testAnnotationOnMethod() throws Exception { ++ void annotationOnMethod() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("update"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +@@ -54,7 +54,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } -- private final io.dropwizard.metrics5.ExponentiallyDecayingReservoir delegate; -- -- public ExponentiallyDecayingReservoir() { -- this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir()); -- } -- -- public ExponentiallyDecayingReservoir(int size, double alpha) { -- this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir(size, alpha)); -- } -- -- public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock) { -- this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir(size, alpha, clock.getDelegate())); -- } -- -- public ExponentiallyDecayingReservoir(io.dropwizard.metrics5.ExponentiallyDecayingReservoir delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- @Override -- public io.dropwizard.metrics5.Reservoir getDelegate() { -- return delegate; -- } -- -- @Override -- public int size() { -- return delegate.size(); -- } -- -- @Override -- public void update(long value) { -- delegate.update(value); -- } -- -- @Override -- public Snapshot getSnapshot() { -- return Snapshot.of(delegate.getSnapshot()); -- } -+ private final io.dropwizard.metrics5.ExponentiallyDecayingReservoir delegate; -+ -+ public ExponentiallyDecayingReservoir() { -+ this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir()); -+ } -+ -+ public ExponentiallyDecayingReservoir(int size, double alpha) { -+ this(new io.dropwizard.metrics5.ExponentiallyDecayingReservoir(size, alpha)); -+ } -+ -+ public ExponentiallyDecayingReservoir(int size, double alpha, Clock clock) { -+ this( -+ new io.dropwizard.metrics5.ExponentiallyDecayingReservoir( -+ size, alpha, clock.getDelegate())); -+ } -+ -+ public ExponentiallyDecayingReservoir( -+ io.dropwizard.metrics5.ExponentiallyDecayingReservoir delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ @Override -+ public io.dropwizard.metrics5.Reservoir getDelegate() { -+ return delegate; -+ } -+ -+ @Override -+ public int size() { -+ return delegate.size(); -+ } -+ -+ @Override -+ public void update(long value) { -+ delegate.update(value); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ return Snapshot.of(delegate.getSnapshot()); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/FixedNameCsvFileProvider.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/FixedNameCsvFileProvider.java -@@ -5,11 +5,11 @@ import java.io.File; - @Deprecated - public class FixedNameCsvFileProvider implements CsvFileProvider { + @Test +- void testAnnotationOnMethodWithCustomName() throws Exception { ++ void annotationOnMethodWithCustomName() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("customUpdate"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +@@ -64,7 +64,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } -- private final io.dropwizard.metrics5.FixedNameCsvFileProvider delegate = -- new io.dropwizard.metrics5.FixedNameCsvFileProvider(); -+ private final io.dropwizard.metrics5.FixedNameCsvFileProvider delegate = -+ new io.dropwizard.metrics5.FixedNameCsvFileProvider(); + @Test +- void testAnnotationOnMethodWithCustomAbsoluteName() throws Exception { ++ void annotationOnMethodWithCustomAbsoluteName() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("absoluteUpdate"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +@@ -72,7 +72,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } -- @Override -- public File getFile(File directory, String metricName) { -- return delegate.getFile(directory, metricName); -- } -+ @Override -+ public File getFile(File directory, String metricName) { -+ return delegate.getFile(directory, metricName); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Gauge.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Gauge.java -@@ -3,36 +3,36 @@ package com.codahale.metrics; - @Deprecated - public interface Gauge extends Metric { + @Test +- void testAnnotationOnClass() throws Exception { ++ void annotationOnClass() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Bar.class, Bar.class.getMethod("update"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +@@ -82,7 +82,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } -- T getValue(); -+ T getValue(); + @Test +- void testAnnotationOnMethodAndClassWithCustomNames() throws Exception { ++ void annotationOnMethodAndClassWithCustomNames() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn( + new ExtensionMethod(CustomBar.class, CustomBar.class.getMethod("find", String.class))); +@@ -91,14 +91,14 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } -- @Override -- default io.dropwizard.metrics5.Gauge getDelegate() { -- return new GaugeAdapter<>(this); -- } -+ @Override -+ default io.dropwizard.metrics5.Gauge getDelegate() { -+ return new GaugeAdapter<>(this); -+ } - -- @SuppressWarnings("unchecked") -- static Gauge of(io.dropwizard.metrics5.Gauge gauge) { -- if (gauge instanceof GaugeAdapter) { -- return ((GaugeAdapter) gauge).delegate; -- } -- return gauge::getValue; -+ @SuppressWarnings("unchecked") -+ static Gauge of(io.dropwizard.metrics5.Gauge gauge) { -+ if (gauge instanceof GaugeAdapter) { -+ return ((GaugeAdapter) gauge).delegate; - } -+ return gauge::getValue; -+ } + @Test +- void testNoAnnotations() throws Exception { ++ void noAnnotations() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Dummy.class, Dummy.class.getMethod("show"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); + } -- class GaugeAdapter implements io.dropwizard.metrics5.Gauge { -+ class GaugeAdapter implements io.dropwizard.metrics5.Gauge { + @Test +- void testNoMethod() { ++ void noMethod() { + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); + } + } +--- a/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java +@@ -3,7 +3,11 @@ package io.dropwizard.metrics5.jersey2; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; -- private final Gauge delegate; -+ private final Gauge delegate; ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Meter; +@@ -19,7 +23,6 @@ import io.dropwizard.metrics5.annotation.Timed; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -159,7 +162,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(metricName.resolve("1xx-responses")), // 1xx + registry.meter(metricName.resolve("2xx-responses")), // 2xx +@@ -167,11 +170,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(metricName.resolve("4xx-responses")), // 4xx + registry.meter(metricName.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); + this.metricRegistry = registry; + } -- GaugeAdapter(Gauge gauge) { -- this.delegate = gauge; -- } -+ GaugeAdapter(Gauge gauge) { -+ this.delegate = gauge; -+ } +@@ -305,9 +306,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; -- Gauge getGauge() { -- return delegate; -- } -+ Gauge getGauge() { -+ return delegate; -+ } + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -418,14 +419,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } -- @Override -- public T getValue() { -- return delegate.getValue(); -- } -+ @Override -+ public T getValue() { -+ return delegate.getValue(); + private T getClassLevelAnnotation( +@@ -543,7 +541,7 @@ public class InstrumentedResourceMethodApplicationListener + final String... suffixes) { + final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + MetricName metricName; +- if (explicitName != null && !explicitName.isEmpty()) { ++ if (!Strings.isNullOrEmpty(explicitName)) { + metricName = + absolute + ? MetricRegistry.name(explicitName) +@@ -604,8 +602,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); } -+ } + } } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Histogram.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Histogram.java -@@ -5,36 +5,36 @@ import static java.util.Objects.requireNonNull; - @Deprecated - public class Histogram implements Metric, Sampling, Counting { +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java +@@ -14,7 +14,7 @@ import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; -- private final io.dropwizard.metrics5.Histogram delegate; -- -- public Histogram(io.dropwizard.metrics5.Histogram delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- public Histogram(Reservoir reservoir) { -- this.delegate = new io.dropwizard.metrics5.Histogram(reservoir.getDelegate()); -- } -- -- public void update(int value) { -- delegate.update(value); -- } -- -- public void update(long value) { -- delegate.update(value); -- } -- -- @Override -- public long getCount() { -- return delegate.getCount(); -- } -- -- @Override -- public Snapshot getSnapshot() { -- return Snapshot.of(delegate.getSnapshot()); -- } -- -- @Override -- public io.dropwizard.metrics5.Histogram getDelegate() { -- return delegate; -- } -+ private final io.dropwizard.metrics5.Histogram delegate; -+ -+ public Histogram(io.dropwizard.metrics5.Histogram delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ public Histogram(Reservoir reservoir) { -+ this.delegate = new io.dropwizard.metrics5.Histogram(reservoir.getDelegate()); -+ } -+ -+ public void update(int value) { -+ delegate.update(value); -+ } -+ -+ public void update(long value) { -+ delegate.update(value); -+ } -+ -+ @Override -+ public long getCount() { -+ return delegate.getCount(); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ return Snapshot.of(delegate.getSnapshot()); -+ } -+ -+ @Override -+ public io.dropwizard.metrics5.Histogram getDelegate() { -+ return delegate; -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedExecutorService.java -@@ -1,5 +1,7 @@ - package com.codahale.metrics; +-class CustomReservoirImplementationTest extends JerseyTest { ++final class CustomReservoirImplementationTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} with filter tracking + */ +-class SingletonFilterMetricsJerseyTest extends JerseyTest { ++final class SingletonFilterMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -34,8 +34,7 @@ class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } -+import static java.util.Objects.requireNonNull; -+ - import java.util.Collection; - import java.util.List; - import java.util.concurrent.Callable; -@@ -9,87 +11,93 @@ import java.util.concurrent.Future; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.TimeoutException; + @BeforeEach +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -34,9 +34,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); --import static java.util.Objects.requireNonNull; + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); - - @Deprecated - public class InstrumentedExecutorService implements ExecutorService { +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } -- private final io.dropwizard.metrics5.InstrumentedExecutorService delegate; -- -- public InstrumentedExecutorService(io.dropwizard.metrics5.InstrumentedExecutorService delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) { -- this(new io.dropwizard.metrics5.InstrumentedExecutorService(delegate, registry.getDelegate())); -- } -- -- public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry, String name) { -- this(new io.dropwizard.metrics5.InstrumentedExecutorService(delegate, registry.getDelegate(), name)); -- } -- -- @Override -- public void shutdown() { -- delegate.shutdown(); -- } -- -- @Override -- public List shutdownNow() { -- return delegate.shutdownNow(); -- } -- -- @Override -- public boolean isShutdown() { -- return delegate.isShutdown(); -- } -- -- @Override -- public boolean isTerminated() { -- return delegate.isTerminated(); -- } -- -- @Override -- public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { -- return delegate.awaitTermination(timeout, unit); -- } -- -- @Override -- public Future submit(Callable task) { -- return delegate.submit(task); -- } -- -- @Override -- public Future submit(Runnable task, T result) { -- return delegate.submit(task, result); -- } -- -- @Override -- public Future submit(Runnable task) { -- return delegate.submit(task); -- } -- -- @Override -- public List> invokeAll(Collection> tasks) throws InterruptedException { -- return delegate.invokeAll(tasks); -- } -- -- @Override -- public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { -- return delegate.invokeAll(tasks, timeout, unit); -- } -- -- @Override -- public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { -- return delegate.invokeAny(tasks); -- } -- -- @Override -- public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { -- return delegate.invokeAny(tasks, timeout, unit); -- } -- -- @Override -- public void execute(Runnable command) { -- delegate.execute(command); -- } -+ private final io.dropwizard.metrics5.InstrumentedExecutorService delegate; -+ -+ public InstrumentedExecutorService(io.dropwizard.metrics5.InstrumentedExecutorService delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ public InstrumentedExecutorService(ExecutorService delegate, MetricRegistry registry) { -+ this(new io.dropwizard.metrics5.InstrumentedExecutorService(delegate, registry.getDelegate())); -+ } -+ -+ public InstrumentedExecutorService( -+ ExecutorService delegate, MetricRegistry registry, String name) { -+ this( -+ new io.dropwizard.metrics5.InstrumentedExecutorService( -+ delegate, registry.getDelegate(), name)); -+ } -+ -+ @Override -+ public void shutdown() { -+ delegate.shutdown(); -+ } -+ -+ @Override -+ public List shutdownNow() { -+ return delegate.shutdownNow(); -+ } -+ -+ @Override -+ public boolean isShutdown() { -+ return delegate.isShutdown(); -+ } -+ -+ @Override -+ public boolean isTerminated() { -+ return delegate.isTerminated(); -+ } -+ -+ @Override -+ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { -+ return delegate.awaitTermination(timeout, unit); -+ } -+ -+ @Override -+ public Future submit(Callable task) { -+ return delegate.submit(task); -+ } -+ -+ @Override -+ public Future submit(Runnable task, T result) { -+ return delegate.submit(task, result); -+ } -+ -+ @Override -+ public Future submit(Runnable task) { -+ return delegate.submit(task); -+ } -+ -+ @Override -+ public List> invokeAll(Collection> tasks) -+ throws InterruptedException { -+ return delegate.invokeAll(tasks); -+ } -+ -+ @Override -+ public List> invokeAll( -+ Collection> tasks, long timeout, TimeUnit unit) -+ throws InterruptedException { -+ return delegate.invokeAll(tasks, timeout, unit); -+ } -+ -+ @Override -+ public T invokeAny(Collection> tasks) -+ throws InterruptedException, ExecutionException { -+ return delegate.invokeAny(tasks); -+ } -+ -+ @Override -+ public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) -+ throws InterruptedException, ExecutionException, TimeoutException { -+ return delegate.invokeAny(tasks, timeout, unit); -+ } -+ -+ @Override -+ public void execute(Runnable command) { -+ delegate.execute(command); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedScheduledExecutorService.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedScheduledExecutorService.java -@@ -1,5 +1,7 @@ - package com.codahale.metrics; + @Test +@@ -50,7 +48,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -+import static java.util.Objects.requireNonNull; -+ - import java.util.Collection; - import java.util.List; - import java.util.concurrent.Callable; -@@ -10,107 +12,119 @@ import java.util.concurrent.ScheduledFuture; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.TimeoutException; + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); --import static java.util.Objects.requireNonNull; -- - @Deprecated - public class InstrumentedScheduledExecutorService implements ScheduledExecutorService { +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); -- private final io.dropwizard.metrics5.InstrumentedScheduledExecutorService delegate; -- -- public InstrumentedScheduledExecutorService(io.dropwizard.metrics5.InstrumentedScheduledExecutorService delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- public InstrumentedScheduledExecutorService(ScheduledExecutorService delegate, MetricRegistry registry) { -- this(new io.dropwizard.metrics5.InstrumentedScheduledExecutorService(delegate, registry.getDelegate())); -- } -- -- public InstrumentedScheduledExecutorService(ScheduledExecutorService delegate, MetricRegistry registry, String name) { -- this(new io.dropwizard.metrics5.InstrumentedScheduledExecutorService(delegate, registry.getDelegate(), name)); -- } -- -- @Override -- public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { -- return delegate.schedule(command, delay, unit); -- } -- -- @Override -- public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { -- return delegate.schedule(callable, delay, unit); -- } -- -- @Override -- public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { -- return delegate.scheduleAtFixedRate(command, initialDelay, period, unit); -- } -- -- @Override -- public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { -- return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit); -- } -- -- @Override -- public void shutdown() { -- delegate.shutdown(); -- } -- -- @Override -- public List shutdownNow() { -- return delegate.shutdownNow(); -- } -- -- @Override -- public boolean isShutdown() { -- return delegate.isShutdown(); -- } -- -- @Override -- public boolean isTerminated() { -- return delegate.isTerminated(); -- } -- -- @Override -- public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { -- return delegate.awaitTermination(timeout, unit); -- } -- -- @Override -- public Future submit(Callable task) { -- return delegate.submit(task); -- } -- -- @Override -- public Future submit(Runnable task, T result) { -- return delegate.submit(task, result); -- } -- -- @Override -- public Future submit(Runnable task) { -- return delegate.submit(task); -- } -- -- @Override -- public List> invokeAll(Collection> tasks) throws InterruptedException { -- return delegate.invokeAll(tasks); -- } -- -- @Override -- public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { -- return delegate.invokeAll(tasks, timeout, unit); -- } -- -- @Override -- public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { -- return delegate.invokeAny(tasks); -- } -- -- @Override -- public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { -- return delegate.invokeAny(tasks, timeout, unit); -- } -- -- @Override -- public void execute(Runnable command) { -- delegate.execute(command); -- } -+ private final io.dropwizard.metrics5.InstrumentedScheduledExecutorService delegate; -+ -+ public InstrumentedScheduledExecutorService( -+ io.dropwizard.metrics5.InstrumentedScheduledExecutorService delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ public InstrumentedScheduledExecutorService( -+ ScheduledExecutorService delegate, MetricRegistry registry) { -+ this( -+ new io.dropwizard.metrics5.InstrumentedScheduledExecutorService( -+ delegate, registry.getDelegate())); -+ } -+ -+ public InstrumentedScheduledExecutorService( -+ ScheduledExecutorService delegate, MetricRegistry registry, String name) { -+ this( -+ new io.dropwizard.metrics5.InstrumentedScheduledExecutorService( -+ delegate, registry.getDelegate(), name)); -+ } -+ -+ @Override -+ public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { -+ return delegate.schedule(command, delay, unit); -+ } -+ -+ @Override -+ public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { -+ return delegate.schedule(callable, delay, unit); -+ } -+ -+ @Override -+ public ScheduledFuture scheduleAtFixedRate( -+ Runnable command, long initialDelay, long period, TimeUnit unit) { -+ return delegate.scheduleAtFixedRate(command, initialDelay, period, unit); -+ } -+ -+ @Override -+ public ScheduledFuture scheduleWithFixedDelay( -+ Runnable command, long initialDelay, long delay, TimeUnit unit) { -+ return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit); -+ } -+ -+ @Override -+ public void shutdown() { -+ delegate.shutdown(); -+ } -+ -+ @Override -+ public List shutdownNow() { -+ return delegate.shutdownNow(); -+ } -+ -+ @Override -+ public boolean isShutdown() { -+ return delegate.isShutdown(); -+ } -+ -+ @Override -+ public boolean isTerminated() { -+ return delegate.isTerminated(); -+ } -+ -+ @Override -+ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { -+ return delegate.awaitTermination(timeout, unit); -+ } -+ -+ @Override -+ public Future submit(Callable task) { -+ return delegate.submit(task); -+ } -+ -+ @Override -+ public Future submit(Runnable task, T result) { -+ return delegate.submit(task, result); -+ } -+ -+ @Override -+ public Future submit(Runnable task) { -+ return delegate.submit(task); -+ } -+ -+ @Override -+ public List> invokeAll(Collection> tasks) -+ throws InterruptedException { -+ return delegate.invokeAll(tasks); -+ } -+ -+ @Override -+ public List> invokeAll( -+ Collection> tasks, long timeout, TimeUnit unit) -+ throws InterruptedException { -+ return delegate.invokeAll(tasks, timeout, unit); -+ } -+ -+ @Override -+ public T invokeAny(Collection> tasks) -+ throws InterruptedException, ExecutionException { -+ return delegate.invokeAny(tasks); -+ } -+ -+ @Override -+ public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) -+ throws InterruptedException, ExecutionException, TimeoutException { -+ return delegate.invokeAny(tasks, timeout, unit); -+ } -+ -+ @Override -+ public void execute(Runnable command) { -+ delegate.execute(command); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedThreadFactory.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/InstrumentedThreadFactory.java -@@ -1,28 +1,30 @@ - package com.codahale.metrics; + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -75,7 +73,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java +@@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link org.glassfish.jersey.server.ResourceConfig} + */ +-class SingletonMetricsJerseyTest extends JerseyTest { ++final class SingletonMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -37,9 +37,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { --import java.util.concurrent.ThreadFactory; + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); - - import static java.util.Objects.requireNonNull; +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -92,13 +90,13 @@ class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + MetricRegistry.name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); + +- assertThat(meter2xx.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); + assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); -+import java.util.concurrent.ThreadFactory; -+ - @Deprecated - public class InstrumentedThreadFactory implements ThreadFactory { +- assertThat(meter4xx.getCount()).isZero(); ++ assertThat(meter4xx.getCount()).isEqualTo(0); + assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); -- private final io.dropwizard.metrics5.InstrumentedThreadFactory delegate; -+ private final io.dropwizard.metrics5.InstrumentedThreadFactory delegate; +- assertThat(meter5xx.getCount()).isZero(); ++ assertThat(meter5xx.getCount()).isEqualTo(0); + assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); -- public InstrumentedThreadFactory(io.dropwizard.metrics5.InstrumentedThreadFactory delegate) { -- this.delegate = requireNonNull(delegate); -- } -+ public InstrumentedThreadFactory(io.dropwizard.metrics5.InstrumentedThreadFactory delegate) { -+ this.delegate = requireNonNull(delegate); -+ } + assertThat(meter2xx.getCount()).isEqualTo(1); +@@ -107,7 +105,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + } -- public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry) { -- this(new io.dropwizard.metrics5.InstrumentedThreadFactory(delegate, registry.getDelegate())); -- } -+ public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry) { -+ this(new io.dropwizard.metrics5.InstrumentedThreadFactory(delegate, registry.getDelegate())); -+ } + @Test +- void testResourceNotFound() { ++ void resourceNotFound() { + final Response response = target().path("not-found").request().get(); + assertThat(response.getStatus()).isEqualTo(404); -- public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry, String name) { -- this(new io.dropwizard.metrics5.InstrumentedThreadFactory(delegate, registry.getDelegate(), name)); -- } -+ public InstrumentedThreadFactory(ThreadFactory delegate, MetricRegistry registry, String name) { -+ this( -+ new io.dropwizard.metrics5.InstrumentedThreadFactory( -+ delegate, registry.getDelegate(), name)); -+ } - -- @Override -- public Thread newThread(Runnable r) { -- return delegate.newThread(r); -- } -+ @Override -+ public Thread newThread(Runnable r) { -+ return delegate.newThread(r); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Meter.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Meter.java -@@ -5,55 +5,55 @@ import static java.util.Objects.requireNonNull; - @Deprecated - public class Meter implements Metered { +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -31,9 +31,7 @@ class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); -- private final io.dropwizard.metrics5.Meter delegate; -- -- public Meter() { -- this(new io.dropwizard.metrics5.Meter()); -- } -- -- public Meter(Clock clock) { -- this(new io.dropwizard.metrics5.Meter(clock.getDelegate())); -- } -- -- public Meter(io.dropwizard.metrics5.Meter delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- public void mark() { -- delegate.mark(); -- } -- -- public void mark(long n) { -- delegate.mark(n); -- } -- -- @Override -- public long getCount() { -- return delegate.getCount(); -- } -- -- @Override -- public double getFifteenMinuteRate() { -- return delegate.getFifteenMinuteRate(); -- } -- -- @Override -- public double getFiveMinuteRate() { -- return delegate.getFiveMinuteRate(); -- } + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); - -- @Override -- public double getMeanRate() { -- return delegate.getMeanRate(); -- } +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -1,7 +1,7 @@ + package io.dropwizard.metrics5.jersey2; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; ++import static org.assertj.core.api.Assertions.fail; + + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -34,9 +34,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); - -- @Override -- public double getOneMinuteRate() { -- return delegate.getOneMinuteRate(); -- } +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java +@@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -31,9 +31,7 @@ class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); - -- @Override -- public io.dropwizard.metrics5.Meter getDelegate() { -- return delegate; -- } -+ private final io.dropwizard.metrics5.Meter delegate; -+ -+ public Meter() { -+ this(new io.dropwizard.metrics5.Meter()); -+ } -+ -+ public Meter(Clock clock) { -+ this(new io.dropwizard.metrics5.Meter(clock.getDelegate())); -+ } -+ -+ public Meter(io.dropwizard.metrics5.Meter delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ public void mark() { -+ delegate.mark(); -+ } -+ -+ public void mark(long n) { -+ delegate.mark(n); -+ } -+ -+ @Override -+ public long getCount() { -+ return delegate.getCount(); -+ } -+ -+ @Override -+ public double getFifteenMinuteRate() { -+ return delegate.getFifteenMinuteRate(); -+ } -+ -+ @Override -+ public double getFiveMinuteRate() { -+ return delegate.getFiveMinuteRate(); -+ } -+ -+ @Override -+ public double getMeanRate() { -+ return delegate.getMeanRate(); -+ } -+ -+ @Override -+ public double getOneMinuteRate() { -+ return delegate.getOneMinuteRate(); -+ } -+ -+ @Override -+ public io.dropwizard.metrics5.Meter getDelegate() { -+ return delegate; -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Metered.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Metered.java -@@ -3,14 +3,14 @@ package com.codahale.metrics; - @Deprecated - public interface Metered extends Metric, Counting { +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } -- @Override -- long getCount(); -+ @Override -+ long getCount(); + @Test +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } -- double getFifteenMinuteRate(); -+ double getFifteenMinuteRate(); + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } -- double getFiveMinuteRate(); -+ double getFiveMinuteRate(); + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } -- double getMeanRate(); -+ double getMeanRate(); + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { -- double getOneMinuteRate(); -+ double getOneMinuteRate(); - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Metric.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Metric.java -@@ -3,24 +3,25 @@ package com.codahale.metrics; - @Deprecated - public interface Metric { - -- io.dropwizard.metrics5.Metric getDelegate(); -+ io.dropwizard.metrics5.Metric getDelegate(); - -- @SuppressWarnings("unchecked") -- static Metric of(io.dropwizard.metrics5.Metric metric) { -- if (metric instanceof io.dropwizard.metrics5.Counter) { -- return new Counter((io.dropwizard.metrics5.Counter) metric); -- } else if (metric instanceof io.dropwizard.metrics5.Histogram) { -- return new Histogram((io.dropwizard.metrics5.Histogram) metric); -- } else if (metric instanceof io.dropwizard.metrics5.Meter) { -- return new Meter((io.dropwizard.metrics5.Meter) metric); -- } else if (metric instanceof io.dropwizard.metrics5.Timer) { -- return new Timer((io.dropwizard.metrics5.Timer) metric); -- } else if (metric instanceof io.dropwizard.metrics5.Gauge) { -- return Gauge.of((io.dropwizard.metrics5.Gauge) metric); -- } else if (metric instanceof io.dropwizard.metrics5.MetricSet) { -- return MetricSet.of((io.dropwizard.metrics5.MetricSet) metric); -- } else { -- throw new IllegalArgumentException("Can't find adaptor class for metric of type: " + metric.getClass().getName()); -- } -+ @SuppressWarnings("unchecked") -+ static Metric of(io.dropwizard.metrics5.Metric metric) { -+ if (metric instanceof io.dropwizard.metrics5.Counter) { -+ return new Counter((io.dropwizard.metrics5.Counter) metric); -+ } else if (metric instanceof io.dropwizard.metrics5.Histogram) { -+ return new Histogram((io.dropwizard.metrics5.Histogram) metric); -+ } else if (metric instanceof io.dropwizard.metrics5.Meter) { -+ return new Meter((io.dropwizard.metrics5.Meter) metric); -+ } else if (metric instanceof io.dropwizard.metrics5.Timer) { -+ return new Timer((io.dropwizard.metrics5.Timer) metric); -+ } else if (metric instanceof io.dropwizard.metrics5.Gauge) { -+ return Gauge.of((io.dropwizard.metrics5.Gauge) metric); -+ } else if (metric instanceof io.dropwizard.metrics5.MetricSet) { -+ return MetricSet.of((io.dropwizard.metrics5.MetricSet) metric); -+ } else { -+ throw new IllegalArgumentException( -+ "Can't find adaptor class for metric of type: " + metric.getClass().getName()); + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import javax.ws.rs.core.Response; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,46 +46,46 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered + @Path("/response-2xx-metered") ++ @ResponseMetered + public Response response2xxMetered() { + return Response.ok().build(); + } + + @GET +- @ResponseMetered + @Path("/response-4xx-metered") ++ @ResponseMetered + public Response response4xxMetered() { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + + @GET +- @ResponseMetered + @Path("/response-5xx-metered") ++ @ResponseMetered + public Response response5xxMetered() { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import javax.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +--- a/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java +@@ -4,7 +4,11 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Meter; +@@ -22,7 +26,6 @@ import jakarta.ws.rs.ext.Provider; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -160,7 +163,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(metricName.resolve("1xx-responses")), // 1xx + registry.meter(metricName.resolve("2xx-responses")), // 2xx +@@ -168,11 +171,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(metricName.resolve("4xx-responses")), // 4xx + registry.meter(metricName.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); + this.metricRegistry = registry; } -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricAttribute.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricAttribute.java -@@ -5,40 +5,40 @@ import java.util.Set; - @Deprecated - public enum MetricAttribute { -+ MAX("max"), -+ MEAN("mean"), -+ MIN("min"), -+ STDDEV("stddev"), -+ P50("p50"), -+ P75("p75"), -+ P95("p95"), -+ P98("p98"), -+ P99("p99"), -+ P999("p999"), -+ COUNT("count"), -+ SUM("sum"), -+ M1_RATE("m1_rate"), -+ M5_RATE("m5_rate"), -+ M15_RATE("m15_rate"), -+ MEAN_RATE("mean_rate"); - -- MAX("max"), -- MEAN("mean"), -- MIN("min"), -- STDDEV("stddev"), -- P50("p50"), -- P75("p75"), -- P95("p95"), -- P98("p98"), -- P99("p99"), -- P999("p999"), -- COUNT("count"), -- SUM("sum"), -- M1_RATE("m1_rate"), -- M5_RATE("m5_rate"), -- M15_RATE("m15_rate"), -- MEAN_RATE("mean_rate"); -+ private final String code; - -- private final String code; -+ MetricAttribute(String code) { -+ this.code = code; -+ } - -- MetricAttribute(String code) { -- this.code = code; -- } -- -- public String getCode() { -- return code; -- } -+ public String getCode() { -+ return code; -+ } - -- public static Set transform(Set metricAttributes) { -- EnumSet newAttributes = EnumSet.noneOf( -- io.dropwizard.metrics5.MetricAttribute.class); -- for (MetricAttribute ma : metricAttributes) { -- newAttributes.add(io.dropwizard.metrics5.MetricAttribute.valueOf(ma.name())); -- } -- return newAttributes; -+ public static Set transform( -+ Set metricAttributes) { -+ EnumSet newAttributes = -+ EnumSet.noneOf(io.dropwizard.metrics5.MetricAttribute.class); -+ for (MetricAttribute ma : metricAttributes) { -+ newAttributes.add(io.dropwizard.metrics5.MetricAttribute.valueOf(ma.name())); +@@ -306,9 +307,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -419,14 +420,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -544,7 +542,7 @@ public class InstrumentedResourceMethodApplicationListener + final String... suffixes) { + final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + MetricName metricName; +- if (explicitName != null && !explicitName.isEmpty()) { ++ if (!Strings.isNullOrEmpty(explicitName)) { + metricName = + absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); + } else { +@@ -602,8 +600,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); } -+ return newAttributes; -+ } + } } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricFilter.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricFilter.java -@@ -3,24 +3,24 @@ package com.codahale.metrics; - @Deprecated - public interface MetricFilter { +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java +@@ -14,7 +14,7 @@ import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; -- MetricFilter ALL = (name, metric) -> true; -+ MetricFilter ALL = (name, metric) -> true; +-class CustomReservoirImplementationTest extends JerseyTest { ++final class CustomReservoirImplementationTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java +@@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} with filter tracking + */ +-class SingletonFilterMetricsJerseyTest extends JerseyTest { ++final class SingletonFilterMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,8 +35,7 @@ class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } -- static MetricFilter startsWith(String prefix) { -- return (name, metric) -> name.startsWith(prefix); -- } -+ static MetricFilter startsWith(String prefix) { -+ return (name, metric) -> name.startsWith(prefix); -+ } + @BeforeEach +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,9 +35,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); -- static MetricFilter endsWith(String suffix) { -- return (name, metric) -> name.endsWith(suffix); -- } -+ static MetricFilter endsWith(String suffix) { -+ return (name, metric) -> name.endsWith(suffix); -+ } + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } -- static MetricFilter contains(String substring) { -- return (name, metric) -> name.contains(substring); -- } -+ static MetricFilter contains(String substring) { -+ return (name, metric) -> name.contains(substring); -+ } + @Test +@@ -51,7 +49,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -- boolean matches(String name, Metric metric); -+ boolean matches(String name, Metric metric); + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); -- default io.dropwizard.metrics5.MetricFilter transform() { -- final MetricFilter origin = this; -- return (name, metric) -> origin.matches(name.getKey(), Metric.of(metric)); -- } -+ default io.dropwizard.metrics5.MetricFilter transform() { -+ final MetricFilter origin = this; -+ return (name, metric) -> origin.matches(name.getKey(), Metric.of(metric)); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java -@@ -1,184 +1,181 @@ - package com.codahale.metrics; +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); --import io.dropwizard.metrics5.MetricName; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Collections.unmodifiableSortedSet; -+import static java.util.Objects.requireNonNull; -+import static java.util.stream.Collectors.toCollection; + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); --import java.util.Collections; -+import io.dropwizard.metrics5.MetricName; - import java.util.Map; --import java.util.Objects; - import java.util.SortedMap; - import java.util.SortedSet; - import java.util.TreeMap; - import java.util.TreeSet; --import java.util.stream.Collectors; +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java +@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link org.glassfish.jersey.server.ResourceConfig} + */ +-class SingletonMetricsJerseyTest extends JerseyTest { ++final class SingletonMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -38,9 +38,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); - --import static java.util.Collections.unmodifiableSortedSet; --import static java.util.Objects.requireNonNull; +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -89,13 +87,13 @@ class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter5xx = + registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); + +- assertThat(meter2xx.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); + assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter4xx.getCount()).isZero(); ++ assertThat(meter4xx.getCount()).isEqualTo(0); + assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); + +- assertThat(meter5xx.getCount()).isZero(); ++ assertThat(meter5xx.getCount()).isEqualTo(0); + assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); + + assertThat(meter2xx.getCount()).isEqualTo(1); +@@ -115,9 +113,9 @@ class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -127,28 +125,28 @@ class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } + + @Test +- public void responseMeteredMethodsAreMeteredWithAllLevel() { ++ void responseMeteredMethodsAreMeteredWithAllLevel() { + final Meter meter2xx = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); - @Deprecated - public class MetricRegistry implements MetricSet { +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); -- private final io.dropwizard.metrics5.MetricRegistry delegate; -+ private final io.dropwizard.metrics5.MetricRegistry delegate; +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } -- public static String name(Class klass, String... names) { -- return io.dropwizard.metrics5.MetricRegistry.name(klass, names).getKey(); -- } -+ public static String name(Class klass, String... names) { -+ return io.dropwizard.metrics5.MetricRegistry.name(klass, names).getKey(); -+ } + @Test +- void testResourceNotFound() { ++ void resourceNotFound() { + final Response response = target().path("not-found").request().get(); + assertThat(response.getStatus()).isEqualTo(404); -- public static String name(String name, String... names) { -- return io.dropwizard.metrics5.MetricRegistry.name(name, names).getKey(); -- } -+ public static String name(String name, String... names) { -+ return io.dropwizard.metrics5.MetricRegistry.name(name, names).getKey(); -+ } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -32,9 +32,7 @@ class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); -- public MetricRegistry() { -- this(new io.dropwizard.metrics5.MetricRegistry()); -- } -+ public MetricRegistry() { -+ this(new io.dropwizard.metrics5.MetricRegistry()); -+ } + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } -- public MetricRegistry(io.dropwizard.metrics5.MetricRegistry delegate) { -- this.delegate = requireNonNull(delegate); -- } -+ public MetricRegistry(io.dropwizard.metrics5.MetricRegistry delegate) { -+ this.delegate = requireNonNull(delegate); -+ } + @Test +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -2,7 +2,7 @@ package io.dropwizard.metrics5.jersey3; -- public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { -- delegate.registerGauge(MetricName.build(name), metric.getDelegate()); -- return metric; -- } -+ public Gauge registerGauge(String name, Gauge metric) throws IllegalArgumentException { -+ delegate.registerGauge(MetricName.build(name), metric.getDelegate()); -+ return metric; -+ } - -- public T register(String name, T metric) throws IllegalArgumentException { -- delegate.register(MetricName.build(name), metric.getDelegate()); -- return metric; -- } -+ public T register(String name, T metric) throws IllegalArgumentException { -+ delegate.register(MetricName.build(name), metric.getDelegate()); -+ return metric; -+ } + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; ++import static org.assertj.core.api.Assertions.fail; -- public void registerAll(MetricSet metrics) throws IllegalArgumentException { -- delegate.registerAll(metrics.getDelegate()); -- } -+ public void registerAll(MetricSet metrics) throws IllegalArgumentException { -+ delegate.registerAll(metrics.getDelegate()); -+ } + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,9 +35,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -- @SuppressWarnings("unchecked") -- public Gauge gauge(String name, MetricSupplier supplier) { -- return Gauge.of(delegate.gauge(MetricName.build(name), supplier.transform())); -- } -+ @SuppressWarnings("unchecked") -+ public Gauge gauge(String name, MetricSupplier supplier) { -+ return Gauge.of(delegate.gauge(MetricName.build(name), supplier.transform())); -+ } + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } -- public Counter counter(String name) { -- return new Counter(delegate.counter(name)); -- } -+ public Counter counter(String name) { -+ return new Counter(delegate.counter(name)); -+ } -+ -+ public Counter counter(String name, MetricSupplier supplier) { -+ return new Counter(delegate.counter(MetricName.build(name), supplier.transform())); -+ } -+ -+ public Histogram histogram(String name) { -+ return new Histogram(delegate.histogram(MetricName.build(name))); -+ } -+ -+ public Histogram histogram(String name, MetricSupplier supplier) { -+ return new Histogram(delegate.histogram(MetricName.build(name), supplier.transform())); -+ } -+ -+ public Meter meter(String name) { -+ return new Meter(delegate.meter(MetricName.build(name))); -+ } + @Test +@@ -140,8 +138,8 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + "responseMeteredPerClass", + "200-responses")); -- public Counter counter(String name, MetricSupplier supplier) { -- return new Counter(delegate.counter(MetricName.build(name), supplier.transform())); -- } -+ public Meter meter(String name, MetricSupplier supplier) { -+ return new Meter(delegate.meter(MetricName.build(name), supplier.transform())); -+ } +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); -- public Histogram histogram(String name) { -- return new Histogram(delegate.histogram(MetricName.build(name))); -- } -+ public Timer timer(String name) { -+ return new Timer(delegate.timer(MetricName.build(name))); -+ } + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); +@@ -154,7 +152,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + "2xx-responses")); + assertThat(meter.getCount()).isEqualTo(1); -- public Histogram histogram(String name, MetricSupplier supplier) { -- return new Histogram(delegate.histogram(MetricName.build(name), supplier.transform())); -- } -+ public Timer timer(String name, MetricSupplier supplier) { -+ return new Timer(delegate.timer(MetricName.build(name), supplier.transform())); -+ } +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -32,9 +32,7 @@ class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); -- public Meter meter(String name) { -- return new Meter(delegate.meter(MetricName.build(name))); -- } -+ public boolean remove(String name) { -+ return delegate.remove(MetricName.build(name)); -+ } + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } -- public Meter meter(String name, MetricSupplier supplier) { -- return new Meter(delegate.meter(MetricName.build(name), supplier.transform())); -- } -+ public void removeMatching(MetricFilter filter) { -+ delegate.removeMatching(filter.transform()); -+ } + @Test +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } -- public Timer timer(String name) { -- return new Timer(delegate.timer(MetricName.build(name))); -- } -+ public void addListener(MetricRegistryListener listener) { -+ delegate.addListener(new MetricRegistryListener.Adapter(listener)); -+ } + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } -- public Timer timer(String name, MetricSupplier supplier) { -- return new Timer(delegate.timer(MetricName.build(name), supplier.transform())); -- } -+ public void removeListener(MetricRegistryListener listener) { -+ delegate.removeListener(new MetricRegistryListener.Adapter(listener)); -+ } + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } -- public boolean remove(String name) { -- return delegate.remove(MetricName.build(name)); -- } -+ public SortedSet getNames() { -+ return unmodifiableSortedSet( -+ delegate.getNames().stream().map(MetricName::getKey).collect(toCollection(TreeSet::new))); -+ } + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { -- public void removeMatching(MetricFilter filter) { -- delegate.removeMatching(filter.transform()); -- } -+ public SortedMap getGauges() { -+ return adaptMetrics(delegate.getGauges()); -+ } + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } -- public void addListener(MetricRegistryListener listener) { -- delegate.addListener(new MetricRegistryListener.Adapter(listener)); -- } -+ public SortedMap getGauges(MetricFilter filter) { -+ return adaptMetrics(delegate.getGauges(filter.transform())); -+ } +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,46 +46,46 @@ public class InstrumentedResource { + } -- public void removeListener(MetricRegistryListener listener) { -- delegate.removeListener(new MetricRegistryListener.Adapter(listener)); -- } -+ public SortedMap getCounters() { -+ return adaptMetrics(delegate.getCounters()); -+ } - -- public SortedSet getNames() { -- return unmodifiableSortedSet(delegate.getNames() -- .stream() -- .map(MetricName::getKey) -- .collect(Collectors.toCollection(TreeSet::new))); -- } -+ public SortedMap getCounters(MetricFilter filter) { -+ return adaptMetrics(delegate.getCounters(filter.transform())); -+ } + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } -- public SortedMap getGauges() { -- return adaptMetrics(delegate.getGauges()); -- } -+ public SortedMap getHistograms() { -+ return adaptMetrics(delegate.getHistograms()); -+ } + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } -- public SortedMap getGauges(MetricFilter filter) { -- return adaptMetrics(delegate.getGauges(filter.transform())); -- } -+ public SortedMap getHistograms(MetricFilter filter) { -+ return adaptMetrics(delegate.getHistograms(filter.transform())); -+ } + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } -- public SortedMap getCounters() { -- return adaptMetrics(delegate.getCounters()); -- } -+ public SortedMap getMeters() { -+ return adaptMetrics(delegate.getMeters()); -+ } + @GET +- @ResponseMetered + @Path("/response-2xx-metered") ++ @ResponseMetered + public Response response2xxMetered() { + return Response.ok().build(); + } -- public SortedMap getCounters(MetricFilter filter) { -- return adaptMetrics(delegate.getCounters(filter.transform())); -- } -+ public SortedMap getMeters(MetricFilter filter) { -+ return adaptMetrics(delegate.getMeters(filter.transform())); -+ } + @GET +- @ResponseMetered + @Path("/response-4xx-metered") ++ @ResponseMetered + public Response response4xxMetered() { + return Response.status(Response.Status.BAD_REQUEST).build(); + } -- public SortedMap getHistograms() { -- return adaptMetrics(delegate.getHistograms()); -- } -+ public SortedMap getTimers() { -+ return adaptMetrics(delegate.getTimers()); -+ } + @GET +- @ResponseMetered + @Path("/response-5xx-metered") ++ @ResponseMetered + public Response response5xxMetered() { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; + public class InstrumentedSubResource { -- public SortedMap getHistograms(MetricFilter filter) { -- return adaptMetrics(delegate.getHistograms(filter.transform())); -- } -+ public SortedMap getTimers(MetricFilter filter) { -+ return adaptMetrics(delegate.getTimers(filter.transform())); -+ } + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +--- a/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java +@@ -4,7 +4,11 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; -- public SortedMap getMeters() { -- return adaptMetrics(delegate.getMeters()); -- } -+ @Override -+ public Map getMetrics() { -+ return adaptMetrics(delegate.getMetrics()); -+ } - -- public SortedMap getMeters(MetricFilter filter) { -- return adaptMetrics(delegate.getMeters(filter.transform())); -+ @SuppressWarnings("unchecked") -+ static SortedMap adaptMetrics( -+ Map metrics) { -+ final SortedMap items = new TreeMap<>(); -+ for (Map.Entry entry : -+ metrics.entrySet()) { -+ items.put(entry.getKey().getKey(), (T) Metric.of(entry.getValue())); ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Meter; +@@ -22,7 +26,6 @@ import jakarta.ws.rs.ext.Provider; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -160,7 +163,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(metricName.resolve("1xx-responses")), // 1xx + registry.meter(metricName.resolve("2xx-responses")), // 2xx +@@ -168,11 +171,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(metricName.resolve("4xx-responses")), // 4xx + registry.meter(metricName.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); + this.metricRegistry = registry; } -+ return unmodifiableSortedMap(items); -+ } -- public SortedMap getTimers() { -- return adaptMetrics(delegate.getTimers()); -- } -+ @Override -+ public io.dropwizard.metrics5.MetricRegistry getDelegate() { -+ return delegate; -+ } +@@ -306,9 +307,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; -- public SortedMap getTimers(MetricFilter filter) { -- return adaptMetrics(delegate.getTimers(filter.transform())); -- } -+ @FunctionalInterface -+ public interface MetricSupplier { + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -419,14 +420,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } -- @Override -- public Map getMetrics() { -- return adaptMetrics(delegate.getMetrics()); -- } -+ T newMetric(); - - @SuppressWarnings("unchecked") -- static SortedMap adaptMetrics( -- Map metrics) { -- final SortedMap items = new TreeMap<>(); -- for (Map.Entry entry : metrics.entrySet()) { -- items.put(entry.getKey().getKey(), (T) Metric.of(entry.getValue())); -- } -- return Collections.unmodifiableSortedMap(items); -- } -- -- @Override -- public io.dropwizard.metrics5.MetricRegistry getDelegate() { -- return delegate; -- } -- -- @FunctionalInterface -- public interface MetricSupplier { -- -- T newMetric(); -- -- @SuppressWarnings("unchecked") -- default -+ default - io.dropwizard.metrics5.MetricRegistry.MetricSupplier transform() { -- MetricSupplier original = this; -- return () -> (M) original.newMetric().getDelegate(); -- } -+ MetricSupplier original = this; -+ return () -> (M) original.newMetric().getDelegate(); + private T getClassLevelAnnotation( +@@ -544,7 +542,7 @@ public class InstrumentedResourceMethodApplicationListener + final String... suffixes) { + final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + MetricName metricName; +- if (explicitName != null && !explicitName.isEmpty()) { ++ if (!Strings.isNullOrEmpty(explicitName)) { + metricName = + absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); + } else { +@@ -602,8 +600,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); } -+ } + } } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistryListener.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistryListener.java -@@ -1,144 +1,133 @@ - package com.codahale.metrics; +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java +@@ -14,7 +14,7 @@ import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; - import io.dropwizard.metrics5.MetricName; +-class CustomReservoirImplementationTest extends JerseyTest { ++final class CustomReservoirImplementationTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java +@@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} with filter tracking + */ +-class SingletonFilterMetricsJerseyTest extends JerseyTest { ++final class SingletonFilterMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,8 +35,7 @@ class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @BeforeEach +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,9 +35,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); - - import java.util.EventListener; +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } - @Deprecated - public interface MetricRegistryListener extends EventListener { + @Test +@@ -51,7 +49,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -- abstract class Base implements MetricRegistryListener { -- @Override -- public void onGaugeAdded(String name, Gauge gauge) { -- } -+ abstract class Base implements MetricRegistryListener { -+ @Override -+ public void onGaugeAdded(String name, Gauge gauge) {} + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); -- @Override -- public void onGaugeRemoved(String name) { -- } -+ @Override -+ public void onGaugeRemoved(String name) {} +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); -- @Override -- public void onCounterAdded(String name, Counter counter) { -- } -+ @Override -+ public void onCounterAdded(String name, Counter counter) {} + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); -- @Override -- public void onCounterRemoved(String name) { -- } -+ @Override -+ public void onCounterRemoved(String name) {} +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); -- @Override -- public void onHistogramAdded(String name, Histogram histogram) { -- } -+ @Override -+ public void onHistogramAdded(String name, Histogram histogram) {} + try { + target("subresource/exception-metered") +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java +@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsJerseyTest extends JerseyTest { ++final class SingletonMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -38,9 +38,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { -- @Override -- public void onHistogramRemoved(String name) { -- } -+ @Override -+ public void onHistogramRemoved(String name) {} + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } -- @Override -- public void onMeterAdded(String name, Meter meter) { -- } -+ @Override -+ public void onMeterAdded(String name, Meter meter) {} + @Test +@@ -67,7 +65,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { -- @Override -- public void onMeterRemoved(String name) { -- } -+ @Override -+ public void onMeterRemoved(String name) {} + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); -- @Override -- public void onTimerAdded(String name, Timer timer) { -- } -+ @Override -+ public void onTimerAdded(String name, Timer timer) {} +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); -- @Override -- public void onTimerRemoved(String name) { -- } -- } -+ @Override -+ public void onTimerRemoved(String name) {} -+ } + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -89,33 +87,33 @@ class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter5xx = + registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); + +- assertThat(meter2xx.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); + assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter4xx.getCount()).isZero(); ++ assertThat(meter4xx.getCount()).isEqualTo(0); + assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); + +- assertThat(meter5xx.getCount()).isZero(); ++ assertThat(meter5xx.getCount()).isEqualTo(0); + assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); + } -- void onGaugeAdded(String name, Gauge gauge); -+ void onGaugeAdded(String name, Gauge gauge); + @Test +- public void responseMeteredMethodsAreMeteredWithCoarseLevel() { ++ void responseMeteredMethodsAreMeteredWithCoarseLevel() { + final Meter meter2xx = + registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "2xx-responses")); + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); -- void onGaugeRemoved(String name); -+ void onGaugeRemoved(String name); +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(0); + } -- void onCounterAdded(String name, Counter counter); -+ void onCounterAdded(String name, Counter counter); + @Test +- public void responseMeteredMethodsAreMeteredWithDetailedLevel() { ++ void responseMeteredMethodsAreMeteredWithDetailedLevel() { + final Meter meter2xx = + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "2xx-responses")); +@@ -126,9 +124,9 @@ class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -138,28 +136,28 @@ class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } -- void onCounterRemoved(String name); -+ void onCounterRemoved(String name); + @Test +- public void responseMeteredMethodsAreMeteredWithAllLevel() { ++ void responseMeteredMethodsAreMeteredWithAllLevel() { + final Meter meter2xx = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); -- void onHistogramAdded(String name, Histogram histogram); -+ void onHistogramAdded(String name, Histogram histogram); +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); -- void onHistogramRemoved(String name); -+ void onHistogramRemoved(String name); +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } -- void onMeterAdded(String name, Meter meter); -+ void onMeterAdded(String name, Meter meter); + @Test +- void testResourceNotFound() { ++ void resourceNotFound() { + final Response response = target().path("not-found").request().get(); + assertThat(response.getStatus()).isEqualTo(404); -- void onMeterRemoved(String name); -+ void onMeterRemoved(String name); +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -32,9 +32,7 @@ class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); -- void onTimerAdded(String name, Timer timer); -+ void onTimerAdded(String name, Timer timer); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } -- void onTimerRemoved(String name); -+ void onTimerRemoved(String name); + @Test +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -2,7 +2,7 @@ package io.dropwizard.metrics5.jersey31; -- class Adapter implements io.dropwizard.metrics5.MetricRegistryListener { -+ class Adapter implements io.dropwizard.metrics5.MetricRegistryListener { + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; ++import static org.assertj.core.api.Assertions.fail; -- private MetricRegistryListener delegate; -+ private MetricRegistryListener delegate; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,9 +35,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -- public Adapter(MetricRegistryListener delegate) { -- this.delegate = delegate; -- } -+ public Adapter(MetricRegistryListener delegate) { -+ this.delegate = delegate; -+ } + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } -- @Override -- public void onGaugeAdded(MetricName name, io.dropwizard.metrics5.Gauge gauge) { -- delegate.onGaugeAdded(name.getKey(), Gauge.of(gauge)); -- } -+ @Override -+ public void onGaugeAdded(MetricName name, io.dropwizard.metrics5.Gauge gauge) { -+ delegate.onGaugeAdded(name.getKey(), Gauge.of(gauge)); -+ } - -- @Override -- public void onGaugeRemoved(MetricName name) { -- delegate.onGaugeRemoved(name.getKey()); -- } -+ @Override -+ public void onGaugeRemoved(MetricName name) { -+ delegate.onGaugeRemoved(name.getKey()); -+ } - -- @Override -- public void onCounterAdded(MetricName name, io.dropwizard.metrics5.Counter counter) { -- delegate.onCounterAdded(name.getKey(), new Counter(counter)); -- } -+ @Override -+ public void onCounterAdded(MetricName name, io.dropwizard.metrics5.Counter counter) { -+ delegate.onCounterAdded(name.getKey(), new Counter(counter)); -+ } - -- @Override -- public void onCounterRemoved(MetricName name) { -- delegate.onCounterRemoved(name.getKey()); -- } -+ @Override -+ public void onCounterRemoved(MetricName name) { -+ delegate.onCounterRemoved(name.getKey()); -+ } - -- @Override -- public void onHistogramAdded(MetricName name, io.dropwizard.metrics5.Histogram histogram) { -- delegate.onHistogramAdded(name.getKey(), new Histogram(histogram)); -- } -+ @Override -+ public void onHistogramAdded(MetricName name, io.dropwizard.metrics5.Histogram histogram) { -+ delegate.onHistogramAdded(name.getKey(), new Histogram(histogram)); -+ } - -- @Override -- public void onHistogramRemoved(MetricName name) { -- delegate.onHistogramRemoved(name.getKey()); -- } -+ @Override -+ public void onHistogramRemoved(MetricName name) { -+ delegate.onHistogramRemoved(name.getKey()); -+ } - -- @Override -- public void onMeterAdded(MetricName name, io.dropwizard.metrics5.Meter meter) { -- delegate.onMeterAdded(name.getKey(), new Meter(meter)); -- } -+ @Override -+ public void onMeterAdded(MetricName name, io.dropwizard.metrics5.Meter meter) { -+ delegate.onMeterAdded(name.getKey(), new Meter(meter)); -+ } - -- @Override -- public void onMeterRemoved(MetricName name) { -- delegate.onMeterRemoved(name.getKey()); -- } -+ @Override -+ public void onMeterRemoved(MetricName name) { -+ delegate.onMeterRemoved(name.getKey()); -+ } - -- @Override -- public void onTimerAdded(MetricName name, io.dropwizard.metrics5.Timer timer) { -- delegate.onTimerAdded(name.getKey(), new Timer(timer)); -- } -+ @Override -+ public void onTimerAdded(MetricName name, io.dropwizard.metrics5.Timer timer) { -+ delegate.onTimerAdded(name.getKey(), new Timer(timer)); -+ } - -- @Override -- public void onTimerRemoved(MetricName name) { -- delegate.onTimerRemoved(name.getKey()); -- } -+ @Override -+ public void onTimerRemoved(MetricName name) { -+ delegate.onTimerRemoved(name.getKey()); -+ } - -- @Override -- public boolean equals(Object o) { -- if (o instanceof Adapter) { -- Adapter adapter = (Adapter) o; -- return delegate.equals(adapter.delegate); -- } -- return false; -- } -+ @Override -+ public boolean equals(Object o) { -+ if (o instanceof Adapter) { -+ Adapter adapter = (Adapter) o; -+ return delegate.equals(adapter.delegate); -+ } -+ return false; -+ } - -- @Override -- public int hashCode() { -- return delegate.hashCode(); -- } -+ @Override -+ public int hashCode() { -+ return delegate.hashCode(); - } --} -\ No newline at end of file -+ } -+} ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java -@@ -1,55 +1,55 @@ - package com.codahale.metrics; + @Test +@@ -140,13 +138,13 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + "responseMeteredPerClass", + "200-responses")); --import io.dropwizard.metrics5.MetricName; -+import static java.util.Collections.unmodifiableMap; +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); --import java.util.Collections; -+import io.dropwizard.metrics5.MetricName; - import java.util.HashMap; - import java.util.Map; + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); - @Deprecated - public interface MetricSet extends Metric { +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -32,9 +32,7 @@ class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); -- Map getMetrics(); -- -- @Override -- default io.dropwizard.metrics5.MetricSet getDelegate() { -- return new Adapter(this); -- } -- -- static MetricSet of(io.dropwizard.metrics5.MetricSet original) { -- return new MetricSet() { -- @Override -- public Map getMetrics() { -- final Map items = new HashMap<>(); -- for (Map.Entry entry : original.getMetrics().entrySet()) { -- items.put(entry.getKey().getKey(), Metric.of(entry.getValue())); -- } -- return Collections.unmodifiableMap(items); -- } + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); - -- @Override -- public io.dropwizard.metrics5.MetricSet getDelegate() { -- return original; -- } -- }; -- } -+ Map getMetrics(); -+ -+ @Override -+ default io.dropwizard.metrics5.MetricSet getDelegate() { -+ return new Adapter(this); -+ } -+ -+ static MetricSet of(io.dropwizard.metrics5.MetricSet original) { -+ return new MetricSet() { -+ @Override -+ public Map getMetrics() { -+ final Map items = new HashMap<>(); -+ for (Map.Entry entry : -+ original.getMetrics().entrySet()) { -+ items.put(entry.getKey().getKey(), Metric.of(entry.getValue())); -+ } -+ return unmodifiableMap(items); -+ } +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } -- class Adapter implements io.dropwizard.metrics5.MetricSet { -+ @Override -+ public io.dropwizard.metrics5.MetricSet getDelegate() { -+ return original; -+ } -+ }; -+ } + @Test +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } -- private final MetricSet delegate; -+ class Adapter implements io.dropwizard.metrics5.MetricSet { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } -- Adapter(MetricSet delegate) { -- this.delegate = delegate; -- } -+ private final MetricSet delegate; - -- @Override -- public Map getMetrics() { -- final Map items = new HashMap<>(); -- for (Map.Entry entry : delegate.getMetrics().entrySet()) { -- items.put(MetricName.build(entry.getKey()), entry.getValue().getDelegate()); -- } -- return Collections.unmodifiableMap(items); -- } -+ Adapter(MetricSet delegate) { -+ this.delegate = delegate; - } + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } -+ @Override -+ public Map getMetrics() { -+ final Map items = new HashMap<>(); -+ for (Map.Entry entry : delegate.getMetrics().entrySet()) { -+ items.put(MetricName.build(entry.getKey()), entry.getValue().getDelegate()); -+ } -+ return unmodifiableMap(items); -+ } -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/RatioGauge.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/RatioGauge.java -@@ -5,32 +5,32 @@ import static java.util.Objects.requireNonNull; - @Deprecated - public abstract class RatioGauge implements Gauge { + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { -- public static class Ratio { -+ public static class Ratio { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } -- private io.dropwizard.metrics5.RatioGauge.Ratio delegate; -+ private io.dropwizard.metrics5.RatioGauge.Ratio delegate; +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,46 +46,46 @@ public class InstrumentedResource { + } -- public static Ratio of(double numerator, double denominator) { -- return new Ratio(io.dropwizard.metrics5.RatioGauge.Ratio.of(numerator, denominator)); -- } -- -- public Ratio(io.dropwizard.metrics5.RatioGauge.Ratio delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- public double getValue() { -- return delegate.getValue(); -- } -+ public static Ratio of(double numerator, double denominator) { -+ return new Ratio(io.dropwizard.metrics5.RatioGauge.Ratio.of(numerator, denominator)); -+ } + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } -- @Override -- public String toString() { -- return delegate.toString(); -- } -+ public Ratio(io.dropwizard.metrics5.RatioGauge.Ratio delegate) { -+ this.delegate = requireNonNull(delegate); - } + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } -- protected abstract Ratio getRatio(); -+ public double getValue() { -+ return delegate.getValue(); -+ } + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } - @Override -- public Double getValue() { -- return getRatio().getValue(); -+ public String toString() { -+ return delegate.toString(); - } -+ } -+ -+ protected abstract Ratio getRatio(); -+ -+ @Override -+ public Double getValue() { -+ return getRatio().getValue(); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Reporter.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Reporter.java -@@ -1,6 +1,4 @@ - package com.codahale.metrics; + @GET +- @ResponseMetered + @Path("/response-2xx-metered") ++ @ResponseMetered + public Response response2xxMetered() { + return Response.ok().build(); + } - @Deprecated --public interface Reporter { -- --} -+public interface Reporter {} ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Reservoir.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Reservoir.java -@@ -3,11 +3,11 @@ package com.codahale.metrics; - @Deprecated - public interface Reservoir { + @GET +- @ResponseMetered + @Path("/response-4xx-metered") ++ @ResponseMetered + public Response response4xxMetered() { + return Response.status(Response.Status.BAD_REQUEST).build(); + } -- int size(); -+ int size(); + @GET +- @ResponseMetered + @Path("/response-5xx-metered") ++ @ResponseMetered + public Response response5xxMetered() { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; + public class InstrumentedSubResource { -- void update(long value); -+ void update(long value); + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java +@@ -4,7 +4,10 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; -- Snapshot getSnapshot(); -+ Snapshot getSnapshot(); ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -14,7 +17,6 @@ import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -173,7 +175,7 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); -- io.dropwizard.metrics5.Reservoir getDelegate(); -+ io.dropwizard.metrics5.Reservoir getDelegate(); - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Sampling.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Sampling.java -@@ -3,5 +3,5 @@ package com.codahale.metrics; - @Deprecated - public interface Sampling { + this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); +@@ -188,7 +190,7 @@ public class InstrumentedHandler extends HandlerWrapper { -- Snapshot getSnapshot(); -+ Snapshot getSnapshot(); - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java -@@ -1,9 +1,10 @@ - package com.codahale.metrics; + if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { + this.responses = +- Collections.unmodifiableList( ++ unmodifiableList( + Arrays.asList( + metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx +@@ -253,7 +255,7 @@ public class InstrumentedHandler extends HandlerWrapper { + } + }); + } else { +- this.responses = Collections.emptyList(); ++ this.responses = ImmutableList.of(); + } --import io.dropwizard.metrics5.MetricName; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Objects.requireNonNull; + this.listener = new AsyncAttachingListener(); +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java +@@ -3,7 +3,10 @@ package io.dropwizard.metrics5.jetty10; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; -+import io.dropwizard.metrics5.MetricName; - import java.io.Closeable; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -14,7 +17,6 @@ import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; -import java.util.Collections; + import java.util.EnumSet; + import java.util.List; import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -11,142 +12,218 @@ import java.util.TreeMap; - import java.util.concurrent.ScheduledExecutorService; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(prefix.resolve("1xx-responses")), // 1xx + registry.meter(prefix.resolve("2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(prefix.resolve("4xx-responses")), // 4xx + registry.meter(prefix.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); + + this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); + this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java +@@ -21,7 +21,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedConnectionFactoryTest { ++final class InstrumentedConnectionFactoryTest { + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); + private final ServerConnector connector = +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java +@@ -3,13 +3,13 @@ package io.dropwizard.metrics5.jetty10; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; + + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; + import javax.servlet.AsyncContext; + import javax.servlet.ServletException; +@@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; --import static java.util.Objects.requireNonNull; -- - @Deprecated - public abstract class ScheduledReporter implements Closeable, Reporter { +-class InstrumentedHandlerTest { ++final class InstrumentedHandlerTest { + private final HttpClient client = new HttpClient(); + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); +@@ -118,7 +118,7 @@ class InstrumentedHandlerTest { + } -- private io.dropwizard.metrics5.ScheduledReporter delegate; -- -- protected ScheduledReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, -- TimeUnit durationUnit) { -- delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, this); -- } -- -- protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, -- TimeUnit durationUnit, ScheduledExecutorService executor) { -- delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, executor, this); -- } -- -- protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, -- TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop) { -- delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, this); -- } -- -- protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, -- TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop, -- Set disabledMetricAttributes) { -- delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, -- disabledMetricAttributes, this); -- } -- -- public void start(long period, TimeUnit unit) { -- delegate.start(period, unit); -- } -- -- synchronized public void start(long initialDelay, long period, TimeUnit unit) { -- delegate.start(initialDelay, period, unit); -- } -- -- public void stop() { -- delegate.stop(); -+ private io.dropwizard.metrics5.ScheduledReporter delegate; -+ -+ protected ScheduledReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ protected ScheduledReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit) { -+ delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, this); -+ } -+ -+ protected ScheduledReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor) { -+ delegate = new Adapter(registry, name, filter, rateUnit, durationUnit, executor, this); -+ } -+ -+ protected ScheduledReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop) { -+ delegate = -+ new Adapter( -+ registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, this); -+ } -+ -+ protected ScheduledReporter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes) { -+ delegate = -+ new Adapter( -+ registry, -+ name, -+ filter, -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop, -+ disabledMetricAttributes, -+ this); -+ } -+ -+ public void start(long period, TimeUnit unit) { -+ delegate.start(period, unit); -+ } -+ -+ public synchronized void start(long initialDelay, long period, TimeUnit unit) { -+ delegate.start(initialDelay, period, unit); -+ } -+ -+ public void stop() { -+ delegate.stop(); -+ } -+ -+ @Override -+ public void close() { -+ delegate.close(); -+ } -+ -+ public void report() { -+ delegate.report(); -+ } -+ -+ public io.dropwizard.metrics5.ScheduledReporter getDelegate() { -+ return delegate; -+ } -+ -+ @SuppressWarnings("rawtypes") -+ public abstract void report( -+ SortedMap gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers); -+ -+ @SuppressWarnings("unchecked") -+ protected SortedMap transform( -+ SortedMap metrics) { -+ final SortedMap items = new TreeMap<>(); -+ for (Map.Entry entry : metrics.entrySet()) { -+ items.put(MetricName.build(entry.getKey()), (T) entry.getValue().getDelegate()); -+ } -+ return unmodifiableSortedMap(items); -+ } -+ -+ protected String getRateUnit() { -+ return delegate.getRateUnit(); -+ } -+ -+ protected String getDurationUnit() { -+ return delegate.getDurationUnit(); -+ } -+ -+ protected double convertDuration(double duration) { -+ return delegate.convertDuration(duration); -+ } -+ -+ protected double convertRate(double rate) { -+ return delegate.convertRate(rate); -+ } -+ -+ protected boolean isShutdownExecutorOnStop() { -+ return delegate.isShutdownExecutorOnStop(); -+ } -+ -+ protected Set getDisabledMetricAttributes() { -+ return delegate.getDisabledMetricAttributes(); -+ } -+ -+ public static class Adapter extends io.dropwizard.metrics5.ScheduledReporter { -+ -+ private final ScheduledReporter delegate; -+ -+ public Adapter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledReporter delegate) { -+ super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit); -+ this.delegate = delegate; -+ } -+ -+ public Adapter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor, -+ ScheduledReporter delegate) { -+ super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit, executor); -+ this.delegate = delegate; -+ } -+ -+ public Adapter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ ScheduledReporter delegate) { -+ super( -+ registry.getDelegate(), -+ name, -+ filter.transform(), -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop); -+ this.delegate = delegate; -+ } -+ -+ public Adapter( -+ MetricRegistry registry, -+ String name, -+ MetricFilter filter, -+ TimeUnit rateUnit, -+ TimeUnit durationUnit, -+ ScheduledExecutorService executor, -+ boolean shutdownExecutorOnStop, -+ Set disabledMetricAttributes, -+ ScheduledReporter delegate) { -+ super( -+ registry.getDelegate(), -+ name, -+ filter.transform(), -+ rateUnit, -+ durationUnit, -+ executor, -+ shutdownExecutorOnStop, -+ MetricAttribute.transform(disabledMetricAttributes)); -+ this.delegate = delegate; - } + @Test +- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { ++ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { + InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -128,7 +128,7 @@ class InstrumentedHandlerTest { + } + + @Test +- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { ++ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { + InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -137,8 +137,8 @@ class InstrumentedHandlerTest { + .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); + } - @Override -- public void close() { -- delegate.close(); -- } -- -- public void report() { -- delegate.report(); -- } -- -- public io.dropwizard.metrics5.ScheduledReporter getDelegate() { -- return delegate; -- } -- -- @SuppressWarnings("rawtypes") -- public abstract void report(SortedMap gauges, -- SortedMap counters, -- SortedMap histograms, -- SortedMap meters, -- SortedMap timers); -- -- @SuppressWarnings("unchecked") -- protected SortedMap transform( -- SortedMap metrics) { -- final SortedMap items = new TreeMap<>(); -- for (Map.Entry entry : metrics.entrySet()) { -- items.put(MetricName.build(entry.getKey()), (T) entry.getValue().getDelegate()); -- } -- return Collections.unmodifiableSortedMap(items); -- } -- -- protected String getRateUnit() { -- return delegate.getRateUnit(); -- } -- -- protected String getDurationUnit() { -- return delegate.getDurationUnit(); -- } -- -- protected double convertDuration(double duration) { -- return delegate.convertDuration(duration); -- } -- -- protected double convertRate(double rate) { -- return delegate.convertRate(rate); -- } -- -- protected boolean isShutdownExecutorOnStop() { -- return delegate.isShutdownExecutorOnStop(); -- } -- -- protected Set getDisabledMetricAttributes() { -- return delegate.getDisabledMetricAttributes(); -- } -- -- public static class Adapter extends io.dropwizard.metrics5.ScheduledReporter { -- -- private final ScheduledReporter delegate; -- -- public Adapter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, -- ScheduledReporter delegate) { -- super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit); -- this.delegate = delegate; -- } -- -- public Adapter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, -- ScheduledExecutorService executor, ScheduledReporter delegate) { -- super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit, executor); -- this.delegate = delegate; -- } -- -- public Adapter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, -- ScheduledExecutorService executor, boolean shutdownExecutorOnStop, ScheduledReporter delegate) { -- super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit, executor, shutdownExecutorOnStop); -- this.delegate = delegate; -- } -- -- public Adapter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, -- ScheduledExecutorService executor, boolean shutdownExecutorOnStop, Set disabledMetricAttributes, -- ScheduledReporter delegate) { -- super(registry.getDelegate(), name, filter.transform(), rateUnit, durationUnit, executor, shutdownExecutorOnStop, -- MetricAttribute.transform(disabledMetricAttributes)); -- this.delegate = delegate; -- } -- -- @Override -- public void report(SortedMap> gauges, SortedMap counters, -- SortedMap histograms, SortedMap meters, -- SortedMap timers) { -- delegate.report(MetricRegistry.adaptMetrics(gauges), MetricRegistry.adaptMetrics(counters), -- MetricRegistry.adaptMetrics(histograms), MetricRegistry.adaptMetrics(meters), -- MetricRegistry.adaptMetrics(timers)); -- } -- } -+ public void report( -+ SortedMap> gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ delegate.report( -+ MetricRegistry.adaptMetrics(gauges), -+ MetricRegistry.adaptMetrics(counters), -+ MetricRegistry.adaptMetrics(histograms), -+ MetricRegistry.adaptMetrics(meters), -+ MetricRegistry.adaptMetrics(timers)); -+ } -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SharedMetricRegistries.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SharedMetricRegistries.java -@@ -2,48 +2,47 @@ package com.codahale.metrics; +- @Test + @Disabled("flaky on virtual machines") ++ @Test + void responseTimesAreRecordedForAsyncResponses() throws Exception { - import java.util.Optional; - import java.util.Set; --import java.util.concurrent.atomic.AtomicReference; + final ContentResponse response = client.GET(uri("/async")); +@@ -150,7 +150,7 @@ class InstrumentedHandlerTest { - @Deprecated - public class SharedMetricRegistries { + private void assertResponseTimesValid() { + assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) +- .isGreaterThan(0L); ++ .isPositive(); -- public static void clear() { -- io.dropwizard.metrics5.SharedMetricRegistries.clear(); -- } -- -- public static Set names() { -- return io.dropwizard.metrics5.SharedMetricRegistries.names(); -- } -- -- public static void remove(String key) { -- io.dropwizard.metrics5.SharedMetricRegistries.remove(key); -- } -- -- public static MetricRegistry add(String name, MetricRegistry registry) { -- io.dropwizard.metrics5.SharedMetricRegistries.add(name, registry.getDelegate()); -- return registry; -- } -- -- public static MetricRegistry getOrCreate(String name) { -- return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.getOrCreate(name)); -- } -- -- public synchronized static MetricRegistry setDefault(String name) { -- return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.setDefault(name)); -- } -- -- public static MetricRegistry setDefault(String name, MetricRegistry metricRegistry) { -- io.dropwizard.metrics5.SharedMetricRegistries.setDefault(name, metricRegistry.getDelegate()); -- return metricRegistry; -- } -- -- public static MetricRegistry getDefault() { -- return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.getDefault()); -- } -- -- public static MetricRegistry tryGetDefault() { -- return Optional.ofNullable(io.dropwizard.metrics5.SharedMetricRegistries.tryGetDefault()) -- .map(MetricRegistry::new) -- .orElse(null); -- } -+ public static void clear() { -+ io.dropwizard.metrics5.SharedMetricRegistries.clear(); -+ } -+ -+ public static Set names() { -+ return io.dropwizard.metrics5.SharedMetricRegistries.names(); -+ } -+ -+ public static void remove(String key) { -+ io.dropwizard.metrics5.SharedMetricRegistries.remove(key); -+ } -+ -+ public static MetricRegistry add(String name, MetricRegistry registry) { -+ io.dropwizard.metrics5.SharedMetricRegistries.add(name, registry.getDelegate()); -+ return registry; -+ } -+ -+ public static MetricRegistry getOrCreate(String name) { -+ return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.getOrCreate(name)); -+ } -+ -+ public static synchronized MetricRegistry setDefault(String name) { -+ return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.setDefault(name)); -+ } -+ -+ public static MetricRegistry setDefault(String name, MetricRegistry metricRegistry) { -+ io.dropwizard.metrics5.SharedMetricRegistries.setDefault(name, metricRegistry.getDelegate()); -+ return metricRegistry; -+ } -+ -+ public static MetricRegistry getDefault() { -+ return new MetricRegistry(io.dropwizard.metrics5.SharedMetricRegistries.getDefault()); -+ } -+ -+ public static MetricRegistry tryGetDefault() { -+ return Optional.ofNullable(io.dropwizard.metrics5.SharedMetricRegistries.tryGetDefault()) -+ .map(MetricRegistry::new) -+ .orElse(null); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Slf4jReporter.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Slf4jReporter.java -@@ -1,91 +1,106 @@ - package com.codahale.metrics; + assertThat( + registry +@@ -158,11 +158,11 @@ class InstrumentedHandlerTest { + .get(metricName().resolve("get-requests")) + .getSnapshot() + .getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); --import org.slf4j.Logger; --import org.slf4j.Marker; -+import static java.util.Objects.requireNonNull; + assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } - import java.util.SortedMap; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; -- --import static java.util.Objects.requireNonNull; -+import org.slf4j.Logger; -+import org.slf4j.Marker; +@@ -225,7 +225,7 @@ class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } - @Deprecated - public class Slf4jReporter extends ScheduledReporter { +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java +@@ -1,12 +1,12 @@ + package io.dropwizard.metrics5.jetty10; -- public static Slf4jReporter.Builder forRegistry(MetricRegistry registry) { -- return new Slf4jReporter.Builder(io.dropwizard.metrics5.Slf4jReporter.forRegistry(registry.getDelegate())); -- } -- -- public enum LoggingLevel {TRACE, DEBUG, INFO, WARN, ERROR} -+ public static Slf4jReporter.Builder forRegistry(MetricRegistry registry) { -+ return new Slf4jReporter.Builder( -+ io.dropwizard.metrics5.Slf4jReporter.forRegistry(registry.getDelegate())); -+ } - -- public static class Builder { -+ public enum LoggingLevel { -+ TRACE, -+ DEBUG, -+ INFO, -+ WARN, -+ ERROR -+ } - -- private io.dropwizard.metrics5.Slf4jReporter.Builder delegate; -+ public static class Builder { - -- private Builder(io.dropwizard.metrics5.Slf4jReporter.Builder delegate) { -- this.delegate = requireNonNull(delegate); -- } -+ private io.dropwizard.metrics5.Slf4jReporter.Builder delegate; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; -- public Slf4jReporter.Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -- delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); -- return this; -- } -- -- public Slf4jReporter.Builder scheduleOn(ScheduledExecutorService executor) { -- delegate.scheduleOn(executor); -- return this; -- } -+ private Builder(io.dropwizard.metrics5.Slf4jReporter.Builder delegate) { -+ this.delegate = requireNonNull(delegate); -+ } + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import javax.servlet.AsyncContext; + import javax.servlet.ServletOutputStream; + import javax.servlet.WriteListener; +@@ -22,7 +22,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- public Slf4jReporter.Builder outputTo(Logger logger) { -- delegate.outputTo(logger); -- return this; -- } -+ public Slf4jReporter.Builder shutdownExecutorOnStop(boolean shutdownExecutorOnStop) { -+ delegate.shutdownExecutorOnStop(shutdownExecutorOnStop); -+ return this; -+ } - -- public Slf4jReporter.Builder markWith(Marker marker) { -- delegate.markWith(marker); -- return this; -- } -+ public Slf4jReporter.Builder scheduleOn(ScheduledExecutorService executor) { -+ delegate.scheduleOn(executor); -+ return this; -+ } - -- public Slf4jReporter.Builder prefixedWith(String prefix) { -- delegate.prefixedWith(prefix); -- return this; -- } -+ public Slf4jReporter.Builder outputTo(Logger logger) { -+ delegate.outputTo(logger); -+ return this; -+ } - -- public Slf4jReporter.Builder convertRatesTo(TimeUnit rateUnit) { -- delegate.convertRatesTo(rateUnit); -- return this; -- } -+ public Slf4jReporter.Builder markWith(Marker marker) { -+ delegate.markWith(marker); -+ return this; -+ } - -- public Slf4jReporter.Builder convertDurationsTo(TimeUnit durationUnit) { -- delegate.convertDurationsTo(durationUnit); -- return this; -- } -+ public Slf4jReporter.Builder prefixedWith(String prefix) { -+ delegate.prefixedWith(prefix); -+ return this; -+ } - -- public Slf4jReporter.Builder filter(MetricFilter filter) { -- delegate.filter(filter.transform()); -- return this; -- } -+ public Slf4jReporter.Builder convertRatesTo(TimeUnit rateUnit) { -+ delegate.convertRatesTo(rateUnit); -+ return this; -+ } - -- public Slf4jReporter.Builder withLoggingLevel(LoggingLevel loggingLevel) { -- delegate.withLoggingLevel(io.dropwizard.metrics5.Slf4jReporter.LoggingLevel.valueOf(loggingLevel.name())); -- return this; -- } -+ public Slf4jReporter.Builder convertDurationsTo(TimeUnit durationUnit) { -+ delegate.convertDurationsTo(durationUnit); -+ return this; -+ } +-class InstrumentedHttpChannelListenerTest { ++final class InstrumentedHttpChannelListenerTest { + private final HttpClient client = new HttpClient(); + private final Server server = new Server(); + private final ServerConnector connector = new ServerConnector(server); +@@ -188,7 +188,7 @@ class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } -- public Slf4jReporter build() { -- return new Slf4jReporter(delegate.build()); -- } -+ public Slf4jReporter.Builder filter(MetricFilter filter) { -+ delegate.filter(filter.transform()); -+ return this; - } +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java +@@ -8,7 +8,7 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- private Slf4jReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { -- super(delegate); -+ public Slf4jReporter.Builder withLoggingLevel(LoggingLevel loggingLevel) { -+ delegate.withLoggingLevel( -+ io.dropwizard.metrics5.Slf4jReporter.LoggingLevel.valueOf(loggingLevel.name())); -+ return this; - } +-class InstrumentedQueuedThreadPoolTest { ++final class InstrumentedQueuedThreadPoolTest { + private static final String PREFIX = "prefix"; + + private MetricRegistry metricRegistry; +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java +@@ -4,7 +4,10 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -19,7 +22,6 @@ import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -173,7 +175,7 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); + + this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); +@@ -188,7 +190,7 @@ public class InstrumentedHandler extends HandlerWrapper { -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap gauges, SortedMap counters, -- SortedMap histograms, SortedMap meters, -- SortedMap timers) { -- getDelegate().report(transform(gauges), transform(counters), transform(histograms), transform(meters), -- transform(timers)); -+ public Slf4jReporter build() { -+ return new Slf4jReporter(delegate.build()); + if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { + this.responses = +- Collections.unmodifiableList( ++ unmodifiableList( + Arrays.asList( + metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx +@@ -253,7 +255,7 @@ public class InstrumentedHandler extends HandlerWrapper { + } + }); + } else { +- this.responses = Collections.emptyList(); ++ this.responses = ImmutableList.of(); } -+ } -+ -+ private Slf4jReporter(io.dropwizard.metrics5.ScheduledReporter delegate) { -+ super(delegate); -+ } -+ -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ getDelegate() -+ .report( -+ transform(gauges), -+ transform(counters), -+ transform(histograms), -+ transform(meters), -+ transform(timers)); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingTimeWindowArrayReservoir.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingTimeWindowArrayReservoir.java -@@ -1,43 +1,46 @@ - package com.codahale.metrics; --import java.util.concurrent.TimeUnit; -- - import static java.util.Objects.requireNonNull; + this.listener = new AsyncAttachingListener(); +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java +@@ -3,7 +3,10 @@ package io.dropwizard.metrics5.jetty11; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; -+import java.util.concurrent.TimeUnit; -+ - @Deprecated - public class SlidingTimeWindowArrayReservoir implements Reservoir { ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(prefix.resolve("1xx-responses")), // 1xx + registry.meter(prefix.resolve("2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(prefix.resolve("4xx-responses")), // 4xx + registry.meter(prefix.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); -- private io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir delegate; -- -- public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit) { -- this(new io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir(window, windowUnit)); -- } -- -- public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit, Clock clock) { -- this(new io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir(window, windowUnit, clock.getDelegate())); -- } -- -- public SlidingTimeWindowArrayReservoir(io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- @Override -- public io.dropwizard.metrics5.Reservoir getDelegate() { -- return delegate; -- } -- -- @Override -- public int size() { -- return delegate.size(); -- } -- -- @Override -- public void update(long value) { -- delegate.update(value); -- } -- -- @Override -- public Snapshot getSnapshot() { -- return Snapshot.of(delegate.getSnapshot()); -- } -+ private io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir delegate; -+ -+ public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit) { -+ this(new io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir(window, windowUnit)); -+ } -+ -+ public SlidingTimeWindowArrayReservoir(long window, TimeUnit windowUnit, Clock clock) { -+ this( -+ new io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir( -+ window, windowUnit, clock.getDelegate())); -+ } -+ -+ public SlidingTimeWindowArrayReservoir( -+ io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ @Override -+ public io.dropwizard.metrics5.Reservoir getDelegate() { -+ return delegate; -+ } -+ -+ @Override -+ public int size() { -+ return delegate.size(); -+ } -+ -+ @Override -+ public void update(long value) { -+ delegate.update(value); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ return Snapshot.of(delegate.getSnapshot()); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingTimeWindowReservoir.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingTimeWindowReservoir.java -@@ -1,43 +1,45 @@ - package com.codahale.metrics; + this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); + this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java +@@ -21,7 +21,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; --import java.util.concurrent.TimeUnit; -- - import static java.util.Objects.requireNonNull; +-class InstrumentedConnectionFactoryTest { ++final class InstrumentedConnectionFactoryTest { + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); + private final ServerConnector connector = +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java +@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.jetty11; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; -+import java.util.concurrent.TimeUnit; -+ - @Deprecated - public class SlidingTimeWindowReservoir implements Reservoir { +@@ -15,7 +16,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; +@@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; -- private io.dropwizard.metrics5.SlidingTimeWindowReservoir delegate; -- -- public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit) { -- this(new io.dropwizard.metrics5.SlidingTimeWindowReservoir(window, windowUnit)); -- } -- -- public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) { -- this(new io.dropwizard.metrics5.SlidingTimeWindowReservoir(window, windowUnit, clock.getDelegate())); -- } -- -- public SlidingTimeWindowReservoir(io.dropwizard.metrics5.SlidingTimeWindowReservoir delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- @Override -- public io.dropwizard.metrics5.Reservoir getDelegate() { -- return delegate; -- } -- -- @Override -- public int size() { -- return delegate.size(); -- } -- -- @Override -- public void update(long value) { -- delegate.update(value); -- } -- -- @Override -- public Snapshot getSnapshot() { -- return Snapshot.of(delegate.getSnapshot()); -- } -+ private io.dropwizard.metrics5.SlidingTimeWindowReservoir delegate; -+ -+ public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit) { -+ this(new io.dropwizard.metrics5.SlidingTimeWindowReservoir(window, windowUnit)); -+ } -+ -+ public SlidingTimeWindowReservoir(long window, TimeUnit windowUnit, Clock clock) { -+ this( -+ new io.dropwizard.metrics5.SlidingTimeWindowReservoir( -+ window, windowUnit, clock.getDelegate())); -+ } -+ -+ public SlidingTimeWindowReservoir(io.dropwizard.metrics5.SlidingTimeWindowReservoir delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ @Override -+ public io.dropwizard.metrics5.Reservoir getDelegate() { -+ return delegate; -+ } -+ -+ @Override -+ public int size() { -+ return delegate.size(); -+ } -+ -+ @Override -+ public void update(long value) { -+ delegate.update(value); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ return Snapshot.of(delegate.getSnapshot()); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingWindowReservoir.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/SlidingWindowReservoir.java -@@ -5,33 +5,33 @@ import static java.util.Objects.requireNonNull; - @Deprecated - public class SlidingWindowReservoir implements Reservoir { +-class InstrumentedHandlerTest { ++final class InstrumentedHandlerTest { + private final HttpClient client = new HttpClient(); + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); +@@ -118,7 +118,7 @@ class InstrumentedHandlerTest { + } -- private io.dropwizard.metrics5.SlidingWindowReservoir delegate; -- -- public SlidingWindowReservoir(int size) { -- this(new io.dropwizard.metrics5.SlidingWindowReservoir(size)); -- } -- -- public SlidingWindowReservoir(io.dropwizard.metrics5.SlidingWindowReservoir delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- @Override -- public io.dropwizard.metrics5.Reservoir getDelegate() { -- return delegate; -- } -- -- @Override -- public int size() { -- return delegate.size(); -- } -- -- @Override -- public void update(long value) { -- delegate.update(value); -- } -- -- @Override -- public Snapshot getSnapshot() { -- return Snapshot.of(delegate.getSnapshot()); -- } -+ private io.dropwizard.metrics5.SlidingWindowReservoir delegate; -+ -+ public SlidingWindowReservoir(int size) { -+ this(new io.dropwizard.metrics5.SlidingWindowReservoir(size)); -+ } -+ -+ public SlidingWindowReservoir(io.dropwizard.metrics5.SlidingWindowReservoir delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ @Override -+ public io.dropwizard.metrics5.Reservoir getDelegate() { -+ return delegate; -+ } -+ -+ @Override -+ public int size() { -+ return delegate.size(); -+ } -+ -+ @Override -+ public void update(long value) { -+ delegate.update(value); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ return Snapshot.of(delegate.getSnapshot()); -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Snapshot.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Snapshot.java -@@ -5,88 +5,88 @@ import java.io.OutputStream; - @Deprecated - public abstract class Snapshot { + @Test +- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { ++ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { + InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -128,7 +128,7 @@ class InstrumentedHandlerTest { + } -- public abstract double getValue(double quantile); -+ public abstract double getValue(double quantile); + @Test +- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { ++ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { + InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -137,8 +137,8 @@ class InstrumentedHandlerTest { + .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); + } -- public abstract long[] getValues(); -+ public abstract long[] getValues(); +- @Test + @Disabled("flaky on virtual machines") ++ @Test + void responseTimesAreRecordedForAsyncResponses() throws Exception { -- public abstract int size(); -+ public abstract int size(); + final ContentResponse response = client.GET(uri("/async")); +@@ -150,7 +150,7 @@ class InstrumentedHandlerTest { -- public double getMedian() { -- return getValue(0.5); -- } -+ public double getMedian() { -+ return getValue(0.5); -+ } + private void assertResponseTimesValid() { + assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) +- .isGreaterThan(0L); ++ .isPositive(); -- public double get75thPercentile() { -- return getValue(0.75); -- } -+ public double get75thPercentile() { -+ return getValue(0.75); -+ } + assertThat( + registry +@@ -158,11 +158,11 @@ class InstrumentedHandlerTest { + .get(metricName().resolve("get-requests")) + .getSnapshot() + .getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); -- public double get95thPercentile() { -- return getValue(0.95); -- } -+ public double get95thPercentile() { -+ return getValue(0.95); -+ } + assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } -- public double get98thPercentile() { -- return getValue(0.98); -- } -+ public double get98thPercentile() { -+ return getValue(0.98); -+ } +@@ -225,7 +225,7 @@ class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } -- public double get99thPercentile() { -- return getValue(0.99); -- } -+ public double get99thPercentile() { -+ return getValue(0.99); -+ } +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics5.jetty11; -- public double get999thPercentile() { -- return getValue(0.999); -- } -+ public double get999thPercentile() { -+ return getValue(0.999); -+ } - -- public abstract long getMax(); -+ public abstract long getMax(); - -- public abstract double getMean(); -+ public abstract double getMean(); - -- public abstract long getMin(); -+ public abstract long getMin(); - -- public abstract double getStdDev(); -+ public abstract double getStdDev(); - -- public abstract void dump(OutputStream output); -+ public abstract void dump(OutputStream output); - -- public static Snapshot of(io.dropwizard.metrics5.Snapshot delegate) { -- return new Snapshot() { -+ public static Snapshot of(io.dropwizard.metrics5.Snapshot delegate) { -+ return new Snapshot() { - -- @Override -- public double getValue(double quantile) { -- return delegate.getValue(quantile); -- } -+ @Override -+ public double getValue(double quantile) { -+ return delegate.getValue(quantile); -+ } - -- @Override -- public long[] getValues() { -- return delegate.getValues(); -- } -+ @Override -+ public long[] getValues() { -+ return delegate.getValues(); -+ } - -- @Override -- public int size() { -- return delegate.size(); -- } -+ @Override -+ public int size() { -+ return delegate.size(); -+ } - -- @Override -- public long getMax() { -- return delegate.getMax(); -- } -+ @Override -+ public long getMax() { -+ return delegate.getMax(); -+ } - -- @Override -- public double getMean() { -- return delegate.getMean(); -- } -+ @Override -+ public double getMean() { -+ return delegate.getMean(); -+ } - -- @Override -- public long getMin() { -- return delegate.getMin(); -- } -+ @Override -+ public long getMin() { -+ return delegate.getMin(); -+ } - -- @Override -- public double getStdDev() { -- return delegate.getStdDev(); -- } -+ @Override -+ public double getStdDev() { -+ return delegate.getStdDev(); -+ } - -- @Override -- public void dump(OutputStream output) { -- delegate.dump(output); -- } -- }; -- } -+ @Override -+ public void dump(OutputStream output) { -+ delegate.dump(output); -+ } -+ }; -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Timer.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/Timer.java -@@ -1,109 +1,107 @@ - package com.codahale.metrics; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; -+import static java.util.Objects.requireNonNull; -+ - import java.io.Closeable; - import java.time.Duration; - import java.util.concurrent.Callable; - import java.util.concurrent.TimeUnit; - import java.util.function.Supplier; + import io.dropwizard.metrics5.MetricName; +@@ -11,7 +12,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.Request; +@@ -22,7 +22,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; --import static java.util.Objects.requireNonNull; -- - @Deprecated - public class Timer implements Metered, Sampling { +-class InstrumentedHttpChannelListenerTest { ++final class InstrumentedHttpChannelListenerTest { + private final HttpClient client = new HttpClient(); + private final Server server = new Server(); + private final ServerConnector connector = new ServerConnector(server); +@@ -188,7 +188,7 @@ class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } -- private final io.dropwizard.metrics5.Timer delegate; -- -- public static class Context implements Closeable { -- -- private final io.dropwizard.metrics5.Timer.Context context; -- -- private Context(io.dropwizard.metrics5.Timer.Context context) { -- this.context = context; -- } -- -- public long stop() { -- return context.stop(); -- } -- -- @Override -- public void close() { -- context.close(); -- } -- } -- -- public Timer() { -- this(new io.dropwizard.metrics5.Timer()); -- } -- -- public Timer(Reservoir reservoir) { -- this(reservoir, Clock.defaultClock()); -- } -+ private final io.dropwizard.metrics5.Timer delegate; +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java +@@ -8,7 +8,7 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- public Timer(Reservoir reservoir, Clock clock) { -- this(new io.dropwizard.metrics5.Timer(reservoir.getDelegate(), clock.getDelegate())); -- } -- -- public Timer(io.dropwizard.metrics5.Timer delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- @Override -- public Snapshot getSnapshot() { -- return Snapshot.of(delegate.getSnapshot()); -- } -- -- @Override -- public long getCount() { -- return delegate.getCount(); -- } -+ public static class Context implements Closeable { +-class InstrumentedQueuedThreadPoolTest { ++final class InstrumentedQueuedThreadPoolTest { + private static final String PREFIX = "prefix"; -- @Override -- public double getFifteenMinuteRate() { -- return delegate.getFifteenMinuteRate(); -- } -+ private final io.dropwizard.metrics5.Timer.Context context; + private MetricRegistry metricRegistry; +--- a/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java ++++ b/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java +@@ -3,6 +3,7 @@ package io.dropwizard.metrics.jetty12.ee10; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatCode; -- @Override -- public double getFiveMinuteRate() { -- return delegate.getFiveMinuteRate(); -+ private Context(io.dropwizard.metrics5.Timer.Context context) { -+ this.context = context; - } +@@ -14,7 +15,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.client.ContentResponse; + import org.eclipse.jetty.client.HttpClient; +@@ -32,7 +32,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; -- @Override -- public double getMeanRate() { -- return delegate.getMeanRate(); -+ public long stop() { -+ return context.stop(); - } +-public class InstrumentedEE10HandlerTest { ++final class InstrumentedEE10HandlerTest { + private final HttpClient client = new HttpClient(); + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); +@@ -40,7 +40,7 @@ public class InstrumentedEE10HandlerTest { + private final InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); + + @BeforeEach +- public void setUp() throws Exception { ++ void setUp() throws Exception { + handler.setName("handler"); - @Override -- public double getOneMinuteRate() { -- return delegate.getOneMinuteRate(); -- } -- -- public void update(long duration, TimeUnit unit) { -- delegate.update(duration, unit); -- } -- -- public void update(Duration duration) { -- delegate.update(duration); -- } -- -- public T time(Callable event) throws Exception { -- return delegate.time(event); -- } -- -- public void time(Runnable event) { -- delegate.time(event); -- } -- -- public T timeSupplier(Supplier event) { -- return delegate.timeSupplier(event); -- } -- -- public Context time() { -- return new Context(delegate.time()); -- } -- -- public io.dropwizard.metrics5.Timer getDelegate() { -- return delegate; -- } -- -- -+ public void close() { -+ context.close(); -+ } -+ } -+ -+ public Timer() { -+ this(new io.dropwizard.metrics5.Timer()); -+ } -+ -+ public Timer(Reservoir reservoir) { -+ this(reservoir, Clock.defaultClock()); -+ } -+ -+ public Timer(Reservoir reservoir, Clock clock) { -+ this(new io.dropwizard.metrics5.Timer(reservoir.getDelegate(), clock.getDelegate())); -+ } -+ -+ public Timer(io.dropwizard.metrics5.Timer delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ return Snapshot.of(delegate.getSnapshot()); -+ } -+ -+ @Override -+ public long getCount() { -+ return delegate.getCount(); -+ } -+ -+ @Override -+ public double getFifteenMinuteRate() { -+ return delegate.getFifteenMinuteRate(); -+ } -+ -+ @Override -+ public double getFiveMinuteRate() { -+ return delegate.getFiveMinuteRate(); -+ } -+ -+ @Override -+ public double getMeanRate() { -+ return delegate.getMeanRate(); -+ } -+ -+ @Override -+ public double getOneMinuteRate() { -+ return delegate.getOneMinuteRate(); -+ } -+ -+ public void update(long duration, TimeUnit unit) { -+ delegate.update(duration, unit); -+ } -+ -+ public void update(Duration duration) { -+ delegate.update(duration); -+ } -+ -+ public T time(Callable event) throws Exception { -+ return delegate.time(event); -+ } -+ -+ public void time(Runnable event) { -+ delegate.time(event); -+ } -+ -+ public T timeSupplier(Supplier event) { -+ return delegate.timeSupplier(event); -+ } -+ -+ public Context time() { -+ return new Context(delegate.time()); -+ } -+ -+ public io.dropwizard.metrics5.Timer getDelegate() { -+ return delegate; -+ } - } ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/UniformReservoir.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/UniformReservoir.java -@@ -5,37 +5,37 @@ import static java.util.Objects.requireNonNull; - @Deprecated - public class UniformReservoir implements Reservoir { + TestHandler testHandler = new TestHandler(); +@@ -62,18 +62,18 @@ public class InstrumentedEE10HandlerTest { + } -- private io.dropwizard.metrics5.UniformReservoir delegate; -- -- public UniformReservoir() { -- this(new io.dropwizard.metrics5.UniformReservoir()); -- } -- -- public UniformReservoir(int size) { -- this(new io.dropwizard.metrics5.UniformReservoir(size)); -- } -- -- public UniformReservoir(io.dropwizard.metrics5.UniformReservoir delegate) { -- this.delegate = requireNonNull(delegate); -- } -- -- @Override -- public io.dropwizard.metrics5.Reservoir getDelegate() { -- return delegate; -- } -- -- @Override -- public int size() { -- return delegate.size(); -- } -- -- @Override -- public void update(long value) { -- delegate.update(value); -- } -- -- @Override -- public Snapshot getSnapshot() { -- return Snapshot.of(delegate.getSnapshot()); -- } -+ private io.dropwizard.metrics5.UniformReservoir delegate; -+ -+ public UniformReservoir() { -+ this(new io.dropwizard.metrics5.UniformReservoir()); -+ } -+ -+ public UniformReservoir(int size) { -+ this(new io.dropwizard.metrics5.UniformReservoir(size)); -+ } -+ -+ public UniformReservoir(io.dropwizard.metrics5.UniformReservoir delegate) { -+ this.delegate = requireNonNull(delegate); -+ } -+ -+ @Override -+ public io.dropwizard.metrics5.Reservoir getDelegate() { -+ return delegate; -+ } -+ -+ @Override -+ public int size() { -+ return delegate.size(); -+ } -+ -+ @Override -+ public void update(long value) { -+ delegate.update(value); -+ } -+ -+ @Override -+ public Snapshot getSnapshot() { -+ return Snapshot.of(delegate.getSnapshot()); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java -@@ -1,34 +1,34 @@ - package com.codahale.metrics; + @AfterEach +- public void tearDown() throws Exception { ++ void tearDown() throws Exception { + server.stop(); + client.stop(); + } --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; + @Test +- public void hasAName() throws Exception { ++ void hasAName() throws Exception { + assertThat(handler.getName()).isEqualTo("handler"); + } - import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.Test; + @Test +- public void createsAndRemovesMetricsForTheHandler() throws Exception { ++ void createsAndRemovesMetricsForTheHandler() throws Exception { + final ContentResponse response = client.GET(uri("/hello")); - @SuppressWarnings("deprecation") --class CachedGaugeTest { -+final class CachedGaugeTest { + assertThat(response.getStatus()).isEqualTo(404); +@@ -115,9 +115,9 @@ public class InstrumentedEE10HandlerTest { + assertThat(registry.getNames()).isEmpty(); + } -- @Test -- void testCreate() { -- CachedGauge cachedGauge = new CachedGauge(100, TimeUnit.MILLISECONDS) { -- @Override -- protected String loadValue() { -- return "heavyValue"; -- } +- @Test + @Disabled("flaky on virtual machines") +- public void responseTimesAreRecordedForBlockingResponses() throws Exception { + @Test -+ void create() { -+ CachedGauge cachedGauge = -+ new CachedGauge(100, TimeUnit.MILLISECONDS) { -+ @Override -+ protected String loadValue() { -+ return "heavyValue"; -+ } - }; -- assertThat(cachedGauge.getValue()).isEqualTo("heavyValue"); -- } -+ assertThat(cachedGauge.getValue()).isEqualTo("heavyValue"); -+ } - -- @Test -- void testCreateWothClock() { -- CachedGauge cachedGauge = new CachedGauge(new Clock.UserTimeClock(), 100, -- TimeUnit.MILLISECONDS) { -- @Override -- protected String loadValue() { -- return "heavyValue"; -- } -+ @Test -+ void createWothClock() { -+ CachedGauge cachedGauge = -+ new CachedGauge(new Clock.UserTimeClock(), 100, TimeUnit.MILLISECONDS) { -+ @Override -+ protected String loadValue() { -+ return "heavyValue"; -+ } - }; -- assertThat(cachedGauge.getValue()).isEqualTo("heavyValue"); -- } -+ assertThat(cachedGauge.getValue()).isEqualTo("heavyValue"); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java -@@ -1,32 +1,33 @@ - package com.codahale.metrics; ++ void responseTimesAreRecordedForBlockingResponses() throws Exception { --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; + final ContentResponse response = client.GET(uri("/blocking")); -+import org.junit.jupiter.api.Test; -+ - @SuppressWarnings("deprecation") --class ClockTest { -+final class ClockTest { +@@ -127,7 +127,7 @@ public class InstrumentedEE10HandlerTest { + } -- @Test -- void testDefaultClockCanBeUsed() { -- Clock clock = Clock.defaultClock(); -- assertThat(clock.getTick()).isGreaterThan(0); -- } -+ @Test -+ void defaultClockCanBeUsed() { -+ Clock clock = Clock.defaultClock(); -+ assertThat(clock.getTick()).isPositive(); -+ } + @Test +- public void doStopDoesNotThrowNPE() throws Exception { ++ void doStopDoesNotThrowNPE() throws Exception { + InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); + handler.setHandler(new TestHandler()); -- @Test -- void testUserTimeClockCanBeUsed() { -- Clock clock = new Clock.UserTimeClock(); -- assertThat(clock.getTick()).isGreaterThan(0); -- } -+ @Test -+ void userTimeClockCanBeUsed() { -+ Clock clock = new Clock.UserTimeClock(); -+ assertThat(clock.getTick()).isPositive(); -+ } - -- @Test -- void testCustomTimeClockCanBeUsed() { -- Clock clock = new Clock() { -- @Override -- public long getTick() { -- return 24; -- } +@@ -135,7 +135,7 @@ public class InstrumentedEE10HandlerTest { + } + + @Test +- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { ++ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { + InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "coarse", COARSE); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -145,7 +145,7 @@ public class InstrumentedEE10HandlerTest { + } + + @Test +- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { ++ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { + InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "detailed", DETAILED); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -154,9 +154,9 @@ public class InstrumentedEE10HandlerTest { + .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); + } + +- @Test + @Disabled("flaky on virtual machines") +- public void responseTimesAreRecordedForAsyncResponses() throws Exception { + @Test -+ void customTimeClockCanBeUsed() { -+ Clock clock = -+ new Clock() { -+ @Override -+ public long getTick() { -+ return 24; -+ } - }; -- assertThat(clock.getTick()).isEqualTo(24); -- } -+ assertThat(clock.getTick()).isEqualTo(24); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java -@@ -1,124 +1,129 @@ - package com.codahale.metrics; ++ void responseTimesAreRecordedForAsyncResponses() throws Exception { -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; + final ContentResponse response = client.GET(uri("/async")); - import java.io.ByteArrayOutputStream; - import java.io.PrintStream; --import java.nio.charset.StandardCharsets; - import java.util.EnumSet; - import java.util.Locale; - import java.util.TimeZone; - import java.util.concurrent.Executors; - import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; -- - import org.apache.commons.lang3.JavaVersion; - import org.apache.commons.lang3.SystemUtils; - import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.Test; +@@ -167,9 +167,9 @@ public class InstrumentedEE10HandlerTest { - @SuppressWarnings("deprecation") --class ConsoleReporterTest { -+final class ConsoleReporterTest { + private void assertResponseTimesValid() { + assertThat(registry.getMeters().get(metricName().resolve("2xx-responses")).getCount()) +- .isGreaterThan(0L); ++ .isPositive(); + assertThat(registry.getMeters().get(metricName().resolve(".200-responses")).getCount()) +- .isGreaterThan(0L); ++ .isPositive(); + + assertThat( + registry +@@ -177,12 +177,12 @@ public class InstrumentedEE10HandlerTest { + .get(metricName().resolve(".get-requests")) + .getSnapshot() + .getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat( + registry.getTimers().get(metricName().resolve(".requests")).getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -250,7 +250,7 @@ public class InstrumentedEE10HandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + servletContextRequest.getServletChannel().handle(); + } +--- a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java ++++ b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java +@@ -4,7 +4,10 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -13,7 +16,6 @@ import io.dropwizard.metrics5.RatioGauge; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -164,7 +166,7 @@ public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); -- private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); -- private final String dateHeader = SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8) ? -- "3/17/13 6:04:36 PM =============================================================" : -- // https://bugs.openjdk.org/browse/JDK-8304925 -- SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_20) ? -- "3/17/13, 6:04:36\u202FPM ============================================================" : -- "3/17/13, 6:04:36 PM ============================================================"; -+ private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); -+ private final String dateHeader = -+ SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8) -+ ? "3/17/13 6:04:36 PM =============================================================" -+ : -+ // https://bugs.openjdk.org/browse/JDK-8304925 -+ SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_20) -+ ? "3/17/13, 6:04:36\u202FPM ============================================================" -+ : "3/17/13, 6:04:36 PM ============================================================"; - -- @AfterEach -- void tearDown() throws Exception { -- executor.shutdownNow(); -- } -+ @AfterEach -+ void tearDown() throws Exception { -+ executor.shutdownNow(); -+ } + this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); +@@ -179,7 +181,7 @@ public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { -- @Test -- void testCreateConsoleReporter() throws Exception { -- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); -+ @Test -+ void createConsoleReporter() throws Exception { -+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - -- MetricRegistry metricRegistry = new MetricRegistry(); -- metricRegistry.timer("test-timer"); -- metricRegistry.meter("test-meter"); -- metricRegistry.histogram("test-histogram"); -- metricRegistry.counter("test-counter"); -- metricRegistry.register("test-gauge", (Gauge) () -> 20); -+ MetricRegistry metricRegistry = new MetricRegistry(); -+ metricRegistry.timer("test-timer"); -+ metricRegistry.meter("test-meter"); -+ metricRegistry.histogram("test-histogram"); -+ metricRegistry.counter("test-counter"); -+ metricRegistry.register("test-gauge", (Gauge) () -> 20); - -- ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(metricRegistry) -- .shutdownExecutorOnStop(false) -- .scheduleOn(executor) -- .outputTo(new PrintStream(byteArrayOutputStream)) -- .formattedFor(Locale.ENGLISH) -- .withClock(new Clock() { -+ ConsoleReporter consoleReporter = -+ ConsoleReporter.forRegistry(metricRegistry) -+ .shutdownExecutorOnStop(false) -+ .scheduleOn(executor) -+ .outputTo(new PrintStream(byteArrayOutputStream)) -+ .formattedFor(Locale.ENGLISH) -+ .withClock( -+ new Clock() { - -- @Override -- public long getTime() { -- return 1363568676000L; -- } -+ @Override -+ public long getTime() { -+ return 1363568676000L; -+ } - -- @Override -- public long getTick() { -- return 0; -- } -- }).formattedFor(TimeZone.getTimeZone("America/Los_Angeles")) -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .disabledMetricAttributes(EnumSet.of(MetricAttribute.P98, MetricAttribute.P99)) -- .build(); -- consoleReporter.report(); -+ @Override -+ public long getTick() { -+ return 0; -+ } -+ }) -+ .formattedFor(TimeZone.getTimeZone("America/Los_Angeles")) -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .disabledMetricAttributes(EnumSet.of(MetricAttribute.P98, MetricAttribute.P99)) -+ .build(); -+ consoleReporter.report(); - -- assertThat(new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8)) -- .isEqualToNormalizingNewlines(dateHeader + "\n" + -- "\n" + -- "-- Gauges ----------------------------------------------------------------------\n" + -- "test-gauge\n" + -- " value = 20\n" + -- "\n" + -- "-- Counters --------------------------------------------------------------------\n" + -- "test-counter\n" + -- " count = 0\n" + -- "\n" + -- "-- Histograms ------------------------------------------------------------------\n" + -- "test-histogram\n" + -- " count = 0\n" + -- " sum = 0\n" + -- " min = 0\n" + -- " max = 0\n" + -- " mean = 0.00\n" + -- " stddev = 0.00\n" + -- " median = 0.00\n" + -- " 75% <= 0.00\n" + -- " 95% <= 0.00\n" + -- " 99.9% <= 0.00\n" + -- "\n" + -- "-- Meters ----------------------------------------------------------------------\n" + -- "test-meter\n" + -- " count = 0\n" + -- " sum = 0\n" + -- " mean rate = 0.00 events/second\n" + -- " 1-minute rate = 0.00 events/second\n" + -- " 5-minute rate = 0.00 events/second\n" + -- " 15-minute rate = 0.00 events/second\n" + -- "\n" + -- "-- Timers ----------------------------------------------------------------------\n" + -- "test-timer\n" + -- " count = 0\n" + -- " sum = 0.00\n" + -- " mean rate = 0.00 calls/second\n" + -- " 1-minute rate = 0.00 calls/second\n" + -- " 5-minute rate = 0.00 calls/second\n" + -- " 15-minute rate = 0.00 calls/second\n" + -- " min = 0.00 milliseconds\n" + -- " max = 0.00 milliseconds\n" + -- " mean = 0.00 milliseconds\n" + -- " stddev = 0.00 milliseconds\n" + -- " median = 0.00 milliseconds\n" + -- " 75% <= 0.00 milliseconds\n" + -- " 95% <= 0.00 milliseconds\n" + -- " 99.9% <= 0.00 milliseconds\n" + -- "\n" + -- "\n" -- ); -- } -+ assertThat(new String(byteArrayOutputStream.toByteArray(), UTF_8)) -+ .isEqualToNormalizingNewlines( -+ dateHeader -+ + "\n" -+ + "\n" -+ + "-- Gauges ----------------------------------------------------------------------\n" -+ + "test-gauge\n" -+ + " value = 20\n" -+ + "\n" -+ + "-- Counters --------------------------------------------------------------------\n" -+ + "test-counter\n" -+ + " count = 0\n" -+ + "\n" -+ + "-- Histograms ------------------------------------------------------------------\n" -+ + "test-histogram\n" -+ + " count = 0\n" -+ + " sum = 0\n" -+ + " min = 0\n" -+ + " max = 0\n" -+ + " mean = 0.00\n" -+ + " stddev = 0.00\n" -+ + " median = 0.00\n" -+ + " 75% <= 0.00\n" -+ + " 95% <= 0.00\n" -+ + " 99.9% <= 0.00\n" -+ + "\n" -+ + "-- Meters ----------------------------------------------------------------------\n" -+ + "test-meter\n" -+ + " count = 0\n" -+ + " sum = 0\n" -+ + " mean rate = 0.00 events/second\n" -+ + " 1-minute rate = 0.00 events/second\n" -+ + " 5-minute rate = 0.00 events/second\n" -+ + " 15-minute rate = 0.00 events/second\n" -+ + "\n" -+ + "-- Timers ----------------------------------------------------------------------\n" -+ + "test-timer\n" -+ + " count = 0\n" -+ + " sum = 0.00\n" -+ + " mean rate = 0.00 calls/second\n" -+ + " 1-minute rate = 0.00 calls/second\n" -+ + " 5-minute rate = 0.00 calls/second\n" -+ + " 15-minute rate = 0.00 calls/second\n" -+ + " min = 0.00 milliseconds\n" -+ + " max = 0.00 milliseconds\n" -+ + " mean = 0.00 milliseconds\n" -+ + " stddev = 0.00 milliseconds\n" -+ + " median = 0.00 milliseconds\n" -+ + " 75% <= 0.00 milliseconds\n" -+ + " 95% <= 0.00 milliseconds\n" -+ + " 99.9% <= 0.00 milliseconds\n" -+ + "\n" -+ + "\n"); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java -@@ -1,40 +1,40 @@ - package com.codahale.metrics; + if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { + this.responses = +- Collections.unmodifiableList( ++ unmodifiableList( + Arrays.asList( + metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx +@@ -244,7 +246,7 @@ public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { + } + }); + } else { +- this.responses = Collections.emptyList(); ++ this.responses = ImmutableList.of(); + } + } -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.Counter; +--- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java ++++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java +@@ -19,7 +19,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; -- - @SuppressWarnings("deprecation") --class CounterTest { -+final class CounterTest { +-public class InstrumentedConnectionFactoryTest { ++final class InstrumentedConnectionFactoryTest { + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); + private final ServerConnector connector = +@@ -32,7 +32,7 @@ public class InstrumentedConnectionFactoryTest { + private final HttpClient client = new HttpClient(); + + @BeforeEach +- public void setUp() throws Exception { ++ void setUp() throws Exception { + server.setHandler( + new Handler.Abstract() { + @Override +@@ -50,13 +50,13 @@ public class InstrumentedConnectionFactoryTest { + } -- private Counter counter = new Counter(); -+ private Counter counter = new Counter(); + @AfterEach +- public void tearDown() throws Exception { ++ void tearDown() throws Exception { + server.stop(); + client.stop(); + } -- @Test -- void testIncrementCounter() { -- counter.inc(); -+ @Test -+ void incrementCounter() { -+ counter.inc(); + @Test +- public void instrumentsConnectionTimes() throws Exception { ++ void instrumentsConnectionTimes() throws Exception { + final ContentResponse response = + client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); + assertThat(response.getStatus()).isEqualTo(200); +@@ -70,7 +70,7 @@ public class InstrumentedConnectionFactoryTest { + } -- assertThat(counter.getCount()).isEqualTo(1); -- } -+ assertThat(counter.getCount()).isEqualTo(1); -+ } + @Test +- public void instrumentsActiveConnections() throws Exception { ++ void instrumentsActiveConnections() throws Exception { + final Counter counter = registry.counter("http.active-connections"); -- @Test -- void testIncrementCounterOnManyPoints() { -- counter.inc(5); -+ @Test -+ void incrementCounterOnManyPoints() { -+ counter.inc(5); + final ContentResponse response = +--- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java ++++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java +@@ -7,20 +7,20 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- assertThat(counter.getCount()).isEqualTo(5); -- } -+ assertThat(counter.getCount()).isEqualTo(5); -+ } +-public class InstrumentedQueuedThreadPoolTest { ++final class InstrumentedQueuedThreadPoolTest { + private static final String PREFIX = "prefix"; -- @Test -- void testDecrementCounter() { -- counter.dec(); -+ @Test -+ void decrementCounter() { -+ counter.dec(); + private MetricRegistry metricRegistry; + private InstrumentedQueuedThreadPool iqtp; -- assertThat(counter.getCount()).isEqualTo(-1); -- } -+ assertThat(counter.getCount()).isEqualTo(-1); -+ } + @BeforeEach +- public void setUp() { ++ void setUp() { + metricRegistry = new MetricRegistry(); + iqtp = new InstrumentedQueuedThreadPool(metricRegistry); + } -- @Test -- void testDecrementCounterOnManyPoints() { -- counter.dec(5); -+ @Test -+ void decrementCounterOnManyPoints() { -+ counter.dec(5); + @Test +- public void customMetricsPrefix() throws Exception { ++ void customMetricsPrefix() throws Exception { + iqtp.setPrefix(PREFIX); + iqtp.start(); -- assertThat(counter.getCount()).isEqualTo(-5); -- } -+ assertThat(counter.getCount()).isEqualTo(-5); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java -@@ -1,20 +1,21 @@ - package com.codahale.metrics; +@@ -35,7 +35,7 @@ public class InstrumentedQueuedThreadPoolTest { + } --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; + @Test +- public void metricsPrefixBackwardCompatible() throws Exception { ++ void metricsPrefixBackwardCompatible() throws Exception { + iqtp.start(); + assertThat(metricRegistry.getNames()) + .overridingErrorMessage("The default metrics prefix was changed") +--- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java ++++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java +@@ -10,7 +10,7 @@ import org.slf4j.LoggerFactory; + public class DefaultObjectNameFactory implements ObjectNameFactory { -+import org.junit.jupiter.api.Test; -+ - @SuppressWarnings("deprecation") --class DerivativeGaugeTest { -+final class DerivativeGaugeTest { + private static final char[] QUOTABLE_CHARS = new char[] {',', '=', ':', '"'}; +- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectNameFactory.class); -- @Test -- void testCalculate() { -- DerivativeGauge derivativeGauge = new DerivativeGauge(() -> "23") { -- @Override -- protected Integer transform(String value) { -- return Integer.parseInt(value); -- } -+ @Test -+ void calculate() { -+ DerivativeGauge derivativeGauge = -+ new DerivativeGauge(() -> "23") { -+ @Override -+ protected Integer transform(String value) { -+ return Integer.parseInt(value); -+ } - }; -- assertThat(derivativeGauge.getValue()).isEqualTo(23); -- } -+ assertThat(derivativeGauge.getValue()).isEqualTo(23); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -@@ -1,53 +1,55 @@ - package com.codahale.metrics; + @Override + public ObjectName createName(String type, String domain, MetricName name) { +@@ -38,14 +38,13 @@ public class DefaultObjectNameFactory implements ObjectNameFactory { + || shouldQuote(objectName.getKeyProperty("type"))) { + properties.put("type", ObjectName.quote(type)); + } +- objectName = new ObjectName(domain, properties); ++ return new ObjectName(domain, properties); --import org.assertj.core.data.Offset; --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; +- return objectName; + } catch (MalformedObjectNameException e) { + try { + return new ObjectName(domain, "name", ObjectName.quote(name.getKey())); + } catch (MalformedObjectNameException e1) { +- LOGGER.warn("Unable to register {} {}", type, name, e1); ++ LOG.warn("Unable to register {} {}", type, name, e1); + throw new RuntimeException(e1); + } + } +--- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java ++++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.jmx; --@SuppressWarnings("deprecation") --class ExponentiallyDecayingReservoirTest { -- -- @Test -- void testCreateReservoir() { -- ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(); -- reservoir.update(120); -- reservoir.update(190); -- reservoir.update(200); -- reservoir.update(130); -- reservoir.update(140); -- -- Snapshot snapshot = reservoir.getSnapshot(); -- assertThat(snapshot.size()).isEqualTo(5); -- assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); -- assertThat(snapshot.getMin()).isEqualTo(120); -- assertThat(snapshot.getMax()).isEqualTo(200); -- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); -- assertThat(snapshot.get75thPercentile()).isEqualTo(190); -- assertThat(snapshot.get95thPercentile()).isEqualTo(200); -- assertThat(snapshot.get98thPercentile()).isEqualTo(200); -- assertThat(snapshot.get99thPercentile()).isEqualTo(200); -- assertThat(snapshot.get999thPercentile()).isEqualTo(200); -- } -- -- @Test -- void testCreateReservoirWithCustomSizeAndAlpha() { -- ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01); -- reservoir.update(100); -- assertThat(reservoir.size()).isEqualTo(1); -- } -- -+import org.junit.jupiter.api.Test; - -- @Test -- void testCreateReservoirWithCustomSizeAlphaAndClock() { -- ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01, -- new Clock() { -- @Override -- public long getTick() { -- return 24; -- } -- }); -- reservoir.update(100); -- assertThat(reservoir.size()).isEqualTo(1); -- } -+@SuppressWarnings("deprecation") -+final class ExponentiallyDecayingReservoirTest { -+ -+ @Test -+ void createReservoir() { -+ ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(); -+ reservoir.update(120); -+ reservoir.update(190); -+ reservoir.update(200); -+ reservoir.update(130); -+ reservoir.update(140); -+ -+ Snapshot snapshot = reservoir.getSnapshot(); -+ assertThat(snapshot.size()).isEqualTo(5); -+ assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); -+ assertThat(snapshot.getMin()).isEqualTo(120); -+ assertThat(snapshot.getMax()).isEqualTo(200); -+ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); -+ assertThat(snapshot.get75thPercentile()).isEqualTo(190); -+ assertThat(snapshot.get95thPercentile()).isEqualTo(200); -+ assertThat(snapshot.get98thPercentile()).isEqualTo(200); -+ assertThat(snapshot.get99thPercentile()).isEqualTo(200); -+ assertThat(snapshot.get999thPercentile()).isEqualTo(200); -+ } -+ -+ @Test -+ void createReservoirWithCustomSizeAndAlpha() { -+ ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01); -+ reservoir.update(100); -+ assertThat(reservoir.size()).isEqualTo(1); -+ } ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Collections.unmodifiableMap; + -+ @Test -+ void createReservoirWithCustomSizeAlphaAndClock() { -+ ExponentiallyDecayingReservoir reservoir = -+ new ExponentiallyDecayingReservoir( -+ 512, -+ 0.01, -+ new Clock() { -+ @Override -+ public long getTick() { -+ return 24; -+ } -+ }); -+ reservoir.update(100); -+ assertThat(reservoir.size()).isEqualTo(1); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java -@@ -1,35 +1,34 @@ - package com.codahale.metrics; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Histogram; +@@ -13,7 +17,6 @@ import io.dropwizard.metrics5.Reporter; + import io.dropwizard.metrics5.Timer; + import java.io.Closeable; + import java.lang.management.ManagementFactory; +-import java.util.Collections; + import java.util.Locale; + import java.util.Map; + import java.util.concurrent.ConcurrentHashMap; +@@ -61,8 +64,8 @@ public class JmxReporter implements Reporter, Closeable { + this.durationUnit = TimeUnit.MILLISECONDS; + this.domain = "metrics"; + this.objectNameFactory = new DefaultObjectNameFactory(); +- this.specificDurationUnits = Collections.emptyMap(); +- this.specificRateUnits = Collections.emptyMap(); ++ this.specificDurationUnits = ImmutableMap.of(); ++ this.specificRateUnits = ImmutableMap.of(); + } --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; + /** +@@ -88,9 +91,7 @@ public class JmxReporter implements Reporter, Closeable { + } - import java.io.File; - import java.nio.file.Files; - import java.nio.file.Path; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; + public Builder createsObjectNamesWith(ObjectNameFactory onFactory) { +- if (onFactory == null) { +- throw new IllegalArgumentException("null objectNameFactory"); +- } ++ checkArgument(onFactory != null, "null objectNameFactory"); + this.objectNameFactory = onFactory; + return this; + } +@@ -129,7 +130,7 @@ public class JmxReporter implements Reporter, Closeable { + * @return {@code this} + */ + public Builder specificDurationUnits(Map specificDurationUnits) { +- this.specificDurationUnits = Collections.unmodifiableMap(specificDurationUnits); ++ this.specificDurationUnits = unmodifiableMap(specificDurationUnits); + return this; + } - @SuppressWarnings("deprecation") --class FixedNameCsvFileProviderTest { -- -- private Path tempDirectory; -- private FixedNameCsvFileProvider fixedNameCsvFileProvider = new FixedNameCsvFileProvider(); -- -- @BeforeEach -- void setUp() throws Exception { -- tempDirectory = Files.createTempDirectory("csv-test"); -- } -- -- @AfterEach -- void tearDown() throws Exception { -- Files.delete(tempDirectory); -- } -- -- @Test -- void getFile() throws Exception { -- File file = fixedNameCsvFileProvider.getFile(tempDirectory.toFile(), "timer-test"); -- assertThat(file.toString()).startsWith(tempDirectory.toString()); -- assertThat(file.toString()).endsWith("timer-test.csv"); -- } -+final class FixedNameCsvFileProviderTest { -+ -+ private Path tempDirectory; -+ private FixedNameCsvFileProvider fixedNameCsvFileProvider = new FixedNameCsvFileProvider(); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ tempDirectory = Files.createTempDirectory("csv-test"); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ Files.delete(tempDirectory); -+ } -+ -+ @Test -+ void getFile() throws Exception { -+ File file = fixedNameCsvFileProvider.getFile(tempDirectory.toFile(), "timer-test"); -+ assertThat(file.toString()).startsWith(tempDirectory.toString()); -+ assertThat(file.toString()).endsWith("timer-test.csv"); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java -@@ -1,16 +1,16 @@ - package com.codahale.metrics; +@@ -140,7 +141,7 @@ public class JmxReporter implements Reporter, Closeable { + * @return {@code this} + */ + public Builder specificRateUnits(Map specificRateUnits) { +- this.specificRateUnits = Collections.unmodifiableMap(specificRateUnits); ++ this.specificRateUnits = unmodifiableMap(specificRateUnits); + return this; + } --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; +@@ -159,7 +160,7 @@ public class JmxReporter implements Reporter, Closeable { + } + } -+import org.junit.jupiter.api.Test; -+ - @SuppressWarnings("deprecation") --class GaugeTest { -+final class GaugeTest { +- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(JmxReporter.class); -- private Gauge gauge = () -> 83; -+ private Gauge gauge = () -> 83; + @SuppressWarnings("UnusedDeclaration") + public interface MetricMBean { +@@ -570,9 +571,9 @@ public class JmxReporter implements Reporter, Closeable { + registerMBean(new JmxGauge(gauge, objectName), objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register gauge", e); ++ LOG.debug("Unable to register gauge", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register gauge", e); ++ LOG.warn("Unable to register gauge", e); + } + } -- @Test -- void testGetValue() { -- assertThat(gauge.getValue()).isEqualTo(83); -- } -+ @Test -+ void getValue() { -+ assertThat(gauge.getValue()).isEqualTo(83); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java -@@ -1,33 +1,33 @@ - package com.codahale.metrics; +@@ -582,9 +583,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("gauges", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister gauge", e); ++ LOG.debug("Unable to unregister gauge", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister gauge", e); ++ LOG.warn("Unable to unregister gauge", e); + } + } --import org.assertj.core.data.Offset; --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; -+ -+import org.junit.jupiter.api.Test; +@@ -596,9 +597,9 @@ public class JmxReporter implements Reporter, Closeable { + registerMBean(new JmxCounter(counter, objectName), objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register counter", e); ++ LOG.debug("Unable to register counter", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register counter", e); ++ LOG.warn("Unable to register counter", e); + } + } - @SuppressWarnings("deprecation") --class HistogramTest { -+final class HistogramTest { +@@ -608,9 +609,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("counters", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister counter", e); ++ LOG.debug("Unable to unregister counter", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister counter", e); ++ LOG.warn("Unable to unregister counter", e); + } + } -- @Test -- void testCreate() { -- Histogram histogram = new Histogram(new ExponentiallyDecayingReservoir()); -- histogram.update(120); -- histogram.update(190); -- histogram.update(200L); -- histogram.update(130); -- histogram.update(140); -+ @Test -+ void create() { -+ Histogram histogram = new Histogram(new ExponentiallyDecayingReservoir()); -+ histogram.update(120); -+ histogram.update(190); -+ histogram.update(200L); -+ histogram.update(130); -+ histogram.update(140); - -- assertThat(histogram.getCount()).isEqualTo(5); -- Snapshot snapshot = histogram.getSnapshot(); -- assertThat(snapshot.size()).isEqualTo(5); -- assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); -- assertThat(snapshot.getMin()).isEqualTo(120); -- assertThat(snapshot.getMax()).isEqualTo(200); -- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); -- assertThat(snapshot.get75thPercentile()).isEqualTo(190); -- assertThat(snapshot.get95thPercentile()).isEqualTo(200); -- assertThat(snapshot.get98thPercentile()).isEqualTo(200); -- assertThat(snapshot.get99thPercentile()).isEqualTo(200); -- assertThat(snapshot.get999thPercentile()).isEqualTo(200); -- } -+ assertThat(histogram.getCount()).isEqualTo(5); -+ Snapshot snapshot = histogram.getSnapshot(); -+ assertThat(snapshot.size()).isEqualTo(5); -+ assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); -+ assertThat(snapshot.getMin()).isEqualTo(120); -+ assertThat(snapshot.getMax()).isEqualTo(200); -+ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); -+ assertThat(snapshot.get75thPercentile()).isEqualTo(190); -+ assertThat(snapshot.get95thPercentile()).isEqualTo(200); -+ assertThat(snapshot.get98thPercentile()).isEqualTo(200); -+ assertThat(snapshot.get99thPercentile()).isEqualTo(200); -+ assertThat(snapshot.get999thPercentile()).isEqualTo(200); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java -@@ -1,34 +1,37 @@ - package com.codahale.metrics; +@@ -622,9 +623,9 @@ public class JmxReporter implements Reporter, Closeable { + registerMBean(new JmxHistogram(histogram, objectName), objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register histogram", e); ++ LOG.debug("Unable to register histogram", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register histogram", e); ++ LOG.warn("Unable to register histogram", e); + } + } --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; +@@ -634,9 +635,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("histograms", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister histogram", e); ++ LOG.debug("Unable to unregister histogram", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister histogram", e); ++ LOG.warn("Unable to unregister histogram", e); + } + } - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.ExecutorService; - import java.util.concurrent.Executors; - import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.Test; +@@ -649,9 +650,9 @@ public class JmxReporter implements Reporter, Closeable { + new JmxMeter(meter, objectName, timeUnits.rateFor(name.getKey())), objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register meter", e); ++ LOG.debug("Unable to register meter", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register meter", e); ++ LOG.warn("Unable to register meter", e); + } + } - @SuppressWarnings("deprecation") --class InstrumentedExecutorServiceTest { -- -+final class InstrumentedExecutorServiceTest { +@@ -661,9 +662,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("meters", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister meter", e); ++ LOG.debug("Unable to unregister meter", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister meter", e); ++ LOG.warn("Unable to unregister meter", e); + } + } -- @Test -- void testCreate() throws Exception { -- ExecutorService executorService = Executors.newSingleThreadExecutor(); -- MetricRegistry registry = new MetricRegistry(); -- InstrumentedExecutorService instrumentedExecutorService = new InstrumentedExecutorService(executorService, -- registry, "test-instrumented"); -- CountDownLatch countDownLatch = new CountDownLatch(10); -- for (int i = 0; i < 10; i++) { -- instrumentedExecutorService.submit(countDownLatch::countDown); -- } -- countDownLatch.await(5, TimeUnit.SECONDS); -- executorService.shutdown(); -- executorService.awaitTermination(5, TimeUnit.SECONDS); -- -- assertThat(registry.getMetrics()).containsOnlyKeys("test-instrumented.completed", -- "test-instrumented.submitted", "test-instrumented.duration", "test-instrumented.idle", -- "test-instrumented.running", "test-instrumented.rejected"); -+ @Test -+ void create() throws Exception { -+ ExecutorService executorService = Executors.newSingleThreadExecutor(); -+ MetricRegistry registry = new MetricRegistry(); -+ InstrumentedExecutorService instrumentedExecutorService = -+ new InstrumentedExecutorService(executorService, registry, "test-instrumented"); -+ CountDownLatch countDownLatch = new CountDownLatch(10); -+ for (int i = 0; i < 10; i++) { -+ instrumentedExecutorService.submit(countDownLatch::countDown); +@@ -681,9 +682,9 @@ public class JmxReporter implements Reporter, Closeable { + objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register timer", e); ++ LOG.debug("Unable to register timer", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register timer", e); ++ LOG.warn("Unable to register timer", e); + } } -+ countDownLatch.await(5, TimeUnit.SECONDS); -+ executorService.shutdown(); -+ executorService.awaitTermination(5, TimeUnit.SECONDS); -+ -+ assertThat(registry.getMetrics()) -+ .containsOnlyKeys( -+ "test-instrumented.completed", -+ "test-instrumented.submitted", -+ "test-instrumented.duration", -+ "test-instrumented.idle", -+ "test-instrumented.running", -+ "test-instrumented.rejected"); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java -@@ -1,37 +1,44 @@ - package com.codahale.metrics; --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; +@@ -693,9 +694,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("timers", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister timer", e); ++ LOG.debug("Unable to unregister timer", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister timer", e); ++ LOG.warn("Unable to unregister timer", e); + } + } + +@@ -708,9 +709,9 @@ public class JmxReporter implements Reporter, Closeable { + try { + unregisterMBean(name); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister metric", e); ++ LOG.debug("Unable to unregister metric", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister metric", e); ++ LOG.warn("Unable to unregister metric", e); + } + } + registered.clear(); +--- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java ++++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java +@@ -7,7 +7,7 @@ import io.dropwizard.metrics5.MetricName; + import javax.management.ObjectName; + import org.junit.jupiter.api.Test; + +-class DefaultObjectNameFactoryTest { ++final class DefaultObjectNameFactoryTest { - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.Executors; - import java.util.concurrent.ScheduledExecutorService; + @Test + void createsObjectNameWithDomainInInput() { +--- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java ++++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.jmx; + ++import static java.util.UUID.randomUUID; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +@@ -21,7 +22,6 @@ import io.dropwizard.metrics5.Timer; + import java.lang.management.ManagementFactory; + import java.util.SortedMap; + import java.util.TreeMap; +-import java.util.UUID; import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.Test; + import javax.management.Attribute; + import javax.management.AttributeList; +@@ -35,9 +35,9 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; - @SuppressWarnings("deprecation") --class InstrumentedScheduledExecutorServiceTest { -- private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); -+final class InstrumentedScheduledExecutorServiceTest { -+ private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + @SuppressWarnings("rawtypes") +-class JmxReporterTest { ++final class JmxReporterTest { + private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); +- private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); ++ private final String name = randomUUID().toString().replaceAll("[{\\-}]", ""); + private final MetricRegistry registry = new MetricRegistry(); + + private final JmxReporter reporter = +@@ -49,12 +49,12 @@ class JmxReporterTest { + .filter(MetricFilter.ALL) + .build(); + +- private final Gauge gauge = mock(Gauge.class); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); +- private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); ++ private final Gauge gauge = mock(); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); ++ private final ObjectNameFactory mockObjectNameFactory = mock(); + private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); -- @AfterEach -- void tearDown() { -- executorService.shutdown(); -- } -+ @AfterEach -+ void tearDown() { -+ executorService.shutdown(); -+ } - -- @Test -- void testCreate() throws Exception { -- MetricRegistry registry = new MetricRegistry(); -- InstrumentedScheduledExecutorService instrumentedExecutorService = new InstrumentedScheduledExecutorService( -- executorService, registry, "test-scheduled-instrumented"); -- CountDownLatch countDownLatch = new CountDownLatch(10); -- instrumentedExecutorService.scheduleAtFixedRate(countDownLatch::countDown, 0, 10, TimeUnit.MILLISECONDS); -- countDownLatch.await(5, TimeUnit.SECONDS); -- instrumentedExecutorService.shutdown(); -+ @Test -+ void create() throws Exception { -+ MetricRegistry registry = new MetricRegistry(); -+ InstrumentedScheduledExecutorService instrumentedExecutorService = -+ new InstrumentedScheduledExecutorService( -+ executorService, registry, "test-scheduled-instrumented"); -+ CountDownLatch countDownLatch = new CountDownLatch(10); -+ instrumentedExecutorService.scheduleAtFixedRate( -+ countDownLatch::countDown, 0, 10, TimeUnit.MILLISECONDS); -+ countDownLatch.await(5, TimeUnit.SECONDS); -+ instrumentedExecutorService.shutdown(); - -- assertThat(registry.getMetrics()).containsOnlyKeys("test-scheduled-instrumented.completed", -- "test-scheduled-instrumented.submitted", "test-scheduled-instrumented.duration", "test-scheduled-instrumented.running", -- "test-scheduled-instrumented.scheduled.once", "test-scheduled-instrumented.scheduled.overrun", -- "test-scheduled-instrumented.scheduled.percent-of-period", "test-scheduled-instrumented.scheduled.repetitively"); -- } -+ assertThat(registry.getMetrics()) -+ .containsOnlyKeys( -+ "test-scheduled-instrumented.completed", -+ "test-scheduled-instrumented.submitted", -+ "test-scheduled-instrumented.duration", -+ "test-scheduled-instrumented.running", -+ "test-scheduled-instrumented.scheduled.once", -+ "test-scheduled-instrumented.scheduled.overrun", -+ "test-scheduled-instrumented.scheduled.percent-of-period", -+ "test-scheduled-instrumented.scheduled.repetitively"); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java -@@ -1,28 +1,29 @@ - package com.codahale.metrics; + @BeforeEach +@@ -66,7 +66,7 @@ class JmxReporterTest { + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(12L); --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; +- final Snapshot hSnapshot = mock(Snapshot.class); ++ final Snapshot hSnapshot = mock(); + when(hSnapshot.getMax()).thenReturn(2L); + when(hSnapshot.getMean()).thenReturn(3.0); + when(hSnapshot.getMin()).thenReturn(4L); +@@ -95,7 +95,7 @@ class JmxReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot tSnapshot = mock(Snapshot.class); ++ final Snapshot tSnapshot = mock(); + when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -285,7 +285,7 @@ class JmxReporterTest { - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.Test; + @Test + void objectNameModifyingMBeanServer() throws Exception { +- MBeanServer mockedMBeanServer = mock(MBeanServer.class); ++ MBeanServer mockedMBeanServer = mock(); - @SuppressWarnings("deprecation") --class InstrumentedThreadFactoryTest { -+final class InstrumentedThreadFactoryTest { + // overwrite the objectName + when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))) +@@ -310,7 +310,7 @@ class JmxReporterTest { + } -- @Test -- @SuppressWarnings("DoNotCall") -- void testFactory() throws Exception { -- MetricRegistry registry = new MetricRegistry(); -- InstrumentedThreadFactory threadFactory = new InstrumentedThreadFactory(Thread::new, registry, -- "test-instrumented-thread-factory"); -- CountDownLatch latch = new CountDownLatch(4); -- for (int i = 0; i < 4; i++) { -- threadFactory.newThread(latch::countDown).run(); -- } -- latch.await(5, TimeUnit.SECONDS); -- assertThat(registry.meter("test-instrumented-thread-factory.created").getCount()).isEqualTo(4); -- assertThat(registry.counter("test-instrumented-thread-factory.running").getCount()).isEqualTo(0); -- assertThat(registry.meter("test-instrumented-thread-factory.terminated").getCount()).isEqualTo(4); -+ @SuppressWarnings("DoNotCall") -+ @Test -+ void factory() throws Exception { -+ MetricRegistry registry = new MetricRegistry(); -+ InstrumentedThreadFactory threadFactory = -+ new InstrumentedThreadFactory(Thread::new, registry, "test-instrumented-thread-factory"); -+ CountDownLatch latch = new CountDownLatch(4); -+ for (int i = 0; i < 4; i++) { -+ threadFactory.newThread(latch::countDown).run(); - } -+ latch.await(5, TimeUnit.SECONDS); -+ assertThat(registry.meter("test-instrumented-thread-factory.created").getCount()).isEqualTo(4); -+ assertThat(registry.counter("test-instrumented-thread-factory.running").getCount()) -+ .isEqualTo(0); -+ assertThat(registry.meter("test-instrumented-thread-factory.terminated").getCount()) -+ .isEqualTo(4); -+ } + @Test +- void testJmxMetricNameWithAsterisk() { ++ void jmxMetricNameWithAsterisk() { + MetricRegistry metricRegistry = new MetricRegistry(); + JmxReporter.forRegistry(metricRegistry).build().start(); + metricRegistry.counter("test*"); +--- a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java ++++ b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java +@@ -6,9 +6,9 @@ import com.fasterxml.jackson.databind.Module; + import com.fasterxml.jackson.databind.SerializerProvider; + import com.fasterxml.jackson.databind.module.SimpleSerializers; + import com.fasterxml.jackson.databind.ser.std.StdSerializer; ++import com.google.common.collect.ImmutableList; + import io.dropwizard.metrics5.health.HealthCheck; + import java.io.IOException; +-import java.util.Collections; + import java.util.Map; + + public class HealthCheckModule extends Module { +@@ -80,6 +80,6 @@ public class HealthCheckModule extends Module { + @Override + public void setupModule(SetupContext context) { + context.addSerializers( +- new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer()))); ++ new SimpleSerializers(ImmutableList.of(new HealthCheckResultSerializer()))); + } } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java -@@ -1,50 +1,53 @@ - package com.codahale.metrics; +--- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java ++++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java +@@ -10,15 +10,14 @@ import java.util.LinkedHashMap; + import java.util.Map; + import org.junit.jupiter.api.Test; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; +-class HealthCheckModuleTest { ++final class HealthCheckModuleTest { + private final ObjectMapper mapper = new ObjectMapper().registerModule(new HealthCheckModule()); - import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.Test; + @Test + void serializesAHealthyResult() throws Exception { + HealthCheck.Result result = HealthCheck.Result.healthy(); + assertThat(mapper.writeValueAsString(result)) +- .isEqualTo( +- "{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); ++ .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp()); + } - @SuppressWarnings("deprecation") --class MeterTest { -- -- @Test -- void testCreateMeteer() { -- Meter meter = new Meter(); -- assertThat(meter.getCount()).isEqualTo(0); -- } -- -- @Test -- void testCreateMeterWithCustomClock() { -- Meter meter = new Meter(new Clock() { -- @Override -- public long getTick() { -+final class MeterTest { -+ -+ @Test -+ void createMeteer() { -+ Meter meter = new Meter(); -+ assertThat(meter.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void createMeterWithCustomClock() { -+ Meter meter = -+ new Meter( -+ new Clock() { -+ @Override -+ public long getTick() { - return 0; -- } -- }); -- assertThat(meter.getCount()).isEqualTo(0); -- } -+ } -+ }); -+ assertThat(meter.getCount()).isEqualTo(0); -+ } + @Test +@@ -26,14 +25,8 @@ class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":true," +- + "\"message\":\"yay for me\"," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } -- @Test -- void testMark() { -- Meter meter = new Meter(new Clock() { -+ @Test -+ void mark() { -+ Meter meter = -+ new Meter( -+ new Clock() { - -- private long start = System.nanoTime(); -+ private long start = System.nanoTime(); - -- @Override -- public long getTick() { -+ @Override -+ public long getTick() { - return start += TimeUnit.SECONDS.toNanos(1); -- } -- }); -- for (int i = 0; i < 60; i++) { -- meter.mark(); -- } -- for (int i = 0; i < 60; i++) { -- meter.mark(2); -- } -- -- assertThat(meter.getCount()).isEqualTo(180); -- assertThat(meter.getMeanRate()).isBetween(1.0, 2.0); -+ } -+ }); -+ for (int i = 0; i < 60; i++) { -+ meter.mark(); - } -+ for (int i = 0; i < 60; i++) { -+ meter.mark(2); -+ } -+ -+ assertThat(meter.getCount()).isEqualTo(180); -+ assertThat(meter.getMeanRate()).isBetween(1.0, 2.0); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java -@@ -1,509 +1,554 @@ - package com.codahale.metrics; + @Test +@@ -41,14 +34,8 @@ class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"boo\"," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; + @Test +@@ -60,19 +47,8 @@ class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy(e); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"oh no\"," +- + "\"error\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh no\"," +- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" +- + "}," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } - import java.util.HashMap; - import java.util.Map; - import java.util.SortedMap; - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.data.Offset.offset; -+import org.junit.jupiter.api.Test; + @Test +@@ -88,24 +64,8 @@ class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy(b); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"oh well\"," +- + "\"error\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh well\"," +- + "\"stack\":[\"Blah.blee(Blah.java:150)\"]," +- + "\"cause\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh no\"," +- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" +- + "}" +- + "}," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } - @SuppressWarnings("deprecation") --class MetricRegistryTest { -- -- private MetricRegistry metricRegistry = new MetricRegistry(); -- -- @Test -- void testRegisterMetric() { -- Counter counter = metricRegistry.register("test-counter", new Counter()); -- counter.inc(42); -- assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); -- } -- -- @Test -- void testRegisterAll() { -- metricRegistry.registerAll(() -> { -- Map map = new HashMap<>(); -- map.put("test-counter", new Counter()); -- map.put("test-gauge", (Gauge) () -> 28); -- map.put("test-histogram", new Histogram(new ExponentiallyDecayingReservoir())); -- return map; -- }); -- Map metrics = metricRegistry.getMetrics(); -- assertThat(metrics).containsOnlyKeys("test-counter", "test-histogram", "test-gauge"); -- assertThat(metrics.get("test-counter")).isInstanceOf(Counter.class); -- assertThat(metrics.get("test-histogram")).isInstanceOf(Histogram.class); -- assertThat(metrics.get("test-gauge")).isInstanceOf(Gauge.class); -- } -- -- @Test -- void testRegisterGauge() { -- metricRegistry.registerGauge("test-gauge", () -> 42); -- assertThat(metricRegistry.getGauges().get("test-gauge").getValue()).isEqualTo(42); -- } -- -- @Test -- void testCreateCustomGauge() { -- Gauge gauge = metricRegistry.gauge("test-gauge-supplier", () -> () -> 42); -- assertThat(gauge.getValue()).isEqualTo(42); -- } -- -- @Test -- void testCreateCounter() { -- Counter counter = metricRegistry.counter("test-counter"); -- counter.inc(42); -- assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); -- } -- -- @Test -- void testCreateCustomCounter() { -- Counter counter = metricRegistry.counter("test-custom-counter", () -> { -- Counter c = new Counter(); -- c.inc(8); -- return c; -- }); -- counter.inc(16); -- assertThat(metricRegistry.counter("test-custom-counter").getCount()).isEqualTo(24); -- } -- -- @Test -- void testCreateHistogram() { -- Histogram histogram = metricRegistry.histogram("test-histogram"); -- histogram.update(100); -- histogram.update(200); -- histogram.update(180); -- assertThat(metricRegistry.histogram("test-histogram").getSnapshot().getMean()) -- .isCloseTo(160.0, offset(0.1)); -- } -- -- @Test -- void testCreateCustomHistogram() { -- Histogram histogram = metricRegistry.histogram("test-custom-histogram", -- () -> new Histogram(new SlidingWindowReservoir(2))); -- histogram.update(100); -- histogram.update(200); -- histogram.update(180); -- assertThat(metricRegistry.histogram("test-custom-histogram").getSnapshot().getMean()) -- .isCloseTo(190.0, offset(0.1)); -- } -- -- @Test -- void testCreateMeter() { -- Meter meter = metricRegistry.meter("test-meter"); -- meter.mark(); -- meter.mark(2); -- -- assertThat(metricRegistry.meter("test-meter").getCount()).isEqualTo(3); -- } -- -- @Test -- void testCreateCustomMeter() { -- Meter meter = metricRegistry.meter("test-custom-meter", () -> { -- Meter m = new Meter(); -- m.mark(16); -- return m; -- }); -- meter.mark(); -- -- assertThat(metricRegistry.meter("test-custom-meter").getCount()).isEqualTo(17); -- } -- -- @Test -- void testCreateTimer() { -- Timer timer = metricRegistry.timer("test-timer"); -- timer.update(100, TimeUnit.MILLISECONDS); -- timer.update(200, TimeUnit.MILLISECONDS); -- timer.update(180, TimeUnit.MILLISECONDS); -- -- assertThat(metricRegistry.timer("test-timer").getCount()).isEqualTo(3); -- } -- -- @Test -- void testCreateCustomTimer() { -- Timer timer = metricRegistry.timer("custom-test-timer", () -> { -- Timer t = new Timer(new UniformReservoir()); -- t.update(300, TimeUnit.MILLISECONDS); -- t.update(200, TimeUnit.MILLISECONDS); -- return t; -+final class MetricRegistryTest { -+ -+ private MetricRegistry metricRegistry = new MetricRegistry(); -+ -+ @Test -+ void registerMetric() { -+ Counter counter = metricRegistry.register("test-counter", new Counter()); -+ counter.inc(42); -+ assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); -+ } -+ -+ @Test -+ void registerAll() { -+ metricRegistry.registerAll( -+ () -> { -+ Map map = new HashMap<>(); -+ map.put("test-counter", new Counter()); -+ map.put("test-gauge", (Gauge) () -> 28); -+ map.put("test-histogram", new Histogram(new ExponentiallyDecayingReservoir())); -+ return map; - }); -- timer.update(180, TimeUnit.MILLISECONDS); -- -- assertThat(metricRegistry.timer("custom-test-timer").getCount()).isEqualTo(3); -- } -- -- @Test -- void testRemoveMetric() { -- metricRegistry.timer("test-timer"); -- metricRegistry.counter("test-counter"); -- metricRegistry.meter("test-meter"); -- -- assertThat(metricRegistry.remove("test-counter")).isTrue(); -- -- assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-timer", "test-meter"); -- } -- -- @Test -- void testRemoveMatching() { -- metricRegistry.counter("test-counter"); -- metricRegistry.timer("test-timer"); -- metricRegistry.timer("test-custom-timer"); -- metricRegistry.meter("test-meter"); -- -- metricRegistry.removeMatching((name, metric) -> metric instanceof Timer && name.startsWith("test")); -- assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-counter", "test-meter"); -- } -- -- @Test -- void testAddListenerForGauge() throws Exception { -- CountDownLatch gaugeAddedLatch = new CountDownLatch(1); -- CountDownLatch gaugeRemovedLatch = new CountDownLatch(1); -- metricRegistry.addListener(new MetricRegistryListener.Base() { -- @Override -- public void onGaugeAdded(String name, Gauge gauge) { -- assertThat(name).isEqualTo("test-gauge"); -- assertThat(gauge.getValue()).isEqualTo(42); -- gaugeAddedLatch.countDown(); -- } -- -- @Override -- public void onGaugeRemoved(String name) { -- assertThat(name).isEqualTo("test-gauge"); -- gaugeRemovedLatch.countDown(); -- } -+ Map metrics = metricRegistry.getMetrics(); -+ assertThat(metrics).containsOnlyKeys("test-counter", "test-histogram", "test-gauge"); -+ assertThat(metrics.get("test-counter")).isInstanceOf(Counter.class); -+ assertThat(metrics.get("test-histogram")).isInstanceOf(Histogram.class); -+ assertThat(metrics.get("test-gauge")).isInstanceOf(Gauge.class); -+ } -+ -+ @Test -+ void registerGauge() { -+ metricRegistry.registerGauge("test-gauge", () -> 42); -+ assertThat(metricRegistry.getGauges().get("test-gauge").getValue()).isEqualTo(42); -+ } -+ -+ @Test -+ void createCustomGauge() { -+ Gauge gauge = metricRegistry.gauge("test-gauge-supplier", () -> () -> 42); -+ assertThat(gauge.getValue()).isEqualTo(42); -+ } -+ -+ @Test -+ void createCounter() { -+ Counter counter = metricRegistry.counter("test-counter"); -+ counter.inc(42); -+ assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); -+ } -+ -+ @Test -+ void createCustomCounter() { -+ Counter counter = -+ metricRegistry.counter( -+ "test-custom-counter", -+ () -> { -+ Counter c = new Counter(); -+ c.inc(8); -+ return c; -+ }); -+ counter.inc(16); -+ assertThat(metricRegistry.counter("test-custom-counter").getCount()).isEqualTo(24); -+ } -+ -+ @Test -+ void createHistogram() { -+ Histogram histogram = metricRegistry.histogram("test-histogram"); -+ histogram.update(100); -+ histogram.update(200); -+ histogram.update(180); -+ assertThat(metricRegistry.histogram("test-histogram").getSnapshot().getMean()) -+ .isCloseTo(160.0, offset(0.1)); -+ } -+ -+ @Test -+ void createCustomHistogram() { -+ Histogram histogram = -+ metricRegistry.histogram( -+ "test-custom-histogram", () -> new Histogram(new SlidingWindowReservoir(2))); -+ histogram.update(100); -+ histogram.update(200); -+ histogram.update(180); -+ assertThat(metricRegistry.histogram("test-custom-histogram").getSnapshot().getMean()) -+ .isCloseTo(190.0, offset(0.1)); -+ } -+ -+ @Test -+ void createMeter() { -+ Meter meter = metricRegistry.meter("test-meter"); -+ meter.mark(); -+ meter.mark(2); -+ -+ assertThat(metricRegistry.meter("test-meter").getCount()).isEqualTo(3); -+ } -+ -+ @Test -+ void createCustomMeter() { -+ Meter meter = -+ metricRegistry.meter( -+ "test-custom-meter", -+ () -> { -+ Meter m = new Meter(); -+ m.mark(16); -+ return m; -+ }); -+ meter.mark(); -+ -+ assertThat(metricRegistry.meter("test-custom-meter").getCount()).isEqualTo(17); -+ } -+ -+ @Test -+ void createTimer() { -+ Timer timer = metricRegistry.timer("test-timer"); -+ timer.update(100, TimeUnit.MILLISECONDS); -+ timer.update(200, TimeUnit.MILLISECONDS); -+ timer.update(180, TimeUnit.MILLISECONDS); -+ -+ assertThat(metricRegistry.timer("test-timer").getCount()).isEqualTo(3); -+ } -+ -+ @Test -+ void createCustomTimer() { -+ Timer timer = -+ metricRegistry.timer( -+ "custom-test-timer", -+ () -> { -+ Timer t = new Timer(new UniformReservoir()); -+ t.update(300, TimeUnit.MILLISECONDS); -+ t.update(200, TimeUnit.MILLISECONDS); -+ return t; -+ }); -+ timer.update(180, TimeUnit.MILLISECONDS); -+ -+ assertThat(metricRegistry.timer("custom-test-timer").getCount()).isEqualTo(3); -+ } -+ -+ @Test -+ void removeMetric() { -+ metricRegistry.timer("test-timer"); -+ metricRegistry.counter("test-counter"); -+ metricRegistry.meter("test-meter"); -+ -+ assertThat(metricRegistry.remove("test-counter")).isTrue(); -+ -+ assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-timer", "test-meter"); -+ } -+ -+ @Test -+ void removeMatching() { -+ metricRegistry.counter("test-counter"); -+ metricRegistry.timer("test-timer"); -+ metricRegistry.timer("test-custom-timer"); -+ metricRegistry.meter("test-meter"); -+ -+ metricRegistry.removeMatching( -+ (name, metric) -> metric instanceof Timer && name.startsWith("test")); -+ assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-counter", "test-meter"); -+ } -+ -+ @Test -+ void addListenerForGauge() throws Exception { -+ CountDownLatch gaugeAddedLatch = new CountDownLatch(1); -+ CountDownLatch gaugeRemovedLatch = new CountDownLatch(1); -+ metricRegistry.addListener( -+ new MetricRegistryListener.Base() { -+ @Override -+ public void onGaugeAdded(String name, Gauge gauge) { -+ assertThat(name).isEqualTo("test-gauge"); -+ assertThat(gauge.getValue()).isEqualTo(42); -+ gaugeAddedLatch.countDown(); -+ } -+ -+ @Override -+ public void onGaugeRemoved(String name) { -+ assertThat(name).isEqualTo("test-gauge"); -+ gaugeRemovedLatch.countDown(); -+ } - }); + @Test +@@ -129,23 +89,7 @@ class HealthCheckModuleTest { + + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":true," +- + "\"duration\":0," +- + "\"boolean\":true," +- + "\"integer\":1," +- + "\"long\":2," +- + "\"float\":3.546," +- + "\"double\":4.567," +- + "\"BigInteger\":12345," +- + "\"BigDecimal\":12345.56789," +- + "\"String\":\"string\"," +- + "\"complex\":{" +- + "\"field\":\"value\"" +- + "}," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + } +--- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java ++++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java +@@ -16,7 +16,7 @@ import io.dropwizard.metrics5.Timer; + import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; -- metricRegistry.register("test-gauge", (Gauge) () -> 42); -- gaugeAddedLatch.await(5, TimeUnit.SECONDS); -- assertThat(gaugeAddedLatch.getCount()).isEqualTo(0); -- -- metricRegistry.remove("test-gauge"); -- gaugeRemovedLatch.await(5, TimeUnit.SECONDS); -- assertThat(gaugeRemovedLatch.getCount()).isEqualTo(0); -- } -- -- @Test -- void testAddListenerForCounter() throws Exception { -- CountDownLatch counterAddedLatch = new CountDownLatch(1); -- CountDownLatch counterRemovedLatch = new CountDownLatch(1); -- metricRegistry.addListener(new MetricRegistryListener.Base() { -- @Override -- public void onCounterAdded(String name, Counter counter) { -- assertThat(name).isEqualTo("test-counter"); -- counterAddedLatch.countDown(); -- } -- -- @Override -- public void onCounterRemoved(String name) { -- assertThat(name).isEqualTo("test-counter"); -- counterRemovedLatch.countDown(); -- } -+ metricRegistry.register("test-gauge", (Gauge) () -> 42); -+ gaugeAddedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(gaugeAddedLatch.getCount()).isEqualTo(0); -+ -+ metricRegistry.remove("test-gauge"); -+ gaugeRemovedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(gaugeRemovedLatch.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void addListenerForCounter() throws Exception { -+ CountDownLatch counterAddedLatch = new CountDownLatch(1); -+ CountDownLatch counterRemovedLatch = new CountDownLatch(1); -+ metricRegistry.addListener( -+ new MetricRegistryListener.Base() { -+ @Override -+ public void onCounterAdded(String name, Counter counter) { -+ assertThat(name).isEqualTo("test-counter"); -+ counterAddedLatch.countDown(); -+ } -+ -+ @Override -+ public void onCounterRemoved(String name) { -+ assertThat(name).isEqualTo("test-counter"); -+ counterRemovedLatch.countDown(); -+ } - }); +-class MetricsModuleTest { ++final class MetricsModuleTest { + private final ObjectMapper mapper = + new ObjectMapper() + .registerModule( +@@ -42,7 +42,7 @@ class MetricsModuleTest { -- metricRegistry.counter("test-counter"); -- counterAddedLatch.await(5, TimeUnit.SECONDS); -- assertThat(counterAddedLatch.getCount()).isEqualTo(0); -- -- metricRegistry.remove("test-counter"); -- counterRemovedLatch.await(5, TimeUnit.SECONDS); -- assertThat(counterRemovedLatch.getCount()).isEqualTo(0); -- } -- -- @Test -- void testAddListenerForHistogram() throws Exception { -- CountDownLatch histogramAddedLatch = new CountDownLatch(1); -- CountDownLatch histogramRemovedLatch = new CountDownLatch(1); -- metricRegistry.addListener(new MetricRegistryListener.Base() { -- -- -- @Override -- public void onHistogramAdded(String name, Histogram histogram) { -- assertThat(name).isEqualTo("test-histogram"); -- histogramAddedLatch.countDown(); -- } -- -- @Override -- public void onHistogramRemoved(String name) { -- assertThat(name).isEqualTo("test-histogram"); -- histogramRemovedLatch.countDown(); -- } -+ metricRegistry.counter("test-counter"); -+ counterAddedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(counterAddedLatch.getCount()).isEqualTo(0); -+ -+ metricRegistry.remove("test-counter"); -+ counterRemovedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(counterRemovedLatch.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void addListenerForHistogram() throws Exception { -+ CountDownLatch histogramAddedLatch = new CountDownLatch(1); -+ CountDownLatch histogramRemovedLatch = new CountDownLatch(1); -+ metricRegistry.addListener( -+ new MetricRegistryListener.Base() { -+ -+ @Override -+ public void onHistogramAdded(String name, Histogram histogram) { -+ assertThat(name).isEqualTo("test-histogram"); -+ histogramAddedLatch.countDown(); -+ } -+ -+ @Override -+ public void onHistogramRemoved(String name) { -+ assertThat(name).isEqualTo("test-histogram"); -+ histogramRemovedLatch.countDown(); -+ } - }); + @Test + void serializesCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); -- metricRegistry.histogram("test-histogram"); -- histogramAddedLatch.await(5, TimeUnit.SECONDS); -- assertThat(histogramAddedLatch.getCount()).isEqualTo(0); -- -- metricRegistry.remove("test-histogram"); -- histogramRemovedLatch.await(5, TimeUnit.SECONDS); -- assertThat(histogramRemovedLatch.getCount()).isEqualTo(0); -- } -- -- @Test -- void testAddListenerForMeter() throws Exception { -- CountDownLatch meterAddedLatch = new CountDownLatch(1); -- CountDownLatch meterRemovedLatch = new CountDownLatch(1); -- metricRegistry.addListener(new MetricRegistryListener.Base() { -- -- @Override -- public void onMeterAdded(String name, Meter meter) { -- assertThat(name).isEqualTo("test-meter"); -- meterAddedLatch.countDown(); -- } -- -- @Override -- public void onMeterRemoved(String name) { -- assertThat(name).isEqualTo("test-meter"); -- meterRemovedLatch.countDown(); -- } -+ metricRegistry.histogram("test-histogram"); -+ histogramAddedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(histogramAddedLatch.getCount()).isEqualTo(0); -+ -+ metricRegistry.remove("test-histogram"); -+ histogramRemovedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(histogramRemovedLatch.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void addListenerForMeter() throws Exception { -+ CountDownLatch meterAddedLatch = new CountDownLatch(1); -+ CountDownLatch meterRemovedLatch = new CountDownLatch(1); -+ metricRegistry.addListener( -+ new MetricRegistryListener.Base() { -+ -+ @Override -+ public void onMeterAdded(String name, Meter meter) { -+ assertThat(name).isEqualTo("test-meter"); -+ meterAddedLatch.countDown(); -+ } -+ -+ @Override -+ public void onMeterRemoved(String name) { -+ assertThat(name).isEqualTo("test-meter"); -+ meterRemovedLatch.countDown(); -+ } - }); + assertThat(mapper.writeValueAsString(counter)).isEqualTo("{\"count\":100}"); +@@ -50,10 +50,10 @@ class MetricsModuleTest { -- metricRegistry.meter("test-meter"); -- meterAddedLatch.await(5, TimeUnit.SECONDS); -- assertThat(meterAddedLatch.getCount()).isEqualTo(0); -- -- metricRegistry.remove("test-meter"); -- meterRemovedLatch.await(5, TimeUnit.SECONDS); -- assertThat(meterRemovedLatch.getCount()).isEqualTo(0); -- } -- -- @Test -- void testAddListenerForTimer() throws Exception { -- CountDownLatch timerAddedLatch = new CountDownLatch(1); -- CountDownLatch timerRemovedLatch = new CountDownLatch(1); -- metricRegistry.addListener(new MetricRegistryListener.Base() { -- -- @Override -- public void onTimerAdded(String name, Timer timer) { -- assertThat(name).isEqualTo("test-timer"); -- timerAddedLatch.countDown(); -- } -- -- @Override -- public void onTimerRemoved(String name) { -- assertThat(name).isEqualTo("test-timer"); -- timerRemovedLatch.countDown(); -- } -+ metricRegistry.meter("test-meter"); -+ meterAddedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(meterAddedLatch.getCount()).isEqualTo(0); -+ -+ metricRegistry.remove("test-meter"); -+ meterRemovedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(meterRemovedLatch.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void addListenerForTimer() throws Exception { -+ CountDownLatch timerAddedLatch = new CountDownLatch(1); -+ CountDownLatch timerRemovedLatch = new CountDownLatch(1); -+ metricRegistry.addListener( -+ new MetricRegistryListener.Base() { -+ -+ @Override -+ public void onTimerAdded(String name, Timer timer) { -+ assertThat(name).isEqualTo("test-timer"); -+ timerAddedLatch.countDown(); -+ } -+ -+ @Override -+ public void onTimerRemoved(String name) { -+ assertThat(name).isEqualTo("test-timer"); -+ timerRemovedLatch.countDown(); -+ } - }); + @Test + void serializesHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); -- metricRegistry.timer("test-timer"); -- timerAddedLatch.await(5, TimeUnit.SECONDS); -- assertThat(timerAddedLatch.getCount()).isEqualTo(0); -- -- metricRegistry.remove("test-timer"); -- timerRemovedLatch.await(5, TimeUnit.SECONDS); -- assertThat(timerRemovedLatch.getCount()).isEqualTo(0); -- } -- -- @Test -- void testRemoveListener() throws Exception { -- CountDownLatch gaugeAddedLatch = new CountDownLatch(1); -- MetricRegistryListener listener = new MetricRegistryListener.Base() { -- @Override -- public void onGaugeAdded(String name, Gauge gauge) { -- gaugeAddedLatch.countDown(); -- } -+ metricRegistry.timer("test-timer"); -+ timerAddedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(timerAddedLatch.getCount()).isEqualTo(0); -+ -+ metricRegistry.remove("test-timer"); -+ timerRemovedLatch.await(5, TimeUnit.SECONDS); -+ assertThat(timerRemovedLatch.getCount()).isEqualTo(0); -+ } -+ -+ @Test -+ void removeListener() throws Exception { -+ CountDownLatch gaugeAddedLatch = new CountDownLatch(1); -+ MetricRegistryListener listener = -+ new MetricRegistryListener.Base() { -+ @Override -+ public void onGaugeAdded(String name, Gauge gauge) { -+ gaugeAddedLatch.countDown(); -+ } - }; -- metricRegistry.addListener(listener); -- metricRegistry.removeListener(listener); -- -- metricRegistry.register("test-gauge", (Gauge) () -> 39); -- -- gaugeAddedLatch.await(100, TimeUnit.MILLISECONDS); -- assertThat(gaugeAddedLatch.getCount()).isEqualTo(1); -- } -- -- @Test -- void testGetNames() { -- metricRegistry.counter("test-counter"); -- metricRegistry.timer("test-timer"); -- metricRegistry.timer("test-custom-timer"); -- metricRegistry.meter("test-meter"); -- -- assertThat(metricRegistry.getNames()).containsExactly("test-counter", "test-custom-timer", -- "test-meter", "test-timer"); -- } -- -- @Test -- void testGetGauges() { -- metricRegistry.counter("test-counter"); -- metricRegistry.timer("test-timer"); -- metricRegistry.meter("test-meter"); -- metricRegistry.register("test-text-gauge-2", new CachedGauge(1, TimeUnit.MINUTES) { -- @Override -- protected String loadValue() { -- return "eu2"; -- } -+ metricRegistry.addListener(listener); -+ metricRegistry.removeListener(listener); -+ -+ metricRegistry.register("test-gauge", (Gauge) () -> 39); -+ -+ gaugeAddedLatch.await(100, TimeUnit.MILLISECONDS); -+ assertThat(gaugeAddedLatch.getCount()).isEqualTo(1); -+ } -+ -+ @Test -+ void getNames() { -+ metricRegistry.counter("test-counter"); -+ metricRegistry.timer("test-timer"); -+ metricRegistry.timer("test-custom-timer"); -+ metricRegistry.meter("test-meter"); -+ -+ assertThat(metricRegistry.getNames()) -+ .containsExactly("test-counter", "test-custom-timer", "test-meter", "test-timer"); -+ } -+ -+ @Test -+ void getGauges() { -+ metricRegistry.counter("test-counter"); -+ metricRegistry.timer("test-timer"); -+ metricRegistry.meter("test-meter"); -+ metricRegistry.register( -+ "test-text-gauge-2", -+ new CachedGauge(1, TimeUnit.MINUTES) { -+ @Override -+ protected String loadValue() { -+ return "eu2"; -+ } - }); -- metricRegistry.register("test-gauge", (Gauge) () -> 42); -- metricRegistry.register("test-text-gauge-1", new DerivativeGauge(() -> 1) { -- @Override -- protected String transform(Integer value) { -- return "eu" + value; -- } -+ metricRegistry.register("test-gauge", (Gauge) () -> 42); -+ metricRegistry.register( -+ "test-text-gauge-1", -+ new DerivativeGauge(() -> 1) { -+ @Override -+ protected String transform(Integer value) { -+ return "eu" + value; -+ } - }); +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -107,7 +107,7 @@ class MetricsModuleTest { -- SortedMap gauges = metricRegistry.getGauges(); -- assertThat(gauges).containsOnlyKeys("test-gauge", "test-text-gauge-1", "test-text-gauge-2"); -- } -- -- @Test -- void testGetGaugesWithFilter() { -- metricRegistry.counter("test-counter"); -- metricRegistry.timer("test-timer"); -- metricRegistry.meter("test-meter"); -- metricRegistry.register("test-text-gauge-2", new CachedGauge(1, TimeUnit.MINUTES) { -- @Override -- protected String loadValue() { -- return "eu2"; -- } -+ SortedMap gauges = metricRegistry.getGauges(); -+ assertThat(gauges).containsOnlyKeys("test-gauge", "test-text-gauge-1", "test-text-gauge-2"); -+ } -+ -+ @Test -+ void getGaugesWithFilter() { -+ metricRegistry.counter("test-counter"); -+ metricRegistry.timer("test-timer"); -+ metricRegistry.meter("test-meter"); -+ metricRegistry.register( -+ "test-text-gauge-2", -+ new CachedGauge(1, TimeUnit.MINUTES) { -+ @Override -+ protected String loadValue() { -+ return "eu2"; -+ } - }); -- metricRegistry.register("test-gauge", (Gauge) () -> 42); -- metricRegistry.register("test-text-gauge-1", new DerivativeGauge(() -> 1) { -- @Override -- protected String transform(Integer value) { -- return "eu" + value; -- } -+ metricRegistry.register("test-gauge", (Gauge) () -> 42); -+ metricRegistry.register( -+ "test-text-gauge-1", -+ new DerivativeGauge(() -> 1) { -+ @Override -+ protected String transform(Integer value) { -+ return "eu" + value; -+ } - }); + @Test + void serializesMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(5.0); +@@ -127,14 +127,14 @@ class MetricsModuleTest { -- assertThat(metricRegistry.getGauges((name, metric) -> name.contains("gauge") && metric instanceof CachedGauge)) -- .containsOnlyKeys("test-text-gauge-2"); -- } -- -- @Test -- void testGetHistograms() { -- metricRegistry.counter("test-counter"); -- metricRegistry.timer("test-timer"); -- metricRegistry.meter("test-meter"); -- metricRegistry.histogram("test-histogram-1"); -- metricRegistry.histogram("test-histogram-3"); -- metricRegistry.histogram("test-histogram-2"); -- -- assertThat(metricRegistry.getHistograms()) -- .containsOnlyKeys("test-histogram-1", "test-histogram-2", "test-histogram-3"); -- } -- -- @Test -- void testGetHistogramsWithFilter() { -- metricRegistry.counter("sw-counter"); -- metricRegistry.timer("sw-timer"); -- metricRegistry.meter("sw-meter"); -- metricRegistry.histogram("sw-histogram-1"); -- metricRegistry.histogram("se-histogram-3"); -- metricRegistry.histogram("sw-histogram-2"); -- -- assertThat(metricRegistry.getHistograms(MetricFilter.startsWith("sw"))) -- .containsOnlyKeys("sw-histogram-1", "sw-histogram-2"); -- } -- -- @Test -- void testGetCounters() { -- metricRegistry.histogram("test-histogram"); -- metricRegistry.timer("test-timer"); -- metricRegistry.meter("test-meter"); -- metricRegistry.counter("test-counter-1"); -- metricRegistry.counter("test-counter-3"); -- metricRegistry.counter("test-counter-2"); -- -- assertThat(metricRegistry.getCounters()) -- .containsOnlyKeys("test-counter-1", "test-counter-2", "test-counter-3"); -- } -- -- @Test -- void testGetCountersWithFilter() { -- metricRegistry.histogram("test-histogram"); -- metricRegistry.timer("test-timer"); -- metricRegistry.meter("test-meter"); -- metricRegistry.counter("test-counter-1"); -- metricRegistry.counter("test-counter-3"); -- metricRegistry.counter("test-cnt-2"); -- -- assertThat(metricRegistry.getCounters(MetricFilter.contains("counter"))) -- .containsOnlyKeys("test-counter-1", "test-counter-3"); -- } -- -- @Test -- void testGetMeters() { -- metricRegistry.register("test-gauge", (Gauge) () -> 42); -- metricRegistry.histogram("test-histogram"); -- metricRegistry.timer("test-timer"); -- metricRegistry.counter("test-counter"); -- metricRegistry.meter("test-meter-1"); -- metricRegistry.meter("test-meter-3"); -- metricRegistry.meter("test-meter-2"); -- -- assertThat(metricRegistry.getMeters()).containsOnlyKeys("test-meter-1", "test-meter-2", "test-meter-3"); -- } -- -- @Test -- void testGetMetersWithFilter() { -- metricRegistry.register("sw-gauge", (Gauge) () -> 42); -- metricRegistry.histogram("sw-histogram"); -- metricRegistry.timer("sw-timer"); -- metricRegistry.counter("sw-counter"); -- metricRegistry.meter("nw-meter-1"); -- metricRegistry.meter("sw-meter-3"); -- metricRegistry.meter("nw-meter-2"); -- -- assertThat(metricRegistry.getMeters(MetricFilter.startsWith("sw"))).containsOnlyKeys("sw-meter-3"); -- } -- -- @Test -- void testGetTimers() { -- metricRegistry.histogram("test-histogram"); -- metricRegistry.meter("test-meter"); -- metricRegistry.counter("test-counter"); -- metricRegistry.timer("test-timer-1"); -- metricRegistry.timer("test-timer-3"); -- metricRegistry.timer("test-timer-2"); -- -- assertThat(metricRegistry.getTimers()).containsOnlyKeys("test-timer-1", "test-timer-2", "test-timer-3"); -- } -- -- @Test -- void testGetTimersWithFilter() { -- metricRegistry.histogram("test-histogram-2"); -- metricRegistry.meter("test-meter-2"); -- metricRegistry.counter("test-counter-2"); -- metricRegistry.timer("test-timer-1"); -- metricRegistry.timer("test-timer-3"); -- metricRegistry.timer("test-timer-2"); -- -- assertThat(metricRegistry.getTimers(MetricFilter.endsWith("2"))).containsOnlyKeys("test-timer-2"); -- } -- -- @Test -- void testGetMetrics() { -- metricRegistry.register("test-text-gauge-2", new CachedGauge(1, TimeUnit.MINUTES) { -- @Override -- protected String loadValue() { -- return "eu2"; -- } -+ assertThat( -+ metricRegistry.getGauges( -+ (name, metric) -> name.contains("gauge") && metric instanceof CachedGauge)) -+ .containsOnlyKeys("test-text-gauge-2"); -+ } -+ -+ @Test -+ void getHistograms() { -+ metricRegistry.counter("test-counter"); -+ metricRegistry.timer("test-timer"); -+ metricRegistry.meter("test-meter"); -+ metricRegistry.histogram("test-histogram-1"); -+ metricRegistry.histogram("test-histogram-3"); -+ metricRegistry.histogram("test-histogram-2"); -+ -+ assertThat(metricRegistry.getHistograms()) -+ .containsOnlyKeys("test-histogram-1", "test-histogram-2", "test-histogram-3"); -+ } -+ -+ @Test -+ void getHistogramsWithFilter() { -+ metricRegistry.counter("sw-counter"); -+ metricRegistry.timer("sw-timer"); -+ metricRegistry.meter("sw-meter"); -+ metricRegistry.histogram("sw-histogram-1"); -+ metricRegistry.histogram("se-histogram-3"); -+ metricRegistry.histogram("sw-histogram-2"); -+ -+ assertThat(metricRegistry.getHistograms(MetricFilter.startsWith("sw"))) -+ .containsOnlyKeys("sw-histogram-1", "sw-histogram-2"); -+ } -+ -+ @Test -+ void getCounters() { -+ metricRegistry.histogram("test-histogram"); -+ metricRegistry.timer("test-timer"); -+ metricRegistry.meter("test-meter"); -+ metricRegistry.counter("test-counter-1"); -+ metricRegistry.counter("test-counter-3"); -+ metricRegistry.counter("test-counter-2"); -+ -+ assertThat(metricRegistry.getCounters()) -+ .containsOnlyKeys("test-counter-1", "test-counter-2", "test-counter-3"); -+ } -+ -+ @Test -+ void getCountersWithFilter() { -+ metricRegistry.histogram("test-histogram"); -+ metricRegistry.timer("test-timer"); -+ metricRegistry.meter("test-meter"); -+ metricRegistry.counter("test-counter-1"); -+ metricRegistry.counter("test-counter-3"); -+ metricRegistry.counter("test-cnt-2"); -+ -+ assertThat(metricRegistry.getCounters(MetricFilter.contains("counter"))) -+ .containsOnlyKeys("test-counter-1", "test-counter-3"); -+ } -+ -+ @Test -+ void getMeters() { -+ metricRegistry.register("test-gauge", (Gauge) () -> 42); -+ metricRegistry.histogram("test-histogram"); -+ metricRegistry.timer("test-timer"); -+ metricRegistry.counter("test-counter"); -+ metricRegistry.meter("test-meter-1"); -+ metricRegistry.meter("test-meter-3"); -+ metricRegistry.meter("test-meter-2"); -+ -+ assertThat(metricRegistry.getMeters()) -+ .containsOnlyKeys("test-meter-1", "test-meter-2", "test-meter-3"); -+ } -+ -+ @Test -+ void getMetersWithFilter() { -+ metricRegistry.register("sw-gauge", (Gauge) () -> 42); -+ metricRegistry.histogram("sw-histogram"); -+ metricRegistry.timer("sw-timer"); -+ metricRegistry.counter("sw-counter"); -+ metricRegistry.meter("nw-meter-1"); -+ metricRegistry.meter("sw-meter-3"); -+ metricRegistry.meter("nw-meter-2"); -+ -+ assertThat(metricRegistry.getMeters(MetricFilter.startsWith("sw"))) -+ .containsOnlyKeys("sw-meter-3"); -+ } -+ -+ @Test -+ void getTimers() { -+ metricRegistry.histogram("test-histogram"); -+ metricRegistry.meter("test-meter"); -+ metricRegistry.counter("test-counter"); -+ metricRegistry.timer("test-timer-1"); -+ metricRegistry.timer("test-timer-3"); -+ metricRegistry.timer("test-timer-2"); + @Test + void serializesTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java +@@ -1,10 +1,11 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; + -+ assertThat(metricRegistry.getTimers()) -+ .containsOnlyKeys("test-timer-1", "test-timer-2", "test-timer-3"); -+ } + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricSet; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + import javax.management.JMException; +@@ -19,7 +20,7 @@ import org.slf4j.LoggerFactory; + *

    These JMX objects are only available on Java 7 and above. + */ + public class BufferPoolMetricSet implements MetricSet { +- private static final Logger LOGGER = LoggerFactory.getLogger(BufferPoolMetricSet.class); ++ private static final Logger LOG = LoggerFactory.getLogger(BufferPoolMetricSet.class); + private static final String[] ATTRIBUTES = {"Count", "MemoryUsed", "TotalCapacity"}; + private static final String[] NAMES = {"count", "used", "capacity"}; + private static final String[] POOLS = {"direct", "mapped"}; +@@ -43,10 +44,10 @@ public class BufferPoolMetricSet implements MetricSet { + gauges.put( + MetricRegistry.name(pool, name), new JmxAttributeGauge(mBeanServer, on, attribute)); + } catch (JMException ignored) { +- LOGGER.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); ++ LOG.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); + } + } + } +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; + -+ @Test -+ void getTimersWithFilter() { -+ metricRegistry.histogram("test-histogram-2"); -+ metricRegistry.meter("test-meter-2"); -+ metricRegistry.counter("test-counter-2"); -+ metricRegistry.timer("test-timer-1"); -+ metricRegistry.timer("test-timer-3"); -+ metricRegistry.timer("test-timer-2"); + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; +@@ -9,7 +11,6 @@ import java.lang.management.GarbageCollectorMXBean; + import java.lang.management.ManagementFactory; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -43,6 +44,6 @@ public class GarbageCollectorMetricSet implements MetricSet { + gauges.put(MetricRegistry.name(name, "count"), (Gauge) gc::getCollectionCount); + gauges.put(MetricRegistry.name(name, "time"), (Gauge) gc::getCollectionTime); + } +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java +@@ -1,12 +1,13 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; + -+ assertThat(metricRegistry.getTimers(MetricFilter.endsWith("2"))) -+ .containsOnlyKeys("test-timer-2"); -+ } + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricSet; + import java.lang.management.ManagementFactory; + import java.lang.management.RuntimeMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Locale; + import java.util.Map; +@@ -47,6 +48,6 @@ public class JvmAttributeGaugeSet implements MetricSet { + runtime.getSpecVersion())); + gauges.put(MetricName.build("uptime"), (Gauge) runtime::getUptime); + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; + -+ @Test -+ void getMetrics() { -+ metricRegistry.register( -+ "test-text-gauge-2", -+ new CachedGauge(1, TimeUnit.MINUTES) { -+ @Override -+ protected String loadValue() { -+ return "eu2"; -+ } - }); -- metricRegistry.register("test-gauge", (Gauge) () -> 42); -- metricRegistry.register("test-text-gauge-1", new RatioGauge() { -- @Override -- protected Ratio getRatio() { -- return Ratio.of(1, 2); -- } -+ metricRegistry.register("test-gauge", (Gauge) () -> 42); -+ metricRegistry.register( -+ "test-text-gauge-1", -+ new RatioGauge() { -+ @Override -+ protected Ratio getRatio() { -+ return Ratio.of(1, 2); -+ } - }); -- metricRegistry.histogram("test-histogram-1"); -- metricRegistry.histogram("test-histogram-2"); -- metricRegistry.meter("test-meter-1"); -- metricRegistry.meter("test-meter-2"); -- metricRegistry.counter("test-counter"); -- metricRegistry.timer("test-timer-1"); -- metricRegistry.timer("test-timer-2"); -- MetricRegistry subMetrics = new MetricRegistry(); -- subMetrics.counter("sb-counter-1"); -- subMetrics.counter("sb-counter-2"); -- subMetrics.histogram("sb-histogram-1"); -- metricRegistry.register("test-ms", subMetrics); -- -- assertThat(metricRegistry.getMetrics()).containsOnlyKeys("test-text-gauge-2", "test-gauge", "test-text-gauge-1", -- "test-histogram-1", "test-histogram-2", "test-meter-1", "test-meter-2", "test-counter", -- "test-timer-1", "test-timer-2", -- "test-ms.sb-counter-1", "test-ms.sb-counter-2", "test-ms.sb-histogram-1"); -- } -+ metricRegistry.histogram("test-histogram-1"); -+ metricRegistry.histogram("test-histogram-2"); -+ metricRegistry.meter("test-meter-1"); -+ metricRegistry.meter("test-meter-2"); -+ metricRegistry.counter("test-counter"); -+ metricRegistry.timer("test-timer-1"); -+ metricRegistry.timer("test-timer-2"); -+ MetricRegistry subMetrics = new MetricRegistry(); -+ subMetrics.counter("sb-counter-1"); -+ subMetrics.counter("sb-counter-2"); -+ subMetrics.histogram("sb-histogram-1"); -+ metricRegistry.register("test-ms", subMetrics); + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; +@@ -12,7 +14,6 @@ import java.lang.management.MemoryPoolMXBean; + import java.lang.management.MemoryUsage; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -139,6 +140,6 @@ public class MemoryUsageGaugeSet implements MetricSet { + MetricRegistry.name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); + } + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java +@@ -1,9 +1,11 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableSet; + -+ assertThat(metricRegistry.getMetrics()) -+ .containsOnlyKeys( -+ "test-text-gauge-2", -+ "test-gauge", -+ "test-text-gauge-1", -+ "test-histogram-1", -+ "test-histogram-2", -+ "test-meter-1", -+ "test-meter-2", -+ "test-counter", -+ "test-timer-1", -+ "test-timer-2", -+ "test-ms.sb-counter-1", -+ "test-ms.sb-counter-2", -+ "test-ms.sb-histogram-1"); -+ } ++import com.google.common.collect.ImmutableSet; + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashSet; + import java.util.Set; + +@@ -40,19 +42,16 @@ public class ThreadDeadlockDetector { + for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { + final StringBuilder stackTrace = new StringBuilder(); + for (StackTraceElement element : info.getStackTrace()) { +- stackTrace.append("\t at ").append(element.toString()).append(String.format("%n")); ++ stackTrace.append("\t at ").append(element).append(String.format("%n")); + } + + deadlocks.add( + String.format( + "%s locked on %s (owned by %s):%n%s", +- info.getThreadName(), +- info.getLockName(), +- info.getLockOwnerName(), +- stackTrace.toString())); ++ info.getThreadName(), info.getLockName(), info.getLockOwnerName(), stackTrace)); + } +- return Collections.unmodifiableSet(deadlocks); ++ return unmodifiableSet(deadlocks); + } +- return Collections.emptySet(); ++ return ImmutableSet.of(); + } } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java -@@ -1,28 +1,28 @@ - package com.codahale.metrics; +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.jvm; --import org.assertj.core.data.Offset; --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; ++import static java.util.Collections.unmodifiableMap; + -+import org.junit.jupiter.api.Test; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; +@@ -8,7 +10,6 @@ import io.dropwizard.metrics5.MetricSet; + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + import java.util.Set; +@@ -59,7 +60,7 @@ public class ThreadStatesGaugeSet implements MetricSet { + gauges.put( + MetricName.build("deadlocks"), (Gauge>) deadlockDetector::getDeadlockedThreads); - @SuppressWarnings("deprecation") --class RatioGaugeTest { -+final class RatioGaugeTest { +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } -- private RatioGauge ratioGauge = new RatioGauge() { -+ private RatioGauge ratioGauge = -+ new RatioGauge() { - @Override - protected Ratio getRatio() { -- return Ratio.of(1, 3); -+ return Ratio.of(1, 3); - } -- }; -- -- @Test -- void testViewRatin() { -- assertThat(ratioGauge.getRatio().toString()).isEqualTo("1.0:3.0"); -- } -+ }; + private int getThreadCount(Thread.State state) { +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java +@@ -13,7 +13,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -+ @Test -+ void viewRatin() { -+ assertThat(ratioGauge.getRatio()).hasToString("1.0:3.0"); -+ } + @SuppressWarnings("rawtypes") +-class BufferPoolMetricSetTest { ++final class BufferPoolMetricSetTest { -- @Test -- void testCalculateRatio() { -- assertThat(ratioGauge.getValue()).isCloseTo(0.33, Offset.offset(0.01)); -- } -+ @Test -+ void calculateRatio() { -+ assertThat(ratioGauge.getValue()).isCloseTo(0.33, offset(0.01)); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java -@@ -1,80 +1,82 @@ - package com.codahale.metrics; + private static final MetricName DIRECT = MetricName.build("direct"); + private static final MetricName MAPPED = MetricName.build("mapped"); +@@ -24,7 +24,7 @@ class BufferPoolMetricSetTest { + private static final MetricName MAPPED_CAPACITY = MAPPED.resolve("capacity"); + private static final MetricName MAPPED_USED = MAPPED.resolve("used"); --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; +- private final MBeanServer mBeanServer = mock(MBeanServer.class); ++ private final MBeanServer mBeanServer = mock(); + private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); - import java.util.SortedMap; - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; + private ObjectName mapped; +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java +@@ -11,9 +11,9 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; - @SuppressWarnings("deprecation") --class ScheduledReporterTest { -+final class ScheduledReporterTest { + @SuppressWarnings("rawtypes") +-class ClassLoadingGaugeSetTest { ++final class ClassLoadingGaugeSetTest { -- private MetricRegistry metricRegistry = new MetricRegistry(); -- private ScheduledReporter scheduledReporter; -+ private MetricRegistry metricRegistry = new MetricRegistry(); -+ private ScheduledReporter scheduledReporter; - -- @BeforeEach -- void setUp() throws Exception { -- metricRegistry.register("sw-gauge", (Gauge) () -> 28); -- metricRegistry.counter("sw-counter"); -- metricRegistry.timer("sw-timer"); -- metricRegistry.meter("sw-meter"); -- metricRegistry.histogram("sw-histogram"); -- } -+ @BeforeEach -+ void setUp() throws Exception { -+ metricRegistry.register("sw-gauge", (Gauge) () -> 28); -+ metricRegistry.counter("sw-counter"); -+ metricRegistry.timer("sw-timer"); -+ metricRegistry.meter("sw-meter"); -+ metricRegistry.histogram("sw-histogram"); -+ } - -- @AfterEach -- void tearDown() throws Exception { -- scheduledReporter.stop(); -- } -+ @AfterEach -+ void tearDown() throws Exception { -+ scheduledReporter.stop(); -+ } - -- private ScheduledReporter createScheduledReporter(CountDownLatch latch) { -- return new ScheduledReporter(metricRegistry, "test", MetricFilter.ALL, TimeUnit.MILLISECONDS, -- TimeUnit.MINUTES) { -- @Override -- @SuppressWarnings("rawtypes") -- public void report(SortedMap gauges, SortedMap counters, -- SortedMap histograms, SortedMap meters, -- SortedMap timers) { -- assertThat(gauges).containsOnlyKeys("sw-gauge"); -- assertThat(counters).containsOnlyKeys("sw-counter"); -- assertThat(histograms).containsOnlyKeys("sw-histogram"); -- assertThat(meters).containsOnlyKeys("sw-meter"); -- assertThat(timers).containsOnlyKeys("sw-timer"); -- latch.countDown(); -- } -- }; -- } -+ private ScheduledReporter createScheduledReporter(CountDownLatch latch) { -+ return new ScheduledReporter( -+ metricRegistry, "test", MetricFilter.ALL, TimeUnit.MILLISECONDS, TimeUnit.MINUTES) { -+ @Override -+ @SuppressWarnings("rawtypes") -+ public void report( -+ SortedMap gauges, -+ SortedMap counters, -+ SortedMap histograms, -+ SortedMap meters, -+ SortedMap timers) { -+ assertThat(gauges).containsOnlyKeys("sw-gauge"); -+ assertThat(counters).containsOnlyKeys("sw-counter"); -+ assertThat(histograms).containsOnlyKeys("sw-histogram"); -+ assertThat(meters).containsOnlyKeys("sw-meter"); -+ assertThat(timers).containsOnlyKeys("sw-timer"); -+ latch.countDown(); -+ } -+ }; -+ } - -- @Test -- void testReport() throws Exception { -- CountDownLatch latch = new CountDownLatch(1); -- scheduledReporter = createScheduledReporter(latch); -- scheduledReporter.report(); -+ @Test -+ void report() throws Exception { -+ CountDownLatch latch = new CountDownLatch(1); -+ scheduledReporter = createScheduledReporter(latch); -+ scheduledReporter.report(); +- private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); ++ private final ClassLoadingMXBean cl = mock(); + private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); -- latch.await(5, TimeUnit.SECONDS); -- assertThat(latch.getCount()).isEqualTo(0); -- } -+ latch.await(5, TimeUnit.SECONDS); -+ assertThat(latch.getCount()).isEqualTo(0); -+ } - -- @Test -- void testStart() throws Exception { -- CountDownLatch latch = new CountDownLatch(2); -- scheduledReporter = createScheduledReporter(latch); -- scheduledReporter.start(10, TimeUnit.MILLISECONDS); -+ @Test -+ void start() throws Exception { -+ CountDownLatch latch = new CountDownLatch(2); -+ scheduledReporter = createScheduledReporter(latch); -+ scheduledReporter.start(10, TimeUnit.MILLISECONDS); + @BeforeEach +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java +@@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.offset; + import java.lang.management.ManagementFactory; + import org.junit.jupiter.api.Test; -- latch.await(5, TimeUnit.SECONDS); -- assertThat(latch.getCount()).isEqualTo(0); -- } -+ latch.await(5, TimeUnit.SECONDS); -+ assertThat(latch.getCount()).isEqualTo(0); -+ } - -- @Test -- void testStartWithoutDelay() throws Exception { -- CountDownLatch latch = new CountDownLatch(2); -- scheduledReporter = createScheduledReporter(latch); -- scheduledReporter.start(0, 10, TimeUnit.MILLISECONDS); -+ @Test -+ void startWithoutDelay() throws Exception { -+ CountDownLatch latch = new CountDownLatch(2); -+ scheduledReporter = createScheduledReporter(latch); -+ scheduledReporter.start(0, 10, TimeUnit.MILLISECONDS); +-class CpuTimeClockTest { ++final class CpuTimeClockTest { -- latch.await(5, TimeUnit.SECONDS); -- assertThat(latch.getCount()).isEqualTo(0); -- } -+ latch.await(5, TimeUnit.SECONDS); -+ assertThat(latch.getCount()).isEqualTo(0); -+ } + @Test + void cpuTimeClock() { +@@ -14,10 +14,10 @@ class CpuTimeClockTest { + + final long clockTime = clock.getTime(); + final long systemTime = System.currentTimeMillis(); +- assertThat((double) clockTime).isEqualTo(systemTime, offset(200.0)); ++ assertThat((double) clockTime).isCloseTo(systemTime, offset(200.0)); + + final long clockTick = clock.getTick(); + final long systemTick = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(); +- assertThat((double) clockTick).isEqualTo(systemTick, offset(1000000.0)); ++ assertThat((double) clockTick).isCloseTo(systemTick, offset(1000000.0)); + } } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java -@@ -1,53 +1,55 @@ - package com.codahale.metrics; +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.jvm; +import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; -+ - import org.junit.jupiter.api.AfterEach; + import static org.junit.jupiter.api.Assumptions.assumeTrue; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; +@@ -7,13 +8,12 @@ import static org.mockito.Mockito.when; + import com.sun.management.UnixOperatingSystemMXBean; + import java.lang.management.ManagementFactory; + import java.lang.management.OperatingSystemMXBean; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -- - @SuppressWarnings("deprecation") --class SharedMetricRegistriesTest { -- -- @AfterEach -- void tearDown() throws Exception { -- SharedMetricRegistries.clear(); -- } -- -- @Test -- void testGetOrCreateMetricRegistry() { -- SharedMetricRegistries.getOrCreate("get-or-create").counter("test-counter"); -- -- assertThat(SharedMetricRegistries.getOrCreate("get-or-create").getCounters()) -- .containsOnlyKeys("test-counter"); -- } -- -- @Test -- void testAddMetricRegistry() { -- MetricRegistry metricRegistry = new MetricRegistry(); -- metricRegistry.histogram("test-histogram"); -- SharedMetricRegistries.add("add", metricRegistry); -- -- assertThat(SharedMetricRegistries.getOrCreate("add").getHistograms()) -- .containsOnlyKeys("test-histogram"); -- } -- -- @Test -- void testNames() { -- SharedMetricRegistries.add("registry-1", new MetricRegistry()); -- SharedMetricRegistries.add("registry-2", new MetricRegistry()); -- SharedMetricRegistries.add("registry-3", new MetricRegistry()); -- -- assertThat(SharedMetricRegistries.names()).containsOnly("registry-1", "registry-2", "registry-3"); -- } -- -- @Test -- void testTryGetDefaultRegistry() { -- assertThat(SharedMetricRegistries.tryGetDefault()).isNull(); -- } -- -- @Test -- void testGetDefaultRegistry() { -- assertThatIllegalStateException().isThrownBy(SharedMetricRegistries::getDefault); -- } -+final class SharedMetricRegistriesTest { -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ SharedMetricRegistries.clear(); -+ } -+ -+ @Test -+ void getOrCreateMetricRegistry() { -+ SharedMetricRegistries.getOrCreate("get-or-create").counter("test-counter"); -+ -+ assertThat(SharedMetricRegistries.getOrCreate("get-or-create").getCounters()) -+ .containsOnlyKeys("test-counter"); -+ } -+ -+ @Test -+ void addMetricRegistry() { -+ MetricRegistry metricRegistry = new MetricRegistry(); -+ metricRegistry.histogram("test-histogram"); -+ SharedMetricRegistries.add("add", metricRegistry); -+ -+ assertThat(SharedMetricRegistries.getOrCreate("add").getHistograms()) -+ .containsOnlyKeys("test-histogram"); -+ } -+ -+ @Test -+ void names() { -+ SharedMetricRegistries.add("registry-1", new MetricRegistry()); -+ SharedMetricRegistries.add("registry-2", new MetricRegistry()); -+ SharedMetricRegistries.add("registry-3", new MetricRegistry()); -+ -+ assertThat(SharedMetricRegistries.names()) -+ .containsOnly("registry-1", "registry-2", "registry-3"); -+ } -+ -+ @Test -+ void tryGetDefaultRegistry() { -+ assertThat(SharedMetricRegistries.tryGetDefault()).isNull(); -+ } -+ -+ @Test -+ void getDefaultRegistry() { -+ assertThatThrownBy(SharedMetricRegistries::getDefault) -+ .isInstanceOf(IllegalStateException.class); -+ } + @SuppressWarnings("UnusedDeclaration") +-class FileDescriptorRatioGaugeTest { +- private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); ++final class FileDescriptorRatioGaugeTest { ++ private final UnixOperatingSystemMXBean os = mock(); + + private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); + +@@ -25,7 +25,7 @@ class FileDescriptorRatioGaugeTest { + + @Test + void calculatesTheRatioOfUsedToTotalFileDescriptors() { +- Assertions.assertThat(gauge.getValue()).isEqualTo(0.1); ++ assertThat(gauge.getValue()).isEqualTo(0.1); + } + + @Test +@@ -33,15 +33,11 @@ class FileDescriptorRatioGaugeTest { + OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); + assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); + +- Assertions.assertThat(new FileDescriptorRatioGauge().getValue()) +- .isGreaterThanOrEqualTo(0.0) +- .isLessThanOrEqualTo(1.0); ++ assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative().isLessThanOrEqualTo(1.0); + } + + @Test + void returnsNaNWhenTheInformationIsUnavailable() { +- Assertions.assertThat( +- new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()) +- .isNaN(); ++ assertThat(new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()).isNaN(); + } } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java -@@ -1,55 +1,55 @@ - package com.codahale.metrics; +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java +@@ -4,18 +4,18 @@ import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ -+import java.util.concurrent.Executors; -+import java.util.concurrent.ScheduledExecutorService; -+import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.AfterEach; ++import com.google.common.collect.ImmutableList; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricName; + import java.lang.management.GarbageCollectorMXBean; +-import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - import org.slf4j.Logger; - import org.slf4j.Marker; --import java.util.concurrent.Executors; --import java.util.concurrent.ScheduledExecutorService; --import java.util.concurrent.TimeUnit; -- --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- - @SuppressWarnings("deprecation") --class Slf4jReporterTest { -- -- private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); -- private Logger logger = mock(Logger.class); -- private Marker marker = mock(Marker.class); -- -- @BeforeEach -- void setUp() throws Exception { -- when(logger.isInfoEnabled(marker)).thenReturn(true); -- } -- -- @AfterEach -- void tearDown() throws Exception { -- executor.shutdownNow(); -- } -- -- @Test -- void testReport() throws Exception { -- MetricRegistry metricRegistry = new MetricRegistry(); -- metricRegistry.counter("test-counter").inc(100); -- -- Slf4jReporter slf4jReporter = Slf4jReporter.forRegistry(metricRegistry) -- .shutdownExecutorOnStop(false) -- .scheduleOn(executor) -- .outputTo(logger) -- .markWith(marker) -- .prefixedWith("us-nw") -- .convertRatesTo(TimeUnit.SECONDS) -- .convertDurationsTo(TimeUnit.MILLISECONDS) -- .filter(MetricFilter.ALL) -- .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) -- .build(); -- -- slf4jReporter.report(); -- -- verify(logger).info(marker, "type=COUNTER, name=us-nw.test-counter, count=100"); -- } -+final class Slf4jReporterTest { -+ -+ private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); -+ private Logger logger = mock(); -+ private Marker marker = mock(); -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ when(logger.isInfoEnabled(marker)).thenReturn(true); -+ } -+ -+ @AfterEach -+ void tearDown() throws Exception { -+ executor.shutdownNow(); -+ } -+ -+ @Test -+ void report() throws Exception { -+ MetricRegistry metricRegistry = new MetricRegistry(); -+ metricRegistry.counter("test-counter").inc(100); -+ -+ Slf4jReporter slf4jReporter = -+ Slf4jReporter.forRegistry(metricRegistry) -+ .shutdownExecutorOnStop(false) -+ .scheduleOn(executor) -+ .outputTo(logger) -+ .markWith(marker) -+ .prefixedWith("us-nw") -+ .convertRatesTo(TimeUnit.SECONDS) -+ .convertDurationsTo(TimeUnit.MILLISECONDS) -+ .filter(MetricFilter.ALL) -+ .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) -+ .build(); -+ -+ slf4jReporter.report(); -+ -+ verify(logger).info(marker, "type=COUNTER, name=us-nw.test-counter, count=100"); -+ } + @SuppressWarnings("unchecked") +-class GarbageCollectorMetricSetTest { +- private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); ++final class GarbageCollectorMetricSetTest { ++ private final GarbageCollectorMXBean gc = mock(); + private final GarbageCollectorMetricSet metrics = +- new GarbageCollectorMetricSet(Collections.singletonList(gc)); ++ new GarbageCollectorMetricSet(ImmutableList.of(gc)); + + private static final MetricName PS_OLDGEN_TIME = MetricName.build("PS-OldGen.time"); + private static final MetricName PS_OLDGEN_COUNT = MetricName.build("PS-OldGen.count"); +@@ -46,6 +46,6 @@ class GarbageCollectorMetricSetTest { + + @Test + void autoDiscoversGCs() { +- assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()).isNotEmpty(); ++ assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty(); + } } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java -@@ -1,34 +1,34 @@ - package com.codahale.metrics; +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java +@@ -13,7 +13,7 @@ import org.junit.jupiter.api.AfterAll; + import org.junit.jupiter.api.BeforeAll; + import org.junit.jupiter.api.Test; + +-class JmxAttributeGaugeTest { ++final class JmxAttributeGaugeTest { + + private static MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + +@@ -53,7 +53,7 @@ class JmxAttributeGaugeTest { + JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); + + assertThat(gauge.getValue()).isInstanceOf(Integer.class); +- assertThat((Integer) gauge.getValue()).isGreaterThan(0); ++ assertThat((Integer) gauge.getValue()).isPositive(); + } + + @Test +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java +@@ -11,8 +11,8 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("unchecked") +-class JvmAttributeGaugeSetTest { +- private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); ++final class JvmAttributeGaugeSetTest { ++ private final RuntimeMXBean runtime = mock(); + private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); --import org.assertj.core.data.Offset; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; + @BeforeEach +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java +@@ -14,15 +14,15 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; - import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.Test; + @SuppressWarnings("rawtypes") +-class MemoryUsageGaugeSetTest { +- private final MemoryUsage heap = mock(MemoryUsage.class); +- private final MemoryUsage nonHeap = mock(MemoryUsage.class); +- private final MemoryUsage pool = mock(MemoryUsage.class); +- private final MemoryUsage weirdPool = mock(MemoryUsage.class); +- private final MemoryUsage weirdCollection = mock(MemoryUsage.class); +- private final MemoryMXBean mxBean = mock(MemoryMXBean.class); +- private final MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); +- private final MemoryPoolMXBean weirdMemoryPool = mock(MemoryPoolMXBean.class); ++final class MemoryUsageGaugeSetTest { ++ private final MemoryUsage heap = mock(); ++ private final MemoryUsage nonHeap = mock(); ++ private final MemoryUsage pool = mock(); ++ private final MemoryUsage weirdPool = mock(); ++ private final MemoryUsage weirdCollection = mock(); ++ private final MemoryMXBean mxBean = mock(); ++ private final MemoryPoolMXBean memoryPool = mock(); ++ private final MemoryPoolMXBean weirdMemoryPool = mock(); - @SuppressWarnings("deprecation") --class SlidingTimeWindowArrayReservoirTest { -- -- @Test -- void testCreateWithWindow() { -- SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS); -- reservoir.update(100); -- reservoir.update(200); -- reservoir.update(30); -- -- assertThat(reservoir.size()).isEqualTo(3); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); -- } -- -- @Test -- void testCreateWithWindowAndClock() { -- SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS, -- new Clock.UserTimeClock()); -- reservoir.update(400); -- reservoir.update(300); -- -- assertThat(reservoir.size()).isEqualTo(2); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); -- } -+final class SlidingTimeWindowArrayReservoirTest { -+ -+ @Test -+ void createWithWindow() { -+ SlidingTimeWindowArrayReservoir reservoir = -+ new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS); -+ reservoir.update(100); -+ reservoir.update(200); -+ reservoir.update(30); -+ -+ assertThat(reservoir.size()).isEqualTo(3); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); -+ } -+ -+ @Test -+ void createWithWindowAndClock() { -+ SlidingTimeWindowArrayReservoir reservoir = -+ new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); -+ reservoir.update(400); -+ reservoir.update(300); -+ -+ assertThat(reservoir.size()).isEqualTo(2); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java -@@ -1,34 +1,33 @@ - package com.codahale.metrics; + private final MemoryUsageGaugeSet gauges = + new MemoryUsageGaugeSet(mxBean, Arrays.asList(memoryPool, weirdMemoryPool)); +@@ -159,7 +159,7 @@ class MemoryUsageGaugeSetTest { + } --import org.assertj.core.data.Offset; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; + @Test +- public void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { ++ void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { + when(nonHeap.getMax()).thenReturn(-1L); - import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.Test; + final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); +@@ -238,7 +238,7 @@ class MemoryUsageGaugeSetTest { + } - @SuppressWarnings("deprecation") --class SlidingTimeWindowReservoirTest { -- -- @Test -- void testCreateWithWindow() { -- SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS); -- reservoir.update(100); -- reservoir.update(200); -- reservoir.update(30); -- -- assertThat(reservoir.size()).isEqualTo(3); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); -- } -- -- @Test -- void testCreateWithWindowAndClock() { -- SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS, -- new Clock.UserTimeClock()); -- reservoir.update(400); -- reservoir.update(300); -- -- assertThat(reservoir.size()).isEqualTo(2); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); -- } -+final class SlidingTimeWindowReservoirTest { -+ -+ @Test -+ void createWithWindow() { -+ SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS); -+ reservoir.update(100); -+ reservoir.update(200); -+ reservoir.update(30); -+ -+ assertThat(reservoir.size()).isEqualTo(3); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); -+ } -+ -+ @Test -+ void createWithWindowAndClock() { -+ SlidingTimeWindowReservoir reservoir = -+ new SlidingTimeWindowReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); -+ reservoir.update(400); -+ reservoir.update(300); -+ -+ assertThat(reservoir.size()).isEqualTo(2); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); -+ } + @Test +- public void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { ++ void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { + when(nonHeap.getMax()).thenReturn(-1L); + final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); + +@@ -296,6 +296,6 @@ class MemoryUsageGaugeSetTest { + + @Test + void autoDetectsMemoryUsageBeanAndMemoryPools() { +- assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()).isNotEmpty(); ++ assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty(); + } } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java -@@ -1,33 +1,33 @@ - package com.codahale.metrics; +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java +@@ -11,8 +11,8 @@ import java.lang.management.ThreadMXBean; + import java.util.Locale; + import org.junit.jupiter.api.Test; --import org.assertj.core.data.Offset; --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; -+ -+import org.junit.jupiter.api.Test; +-class ThreadDeadlockDetectorTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); ++final class ThreadDeadlockDetectorTest { ++ private final ThreadMXBean threads = mock(); + private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); - @SuppressWarnings("deprecation") --class SlidingWindowReservoirTest { -+final class SlidingWindowReservoirTest { + @Test +@@ -24,7 +24,7 @@ class ThreadDeadlockDetectorTest { -- @Test -- void testCreateWithBigWindow() { -- SlidingWindowReservoir reservoir = new SlidingWindowReservoir(100); -- reservoir.update(100); -- reservoir.update(220); -- reservoir.update(130); -+ @Test -+ void createWithBigWindow() { -+ SlidingWindowReservoir reservoir = new SlidingWindowReservoir(100); -+ reservoir.update(100); -+ reservoir.update(220); -+ reservoir.update(130); + @Test + void returnsASetOfThreadsIfAnyAreDeadlocked() { +- final ThreadInfo thread1 = mock(ThreadInfo.class); ++ final ThreadInfo thread1 = mock(); + when(thread1.getThreadName()).thenReturn("thread1"); + when(thread1.getLockName()).thenReturn("lock2"); + when(thread1.getLockOwnerName()).thenReturn("thread2"); +@@ -35,7 +35,7 @@ class ThreadDeadlockDetectorTest { + new StackTraceElement("Blah", "blee", "Blah.java", 100) + }); + +- final ThreadInfo thread2 = mock(ThreadInfo.class); ++ final ThreadInfo thread2 = mock(); + when(thread2.getThreadName()).thenReturn("thread2"); + when(thread2.getLockName()).thenReturn("lock1"); + when(thread2.getLockOwnerName()).thenReturn("thread1"); +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java +@@ -14,11 +14,11 @@ import org.junit.jupiter.api.Test; -- assertThat(reservoir.size()).isEqualTo(3); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, Offset.offset(0.1)); -- } -+ assertThat(reservoir.size()).isEqualTo(3); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, offset(0.1)); -+ } - -- @Test -- void testCreateWithLowWindow() { -- SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); -- reservoir.update(500); -- reservoir.update(220); -- reservoir.update(100); -- reservoir.update(40); -+ @Test -+ void createWithLowWindow() { -+ SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); -+ reservoir.update(500); -+ reservoir.update(220); -+ reservoir.update(100); -+ reservoir.update(40); - -- assertThat(reservoir.size()).isEqualTo(3); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, Offset.offset(0.1)); -- } -+ assertThat(reservoir.size()).isEqualTo(3); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, offset(0.1)); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java -@@ -1,38 +1,34 @@ - package com.codahale.metrics; + // TODO: 3/12/13 -- improve test coverage for ThreadDump --import io.dropwizard.metrics5.UniformSnapshot; --import org.assertj.core.data.Offset; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; +-class ThreadDumpTest { +- private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); ++final class ThreadDumpTest { ++ private final ThreadMXBean threadMXBean = mock(); + private final ThreadDump threadDump = new ThreadDump(threadMXBean); -+import io.dropwizard.metrics5.UniformSnapshot; - import java.io.ByteArrayOutputStream; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.Test; +- private final ThreadInfo runnable = mock(ThreadInfo.class); ++ private final ThreadInfo runnable = mock(); - @SuppressWarnings("deprecation") --class SnapshotTest { -+final class SnapshotTest { + @BeforeEach + void setUp() { +@@ -39,8 +39,8 @@ class ThreadDumpTest { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + threadDump.dump(output); -- @Test -- void testCreateSnapshot() throws Exception { -- Snapshot snapshot = Snapshot.of(new UniformSnapshot(new long[]{5, 1, 2, 3, 4})); -+ @Test -+ void createSnapshot() throws Exception { -+ Snapshot snapshot = Snapshot.of(new UniformSnapshot(new long[] {5, 1, 2, 3, 4})); - -- assertThat(snapshot.getValues()).isEqualTo(new long[]{1, 2, 3, 4, 5}); -- assertThat(snapshot.size()).isEqualTo(5); -- assertThat(snapshot.getMin()).isEqualTo(1); -- assertThat(snapshot.getMax()).isEqualTo(5); -- assertThat(snapshot.getStdDev()).isEqualTo(1.58, Offset.offset(0.01)); -- assertThat(snapshot.getMedian()).isEqualTo(3, Offset.offset(0.01)); -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, Offset.offset(0.01)); -- assertThat(snapshot.get95thPercentile()).isEqualTo(5, Offset.offset(0.01)); -- assertThat(snapshot.get98thPercentile()).isEqualTo(5, Offset.offset(0.01)); -- assertThat(snapshot.get99thPercentile()).isEqualTo(5, Offset.offset(0.01)); -- assertThat(snapshot.get999thPercentile()).isEqualTo(5, Offset.offset(0.01)); -+ assertThat(snapshot.getValues()).isEqualTo(new long[] {1, 2, 3, 4, 5}); -+ assertThat(snapshot.size()).isEqualTo(5); -+ assertThat(snapshot.getMin()).isEqualTo(1); -+ assertThat(snapshot.getMax()).isEqualTo(5); -+ assertThat(snapshot.getStdDev()).isCloseTo(1.58, offset(0.01)); -+ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.01)); -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.01)); -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5, offset(0.01)); -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5, offset(0.01)); -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5, offset(0.01)); -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5, offset(0.01)); +- assertThat(output.toString()) +- .isEqualTo( ++ assertThat(output) ++ .hasToString( + String.format( + "\"runnable\" id=100 state=RUNNABLE%n" + + " at Blah.blee(Blah.java:100)%n" +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java +@@ -10,22 +10,21 @@ import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; + import java.util.HashSet; + import java.util.Set; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- ByteArrayOutputStream baos = new ByteArrayOutputStream(); -- snapshot.dump(baos); -- assertThat(baos.toString("UTF-8")).isEqualToNormalizingNewlines("1\n" + -- "2\n" + -- "3\n" + -- "4\n" + -- "5\n"); -- } -+ ByteArrayOutputStream baos = new ByteArrayOutputStream(); -+ snapshot.dump(baos); -+ assertThat(baos.toString("UTF-8")) -+ .isEqualToNormalizingNewlines("1\n" + "2\n" + "3\n" + "4\n" + "5\n"); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java -@@ -1,103 +1,102 @@ +-class ThreadStatesGaugeSetTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); +- private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++final class ThreadStatesGaugeSetTest { ++ private final ThreadMXBean threads = mock(); ++ private final ThreadDeadlockDetector detector = mock(); + private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); + private final long[] ids = new long[] {1, 2, 3}; + +- private final ThreadInfo newThread = mock(ThreadInfo.class); +- private final ThreadInfo runnableThread = mock(ThreadInfo.class); +- private final ThreadInfo blockedThread = mock(ThreadInfo.class); +- private final ThreadInfo waitingThread = mock(ThreadInfo.class); +- private final ThreadInfo timedWaitingThread = mock(ThreadInfo.class); +- private final ThreadInfo terminatedThread = mock(ThreadInfo.class); ++ private final ThreadInfo newThread = mock(); ++ private final ThreadInfo runnableThread = mock(); ++ private final ThreadInfo blockedThread = mock(); ++ private final ThreadInfo waitingThread = mock(); ++ private final ThreadInfo timedWaitingThread = mock(); ++ private final ThreadInfo terminatedThread = mock(); + + private final Set deadlocks = new HashSet<>(); + +@@ -87,7 +86,7 @@ class ThreadStatesGaugeSetTest { + + @Test + void hasAGaugeForEachThreadState() { +- Assertions.assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1); ++ assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1); + + assertThat(((Gauge) gauges.getMetrics().get(RUNNABLE_COUNT)).getValue()).isEqualTo(1); + +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java +@@ -1,16 +1,16 @@ package com.codahale.metrics; --import org.junit.jupiter.api.Test; -+import static org.assertj.core.api.Assertions.assertThat; ++import static java.util.Collections.unmodifiableSortedMap; + import static java.util.Collections.unmodifiableSortedSet; + import static java.util.Objects.requireNonNull; ++import static java.util.stream.Collectors.toCollection; - import java.time.Duration; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicInteger; -- --import static org.assertj.core.api.Assertions.assertThat; -+import org.junit.jupiter.api.Test; + import io.dropwizard.metrics5.MetricName; +-import java.util.Collections; + import java.util.Map; + import java.util.SortedMap; + import java.util.SortedSet; + import java.util.TreeMap; + import java.util.TreeSet; +-import java.util.stream.Collectors; - @SuppressWarnings("deprecation") --class TimerTest { -+final class TimerTest { + @Deprecated + public class MetricRegistry implements MetricSet { +@@ -102,9 +102,7 @@ public class MetricRegistry implements MetricSet { -- private static class ManualClock extends Clock { -+ private static class ManualClock extends Clock { + public SortedSet getNames() { + return unmodifiableSortedSet( +- delegate.getNames().stream() +- .map(MetricName::getKey) +- .collect(Collectors.toCollection(TreeSet::new))); ++ delegate.getNames().stream().map(MetricName::getKey).collect(toCollection(TreeSet::new))); + } -- long startTime = System.nanoTime(); -+ long startTime = System.nanoTime(); + public SortedMap getGauges() { +@@ -160,7 +158,7 @@ public class MetricRegistry implements MetricSet { + metrics.entrySet()) { + items.put(entry.getKey().getKey(), (T) Metric.of(entry.getValue())); + } +- return Collections.unmodifiableSortedMap(items); ++ return unmodifiableSortedMap(items); + } -- @Override -- public long getTick() { -- return startTime += 100_000_000; -- } -+ @Override -+ public long getTick() { -+ return startTime += 100_000_000; + @Override +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java +@@ -1,7 +1,8 @@ + package com.codahale.metrics; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.MetricName; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + +@@ -24,7 +25,7 @@ public interface MetricSet extends Metric { + original.getMetrics().entrySet()) { + items.put(entry.getKey().getKey(), Metric.of(entry.getValue())); + } +- return Collections.unmodifiableMap(items); ++ return unmodifiableMap(items); + } + + @Override +@@ -48,7 +49,7 @@ public interface MetricSet extends Metric { + for (Map.Entry entry : delegate.getMetrics().entrySet()) { + items.put(MetricName.build(entry.getKey()), entry.getValue().getDelegate()); + } +- return Collections.unmodifiableMap(items); ++ return unmodifiableMap(items); } -+ } + } + } +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java +@@ -1,10 +1,10 @@ + package com.codahale.metrics; -- private static void verifyOneEvent(Timer timer) { -- assertThat(timer.getCount()).isEqualTo(1); -- assertThat(timer.getSnapshot().getValues()).containsExactly(100_000_000L); -- } -+ private static void verifyOneEvent(Timer timer) { -+ assertThat(timer.getCount()).isEqualTo(1); -+ assertThat(timer.getSnapshot().getValues()).containsExactly(100_000_000L); -+ } - -- @Test -- void testCreate() { -- Timer timer = new Timer(); -- timer.update(100, TimeUnit.MILLISECONDS); -- timer.update(200, TimeUnit.MILLISECONDS); -+ @Test -+ void create() { -+ Timer timer = new Timer(); -+ timer.update(100, TimeUnit.MILLISECONDS); -+ timer.update(200, TimeUnit.MILLISECONDS); ++import static java.util.Collections.unmodifiableSortedMap; + import static java.util.Objects.requireNonNull; -- assertThat(timer.getCount()).isEqualTo(2); -- } -+ assertThat(timer.getCount()).isEqualTo(2); -+ } - -- @Test -- void testCreateWithCustomReservoir() { -- Timer timer = new Timer(new SlidingWindowReservoir(100)); -- timer.update(100, TimeUnit.MILLISECONDS); -- timer.update(200, TimeUnit.MILLISECONDS); -+ @Test -+ void createWithCustomReservoir() { -+ Timer timer = new Timer(new SlidingWindowReservoir(100)); -+ timer.update(100, TimeUnit.MILLISECONDS); -+ timer.update(200, TimeUnit.MILLISECONDS); + import io.dropwizard.metrics5.MetricName; + import java.io.Closeable; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -115,7 +115,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + for (Map.Entry entry : metrics.entrySet()) { + items.put(MetricName.build(entry.getKey()), (T) entry.getValue().getDelegate()); + } +- return Collections.unmodifiableSortedMap(items); ++ return unmodifiableSortedMap(items); + } -- assertThat(timer.getCount()).isEqualTo(2); -- } -+ assertThat(timer.getCount()).isEqualTo(2); -+ } - -- @Test -- void testCreateWithCustomReservoirAndClock() { -- Timer timer = new Timer(new SlidingWindowReservoir(100), new Clock.UserTimeClock()); -- timer.update(100, TimeUnit.MILLISECONDS); -- timer.update(200, TimeUnit.MILLISECONDS); -+ @Test -+ void createWithCustomReservoirAndClock() { -+ Timer timer = new Timer(new SlidingWindowReservoir(100), new Clock.UserTimeClock()); -+ timer.update(100, TimeUnit.MILLISECONDS); -+ timer.update(200, TimeUnit.MILLISECONDS); + protected String getRateUnit() { +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java +@@ -6,10 +6,10 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; -- assertThat(timer.getCount()).isEqualTo(2); -- } -+ assertThat(timer.getCount()).isEqualTo(2); -+ } + @SuppressWarnings("deprecation") +-class CachedGaugeTest { ++final class CachedGaugeTest { -- @Test -- void testTimerContext() { -- Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); -- timer.time().stop(); -+ @Test -+ void timerContext() { -+ Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); -+ timer.time().stop(); + @Test +- void testCreate() { ++ void create() { + CachedGauge cachedGauge = + new CachedGauge(100, TimeUnit.MILLISECONDS) { + @Override +@@ -21,7 +21,7 @@ class CachedGaugeTest { + } -- verifyOneEvent(timer); -- } -+ verifyOneEvent(timer); -+ } + @Test +- void testCreateWothClock() { ++ void createWothClock() { + CachedGauge cachedGauge = + new CachedGauge(new Clock.UserTimeClock(), 100, TimeUnit.MILLISECONDS) { + @Override +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java +@@ -5,22 +5,22 @@ import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; -- @Test -- void testTimerRunnable() { -- Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); -+ @Test -+ void timerRunnable() { -+ Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + @SuppressWarnings("deprecation") +-class ClockTest { ++final class ClockTest { -- AtomicInteger counter = new AtomicInteger(); -- timer.time((Runnable) counter::incrementAndGet); -+ AtomicInteger counter = new AtomicInteger(); -+ timer.time((Runnable) counter::incrementAndGet); + @Test +- void testDefaultClockCanBeUsed() { ++ void defaultClockCanBeUsed() { + Clock clock = Clock.defaultClock(); +- assertThat(clock.getTick()).isGreaterThan(0); ++ assertThat(clock.getTick()).isPositive(); + } -- assertThat(counter.get()).isEqualTo(1); -- verifyOneEvent(timer); -- } -+ assertThat(counter.get()).isEqualTo(1); -+ verifyOneEvent(timer); -+ } + @Test +- void testUserTimeClockCanBeUsed() { ++ void userTimeClockCanBeUsed() { + Clock clock = new Clock.UserTimeClock(); +- assertThat(clock.getTick()).isGreaterThan(0); ++ assertThat(clock.getTick()).isPositive(); + } -- @Test -- void testTimerCallable() throws Exception { -- Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); -+ @Test -+ void timerCallable() throws Exception { -+ Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + @Test +- void testCustomTimeClockCanBeUsed() { ++ void customTimeClockCanBeUsed() { + Clock clock = + new Clock() { + @Override +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java +@@ -1,10 +1,10 @@ + package com.codahale.metrics; -- String message = timer.time(() -> "SUCCESS"); -+ String message = timer.time(() -> "SUCCESS"); ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; -- assertThat(message).isEqualTo("SUCCESS"); -- verifyOneEvent(timer); -- } -+ assertThat(message).isEqualTo("SUCCESS"); -+ verifyOneEvent(timer); -+ } + import java.io.ByteArrayOutputStream; + import java.io.PrintStream; +-import java.nio.charset.StandardCharsets; + import java.util.EnumSet; + import java.util.Locale; + import java.util.TimeZone; +@@ -17,7 +17,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.Test; -- @Test -- void testTimerSupplier() throws Exception { -- Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); -+ @Test -+ void timerSupplier() throws Exception { -+ Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + @SuppressWarnings("deprecation") +-class ConsoleReporterTest { ++final class ConsoleReporterTest { -- Integer result = timer.timeSupplier(() -> 42); -+ Integer result = timer.timeSupplier(() -> 42); + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + private final String dateHeader = +@@ -35,7 +35,7 @@ class ConsoleReporterTest { + } -- assertThat(result).isEqualTo(42); -- verifyOneEvent(timer); -- } -+ assertThat(result).isEqualTo(42); -+ verifyOneEvent(timer); -+ } - -- @Test -- void testUpdateDuration() { -- Timer timer = new Timer(); -- timer.update(Duration.ofMillis(100)); -- timer.update(Duration.ofMillis(200)); -+ @Test -+ void updateDuration() { -+ Timer timer = new Timer(); -+ timer.update(Duration.ofMillis(100)); -+ timer.update(Duration.ofMillis(200)); + @Test +- void testCreateConsoleReporter() throws Exception { ++ void createConsoleReporter() throws Exception { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); -- assertThat(timer.getCount()).isEqualTo(2); -- } -+ assertThat(timer.getCount()).isEqualTo(2); -+ } - } ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java -@@ -1,42 +1,42 @@ - package com.codahale.metrics; + MetricRegistry metricRegistry = new MetricRegistry(); +@@ -72,7 +72,7 @@ class ConsoleReporterTest { + .build(); + consoleReporter.report(); --import org.assertj.core.data.Offset; --import org.junit.jupiter.api.Test; -- - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; -+ -+import org.junit.jupiter.api.Test; +- assertThat(new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8)) ++ assertThat(new String(byteArrayOutputStream.toByteArray(), UTF_8)) + .isEqualToNormalizingNewlines( + dateHeader + + "\n" +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java +@@ -6,33 +6,33 @@ import io.dropwizard.metrics5.Counter; + import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") --class UniformReservoirTest { -+final class UniformReservoirTest { +-class CounterTest { ++final class CounterTest { -- @Test -- void testCreateReservoir() { -- UniformReservoir reservoir = new UniformReservoir(); -- reservoir.update(120); -- reservoir.update(190); -- reservoir.update(200); -- reservoir.update(130); -- reservoir.update(140); -+ @Test -+ void createReservoir() { -+ UniformReservoir reservoir = new UniformReservoir(); -+ reservoir.update(120); -+ reservoir.update(190); -+ reservoir.update(200); -+ reservoir.update(130); -+ reservoir.update(140); - -- Snapshot snapshot = reservoir.getSnapshot(); -- assertThat(snapshot.size()).isEqualTo(5); -- assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); -- assertThat(snapshot.getMin()).isEqualTo(120); -- assertThat(snapshot.getMax()).isEqualTo(200); -- assertThat(snapshot.getStdDev()).isEqualTo(36.47, Offset.offset(0.1)); -- assertThat(snapshot.get75thPercentile()).isEqualTo(195); -- assertThat(snapshot.get95thPercentile()).isEqualTo(200); -- assertThat(snapshot.get98thPercentile()).isEqualTo(200); -- assertThat(snapshot.get99thPercentile()).isEqualTo(200); -- assertThat(snapshot.get999thPercentile()).isEqualTo(200); -- } -+ Snapshot snapshot = reservoir.getSnapshot(); -+ assertThat(snapshot.size()).isEqualTo(5); -+ assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); -+ assertThat(snapshot.getMin()).isEqualTo(120); -+ assertThat(snapshot.getMax()).isEqualTo(200); -+ assertThat(snapshot.getStdDev()).isCloseTo(36.47, offset(0.1)); -+ assertThat(snapshot.get75thPercentile()).isEqualTo(195); -+ assertThat(snapshot.get95thPercentile()).isEqualTo(200); -+ assertThat(snapshot.get98thPercentile()).isEqualTo(200); -+ assertThat(snapshot.get99thPercentile()).isEqualTo(200); -+ assertThat(snapshot.get999thPercentile()).isEqualTo(200); -+ } - -- @Test -- void testCreateReservoirWithCustomSize() { -- UniformReservoir reservoir = new UniformReservoir(128); -- reservoir.update(440); -- reservoir.update(250); -- reservoir.update(380); -+ @Test -+ void createReservoirWithCustomSize() { -+ UniformReservoir reservoir = new UniformReservoir(128); -+ reservoir.update(440); -+ reservoir.update(250); -+ reservoir.update(380); + private Counter counter = new Counter(); -- assertThat(reservoir.size()).isEqualTo(3); -- } -+ assertThat(reservoir.size()).isEqualTo(3); -+ } - } ---- a/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java -+++ b/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java -@@ -1,8 +1,11 @@ - package io.dropwizard.metrics5.log4j2; + @Test +- void testIncrementCounter() { ++ void incrementCounter() { + counter.inc(); -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.SharedMetricRegistries; -+import java.io.Serializable; - import org.apache.logging.log4j.core.Appender; - import org.apache.logging.log4j.core.Filter; - import org.apache.logging.log4j.core.Layout; -@@ -12,127 +15,131 @@ import org.apache.logging.log4j.core.config.plugins.Plugin; - import org.apache.logging.log4j.core.config.plugins.PluginAttribute; - import org.apache.logging.log4j.core.config.plugins.PluginFactory; - --import java.io.Serializable; -- --import static io.dropwizard.metrics5.MetricRegistry.name; -- - /** -- * A Log4J 2.x {@link Appender} which has seven meters, one for each logging level and one for the total -- * number of statements being logged. The meter names are the logging level names appended to the -- * name of the appender. -+ * A Log4J 2.x {@link Appender} which has seven meters, one for each logging level and one for the -+ * total number of statements being logged. The meter names are the logging level names appended to -+ * the name of the appender. - */ - @Plugin(name = "MetricsAppender", category = "Core", elementType = "appender") - public class InstrumentedAppender extends AbstractAppender { - -- private transient final MetricRegistry registry; -+ private final transient MetricRegistry registry; - -- private transient Meter all; -- private transient Meter trace; -- private transient Meter debug; -- private transient Meter info; -- private transient Meter warn; -- private transient Meter error; -- private transient Meter fatal; -+ private transient Meter all; -+ private transient Meter trace; -+ private transient Meter debug; -+ private transient Meter info; -+ private transient Meter warn; -+ private transient Meter error; -+ private transient Meter fatal; - -- /** -- * Create a new instrumented appender using the given registry name. -- * -- * @param registryName the name of the registry in {@link SharedMetricRegistries} -- * @param filter The Filter to associate with the Appender. -- * @param layout The layout to use to format the event. -- * @param ignoreExceptions If true, exceptions will be logged and suppressed. If false errors will be -- * logged and then passed to the application. -- */ -- public InstrumentedAppender(String registryName, Filter filter, Layout layout, boolean ignoreExceptions) { -- this(SharedMetricRegistries.getOrCreate(registryName), filter, layout, ignoreExceptions); -- } -+ /** -+ * Create a new instrumented appender using the given registry name. -+ * -+ * @param registryName the name of the registry in {@link SharedMetricRegistries} -+ * @param filter The Filter to associate with the Appender. -+ * @param layout The layout to use to format the event. -+ * @param ignoreExceptions If true, exceptions will be logged and suppressed. If false errors will -+ * be logged and then passed to the application. -+ */ -+ public InstrumentedAppender( -+ String registryName, -+ Filter filter, -+ Layout layout, -+ boolean ignoreExceptions) { -+ this(SharedMetricRegistries.getOrCreate(registryName), filter, layout, ignoreExceptions); -+ } - -- /** -- * Create a new instrumented appender using the given registry name. -- * -- * @param registryName the name of the registry in {@link SharedMetricRegistries} -- */ -- public InstrumentedAppender(String registryName) { -- this(SharedMetricRegistries.getOrCreate(registryName)); -- } -+ /** -+ * Create a new instrumented appender using the given registry name. -+ * -+ * @param registryName the name of the registry in {@link SharedMetricRegistries} -+ */ -+ public InstrumentedAppender(String registryName) { -+ this(SharedMetricRegistries.getOrCreate(registryName)); -+ } - -- /** -- * Create a new instrumented appender using the given registry. -- * -- * @param registry the metric registry -- */ -- public InstrumentedAppender(MetricRegistry registry) { -- this(registry, null, null, true); -- } -+ /** -+ * Create a new instrumented appender using the given registry. -+ * -+ * @param registry the metric registry -+ */ -+ public InstrumentedAppender(MetricRegistry registry) { -+ this(registry, null, null, true); -+ } - -- /** -- * Create a new instrumented appender using the given registry. -- * -- * @param registry the metric registry -- * @param filter The Filter to associate with the Appender. -- * @param layout The layout to use to format the event. -- * @param ignoreExceptions If true, exceptions will be logged and suppressed. If false errors will be -- * logged and then passed to the application. -- */ -- public InstrumentedAppender(MetricRegistry registry, Filter filter, Layout layout, boolean ignoreExceptions) { -- super(name(Appender.class).getKey(), filter, layout, ignoreExceptions); -- this.registry = registry; -- } -+ /** -+ * Create a new instrumented appender using the given registry. -+ * -+ * @param registry the metric registry -+ * @param filter The Filter to associate with the Appender. -+ * @param layout The layout to use to format the event. -+ * @param ignoreExceptions If true, exceptions will be logged and suppressed. If false errors will -+ * be logged and then passed to the application. -+ */ -+ public InstrumentedAppender( -+ MetricRegistry registry, -+ Filter filter, -+ Layout layout, -+ boolean ignoreExceptions) { -+ super(name(Appender.class).getKey(), filter, layout, ignoreExceptions); -+ this.registry = registry; -+ } - -- /** -- * Create a new instrumented appender using the given appender name and registry. -- * -- * @param appenderName The name of the appender. -- * @param registry the metric registry -- */ -- public InstrumentedAppender(String appenderName, MetricRegistry registry) { -- super(appenderName, null, null, true); -- this.registry = registry; -- } -+ /** -+ * Create a new instrumented appender using the given appender name and registry. -+ * -+ * @param appenderName The name of the appender. -+ * @param registry the metric registry -+ */ -+ public InstrumentedAppender(String appenderName, MetricRegistry registry) { -+ super(appenderName, null, null, true); -+ this.registry = registry; -+ } - -- @PluginFactory -- public static InstrumentedAppender createAppender( -- @PluginAttribute("name") String name, -- @PluginAttribute(value = "registryName", defaultString = "log4j2Metrics") String registry) { -- return new InstrumentedAppender(name, SharedMetricRegistries.getOrCreate(registry)); -- } -+ @PluginFactory -+ public static InstrumentedAppender createAppender( -+ @PluginAttribute("name") String name, -+ @PluginAttribute(value = "registryName", defaultString = "log4j2Metrics") String registry) { -+ return new InstrumentedAppender(name, SharedMetricRegistries.getOrCreate(registry)); -+ } - -- @Override -- public void start() { -- this.all = registry.meter(name(getName(), "all")); -- this.trace = registry.meter(name(getName(), "trace")); -- this.debug = registry.meter(name(getName(), "debug")); -- this.info = registry.meter(name(getName(), "info")); -- this.warn = registry.meter(name(getName(), "warn")); -- this.error = registry.meter(name(getName(), "error")); -- this.fatal = registry.meter(name(getName(), "fatal")); -- super.start(); -- } -+ @Override -+ public void start() { -+ this.all = registry.meter(name(getName(), "all")); -+ this.trace = registry.meter(name(getName(), "trace")); -+ this.debug = registry.meter(name(getName(), "debug")); -+ this.info = registry.meter(name(getName(), "info")); -+ this.warn = registry.meter(name(getName(), "warn")); -+ this.error = registry.meter(name(getName(), "error")); -+ this.fatal = registry.meter(name(getName(), "fatal")); -+ super.start(); -+ } - -- @Override -- public void append(LogEvent event) { -- all.mark(); -- switch (event.getLevel().getStandardLevel()) { -- case TRACE: -- trace.mark(); -- break; -- case DEBUG: -- debug.mark(); -- break; -- case INFO: -- info.mark(); -- break; -- case WARN: -- warn.mark(); -- break; -- case ERROR: -- error.mark(); -- break; -- case FATAL: -- fatal.mark(); -- break; -- default: -- break; -- } -+ @Override -+ public void append(LogEvent event) { -+ all.mark(); -+ switch (event.getLevel().getStandardLevel()) { -+ case TRACE: -+ trace.mark(); -+ break; -+ case DEBUG: -+ debug.mark(); -+ break; -+ case INFO: -+ info.mark(); -+ break; -+ case WARN: -+ warn.mark(); -+ break; -+ case ERROR: -+ error.mark(); -+ break; -+ case FATAL: -+ fatal.mark(); -+ break; -+ default: -+ break; - } -+ } - } ---- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java -+++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.log4j2; + assertThat(counter.getCount()).isEqualTo(1); + } -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.SharedMetricRegistries; - import org.apache.logging.log4j.core.Logger; -@@ -10,57 +12,55 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; + @Test +- void testIncrementCounterOnManyPoints() { ++ void incrementCounterOnManyPoints() { + counter.inc(5); --import static org.assertj.core.api.Assertions.assertThat; -- --public class InstrumentedAppenderConfigTest { -- public static final String METRIC_NAME_PREFIX = "metrics"; -- public static final String REGISTRY_NAME = "shared-metrics-registry"; -- -- private final MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME); -- private ConfigurationSource source; -- private LoggerContext context; -+final class InstrumentedAppenderConfigTest { -+ public static final String METRIC_NAME_PREFIX = "metrics"; -+ public static final String REGISTRY_NAME = "shared-metrics-registry"; + assertThat(counter.getCount()).isEqualTo(5); + } -- @BeforeEach -- void setUp() throws Exception { -- source = new ConfigurationSource(this.getClass().getClassLoader().getResourceAsStream("log4j2-testconfig.xml")); -- context = Configurator.initialize(null, source); -- } -+ private final MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME); -+ private ConfigurationSource source; -+ private LoggerContext context; + @Test +- void testDecrementCounter() { ++ void decrementCounter() { + counter.dec(); -- @AfterEach -- void tearDown() { -- context.stop(); -- } -+ @BeforeEach -+ void setUp() throws Exception { -+ source = -+ new ConfigurationSource( -+ this.getClass().getClassLoader().getResourceAsStream("log4j2-testconfig.xml")); -+ context = Configurator.initialize(null, source); -+ } - -- // The biggest test is that we can initialize the log4j2 config at all. -+ @AfterEach -+ void tearDown() { -+ context.stop(); -+ } - -- @Test -- void canRecordAll() { -- Logger logger = context.getLogger(this.getClass().getName()); -+ // The biggest test is that we can initialize the log4j2 config at all. - -- long initialAllCount = registry.meter(METRIC_NAME_PREFIX + ".all").getCount(); -- logger.error("an error message"); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(initialAllCount + 1); -- } -+ @Test -+ void canRecordAll() { -+ Logger logger = context.getLogger(this.getClass().getName()); - -- @Test -- void canRecordError() { -- Logger logger = context.getLogger(this.getClass().getName()); -+ long initialAllCount = registry.meter(METRIC_NAME_PREFIX + ".all").getCount(); -+ logger.error("an error message"); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -+ .isEqualTo(initialAllCount + 1); -+ } - -- long initialErrorCount = registry.meter(METRIC_NAME_PREFIX + ".error").getCount(); -- logger.error("an error message"); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(initialErrorCount + 1); -- } -+ @Test -+ void canRecordError() { -+ Logger logger = context.getLogger(this.getClass().getName()); - -- @Test -- void noInvalidRecording() { -- Logger logger = context.getLogger(this.getClass().getName()); -+ long initialErrorCount = registry.meter(METRIC_NAME_PREFIX + ".error").getCount(); -+ logger.error("an error message"); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -+ .isEqualTo(initialErrorCount + 1); -+ } - -- long initialInfoCount = registry.meter(METRIC_NAME_PREFIX + ".info").getCount(); -- logger.error("an error message"); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(initialInfoCount); -- } -+ @Test -+ void noInvalidRecording() { -+ Logger logger = context.getLogger(this.getClass().getName()); + assertThat(counter.getCount()).isEqualTo(-1); + } -+ long initialInfoCount = registry.meter(METRIC_NAME_PREFIX + ".info").getCount(); -+ logger.error("an error message"); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(initialInfoCount); -+ } - } ---- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java -+++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.log4j2; + @Test +- void testDecrementCounterOnManyPoints() { ++ void decrementCounterOnManyPoints() { + counter.dec(5); -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.SharedMetricRegistries; - import org.apache.logging.log4j.Level; -@@ -8,121 +12,104 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; + assertThat(counter.getCount()).isEqualTo(-5); +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java +@@ -5,10 +5,10 @@ import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- --public class InstrumentedAppenderTest { -+final class InstrumentedAppenderTest { - -- public static final String METRIC_NAME_PREFIX = "org.apache.logging.log4j.core.Appender"; -+ public static final String METRIC_NAME_PREFIX = "org.apache.logging.log4j.core.Appender"; + @SuppressWarnings("deprecation") +-class DerivativeGaugeTest { ++final class DerivativeGaugeTest { -- private final MetricRegistry registry = new MetricRegistry(); -- private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final LogEvent event = mock(LogEvent.class); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final InstrumentedAppender appender = new InstrumentedAppender(registry); -+ private final LogEvent event = mock(); + @Test +- void testCalculate() { ++ void calculate() { + DerivativeGauge derivativeGauge = + new DerivativeGauge(() -> "23") { + @Override +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java +@@ -1,15 +1,15 @@ + package com.codahale.metrics; -- @BeforeEach -- void setUp() { -- appender.start(); -- } -+ @BeforeEach -+ void setUp() { -+ appender.start(); -+ } + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; -- @AfterEach -- void tearDown() { -- SharedMetricRegistries.clear(); -- } -+ @AfterEach -+ void tearDown() { -+ SharedMetricRegistries.clear(); -+ } - -- @Test -- void metersTraceEvents() { -- when(event.getLevel()).thenReturn(Level.TRACE); -+ @Test -+ void metersTraceEvents() { -+ when(event.getLevel()).thenReturn(Level.TRACE); +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; -- appender.append(event); -+ appender.append(event); + @SuppressWarnings("deprecation") +-class ExponentiallyDecayingReservoirTest { ++final class ExponentiallyDecayingReservoirTest { -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testCreateReservoir() { ++ void createReservoir() { + ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(); + reservoir.update(120); + reservoir.update(190); +@@ -22,7 +22,7 @@ class ExponentiallyDecayingReservoirTest { + assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); + assertThat(snapshot.getMin()).isEqualTo(120); + assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); ++ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); + assertThat(snapshot.get75thPercentile()).isEqualTo(190); + assertThat(snapshot.get95thPercentile()).isEqualTo(200); + assertThat(snapshot.get98thPercentile()).isEqualTo(200); +@@ -31,14 +31,14 @@ class ExponentiallyDecayingReservoirTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()).isEqualTo(1); -+ } + @Test +- void testCreateReservoirWithCustomSizeAndAlpha() { ++ void createReservoirWithCustomSizeAndAlpha() { + ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01); + reservoir.update(100); + assertThat(reservoir.size()).isEqualTo(1); + } -- @Test -- void metersDebugEvents() { -- when(event.getLevel()).thenReturn(Level.DEBUG); -+ @Test -+ void metersDebugEvents() { -+ when(event.getLevel()).thenReturn(Level.DEBUG); + @Test +- void testCreateReservoirWithCustomSizeAlphaAndClock() { ++ void createReservoirWithCustomSizeAlphaAndClock() { + ExponentiallyDecayingReservoir reservoir = + new ExponentiallyDecayingReservoir( + 512, +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java +@@ -10,7 +10,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- appender.append(event); -+ appender.append(event); + @SuppressWarnings("deprecation") +-class FixedNameCsvFileProviderTest { ++final class FixedNameCsvFileProviderTest { -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + private Path tempDirectory; + private FixedNameCsvFileProvider fixedNameCsvFileProvider = new FixedNameCsvFileProvider(); +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java +@@ -5,12 +5,12 @@ import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()).isEqualTo(1); -+ } + @SuppressWarnings("deprecation") +-class GaugeTest { ++final class GaugeTest { -- @Test -- void metersInfoEvents() { -- when(event.getLevel()).thenReturn(Level.INFO); -+ @Test -+ void metersInfoEvents() { -+ when(event.getLevel()).thenReturn(Level.INFO); + private Gauge gauge = () -> 83; -- appender.append(event); -+ appender.append(event); + @Test +- void testGetValue() { ++ void getValue() { + assertThat(gauge.getValue()).isEqualTo(83); + } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java +@@ -1,15 +1,15 @@ + package com.codahale.metrics; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; -- @Test -- void metersWarnEvents() { -- when(event.getLevel()).thenReturn(Level.WARN); -+ @Test -+ void metersWarnEvents() { -+ when(event.getLevel()).thenReturn(Level.WARN); + @SuppressWarnings("deprecation") +-class HistogramTest { ++final class HistogramTest { -- appender.append(event); -+ appender.append(event); + @Test +- void testCreate() { ++ void create() { + Histogram histogram = new Histogram(new ExponentiallyDecayingReservoir()); + histogram.update(120); + histogram.update(190); +@@ -23,7 +23,7 @@ class HistogramTest { + assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); + assertThat(snapshot.getMin()).isEqualTo(120); + assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); ++ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); + assertThat(snapshot.get75thPercentile()).isEqualTo(190); + assertThat(snapshot.get95thPercentile()).isEqualTo(200); + assertThat(snapshot.get98thPercentile()).isEqualTo(200); +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java +@@ -9,10 +9,10 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @SuppressWarnings("deprecation") +-class InstrumentedExecutorServiceTest { ++final class InstrumentedExecutorServiceTest { -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()).isEqualTo(1); -+ } + @Test +- void testCreate() throws Exception { ++ void create() throws Exception { + ExecutorService executorService = Executors.newSingleThreadExecutor(); + MetricRegistry registry = new MetricRegistry(); + InstrumentedExecutorService instrumentedExecutorService = +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java +@@ -10,7 +10,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.Test; -- @Test -- void metersErrorEvents() { -- when(event.getLevel()).thenReturn(Level.ERROR); -+ @Test -+ void metersErrorEvents() { -+ when(event.getLevel()).thenReturn(Level.ERROR); + @SuppressWarnings("deprecation") +-class InstrumentedScheduledExecutorServiceTest { ++final class InstrumentedScheduledExecutorServiceTest { + private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); -- appender.append(event); -+ appender.append(event); + @AfterEach +@@ -19,7 +19,7 @@ class InstrumentedScheduledExecutorServiceTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testCreate() throws Exception { ++ void create() throws Exception { + MetricRegistry registry = new MetricRegistry(); + InstrumentedScheduledExecutorService instrumentedExecutorService = + new InstrumentedScheduledExecutorService( +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java +@@ -7,11 +7,11 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()).isEqualTo(1); -+ } + @SuppressWarnings("deprecation") +-class InstrumentedThreadFactoryTest { ++final class InstrumentedThreadFactoryTest { -- @Test -- void metersFatalEvents() { -- when(event.getLevel()).thenReturn(Level.FATAL); +- @Test + @SuppressWarnings("DoNotCall") +- void testFactory() throws Exception { + @Test -+ void metersFatalEvents() { -+ when(event.getLevel()).thenReturn(Level.FATAL); ++ void factory() throws Exception { + MetricRegistry registry = new MetricRegistry(); + InstrumentedThreadFactory threadFactory = + new InstrumentedThreadFactory(Thread::new, registry, "test-instrumented-thread-factory"); +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java +@@ -6,16 +6,16 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; -- appender.append(event); -+ appender.append(event); + @SuppressWarnings("deprecation") +-class MeterTest { ++final class MeterTest { -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testCreateMeteer() { ++ void createMeteer() { + Meter meter = new Meter(); + assertThat(meter.getCount()).isEqualTo(0); + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".fatal").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".fatal").getCount()).isEqualTo(1); -+ } + @Test +- void testCreateMeterWithCustomClock() { ++ void createMeterWithCustomClock() { + Meter meter = + new Meter( + new Clock() { +@@ -28,7 +28,7 @@ class MeterTest { + } -- @Test -- void usesSharedRegistries() { -+ @Test -+ void usesSharedRegistries() { + @Test +- void testMark() { ++ void mark() { + Meter meter = + new Meter( + new Clock() { +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java +@@ -11,19 +11,19 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class MetricRegistryTest { ++final class MetricRegistryTest { -- String registryName = "registry"; -+ String registryName = "registry"; + private MetricRegistry metricRegistry = new MetricRegistry(); -- SharedMetricRegistries.add(registryName, registry); -+ SharedMetricRegistries.add(registryName, registry); + @Test +- void testRegisterMetric() { ++ void registerMetric() { + Counter counter = metricRegistry.register("test-counter", new Counter()); + counter.inc(42); + assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); + } -- final InstrumentedAppender shared = new InstrumentedAppender(registryName); -- shared.start(); -+ final InstrumentedAppender shared = new InstrumentedAppender(registryName); -+ shared.start(); + @Test +- void testRegisterAll() { ++ void registerAll() { + metricRegistry.registerAll( + () -> { + Map map = new HashMap<>(); +@@ -40,26 +40,26 @@ class MetricRegistryTest { + } -- when(event.getLevel()).thenReturn(Level.INFO); -+ when(event.getLevel()).thenReturn(Level.INFO); + @Test +- void testRegisterGauge() { ++ void registerGauge() { + metricRegistry.registerGauge("test-gauge", () -> 42); + assertThat(metricRegistry.getGauges().get("test-gauge").getValue()).isEqualTo(42); + } -- shared.append(event); -+ shared.append(event); + @Test +- void testCreateCustomGauge() { ++ void createCustomGauge() { + Gauge gauge = metricRegistry.gauge("test-gauge-supplier", () -> () -> 42); + assertThat(gauge.getValue()).isEqualTo(42); + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } - } ---- a/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java -+++ b/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics.logback13; + @Test +- void testCreateCounter() { ++ void createCounter() { + Counter counter = metricRegistry.counter("test-counter"); + counter.inc(42); + assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); + } -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import ch.qos.logback.classic.Level; - import ch.qos.logback.classic.spi.ILoggingEvent; - import ch.qos.logback.core.Appender; -@@ -8,84 +10,79 @@ import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.SharedMetricRegistries; + @Test +- void testCreateCustomCounter() { ++ void createCustomCounter() { + Counter counter = + metricRegistry.counter( + "test-custom-counter", +@@ -73,7 +73,7 @@ class MetricRegistryTest { + } --import static io.dropwizard.metrics5.MetricRegistry.name; -- - /** - * A Logback {@link Appender} which has six meters, one for each logging level and one for the total - * number of statements being logged. The meter names are the logging level names appended to the - * name of the appender. - */ - public class InstrumentedAppender extends UnsynchronizedAppenderBase { -- private final MetricRegistry registry; -- public static final String DEFAULT_REGISTRY = "logback-metrics"; -- public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; -+ private final MetricRegistry registry; -+ public static final String DEFAULT_REGISTRY = "logback-metrics"; -+ public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; - -- private Meter all; -- private Meter trace; -- private Meter debug; -- private Meter info; -- private Meter warn; -- private Meter error; -+ private Meter all; -+ private Meter trace; -+ private Meter debug; -+ private Meter info; -+ private Meter warn; -+ private Meter error; - -+ /** Create a new instrumented appender using the given registry name. */ -+ public InstrumentedAppender() { -+ this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); -+ } - -- /** -- * Create a new instrumented appender using the given registry name. -- */ -- public InstrumentedAppender() { -- this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); -- } -+ /** -+ * Create a new instrumented appender using the given registry name. -+ * -+ * @param registryName the name of the registry in {@link SharedMetricRegistries} -+ */ -+ public InstrumentedAppender(String registryName) { -+ this(SharedMetricRegistries.getOrCreate(registryName)); -+ } - -- /** -- * Create a new instrumented appender using the given registry name. -- * -- * @param registryName the name of the registry in {@link SharedMetricRegistries} -- */ -- public InstrumentedAppender(String registryName) { -- this(SharedMetricRegistries.getOrCreate(registryName)); -- } -- -- /** -- * Create a new instrumented appender using the given registry. -- * -- * @param registry the metric registry -- */ -- public InstrumentedAppender(MetricRegistry registry) { -- this.registry = registry; -- setName(Appender.class.getName()); -- } -+ /** -+ * Create a new instrumented appender using the given registry. -+ * -+ * @param registry the metric registry -+ */ -+ public InstrumentedAppender(MetricRegistry registry) { -+ this.registry = registry; -+ setName(Appender.class.getName()); -+ } - -- @Override -- public void start() { -- this.all = registry.meter(name(getName(), "all")); -- this.trace = registry.meter(name(getName(), "trace")); -- this.debug = registry.meter(name(getName(), "debug")); -- this.info = registry.meter(name(getName(), "info")); -- this.warn = registry.meter(name(getName(), "warn")); -- this.error = registry.meter(name(getName(), "error")); -- super.start(); -- } -+ @Override -+ public void start() { -+ this.all = registry.meter(name(getName(), "all")); -+ this.trace = registry.meter(name(getName(), "trace")); -+ this.debug = registry.meter(name(getName(), "debug")); -+ this.info = registry.meter(name(getName(), "info")); -+ this.warn = registry.meter(name(getName(), "warn")); -+ this.error = registry.meter(name(getName(), "error")); -+ super.start(); -+ } - -- @Override -- protected void append(ILoggingEvent event) { -- all.mark(); -- switch (event.getLevel().toInt()) { -- case Level.TRACE_INT: -- trace.mark(); -- break; -- case Level.DEBUG_INT: -- debug.mark(); -- break; -- case Level.INFO_INT: -- info.mark(); -- break; -- case Level.WARN_INT: -- warn.mark(); -- break; -- case Level.ERROR_INT: -- error.mark(); -- break; -- default: -- break; -- } -+ @Override -+ protected void append(ILoggingEvent event) { -+ all.mark(); -+ switch (event.getLevel().toInt()) { -+ case Level.TRACE_INT: -+ trace.mark(); -+ break; -+ case Level.DEBUG_INT: -+ debug.mark(); -+ break; -+ case Level.INFO_INT: -+ info.mark(); -+ break; -+ case Level.WARN_INT: -+ warn.mark(); -+ break; -+ case Level.ERROR_INT: -+ error.mark(); -+ break; -+ default: -+ break; - } -+ } - } ---- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java -+++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics.logback13; + @Test +- void testCreateHistogram() { ++ void createHistogram() { + Histogram histogram = metricRegistry.histogram("test-histogram"); + histogram.update(100); + histogram.update(200); +@@ -83,7 +83,7 @@ class MetricRegistryTest { + } -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import ch.qos.logback.classic.Level; - import ch.qos.logback.classic.spi.ILoggingEvent; - import io.dropwizard.metrics5.MetricRegistry; -@@ -8,135 +12,117 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; + @Test +- void testCreateCustomHistogram() { ++ void createCustomHistogram() { + Histogram histogram = + metricRegistry.histogram( + "test-custom-histogram", () -> new Histogram(new SlidingWindowReservoir(2))); +@@ -95,7 +95,7 @@ class MetricRegistryTest { + } --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- --public class InstrumentedAppenderTest { -- -- public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; -+final class InstrumentedAppenderTest { + @Test +- void testCreateMeter() { ++ void createMeter() { + Meter meter = metricRegistry.meter("test-meter"); + meter.mark(); + meter.mark(2); +@@ -104,7 +104,7 @@ class MetricRegistryTest { + } -- private final MetricRegistry registry = new MetricRegistry(); -- private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; + @Test +- void testCreateCustomMeter() { ++ void createCustomMeter() { + Meter meter = + metricRegistry.meter( + "test-custom-meter", +@@ -119,7 +119,7 @@ class MetricRegistryTest { + } -- @BeforeEach -- void setUp() { -- appender.start(); -- } -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final InstrumentedAppender appender = new InstrumentedAppender(registry); -+ private final ILoggingEvent event = mock(); + @Test +- void testCreateTimer() { ++ void createTimer() { + Timer timer = metricRegistry.timer("test-timer"); + timer.update(100, TimeUnit.MILLISECONDS); + timer.update(200, TimeUnit.MILLISECONDS); +@@ -129,7 +129,7 @@ class MetricRegistryTest { + } -- @AfterEach -- void tearDown() { -- SharedMetricRegistries.clear(); -- } -+ @BeforeEach -+ void setUp() { -+ appender.start(); -+ } - -- @Test -- void metersTraceEvents() { -- when(event.getLevel()).thenReturn(Level.TRACE); -+ @AfterEach -+ void tearDown() { -+ SharedMetricRegistries.clear(); -+ } - -- appender.doAppend(event); -+ @Test -+ void metersTraceEvents() { -+ when(event.getLevel()).thenReturn(Level.TRACE); + @Test +- void testCreateCustomTimer() { ++ void createCustomTimer() { + Timer timer = + metricRegistry.timer( + "custom-test-timer", +@@ -145,7 +145,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testRemoveMetric() { ++ void removeMetric() { + metricRegistry.timer("test-timer"); + metricRegistry.counter("test-counter"); + metricRegistry.meter("test-meter"); +@@ -156,7 +156,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testRemoveMatching() { ++ void removeMatching() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.timer("test-custom-timer"); +@@ -168,7 +168,7 @@ class MetricRegistryTest { + } -- @Test -- void metersDebugEvents() { -- when(event.getLevel()).thenReturn(Level.DEBUG); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()).isEqualTo(1); -+ } + @Test +- void testAddListenerForGauge() throws Exception { ++ void addListenerForGauge() throws Exception { + CountDownLatch gaugeAddedLatch = new CountDownLatch(1); + CountDownLatch gaugeRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -197,7 +197,7 @@ class MetricRegistryTest { + } -- appender.doAppend(event); -+ @Test -+ void metersDebugEvents() { -+ when(event.getLevel()).thenReturn(Level.DEBUG); + @Test +- void testAddListenerForCounter() throws Exception { ++ void addListenerForCounter() throws Exception { + CountDownLatch counterAddedLatch = new CountDownLatch(1); + CountDownLatch counterRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -225,7 +225,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testAddListenerForHistogram() throws Exception { ++ void addListenerForHistogram() throws Exception { + CountDownLatch histogramAddedLatch = new CountDownLatch(1); + CountDownLatch histogramRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -254,7 +254,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testAddListenerForMeter() throws Exception { ++ void addListenerForMeter() throws Exception { + CountDownLatch meterAddedLatch = new CountDownLatch(1); + CountDownLatch meterRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -283,7 +283,7 @@ class MetricRegistryTest { + } -- @Test -- void metersInfoEvents() { -- when(event.getLevel()).thenReturn(Level.INFO); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()).isEqualTo(1); -+ } + @Test +- void testAddListenerForTimer() throws Exception { ++ void addListenerForTimer() throws Exception { + CountDownLatch timerAddedLatch = new CountDownLatch(1); + CountDownLatch timerRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -312,7 +312,7 @@ class MetricRegistryTest { + } -- appender.doAppend(event); -+ @Test -+ void metersInfoEvents() { -+ when(event.getLevel()).thenReturn(Level.INFO); + @Test +- void testRemoveListener() throws Exception { ++ void removeListener() throws Exception { + CountDownLatch gaugeAddedLatch = new CountDownLatch(1); + MetricRegistryListener listener = + new MetricRegistryListener.Base() { +@@ -331,7 +331,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testGetNames() { ++ void getNames() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.timer("test-custom-timer"); +@@ -342,7 +342,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testGetGauges() { ++ void getGauges() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -369,7 +369,7 @@ class MetricRegistryTest { + } -- @Test -- void metersWarnEvents() { -- when(event.getLevel()).thenReturn(Level.WARN); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } + @Test +- void testGetGaugesWithFilter() { ++ void getGaugesWithFilter() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -398,7 +398,7 @@ class MetricRegistryTest { + } -- appender.doAppend(event); -+ @Test -+ void metersWarnEvents() { -+ when(event.getLevel()).thenReturn(Level.WARN); + @Test +- void testGetHistograms() { ++ void getHistograms() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -411,7 +411,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testGetHistogramsWithFilter() { ++ void getHistogramsWithFilter() { + metricRegistry.counter("sw-counter"); + metricRegistry.timer("sw-timer"); + metricRegistry.meter("sw-meter"); +@@ -424,7 +424,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testGetCounters() { ++ void getCounters() { + metricRegistry.histogram("test-histogram"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -437,7 +437,7 @@ class MetricRegistryTest { + } -- @Test -- void metersErrorEvents() { -- when(event.getLevel()).thenReturn(Level.ERROR); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()).isEqualTo(1); -+ } + @Test +- void testGetCountersWithFilter() { ++ void getCountersWithFilter() { + metricRegistry.histogram("test-histogram"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -450,7 +450,7 @@ class MetricRegistryTest { + } -- appender.doAppend(event); -+ @Test -+ void metersErrorEvents() { -+ when(event.getLevel()).thenReturn(Level.ERROR); + @Test +- void testGetMeters() { ++ void getMeters() { + metricRegistry.register("test-gauge", (Gauge) () -> 42); + metricRegistry.histogram("test-histogram"); + metricRegistry.timer("test-timer"); +@@ -464,7 +464,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testGetMetersWithFilter() { ++ void getMetersWithFilter() { + metricRegistry.register("sw-gauge", (Gauge) () -> 42); + metricRegistry.histogram("sw-histogram"); + metricRegistry.timer("sw-timer"); +@@ -478,7 +478,7 @@ class MetricRegistryTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testGetTimers() { ++ void getTimers() { + metricRegistry.histogram("test-histogram"); + metricRegistry.meter("test-meter"); + metricRegistry.counter("test-counter"); +@@ -491,7 +491,7 @@ class MetricRegistryTest { + } -- @Test -- void usesSharedRegistries() { -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()).isEqualTo(1); -+ } + @Test +- void testGetTimersWithFilter() { ++ void getTimersWithFilter() { + metricRegistry.histogram("test-histogram-2"); + metricRegistry.meter("test-meter-2"); + metricRegistry.counter("test-counter-2"); +@@ -504,7 +504,7 @@ class MetricRegistryTest { + } -- String registryName = "registry"; -+ @Test -+ void usesSharedRegistries() { + @Test +- void testGetMetrics() { ++ void getMetrics() { + metricRegistry.register( + "test-text-gauge-2", + new CachedGauge(1, TimeUnit.MINUTES) { +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java +@@ -1,12 +1,12 @@ + package com.codahale.metrics; -- SharedMetricRegistries.add(registryName, registry); -- final InstrumentedAppender shared = new InstrumentedAppender(registryName); -- shared.start(); -+ String registryName = "registry"; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; -- when(event.getLevel()).thenReturn(Level.INFO); -+ SharedMetricRegistries.add(registryName, registry); -+ final InstrumentedAppender shared = new InstrumentedAppender(registryName); -+ shared.start(); +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; -- shared.doAppend(event); -+ when(event.getLevel()).thenReturn(Level.INFO); + @SuppressWarnings("deprecation") +-class RatioGaugeTest { ++final class RatioGaugeTest { -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ shared.doAppend(event); - -- @Test -- void usesDefaultRegistry() { -- SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); -- final InstrumentedAppender shared = new InstrumentedAppender(); -- shared.start(); -- when(event.getLevel()).thenReturn(Level.INFO); -- shared.doAppend(event); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } - -- assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ @Test -+ void usesDefaultRegistry() { -+ SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); -+ final InstrumentedAppender shared = new InstrumentedAppender(); -+ shared.start(); -+ when(event.getLevel()).thenReturn(Level.INFO); -+ shared.doAppend(event); - -- @Test -- void usesRegistryFromProperty() { -- SharedMetricRegistries.add("something_else", registry); -- System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); -- final InstrumentedAppender shared = new InstrumentedAppender(); -- shared.start(); -- when(event.getLevel()).thenReturn(Level.INFO); -- shared.doAppend(event); -+ assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } - -- assertThat(SharedMetricRegistries.names()).contains("something_else"); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ @Test -+ void usesRegistryFromProperty() { -+ SharedMetricRegistries.add("something_else", registry); -+ System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); -+ final InstrumentedAppender shared = new InstrumentedAppender(); -+ shared.start(); -+ when(event.getLevel()).thenReturn(Level.INFO); -+ shared.doAppend(event); - -+ assertThat(SharedMetricRegistries.names()).contains("something_else"); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } - } ---- a/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java -+++ b/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics.logback14; + private RatioGauge ratioGauge = + new RatioGauge() { +@@ -17,12 +17,12 @@ class RatioGaugeTest { + }; -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import ch.qos.logback.classic.Level; - import ch.qos.logback.classic.spi.ILoggingEvent; - import ch.qos.logback.core.Appender; -@@ -8,84 +10,79 @@ import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.SharedMetricRegistries; + @Test +- void testViewRatin() { +- assertThat(ratioGauge.getRatio().toString()).isEqualTo("1.0:3.0"); ++ void viewRatin() { ++ assertThat(ratioGauge.getRatio()).hasToString("1.0:3.0"); + } --import static io.dropwizard.metrics5.MetricRegistry.name; -- - /** - * A Logback {@link Appender} which has six meters, one for each logging level and one for the total - * number of statements being logged. The meter names are the logging level names appended to the - * name of the appender. - */ - public class InstrumentedAppender extends UnsynchronizedAppenderBase { -- private final MetricRegistry registry; -- public static final String DEFAULT_REGISTRY = "logback-metrics"; -- public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; -+ private final MetricRegistry registry; -+ public static final String DEFAULT_REGISTRY = "logback-metrics"; -+ public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; - -- private Meter all; -- private Meter trace; -- private Meter debug; -- private Meter info; -- private Meter warn; -- private Meter error; -+ private Meter all; -+ private Meter trace; -+ private Meter debug; -+ private Meter info; -+ private Meter warn; -+ private Meter error; - -+ /** Create a new instrumented appender using the given registry name. */ -+ public InstrumentedAppender() { -+ this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); -+ } - -- /** -- * Create a new instrumented appender using the given registry name. -- */ -- public InstrumentedAppender() { -- this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); -- } -+ /** -+ * Create a new instrumented appender using the given registry name. -+ * -+ * @param registryName the name of the registry in {@link SharedMetricRegistries} -+ */ -+ public InstrumentedAppender(String registryName) { -+ this(SharedMetricRegistries.getOrCreate(registryName)); -+ } - -- /** -- * Create a new instrumented appender using the given registry name. -- * -- * @param registryName the name of the registry in {@link SharedMetricRegistries} -- */ -- public InstrumentedAppender(String registryName) { -- this(SharedMetricRegistries.getOrCreate(registryName)); -- } -- -- /** -- * Create a new instrumented appender using the given registry. -- * -- * @param registry the metric registry -- */ -- public InstrumentedAppender(MetricRegistry registry) { -- this.registry = registry; -- setName(Appender.class.getName()); -- } -+ /** -+ * Create a new instrumented appender using the given registry. -+ * -+ * @param registry the metric registry -+ */ -+ public InstrumentedAppender(MetricRegistry registry) { -+ this.registry = registry; -+ setName(Appender.class.getName()); -+ } - -- @Override -- public void start() { -- this.all = registry.meter(name(getName(), "all")); -- this.trace = registry.meter(name(getName(), "trace")); -- this.debug = registry.meter(name(getName(), "debug")); -- this.info = registry.meter(name(getName(), "info")); -- this.warn = registry.meter(name(getName(), "warn")); -- this.error = registry.meter(name(getName(), "error")); -- super.start(); -- } -+ @Override -+ public void start() { -+ this.all = registry.meter(name(getName(), "all")); -+ this.trace = registry.meter(name(getName(), "trace")); -+ this.debug = registry.meter(name(getName(), "debug")); -+ this.info = registry.meter(name(getName(), "info")); -+ this.warn = registry.meter(name(getName(), "warn")); -+ this.error = registry.meter(name(getName(), "error")); -+ super.start(); -+ } - -- @Override -- protected void append(ILoggingEvent event) { -- all.mark(); -- switch (event.getLevel().toInt()) { -- case Level.TRACE_INT: -- trace.mark(); -- break; -- case Level.DEBUG_INT: -- debug.mark(); -- break; -- case Level.INFO_INT: -- info.mark(); -- break; -- case Level.WARN_INT: -- warn.mark(); -- break; -- case Level.ERROR_INT: -- error.mark(); -- break; -- default: -- break; -- } -+ @Override -+ protected void append(ILoggingEvent event) { -+ all.mark(); -+ switch (event.getLevel().toInt()) { -+ case Level.TRACE_INT: -+ trace.mark(); -+ break; -+ case Level.DEBUG_INT: -+ debug.mark(); -+ break; -+ case Level.INFO_INT: -+ info.mark(); -+ break; -+ case Level.WARN_INT: -+ warn.mark(); -+ break; -+ case Level.ERROR_INT: -+ error.mark(); -+ break; -+ default: -+ break; - } -+ } + @Test +- void testCalculateRatio() { +- assertThat(ratioGauge.getValue()).isCloseTo(0.33, Offset.offset(0.01)); ++ void calculateRatio() { ++ assertThat(ratioGauge.getValue()).isCloseTo(0.33, offset(0.01)); + } } ---- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java -+++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics.logback14; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import ch.qos.logback.classic.Level; - import ch.qos.logback.classic.spi.ILoggingEvent; - import io.dropwizard.metrics5.MetricRegistry; -@@ -8,135 +12,117 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java +@@ -10,7 +10,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- --public class InstrumentedAppenderTest { -- -- public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; -+final class InstrumentedAppenderTest { - -- private final MetricRegistry registry = new MetricRegistry(); -- private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; - -- @BeforeEach -- void setUp() { -- appender.start(); -- } -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final InstrumentedAppender appender = new InstrumentedAppender(registry); -+ private final ILoggingEvent event = mock(); + @SuppressWarnings("deprecation") +-class ScheduledReporterTest { ++final class ScheduledReporterTest { -- @AfterEach -- void tearDown() { -- SharedMetricRegistries.clear(); -- } -+ @BeforeEach -+ void setUp() { -+ appender.start(); -+ } - -- @Test -- void metersTraceEvents() { -- when(event.getLevel()).thenReturn(Level.TRACE); -+ @AfterEach -+ void tearDown() { -+ SharedMetricRegistries.clear(); -+ } - -- appender.doAppend(event); -+ @Test -+ void metersTraceEvents() { -+ when(event.getLevel()).thenReturn(Level.TRACE); + private MetricRegistry metricRegistry = new MetricRegistry(); + private ScheduledReporter scheduledReporter; +@@ -51,7 +51,7 @@ class ScheduledReporterTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testReport() throws Exception { ++ void report() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + scheduledReporter = createScheduledReporter(latch); + scheduledReporter.report(); +@@ -61,7 +61,7 @@ class ScheduledReporterTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testStart() throws Exception { ++ void start() throws Exception { + CountDownLatch latch = new CountDownLatch(2); + scheduledReporter = createScheduledReporter(latch); + scheduledReporter.start(10, TimeUnit.MILLISECONDS); +@@ -71,7 +71,7 @@ class ScheduledReporterTest { + } -- @Test -- void metersDebugEvents() { -- when(event.getLevel()).thenReturn(Level.DEBUG); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()).isEqualTo(1); -+ } + @Test +- void testStartWithoutDelay() throws Exception { ++ void startWithoutDelay() throws Exception { + CountDownLatch latch = new CountDownLatch(2); + scheduledReporter = createScheduledReporter(latch); + scheduledReporter.start(0, 10, TimeUnit.MILLISECONDS); +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java +@@ -1,13 +1,13 @@ + package com.codahale.metrics; -- appender.doAppend(event); -+ @Test -+ void metersDebugEvents() { -+ when(event.getLevel()).thenReturn(Level.DEBUG); + import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatIllegalStateException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.Test; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @SuppressWarnings("deprecation") +-class SharedMetricRegistriesTest { ++final class SharedMetricRegistriesTest { -- @Test -- void metersInfoEvents() { -- when(event.getLevel()).thenReturn(Level.INFO); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()).isEqualTo(1); -+ } + @AfterEach + void tearDown() throws Exception { +@@ -15,7 +15,7 @@ class SharedMetricRegistriesTest { + } -- appender.doAppend(event); -+ @Test -+ void metersInfoEvents() { -+ when(event.getLevel()).thenReturn(Level.INFO); + @Test +- void testGetOrCreateMetricRegistry() { ++ void getOrCreateMetricRegistry() { + SharedMetricRegistries.getOrCreate("get-or-create").counter("test-counter"); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + assertThat(SharedMetricRegistries.getOrCreate("get-or-create").getCounters()) +@@ -23,7 +23,7 @@ class SharedMetricRegistriesTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testAddMetricRegistry() { ++ void addMetricRegistry() { + MetricRegistry metricRegistry = new MetricRegistry(); + metricRegistry.histogram("test-histogram"); + SharedMetricRegistries.add("add", metricRegistry); +@@ -33,7 +33,7 @@ class SharedMetricRegistriesTest { + } -- @Test -- void metersWarnEvents() { -- when(event.getLevel()).thenReturn(Level.WARN); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } + @Test +- void testNames() { ++ void names() { + SharedMetricRegistries.add("registry-1", new MetricRegistry()); + SharedMetricRegistries.add("registry-2", new MetricRegistry()); + SharedMetricRegistries.add("registry-3", new MetricRegistry()); +@@ -43,12 +43,13 @@ class SharedMetricRegistriesTest { + } -- appender.doAppend(event); -+ @Test -+ void metersWarnEvents() { -+ when(event.getLevel()).thenReturn(Level.WARN); + @Test +- void testTryGetDefaultRegistry() { ++ void tryGetDefaultRegistry() { + assertThat(SharedMetricRegistries.tryGetDefault()).isNull(); + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testGetDefaultRegistry() { +- assertThatIllegalStateException().isThrownBy(SharedMetricRegistries::getDefault); ++ void getDefaultRegistry() { ++ assertThatThrownBy(SharedMetricRegistries::getDefault) ++ .isInstanceOf(IllegalStateException.class); + } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java +@@ -14,11 +14,11 @@ import org.slf4j.Logger; + import org.slf4j.Marker; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @SuppressWarnings("deprecation") +-class Slf4jReporterTest { ++final class Slf4jReporterTest { -- @Test -- void metersErrorEvents() { -- when(event.getLevel()).thenReturn(Level.ERROR); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()).isEqualTo(1); -+ } + private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); +- private Logger logger = mock(Logger.class); +- private Marker marker = mock(Marker.class); ++ private Logger logger = mock(); ++ private Marker marker = mock(); -- appender.doAppend(event); -+ @Test -+ void metersErrorEvents() { -+ when(event.getLevel()).thenReturn(Level.ERROR); + @BeforeEach + void setUp() throws Exception { +@@ -31,7 +31,7 @@ class Slf4jReporterTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testReport() throws Exception { ++ void report() throws Exception { + MetricRegistry metricRegistry = new MetricRegistry(); + metricRegistry.counter("test-counter").inc(100); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java +@@ -1,16 +1,16 @@ + package com.codahale.metrics; -- @Test -- void usesSharedRegistries() { -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()).isEqualTo(1); -+ } + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; -- String registryName = "registry"; -+ @Test -+ void usesSharedRegistries() { + import java.util.concurrent.TimeUnit; +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; -- SharedMetricRegistries.add(registryName, registry); -- final InstrumentedAppender shared = new InstrumentedAppender(registryName); -- shared.start(); -+ String registryName = "registry"; + @SuppressWarnings("deprecation") +-class SlidingTimeWindowArrayReservoirTest { ++final class SlidingTimeWindowArrayReservoirTest { -- when(event.getLevel()).thenReturn(Level.INFO); -+ SharedMetricRegistries.add(registryName, registry); -+ final InstrumentedAppender shared = new InstrumentedAppender(registryName); -+ shared.start(); + @Test +- void testCreateWithWindow() { ++ void createWithWindow() { + SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS); + reservoir.update(100); +@@ -18,17 +18,17 @@ class SlidingTimeWindowArrayReservoirTest { + reservoir.update(30); + + assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); + } -- shared.doAppend(event); -+ when(event.getLevel()).thenReturn(Level.INFO); + @Test +- void testCreateWithWindowAndClock() { ++ void createWithWindowAndClock() { + SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); + reservoir.update(400); + reservoir.update(300); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ shared.doAppend(event); - -- @Test -- void usesDefaultRegistry() { -- SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); -- final InstrumentedAppender shared = new InstrumentedAppender(); -- shared.start(); -- when(event.getLevel()).thenReturn(Level.INFO); -- shared.doAppend(event); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } - -- assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ @Test -+ void usesDefaultRegistry() { -+ SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); -+ final InstrumentedAppender shared = new InstrumentedAppender(); -+ shared.start(); -+ when(event.getLevel()).thenReturn(Level.INFO); -+ shared.doAppend(event); - -- @Test -- void usesRegistryFromProperty() { -- SharedMetricRegistries.add("something_else", registry); -- System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); -- final InstrumentedAppender shared = new InstrumentedAppender(); -- shared.start(); -- when(event.getLevel()).thenReturn(Level.INFO); -- shared.doAppend(event); -+ assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } - -- assertThat(SharedMetricRegistries.names()).contains("something_else"); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ @Test -+ void usesRegistryFromProperty() { -+ SharedMetricRegistries.add("something_else", registry); -+ System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); -+ final InstrumentedAppender shared = new InstrumentedAppender(); -+ shared.start(); -+ when(event.getLevel()).thenReturn(Level.INFO); -+ shared.doAppend(event); - -+ assertThat(SharedMetricRegistries.names()).contains("something_else"); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } + assertThat(reservoir.size()).isEqualTo(2); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); + } } ---- a/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java -+++ b/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.logback15; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import ch.qos.logback.classic.Level; - import ch.qos.logback.classic.spi.ILoggingEvent; - import ch.qos.logback.core.Appender; -@@ -8,84 +10,79 @@ import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.SharedMetricRegistries; +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java +@@ -1,33 +1,33 @@ + package com.codahale.metrics; --import static io.dropwizard.metrics5.MetricRegistry.name; -- - /** - * A Logback {@link Appender} which has six meters, one for each logging level and one for the total - * number of statements being logged. The meter names are the logging level names appended to the - * name of the appender. - */ - public class InstrumentedAppender extends UnsynchronizedAppenderBase { -- private final MetricRegistry registry; -- public static final String DEFAULT_REGISTRY = "logback-metrics"; -- public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; -+ private final MetricRegistry registry; -+ public static final String DEFAULT_REGISTRY = "logback-metrics"; -+ public static final String REGISTRY_PROPERTY_NAME = "metrics.logback.registry"; - -- private Meter all; -- private Meter trace; -- private Meter debug; -- private Meter info; -- private Meter warn; -- private Meter error; -+ private Meter all; -+ private Meter trace; -+ private Meter debug; -+ private Meter info; -+ private Meter warn; -+ private Meter error; - -+ /** Create a new instrumented appender using the given registry name. */ -+ public InstrumentedAppender() { -+ this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); -+ } - -- /** -- * Create a new instrumented appender using the given registry name. -- */ -- public InstrumentedAppender() { -- this(System.getProperty(REGISTRY_PROPERTY_NAME, DEFAULT_REGISTRY)); -- } -+ /** -+ * Create a new instrumented appender using the given registry name. -+ * -+ * @param registryName the name of the registry in {@link SharedMetricRegistries} -+ */ -+ public InstrumentedAppender(String registryName) { -+ this(SharedMetricRegistries.getOrCreate(registryName)); -+ } - -- /** -- * Create a new instrumented appender using the given registry name. -- * -- * @param registryName the name of the registry in {@link SharedMetricRegistries} -- */ -- public InstrumentedAppender(String registryName) { -- this(SharedMetricRegistries.getOrCreate(registryName)); -- } -- -- /** -- * Create a new instrumented appender using the given registry. -- * -- * @param registry the metric registry -- */ -- public InstrumentedAppender(MetricRegistry registry) { -- this.registry = registry; -- setName(Appender.class.getName()); -- } -+ /** -+ * Create a new instrumented appender using the given registry. -+ * -+ * @param registry the metric registry -+ */ -+ public InstrumentedAppender(MetricRegistry registry) { -+ this.registry = registry; -+ setName(Appender.class.getName()); -+ } - -- @Override -- public void start() { -- this.all = registry.meter(name(getName(), "all")); -- this.trace = registry.meter(name(getName(), "trace")); -- this.debug = registry.meter(name(getName(), "debug")); -- this.info = registry.meter(name(getName(), "info")); -- this.warn = registry.meter(name(getName(), "warn")); -- this.error = registry.meter(name(getName(), "error")); -- super.start(); -- } -+ @Override -+ public void start() { -+ this.all = registry.meter(name(getName(), "all")); -+ this.trace = registry.meter(name(getName(), "trace")); -+ this.debug = registry.meter(name(getName(), "debug")); -+ this.info = registry.meter(name(getName(), "info")); -+ this.warn = registry.meter(name(getName(), "warn")); -+ this.error = registry.meter(name(getName(), "error")); -+ super.start(); -+ } - -- @Override -- protected void append(ILoggingEvent event) { -- all.mark(); -- switch (event.getLevel().toInt()) { -- case Level.TRACE_INT: -- trace.mark(); -- break; -- case Level.DEBUG_INT: -- debug.mark(); -- break; -- case Level.INFO_INT: -- info.mark(); -- break; -- case Level.WARN_INT: -- warn.mark(); -- break; -- case Level.ERROR_INT: -- error.mark(); -- break; -- default: -- break; -- } -+ @Override -+ protected void append(ILoggingEvent event) { -+ all.mark(); -+ switch (event.getLevel().toInt()) { -+ case Level.TRACE_INT: -+ trace.mark(); -+ break; -+ case Level.DEBUG_INT: -+ debug.mark(); -+ break; -+ case Level.INFO_INT: -+ info.mark(); -+ break; -+ case Level.WARN_INT: -+ warn.mark(); -+ break; -+ case Level.ERROR_INT: -+ error.mark(); -+ break; -+ default: -+ break; - } -+ } - } ---- a/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java -+++ b/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.logback15; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import ch.qos.logback.classic.Level; - import ch.qos.logback.classic.spi.ILoggingEvent; - import io.dropwizard.metrics5.MetricRegistry; -@@ -8,135 +12,117 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; + import java.util.concurrent.TimeUnit; +-import org.assertj.core.data.Offset; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- --public class InstrumentedAppenderTest { -- -- public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; -+final class InstrumentedAppenderTest { - -- private final MetricRegistry registry = new MetricRegistry(); -- private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; - -- @BeforeEach -- void setUp() { -- appender.start(); -- } -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final InstrumentedAppender appender = new InstrumentedAppender(registry); -+ private final ILoggingEvent event = mock(); + @SuppressWarnings("deprecation") +-class SlidingTimeWindowReservoirTest { ++final class SlidingTimeWindowReservoirTest { -- @AfterEach -- void tearDown() { -- SharedMetricRegistries.clear(); -- } -+ @BeforeEach -+ void setUp() { -+ appender.start(); -+ } - -- @Test -- void metersTraceEvents() { -- when(event.getLevel()).thenReturn(Level.TRACE); -+ @AfterEach -+ void tearDown() { -+ SharedMetricRegistries.clear(); -+ } - -- appender.doAppend(event); -+ @Test -+ void metersTraceEvents() { -+ when(event.getLevel()).thenReturn(Level.TRACE); + @Test +- void testCreateWithWindow() { ++ void createWithWindow() { + SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS); + reservoir.update(100); + reservoir.update(200); + reservoir.update(30); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testCreateWithWindowAndClock() { ++ void createWithWindowAndClock() { + SlidingTimeWindowReservoir reservoir = + new SlidingTimeWindowReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); + reservoir.update(400); + reservoir.update(300); -- @Test -- void metersDebugEvents() { -- when(event.getLevel()).thenReturn(Level.DEBUG); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".trace").getCount()).isEqualTo(1); -+ } + assertThat(reservoir.size()).isEqualTo(2); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); + } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java +@@ -1,26 +1,26 @@ + package com.codahale.metrics; -- appender.doAppend(event); -+ @Test -+ void metersDebugEvents() { -+ when(event.getLevel()).thenReturn(Level.DEBUG); + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @SuppressWarnings("deprecation") +-class SlidingWindowReservoirTest { ++final class SlidingWindowReservoirTest { -- @Test -- void metersInfoEvents() { -- when(event.getLevel()).thenReturn(Level.INFO); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".debug").getCount()).isEqualTo(1); -+ } + @Test +- void testCreateWithBigWindow() { ++ void createWithBigWindow() { + SlidingWindowReservoir reservoir = new SlidingWindowReservoir(100); + reservoir.update(100); + reservoir.update(220); + reservoir.update(130); -- appender.doAppend(event); -+ @Test -+ void metersInfoEvents() { -+ when(event.getLevel()).thenReturn(Level.INFO); + assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, offset(0.1)); + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testCreateWithLowWindow() { ++ void createWithLowWindow() { + SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); + reservoir.update(500); + reservoir.update(220); +@@ -28,6 +28,6 @@ class SlidingWindowReservoirTest { + reservoir.update(40); + + assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, offset(0.1)); + } + } +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java +@@ -1,30 +1,30 @@ + package com.codahale.metrics; -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; -- @Test -- void metersWarnEvents() { -- when(event.getLevel()).thenReturn(Level.WARN); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } + import io.dropwizard.metrics5.UniformSnapshot; + import java.io.ByteArrayOutputStream; +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; -- appender.doAppend(event); -+ @Test -+ void metersWarnEvents() { -+ when(event.getLevel()).thenReturn(Level.WARN); + @SuppressWarnings("deprecation") +-class SnapshotTest { ++final class SnapshotTest { -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); + @Test +- void testCreateSnapshot() throws Exception { ++ void createSnapshot() throws Exception { + Snapshot snapshot = Snapshot.of(new UniformSnapshot(new long[] {5, 1, 2, 3, 4})); + + assertThat(snapshot.getValues()).isEqualTo(new long[] {1, 2, 3, 4, 5}); + assertThat(snapshot.size()).isEqualTo(5); + assertThat(snapshot.getMin()).isEqualTo(1); + assertThat(snapshot.getMax()).isEqualTo(5); +- assertThat(snapshot.getStdDev()).isEqualTo(1.58, Offset.offset(0.01)); +- assertThat(snapshot.getMedian()).isEqualTo(3, Offset.offset(0.01)); +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, Offset.offset(0.01)); +- assertThat(snapshot.get95thPercentile()).isEqualTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get98thPercentile()).isEqualTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get99thPercentile()).isEqualTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get999thPercentile()).isEqualTo(5, Offset.offset(0.01)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.58, offset(0.01)); ++ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.01)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.01)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5, offset(0.01)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5, offset(0.01)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5, offset(0.01)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5, offset(0.01)); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + snapshot.dump(baos); +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java +@@ -8,7 +8,7 @@ import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.Test; -- @Test -- void metersErrorEvents() { -- when(event.getLevel()).thenReturn(Level.ERROR); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".warn").getCount()).isEqualTo(1); -+ } + @SuppressWarnings("deprecation") +-class TimerTest { ++final class TimerTest { -- appender.doAppend(event); -+ @Test -+ void metersErrorEvents() { -+ when(event.getLevel()).thenReturn(Level.ERROR); + private static class ManualClock extends Clock { -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()) -- .isEqualTo(1); -+ appender.doAppend(event); +@@ -26,7 +26,7 @@ class TimerTest { + } -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()) -- .isEqualTo(1); -- } -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".all").getCount()).isEqualTo(1); + @Test +- void testCreate() { ++ void create() { + Timer timer = new Timer(); + timer.update(100, TimeUnit.MILLISECONDS); + timer.update(200, TimeUnit.MILLISECONDS); +@@ -35,7 +35,7 @@ class TimerTest { + } -- @Test -- void usesSharedRegistries() { -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".error").getCount()).isEqualTo(1); -+ } + @Test +- void testCreateWithCustomReservoir() { ++ void createWithCustomReservoir() { + Timer timer = new Timer(new SlidingWindowReservoir(100)); + timer.update(100, TimeUnit.MILLISECONDS); + timer.update(200, TimeUnit.MILLISECONDS); +@@ -44,7 +44,7 @@ class TimerTest { + } -- String registryName = "registry"; -+ @Test -+ void usesSharedRegistries() { + @Test +- void testCreateWithCustomReservoirAndClock() { ++ void createWithCustomReservoirAndClock() { + Timer timer = new Timer(new SlidingWindowReservoir(100), new Clock.UserTimeClock()); + timer.update(100, TimeUnit.MILLISECONDS); + timer.update(200, TimeUnit.MILLISECONDS); +@@ -53,7 +53,7 @@ class TimerTest { + } -- SharedMetricRegistries.add(registryName, registry); -- final InstrumentedAppender shared = new InstrumentedAppender(registryName); -- shared.start(); -+ String registryName = "registry"; + @Test +- void testTimerContext() { ++ void timerContext() { + Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + timer.time().stop(); -- when(event.getLevel()).thenReturn(Level.INFO); -+ SharedMetricRegistries.add(registryName, registry); -+ final InstrumentedAppender shared = new InstrumentedAppender(registryName); -+ shared.start(); +@@ -61,7 +61,7 @@ class TimerTest { + } -- shared.doAppend(event); -+ when(event.getLevel()).thenReturn(Level.INFO); + @Test +- void testTimerRunnable() { ++ void timerRunnable() { + Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ shared.doAppend(event); - -- @Test -- void usesDefaultRegistry() { -- SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); -- final InstrumentedAppender shared = new InstrumentedAppender(); -- shared.start(); -- when(event.getLevel()).thenReturn(Level.INFO); -- shared.doAppend(event); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } - -- assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ @Test -+ void usesDefaultRegistry() { -+ SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); -+ final InstrumentedAppender shared = new InstrumentedAppender(); -+ shared.start(); -+ when(event.getLevel()).thenReturn(Level.INFO); -+ shared.doAppend(event); - -- @Test -- void usesRegistryFromProperty() { -- SharedMetricRegistries.add("something_else", registry); -- System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); -- final InstrumentedAppender shared = new InstrumentedAppender(); -- shared.start(); -- when(event.getLevel()).thenReturn(Level.INFO); -- shared.doAppend(event); -+ assertThat(SharedMetricRegistries.names()).contains(InstrumentedAppender.DEFAULT_REGISTRY); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } - -- assertThat(SharedMetricRegistries.names()).contains("something_else"); -- assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()) -- .isEqualTo(1); -- } -+ @Test -+ void usesRegistryFromProperty() { -+ SharedMetricRegistries.add("something_else", registry); -+ System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); -+ final InstrumentedAppender shared = new InstrumentedAppender(); -+ shared.start(); -+ when(event.getLevel()).thenReturn(Level.INFO); -+ shared.doAppend(event); - -+ assertThat(SharedMetricRegistries.names()).contains("something_else"); -+ assertThat(registry.meter(METRIC_NAME_PREFIX + ".info").getCount()).isEqualTo(1); -+ } - } ---- a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -+++ b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -@@ -1,10 +1,17 @@ - package io.dropwizard.metrics5.servlet; + AtomicInteger counter = new AtomicInteger(); +@@ -72,7 +72,7 @@ class TimerTest { + } -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ -+import com.google.common.base.Strings; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -- -+import java.io.IOException; -+import java.util.Map; -+import java.util.Map.Entry; -+import java.util.concurrent.ConcurrentHashMap; -+import java.util.concurrent.ConcurrentMap; - import javax.servlet.AsyncEvent; - import javax.servlet.AsyncListener; - import javax.servlet.Filter; -@@ -15,204 +22,192 @@ import javax.servlet.ServletRequest; - import javax.servlet.ServletResponse; - import javax.servlet.http.HttpServletResponse; - import javax.servlet.http.HttpServletResponseWrapper; --import java.io.IOException; --import java.util.Map; --import java.util.Map.Entry; --import java.util.concurrent.ConcurrentHashMap; --import java.util.concurrent.ConcurrentMap; -- --import static io.dropwizard.metrics5.MetricRegistry.name; + @Test +- void testTimerCallable() throws Exception { ++ void timerCallable() throws Exception { + Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); - /** - * {@link Filter} implementation which captures request information and a breakdown of the response - * codes being returned. - */ - public abstract class AbstractInstrumentedFilter implements Filter { -- static final String METRIC_PREFIX = "name-prefix"; -- -- private final String otherMetricName; -- private final Map meterNamesByStatusCode; -- private final String registryAttribute; -- -- // initialized after call of init method -- private ConcurrentMap metersByStatusCode; -- private Meter otherMeter; -- private Meter timeoutsMeter; -- private Meter errorsMeter; -- private Counter activeRequests; -- private Timer requestTimer; -- -- -- /** -- * Creates a new instance of the filter. -- * -- * @param registryAttribute the attribute used to look up the metrics registry in the -- * servlet context -- * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are -- * interested in. -- * @param otherMetricName The name used for the catch-all meter. -- */ -- protected AbstractInstrumentedFilter(String registryAttribute, -- Map meterNamesByStatusCode, -- String otherMetricName) { -- this.registryAttribute = registryAttribute; -- this.otherMetricName = otherMetricName; -- this.meterNamesByStatusCode = meterNamesByStatusCode; -+ static final String METRIC_PREFIX = "name-prefix"; -+ -+ private final String otherMetricName; -+ private final Map meterNamesByStatusCode; -+ private final String registryAttribute; -+ -+ // initialized after call of init method -+ private ConcurrentMap metersByStatusCode; -+ private Meter otherMeter; -+ private Meter timeoutsMeter; -+ private Meter errorsMeter; -+ private Counter activeRequests; -+ private Timer requestTimer; -+ -+ /** -+ * Creates a new instance of the filter. -+ * -+ * @param registryAttribute the attribute used to look up the metrics registry in the servlet -+ * context -+ * @param meterNamesByStatusCode A map, keyed by status code, of meter names that we are -+ * interested in. -+ * @param otherMetricName The name used for the catch-all meter. -+ */ -+ protected AbstractInstrumentedFilter( -+ String registryAttribute, -+ Map meterNamesByStatusCode, -+ String otherMetricName) { -+ this.registryAttribute = registryAttribute; -+ this.otherMetricName = otherMetricName; -+ this.meterNamesByStatusCode = meterNamesByStatusCode; -+ } -+ -+ @Override -+ public void init(FilterConfig filterConfig) throws ServletException { -+ final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); -+ -+ String metricName = filterConfig.getInitParameter(METRIC_PREFIX); -+ if (Strings.isNullOrEmpty(metricName)) { -+ metricName = getClass().getName(); - } + String message = timer.time(() -> "SUCCESS"); +@@ -82,7 +82,7 @@ class TimerTest { + } -- @Override -- public void init(FilterConfig filterConfig) throws ServletException { -- final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); -- -- String metricName = filterConfig.getInitParameter(METRIC_PREFIX); -- if (metricName == null || metricName.isEmpty()) { -- metricName = getClass().getName(); -- } -- -- this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); -- for (Entry entry : meterNamesByStatusCode.entrySet()) { -- metersByStatusCode.put(entry.getKey(), -- metricsRegistry.meter(name(metricName, entry.getValue()))); -- } -- this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); -- this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); -- this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); -- this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); -- this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); -- -+ this.metersByStatusCode = new ConcurrentHashMap<>(meterNamesByStatusCode.size()); -+ for (Entry entry : meterNamesByStatusCode.entrySet()) { -+ metersByStatusCode.put( -+ entry.getKey(), metricsRegistry.meter(name(metricName, entry.getValue()))); - } -- -- private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { -- final MetricRegistry metricsRegistry; -- -- final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); -- if (o instanceof MetricRegistry) { -- metricsRegistry = (MetricRegistry) o; -+ this.otherMeter = metricsRegistry.meter(name(metricName, otherMetricName)); -+ this.timeoutsMeter = metricsRegistry.meter(name(metricName, "timeouts")); -+ this.errorsMeter = metricsRegistry.meter(name(metricName, "errors")); -+ this.activeRequests = metricsRegistry.counter(name(metricName, "activeRequests")); -+ this.requestTimer = metricsRegistry.timer(name(metricName, "requests")); -+ } -+ -+ private MetricRegistry getMetricsFactory(FilterConfig filterConfig) { -+ final MetricRegistry metricsRegistry; -+ -+ final Object o = filterConfig.getServletContext().getAttribute(this.registryAttribute); -+ if (o instanceof MetricRegistry) { -+ metricsRegistry = (MetricRegistry) o; -+ } else { -+ metricsRegistry = new MetricRegistry(); -+ } -+ return metricsRegistry; -+ } -+ -+ @Override -+ public void destroy() {} -+ -+ @Override -+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) -+ throws IOException, ServletException { -+ final StatusExposingServletResponse wrappedResponse = -+ new StatusExposingServletResponse((HttpServletResponse) response); -+ activeRequests.inc(); -+ final Timer.Context context = requestTimer.time(); -+ boolean error = false; -+ try { -+ chain.doFilter(request, wrappedResponse); -+ } catch (IOException | RuntimeException | ServletException e) { -+ error = true; -+ throw e; -+ } finally { -+ if (!error && request.isAsyncStarted()) { -+ request.getAsyncContext().addListener(new AsyncResultListener(context)); -+ } else { -+ context.stop(); -+ activeRequests.dec(); -+ if (error) { -+ errorsMeter.mark(); - } else { -- metricsRegistry = new MetricRegistry(); -+ markMeterForStatusCode(wrappedResponse.getStatus()); - } -- return metricsRegistry; -+ } -+ } -+ } -+ -+ private void markMeterForStatusCode(int status) { -+ final Meter metric = metersByStatusCode.get(status); -+ if (metric != null) { -+ metric.mark(); -+ } else { -+ otherMeter.mark(); - } -+ } + @Test +- void testTimerSupplier() throws Exception { ++ void timerSupplier() throws Exception { + Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); -- @Override -- public void destroy() { -+ private static class StatusExposingServletResponse extends HttpServletResponseWrapper { -+ // The Servlet spec says: calling setStatus is optional, if no status is set, the default is -+ // 200. -+ private int httpStatus = 200; + Integer result = timer.timeSupplier(() -> 42); +@@ -92,7 +92,7 @@ class TimerTest { + } -+ public StatusExposingServletResponse(HttpServletResponse response) { -+ super(response); - } + @Test +- void testUpdateDuration() { ++ void updateDuration() { + Timer timer = new Timer(); + timer.update(Duration.ofMillis(100)); + timer.update(Duration.ofMillis(200)); +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java +@@ -1,15 +1,15 @@ + package com.codahale.metrics; - @Override -- public void doFilter(ServletRequest request, -- ServletResponse response, -- FilterChain chain) throws IOException, ServletException { -- final StatusExposingServletResponse wrappedResponse = -- new StatusExposingServletResponse((HttpServletResponse) response); -- activeRequests.inc(); -- final Timer.Context context = requestTimer.time(); -- boolean error = false; -- try { -- chain.doFilter(request, wrappedResponse); -- } catch (IOException | RuntimeException | ServletException e) { -- error = true; -- throw e; -- } finally { -- if (!error && request.isAsyncStarted()) { -- request.getAsyncContext().addListener(new AsyncResultListener(context)); -- } else { -- context.stop(); -- activeRequests.dec(); -- if (error) { -- errorsMeter.mark(); -- } else { -- markMeterForStatusCode(wrappedResponse.getStatus()); -- } -- } -- } -+ public void sendError(int sc) throws IOException { -+ httpStatus = sc; -+ super.sendError(sc); - } + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; -- private void markMeterForStatusCode(int status) { -- final Meter metric = metersByStatusCode.get(status); -- if (metric != null) { -- metric.mark(); -- } else { -- otherMeter.mark(); -- } -+ @Override -+ public void sendError(int sc, String msg) throws IOException { -+ httpStatus = sc; -+ super.sendError(sc, msg); - } +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; -- private static class StatusExposingServletResponse extends HttpServletResponseWrapper { -- // The Servlet spec says: calling setStatus is optional, if no status is set, the default is 200. -- private int httpStatus = 200; -- -- public StatusExposingServletResponse(HttpServletResponse response) { -- super(response); -- } -- -- @Override -- public void sendError(int sc) throws IOException { -- httpStatus = sc; -- super.sendError(sc); -- } -- -- @Override -- public void sendError(int sc, String msg) throws IOException { -- httpStatus = sc; -- super.sendError(sc, msg); -- } -- -- @Override -- public void setStatus(int sc) { -- httpStatus = sc; -- super.setStatus(sc); -- } -- -- @Override -- @SuppressWarnings("deprecation") -- public void setStatus(int sc, String sm) { -- httpStatus = sc; -- super.setStatus(sc, sm); -- } -- -- @Override -- public int getStatus() { -- return httpStatus; -- } -+ @Override -+ public void setStatus(int sc) { -+ httpStatus = sc; -+ super.setStatus(sc); - } + @SuppressWarnings("deprecation") +-class UniformReservoirTest { ++final class UniformReservoirTest { -- private class AsyncResultListener implements AsyncListener { -- private Timer.Context context; -- private boolean done = false; -+ @Override -+ @SuppressWarnings("deprecation") -+ public void setStatus(int sc, String sm) { -+ httpStatus = sc; -+ super.setStatus(sc, sm); -+ } - -- public AsyncResultListener(Timer.Context context) { -- this.context = context; -- } -+ @Override -+ public int getStatus() { -+ return httpStatus; -+ } -+ } - -- @Override -- public void onComplete(AsyncEvent event) throws IOException { -- if (!done) { -- HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); -- context.stop(); -- activeRequests.dec(); -- markMeterForStatusCode(suppliedResponse.getStatus()); -- } -- } -+ private class AsyncResultListener implements AsyncListener { -+ private Timer.Context context; -+ private boolean done = false; - -- @Override -- public void onTimeout(AsyncEvent event) throws IOException { -- context.stop(); -- activeRequests.dec(); -- timeoutsMeter.mark(); -- done = true; -- } -+ public AsyncResultListener(Timer.Context context) { -+ this.context = context; -+ } - -- @Override -- public void onError(AsyncEvent event) throws IOException { -- context.stop(); -- activeRequests.dec(); -- errorsMeter.mark(); -- done = true; -- } -+ @Override -+ public void onComplete(AsyncEvent event) throws IOException { -+ if (!done) { -+ HttpServletResponse suppliedResponse = (HttpServletResponse) event.getSuppliedResponse(); -+ context.stop(); -+ activeRequests.dec(); -+ markMeterForStatusCode(suppliedResponse.getStatus()); -+ } -+ } - -- @Override -- public void onStartAsync(AsyncEvent event) throws IOException { -+ @Override -+ public void onTimeout(AsyncEvent event) throws IOException { -+ context.stop(); -+ activeRequests.dec(); -+ timeoutsMeter.mark(); -+ done = true; -+ } + @Test +- void testCreateReservoir() { ++ void createReservoir() { + UniformReservoir reservoir = new UniformReservoir(); + reservoir.update(120); + reservoir.update(190); +@@ -22,7 +22,7 @@ class UniformReservoirTest { + assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); + assertThat(snapshot.getMin()).isEqualTo(120); + assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isEqualTo(36.47, Offset.offset(0.1)); ++ assertThat(snapshot.getStdDev()).isCloseTo(36.47, offset(0.1)); + assertThat(snapshot.get75thPercentile()).isEqualTo(195); + assertThat(snapshot.get95thPercentile()).isEqualTo(200); + assertThat(snapshot.get98thPercentile()).isEqualTo(200); +@@ -31,7 +31,7 @@ class UniformReservoirTest { + } -- } -+ @Override -+ public void onError(AsyncEvent event) throws IOException { -+ context.stop(); -+ activeRequests.dec(); -+ errorsMeter.mark(); -+ done = true; - } -+ -+ @Override -+ public void onStartAsync(AsyncEvent event) throws IOException {} -+ } - } ---- a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilter.java -+++ b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilter.java -@@ -4,8 +4,13 @@ import java.util.HashMap; - import java.util.Map; + @Test +- void testCreateReservoirWithCustomSize() { ++ void createReservoirWithCustomSize() { + UniformReservoir reservoir = new UniformReservoir(128); + reservoir.update(440); + reservoir.update(250); +--- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java ++++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java +@@ -12,7 +12,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; - /** -- * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response codes -- * to capture information about.

    Use it in your servlet.xml like this:

    -+ * Implementation of the {@link AbstractInstrumentedFilter} which provides a default set of response -+ * codes to capture information about. -+ * -+ *

    Use it in your servlet.xml like this: -+ * -+ *

    -+ * - *

    {@code
    -  * 
    -  *     instrumentedFilter
    -@@ -18,31 +23,29 @@ import java.util.Map;
    -  * }
    - */ - public class InstrumentedFilter extends AbstractInstrumentedFilter { -- public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; -+ public static final String REGISTRY_ATTRIBUTE = InstrumentedFilter.class.getName() + ".registry"; - -- private static final String NAME_PREFIX = "responseCodes."; -- private static final int OK = 200; -- private static final int CREATED = 201; -- private static final int NO_CONTENT = 204; -- private static final int BAD_REQUEST = 400; -- private static final int NOT_FOUND = 404; -- private static final int SERVER_ERROR = 500; -+ private static final String NAME_PREFIX = "responseCodes."; -+ private static final int OK = 200; -+ private static final int CREATED = 201; -+ private static final int NO_CONTENT = 204; -+ private static final int BAD_REQUEST = 400; -+ private static final int NOT_FOUND = 404; -+ private static final int SERVER_ERROR = 500; - -- /** -- * Creates a new instance of the filter. -- */ -- public InstrumentedFilter() { -- super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); -- } -+ /** Creates a new instance of the filter. */ -+ public InstrumentedFilter() { -+ super(REGISTRY_ATTRIBUTE, createMeterNamesByStatusCode(), NAME_PREFIX + "other"); -+ } - -- private static Map createMeterNamesByStatusCode() { -- final Map meterNamesByStatusCode = new HashMap<>(6); -- meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); -- meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); -- meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); -- meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); -- meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); -- meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); -- return meterNamesByStatusCode; -- } -+ private static Map createMeterNamesByStatusCode() { -+ final Map meterNamesByStatusCode = new HashMap<>(6); -+ meterNamesByStatusCode.put(OK, NAME_PREFIX + "ok"); -+ meterNamesByStatusCode.put(CREATED, NAME_PREFIX + "created"); -+ meterNamesByStatusCode.put(NO_CONTENT, NAME_PREFIX + "noContent"); -+ meterNamesByStatusCode.put(BAD_REQUEST, NAME_PREFIX + "badRequest"); -+ meterNamesByStatusCode.put(NOT_FOUND, NAME_PREFIX + "notFound"); -+ meterNamesByStatusCode.put(SERVER_ERROR, NAME_PREFIX + "serverError"); -+ return meterNamesByStatusCode; -+ } - } ---- a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListener.java -+++ b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListener.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.servlet; +-public class InstrumentedAppenderConfigTest { ++final class InstrumentedAppenderConfigTest { + public static final String METRIC_NAME_PREFIX = "metrics"; + public static final String REGISTRY_NAME = "shared-metrics-registry"; - import io.dropwizard.metrics5.MetricRegistry; -- - import javax.servlet.ServletContextEvent; - import javax.servlet.ServletContextListener; +--- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java ++++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java +@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -@@ -11,17 +10,17 @@ import javax.servlet.ServletContextListener; - * application. - */ - public abstract class InstrumentedFilterContextListener implements ServletContextListener { -- /** -- * @return the {@link MetricRegistry} to inject into the servlet context. -- */ -- protected abstract MetricRegistry getMetricRegistry(); -+ /** -+ * @return the {@link MetricRegistry} to inject into the servlet context. -+ */ -+ protected abstract MetricRegistry getMetricRegistry(); - -- @Override -- public void contextInitialized(ServletContextEvent sce) { -- sce.getServletContext().setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); -- } -+ @Override -+ public void contextInitialized(ServletContextEvent sce) { -+ sce.getServletContext() -+ .setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, getMetricRegistry()); -+ } - -- @Override -- public void contextDestroyed(ServletContextEvent sce) { -- } -+ @Override -+ public void contextDestroyed(ServletContextEvent sce) {} - } ---- a/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -+++ b/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -@@ -1,33 +1,34 @@ - package io.dropwizard.metrics5.servlet; +-public class InstrumentedAppenderTest { ++final class InstrumentedAppenderTest { --import io.dropwizard.metrics5.MetricRegistry; --import org.junit.jupiter.api.Test; -- --import javax.servlet.ServletContext; --import javax.servlet.ServletContextEvent; -- - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; + public static final String METRIC_NAME_PREFIX = "org.apache.logging.log4j.core.Appender"; --class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final InstrumentedFilterContextListener listener = new InstrumentedFilterContextListener() { -+import io.dropwizard.metrics5.MetricRegistry; -+import javax.servlet.ServletContext; -+import javax.servlet.ServletContextEvent; -+import org.junit.jupiter.api.Test; -+ -+final class InstrumentedFilterContextListenerTest { -+ private final MetricRegistry registry = mock(); -+ private final InstrumentedFilterContextListener listener = -+ new InstrumentedFilterContextListener() { - @Override - protected MetricRegistry getMetricRegistry() { -- return registry; -+ return registry; - } -- }; -+ }; + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final LogEvent event = mock(LogEvent.class); ++ private final LogEvent event = mock(); -- @Test -- void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ @Test -+ void injectsTheMetricRegistryIntoTheServletContext() { -+ final ServletContext context = mock(); + @BeforeEach + void setUp() { +--- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java ++++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java +@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- final ServletContextEvent event = mock(ServletContextEvent.class); -- when(event.getServletContext()).thenReturn(context); -+ final ServletContextEvent event = mock(); -+ when(event.getServletContext()).thenReturn(context); +-public class InstrumentedAppenderTest { ++final class InstrumentedAppenderTest { -- listener.contextInitialized(event); -+ listener.contextInitialized(event); + public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; -- verify(context).setAttribute("io.dropwizard.metrics5.servlet.InstrumentedFilter.registry", registry); -- } -+ verify(context) -+ .setAttribute("io.dropwizard.metrics5.servlet.InstrumentedFilter.registry", registry); -+ } - } ---- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/AdminServlet.java -+++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/AdminServlet.java -@@ -1,189 +1,210 @@ - package io.dropwizard.metrics5.servlets; + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); -+import java.io.IOException; -+import java.io.PrintWriter; -+import java.text.MessageFormat; - import javax.servlet.ServletConfig; - import javax.servlet.ServletContext; - import javax.servlet.ServletException; - import javax.servlet.http.HttpServlet; - import javax.servlet.http.HttpServletRequest; - import javax.servlet.http.HttpServletResponse; --import java.io.IOException; --import java.io.PrintWriter; --import java.text.MessageFormat; - - public class AdminServlet extends HttpServlet { -- public static final String DEFAULT_HEALTHCHECK_URI = "/healthcheck"; -- public static final String DEFAULT_METRICS_URI = "/metrics"; -- public static final String DEFAULT_PING_URI = "/ping"; -- public static final String DEFAULT_THREADS_URI = "/threads"; -- public static final String DEFAULT_CPU_PROFILE_URI = "/pprof"; -- -- public static final String METRICS_ENABLED_PARAM_KEY = "metrics-enabled"; -- public static final String METRICS_URI_PARAM_KEY = "metrics-uri"; -- public static final String PING_ENABLED_PARAM_KEY = "ping-enabled"; -- public static final String PING_URI_PARAM_KEY = "ping-uri"; -- public static final String THREADS_ENABLED_PARAM_KEY = "threads-enabled"; -- public static final String THREADS_URI_PARAM_KEY = "threads-uri"; -- public static final String HEALTHCHECK_ENABLED_PARAM_KEY = "healthcheck-enabled"; -- public static final String HEALTHCHECK_URI_PARAM_KEY = "healthcheck-uri"; -- public static final String SERVICE_NAME_PARAM_KEY = "service-name"; -- public static final String CPU_PROFILE_ENABLED_PARAM_KEY = "cpu-profile-enabled"; -- public static final String CPU_PROFILE_URI_PARAM_KEY = "cpu-profile-uri"; -- -- private static final String BASE_TEMPLATE = -- "%n" + -- "%n" + -- "%n" + -- " Metrics{10}%n" + -- "%n" + -- "%n" + -- "

    Operational Menu{10}

    %n" + -- "
      %n" + -- "%s" + -- "
    %n" + -- "%n" + -- ""; -- private static final String METRICS_LINK = "
  • Metrics
  • %n"; -- private static final String PING_LINK = "
  • Ping
  • %n" ; -- private static final String THREADS_LINK = "
  • Threads
  • %n" ; -- private static final String HEALTHCHECK_LINK = "
  • Healthcheck
  • %n" ; -- private static final String CPU_PROFILE_LINK = "
  • CPU Profile
  • %n" + -- "
  • CPU Contention
  • %n"; -- -- -- private static final String CONTENT_TYPE = "text/html"; -- private static final long serialVersionUID = -2850794040708785318L; -- -- private transient HealthCheckServlet healthCheckServlet; -- private transient MetricsServlet metricsServlet; -- private transient PingServlet pingServlet; -- private transient ThreadDumpServlet threadDumpServlet; -- private transient CpuProfileServlet cpuProfileServlet; -- private transient boolean metricsEnabled; -- private transient String metricsUri; -- private transient boolean pingEnabled; -- private transient String pingUri; -- private transient boolean threadsEnabled; -- private transient String threadsUri; -- private transient boolean healthcheckEnabled; -- private transient String healthcheckUri; -- private transient boolean cpuProfileEnabled; -- private transient String cpuProfileUri; -- private transient String serviceName; -- private transient String pageContentTemplate; -- -- @Override -- public void init(ServletConfig config) throws ServletException { -- super.init(config); -- -- final ServletContext context = config.getServletContext(); -- final StringBuilder servletLinks = new StringBuilder(); -- -- this.metricsEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(METRICS_ENABLED_PARAM_KEY), "true")); -- if (this.metricsEnabled) { -- servletLinks.append(METRICS_LINK); -- } -- this.metricsServlet = new MetricsServlet(); -- metricsServlet.init(config); -- -- this.pingEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(PING_ENABLED_PARAM_KEY), "true")); -- if (this.pingEnabled) { -- servletLinks.append(PING_LINK); -- } -- this.pingServlet = new PingServlet(); -- pingServlet.init(config); -- -- this.threadsEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(THREADS_ENABLED_PARAM_KEY), "true")); -- if (this.threadsEnabled) { -- servletLinks.append(THREADS_LINK); -- } -- this.threadDumpServlet = new ThreadDumpServlet(); -- threadDumpServlet.init(config); -- -- this.healthcheckEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(HEALTHCHECK_ENABLED_PARAM_KEY), "true")); -- if (this.healthcheckEnabled) { -- servletLinks.append(HEALTHCHECK_LINK); -- } -- this.healthCheckServlet = new HealthCheckServlet(); -- healthCheckServlet.init(config); -- -- this.cpuProfileEnabled = -- Boolean.parseBoolean(getParam(context.getInitParameter(CPU_PROFILE_ENABLED_PARAM_KEY), "true")); -- if (this.cpuProfileEnabled) { -- servletLinks.append(CPU_PROFILE_LINK); -- } -- this.cpuProfileServlet = new CpuProfileServlet(); -- cpuProfileServlet.init(config); -- -- pageContentTemplate = String.format(BASE_TEMPLATE, String.format(servletLinks.toString())); -- -- this.metricsUri = getParam(context.getInitParameter(METRICS_URI_PARAM_KEY), DEFAULT_METRICS_URI); -- this.pingUri = getParam(context.getInitParameter(PING_URI_PARAM_KEY), DEFAULT_PING_URI); -- this.threadsUri = getParam(context.getInitParameter(THREADS_URI_PARAM_KEY), DEFAULT_THREADS_URI); -- this.healthcheckUri = getParam(context.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI); -- this.cpuProfileUri = getParam(context.getInitParameter(CPU_PROFILE_URI_PARAM_KEY), DEFAULT_CPU_PROFILE_URI); -- this.serviceName = getParam(context.getInitParameter(SERVICE_NAME_PARAM_KEY), null); -+ public static final String DEFAULT_HEALTHCHECK_URI = "/healthcheck"; -+ public static final String DEFAULT_METRICS_URI = "/metrics"; -+ public static final String DEFAULT_PING_URI = "/ping"; -+ public static final String DEFAULT_THREADS_URI = "/threads"; -+ public static final String DEFAULT_CPU_PROFILE_URI = "/pprof"; -+ -+ public static final String METRICS_ENABLED_PARAM_KEY = "metrics-enabled"; -+ public static final String METRICS_URI_PARAM_KEY = "metrics-uri"; -+ public static final String PING_ENABLED_PARAM_KEY = "ping-enabled"; -+ public static final String PING_URI_PARAM_KEY = "ping-uri"; -+ public static final String THREADS_ENABLED_PARAM_KEY = "threads-enabled"; -+ public static final String THREADS_URI_PARAM_KEY = "threads-uri"; -+ public static final String HEALTHCHECK_ENABLED_PARAM_KEY = "healthcheck-enabled"; -+ public static final String HEALTHCHECK_URI_PARAM_KEY = "healthcheck-uri"; -+ public static final String SERVICE_NAME_PARAM_KEY = "service-name"; -+ public static final String CPU_PROFILE_ENABLED_PARAM_KEY = "cpu-profile-enabled"; -+ public static final String CPU_PROFILE_URI_PARAM_KEY = "cpu-profile-uri"; -+ -+ private static final String BASE_TEMPLATE = -+ "%n" -+ + "%n" -+ + "%n" -+ + " Metrics{10}%n" -+ + "%n" -+ + "%n" -+ + "

    Operational Menu{10}

    %n" -+ + "
      %n" -+ + "%s" -+ + "
    %n" -+ + "%n" -+ + ""; -+ private static final String METRICS_LINK = -+ "
  • Metrics
  • %n"; -+ private static final String PING_LINK = "
  • Ping
  • %n"; -+ private static final String THREADS_LINK = "
  • Threads
  • %n"; -+ private static final String HEALTHCHECK_LINK = -+ "
  • Healthcheck
  • %n"; -+ private static final String CPU_PROFILE_LINK = -+ "
  • CPU Profile
  • %n" -+ + "
  • CPU Contention
  • %n"; -+ -+ private static final String CONTENT_TYPE = "text/html"; -+ private static final long serialVersionUID = -2850794040708785318L; -+ -+ private transient HealthCheckServlet healthCheckServlet; -+ private transient MetricsServlet metricsServlet; -+ private transient PingServlet pingServlet; -+ private transient ThreadDumpServlet threadDumpServlet; -+ private transient CpuProfileServlet cpuProfileServlet; -+ private transient boolean metricsEnabled; -+ private transient String metricsUri; -+ private transient boolean pingEnabled; -+ private transient String pingUri; -+ private transient boolean threadsEnabled; -+ private transient String threadsUri; -+ private transient boolean healthcheckEnabled; -+ private transient String healthcheckUri; -+ private transient boolean cpuProfileEnabled; -+ private transient String cpuProfileUri; -+ private transient String serviceName; -+ private transient String pageContentTemplate; -+ -+ @Override -+ public void init(ServletConfig config) throws ServletException { -+ super.init(config); -+ -+ final ServletContext context = config.getServletContext(); -+ final StringBuilder servletLinks = new StringBuilder(); -+ -+ this.metricsEnabled = -+ Boolean.parseBoolean(getParam(context.getInitParameter(METRICS_ENABLED_PARAM_KEY), "true")); -+ if (this.metricsEnabled) { -+ servletLinks.append(METRICS_LINK); - } -+ this.metricsServlet = new MetricsServlet(); -+ metricsServlet.init(config); + @BeforeEach + void setUp() { +--- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java ++++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java +@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- @Override -- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { -- final String path = req.getContextPath() + req.getServletPath(); -- -- resp.setStatus(HttpServletResponse.SC_OK); -- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -- resp.setContentType(CONTENT_TYPE); -- try (PrintWriter writer = resp.getWriter()) { -- writer.println(MessageFormat.format(pageContentTemplate, path, metricsUri, path, pingUri, path, -- threadsUri, path, healthcheckUri, path, cpuProfileUri, -- serviceName == null ? "" : " (" + serviceName + ")")); -- } -+ this.pingEnabled = -+ Boolean.parseBoolean(getParam(context.getInitParameter(PING_ENABLED_PARAM_KEY), "true")); -+ if (this.pingEnabled) { -+ servletLinks.append(PING_LINK); - } -+ this.pingServlet = new PingServlet(); -+ pingServlet.init(config); - -- @Override -- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { -- final String uri = req.getPathInfo(); -- if (uri == null || uri.equals("/")) { -- super.service(req, resp); -- } else if (uri.equals(healthcheckUri)) { -- if (healthcheckEnabled) { -- healthCheckServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else if (uri.startsWith(metricsUri)) { -- if (metricsEnabled) { -- metricsServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else if (uri.equals(pingUri)) { -- if (pingEnabled) { -- pingServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else if (uri.equals(threadsUri)) { -- if (threadsEnabled) { -- threadDumpServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else if (uri.equals(cpuProfileUri)) { -- if (cpuProfileEnabled) { -- cpuProfileServlet.service(req, resp); -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -- } else { -- resp.sendError(HttpServletResponse.SC_NOT_FOUND); -- } -+ this.threadsEnabled = -+ Boolean.parseBoolean(getParam(context.getInitParameter(THREADS_ENABLED_PARAM_KEY), "true")); -+ if (this.threadsEnabled) { -+ servletLinks.append(THREADS_LINK); - } -- -- private static String getParam(String initParam, String defaultValue) { -- return initParam == null ? defaultValue : initParam; -+ this.threadDumpServlet = new ThreadDumpServlet(); -+ threadDumpServlet.init(config); -+ -+ this.healthcheckEnabled = -+ Boolean.parseBoolean( -+ getParam(context.getInitParameter(HEALTHCHECK_ENABLED_PARAM_KEY), "true")); -+ if (this.healthcheckEnabled) { -+ servletLinks.append(HEALTHCHECK_LINK); -+ } -+ this.healthCheckServlet = new HealthCheckServlet(); -+ healthCheckServlet.init(config); -+ -+ this.cpuProfileEnabled = -+ Boolean.parseBoolean( -+ getParam(context.getInitParameter(CPU_PROFILE_ENABLED_PARAM_KEY), "true")); -+ if (this.cpuProfileEnabled) { -+ servletLinks.append(CPU_PROFILE_LINK); -+ } -+ this.cpuProfileServlet = new CpuProfileServlet(); -+ cpuProfileServlet.init(config); -+ -+ pageContentTemplate = String.format(BASE_TEMPLATE, String.format(servletLinks.toString())); -+ -+ this.metricsUri = -+ getParam(context.getInitParameter(METRICS_URI_PARAM_KEY), DEFAULT_METRICS_URI); -+ this.pingUri = getParam(context.getInitParameter(PING_URI_PARAM_KEY), DEFAULT_PING_URI); -+ this.threadsUri = -+ getParam(context.getInitParameter(THREADS_URI_PARAM_KEY), DEFAULT_THREADS_URI); -+ this.healthcheckUri = -+ getParam(context.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI); -+ this.cpuProfileUri = -+ getParam(context.getInitParameter(CPU_PROFILE_URI_PARAM_KEY), DEFAULT_CPU_PROFILE_URI); -+ this.serviceName = getParam(context.getInitParameter(SERVICE_NAME_PARAM_KEY), null); -+ } -+ -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ final String path = req.getContextPath() + req.getServletPath(); -+ -+ resp.setStatus(HttpServletResponse.SC_OK); -+ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -+ resp.setContentType(CONTENT_TYPE); -+ try (PrintWriter writer = resp.getWriter()) { -+ writer.println( -+ MessageFormat.format( -+ pageContentTemplate, -+ path, -+ metricsUri, -+ path, -+ pingUri, -+ path, -+ threadsUri, -+ path, -+ healthcheckUri, -+ path, -+ cpuProfileUri, -+ serviceName == null ? "" : " (" + serviceName + ")")); - } -+ } -+ -+ @Override -+ protected void service(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ final String uri = req.getPathInfo(); -+ if (uri == null || uri.equals("/")) { -+ super.service(req, resp); -+ } else if (uri.equals(healthcheckUri)) { -+ if (healthcheckEnabled) { -+ healthCheckServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else if (uri.startsWith(metricsUri)) { -+ if (metricsEnabled) { -+ metricsServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else if (uri.equals(pingUri)) { -+ if (pingEnabled) { -+ pingServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else if (uri.equals(threadsUri)) { -+ if (threadsEnabled) { -+ threadDumpServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else if (uri.equals(cpuProfileUri)) { -+ if (cpuProfileEnabled) { -+ cpuProfileServlet.service(req, resp); -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } else { -+ resp.sendError(HttpServletResponse.SC_NOT_FOUND); -+ } -+ } -+ -+ private static String getParam(String initParam, String defaultValue) { -+ return initParam == null ? defaultValue : initParam; -+ } - } ---- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java -+++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5.servlets; +-public class InstrumentedAppenderTest { ++final class InstrumentedAppenderTest { -+import com.papertrail.profiler.CpuProfile; - import java.io.IOException; - import java.io.OutputStream; - import java.time.Duration; -@@ -10,70 +11,69 @@ import javax.servlet.http.HttpServlet; - import javax.servlet.http.HttpServletRequest; - import javax.servlet.http.HttpServletResponse; + public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; --import com.papertrail.profiler.CpuProfile; -- - /** -- * An HTTP servlets which outputs a pprof parseable response. -+ * An HTTP servlets which outputs a pprof -+ * parseable response. - */ - public class CpuProfileServlet extends HttpServlet { -- private static final long serialVersionUID = -668666696530287501L; -- private static final String CONTENT_TYPE = "pprof/raw"; -- private static final String CACHE_CONTROL = "Cache-Control"; -- private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; -- private final Lock lock = new ReentrantLock(); -+ private static final long serialVersionUID = -668666696530287501L; -+ private static final String CONTENT_TYPE = "pprof/raw"; -+ private static final String CACHE_CONTROL = "Cache-Control"; -+ private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; -+ private final Lock lock = new ReentrantLock(); - -- @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { - -- int duration = 10; -- if (req.getParameter("duration") != null) { -- try { -- duration = Integer.parseInt(req.getParameter("duration")); -- } catch (NumberFormatException e) { -- duration = 10; -- } -- } -+ int duration = 10; -+ if (req.getParameter("duration") != null) { -+ try { -+ duration = Integer.parseInt(req.getParameter("duration")); -+ } catch (NumberFormatException e) { -+ duration = 10; -+ } -+ } - -- int frequency = 100; -- if (req.getParameter("frequency") != null) { -- try { -- frequency = Integer.parseInt(req.getParameter("frequency")); -- frequency = Math.min(Math.max(frequency, 1), 1000); -- } catch (NumberFormatException e) { -- frequency = 100; -- } -- } -+ int frequency = 100; -+ if (req.getParameter("frequency") != null) { -+ try { -+ frequency = Integer.parseInt(req.getParameter("frequency")); -+ frequency = Math.min(Math.max(frequency, 1), 1000); -+ } catch (NumberFormatException e) { -+ frequency = 100; -+ } -+ } - -- final Thread.State state; -- if ("blocked".equalsIgnoreCase(req.getParameter("state"))) { -- state = Thread.State.BLOCKED; -- } else { -- state = Thread.State.RUNNABLE; -- } -+ final Thread.State state; -+ if ("blocked".equalsIgnoreCase(req.getParameter("state"))) { -+ state = Thread.State.BLOCKED; -+ } else { -+ state = Thread.State.RUNNABLE; -+ } - -- resp.setStatus(HttpServletResponse.SC_OK); -- resp.setHeader(CACHE_CONTROL, NO_CACHE); -- resp.setContentType(CONTENT_TYPE); -- try (OutputStream output = resp.getOutputStream()) { -- doProfile(output, duration, frequency, state); -- } -+ resp.setStatus(HttpServletResponse.SC_OK); -+ resp.setHeader(CACHE_CONTROL, NO_CACHE); -+ resp.setContentType(CONTENT_TYPE); -+ try (OutputStream output = resp.getOutputStream()) { -+ doProfile(output, duration, frequency, state); - } -+ } - -- protected void doProfile(OutputStream out, int duration, int frequency, Thread.State state) throws IOException { -- if (lock.tryLock()) { -- try { -- CpuProfile profile = CpuProfile.record(Duration.ofSeconds(duration), -- frequency, state); -- if (profile == null) { -- throw new RuntimeException("could not create CpuProfile"); -- } -- profile.writeGoogleProfile(out); -- return; -- } finally { -- lock.unlock(); -- } -+ protected void doProfile(OutputStream out, int duration, int frequency, Thread.State state) -+ throws IOException { -+ if (lock.tryLock()) { -+ try { -+ CpuProfile profile = CpuProfile.record(Duration.ofSeconds(duration), frequency, state); -+ if (profile == null) { -+ throw new RuntimeException("could not create CpuProfile"); - } -- throw new RuntimeException("Only one profile request may be active at a time"); -+ profile.writeGoogleProfile(out); -+ return; -+ } finally { -+ lock.unlock(); -+ } - } -+ throw new RuntimeException("Only one profile request may be active at a time"); -+ } - } ---- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -+++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -@@ -6,7 +6,11 @@ import io.dropwizard.metrics5.health.HealthCheck; - import io.dropwizard.metrics5.health.HealthCheckFilter; - import io.dropwizard.metrics5.health.HealthCheckRegistry; - import io.dropwizard.metrics5.json.HealthCheckModule; -- -+import java.io.IOException; -+import java.io.OutputStream; -+import java.util.Map; -+import java.util.SortedMap; -+import java.util.concurrent.ExecutorService; - import javax.servlet.ServletConfig; - import javax.servlet.ServletContext; - import javax.servlet.ServletContextEvent; -@@ -15,181 +19,181 @@ import javax.servlet.ServletException; - import javax.servlet.http.HttpServlet; - import javax.servlet.http.HttpServletRequest; - import javax.servlet.http.HttpServletResponse; --import java.io.IOException; --import java.io.OutputStream; --import java.util.Map; --import java.util.SortedMap; --import java.util.concurrent.ExecutorService; - - public class HealthCheckServlet extends HttpServlet { -- public static abstract class ContextListener implements ServletContextListener { -- /** -- * @return the {@link HealthCheckRegistry} to inject into the servlet context. -- */ -- protected abstract HealthCheckRegistry getHealthCheckRegistry(); -- -- /** -- * @return the {@link ExecutorService} to inject into the servlet context, or {@code null} -- * if the health checks should be run in the servlet worker thread. -- */ -- protected ExecutorService getExecutorService() { -- // don't use a thread pool by default -- return null; -- } -- -- /** -- * @return the {@link HealthCheckFilter} that shall be used to filter health checks, -- * or {@link HealthCheckFilter#ALL} if the default should be used. -- */ -- protected HealthCheckFilter getHealthCheckFilter() { -- return HealthCheckFilter.ALL; -- } -- -- /** -- * @return the {@link ObjectMapper} that shall be used to render health checks, -- * or {@code null} if the default object mapper should be used. -- */ -- protected ObjectMapper getObjectMapper() { -- // don't use an object mapper by default -- return null; -- } -- -- @Override -- public void contextInitialized(ServletContextEvent event) { -- final ServletContext context = event.getServletContext(); -- context.setAttribute(HEALTH_CHECK_REGISTRY, getHealthCheckRegistry()); -- context.setAttribute(HEALTH_CHECK_EXECUTOR, getExecutorService()); -- context.setAttribute(HEALTH_CHECK_MAPPER, getObjectMapper()); -- } -- -- @Override -- public void contextDestroyed(ServletContextEvent event) { -- // no-op -- } -- } -- -- public static final String HEALTH_CHECK_REGISTRY = HealthCheckServlet.class.getCanonicalName() + ".registry"; -- public static final String HEALTH_CHECK_EXECUTOR = HealthCheckServlet.class.getCanonicalName() + ".executor"; -- public static final String HEALTH_CHECK_FILTER = HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter"; -- public static final String HEALTH_CHECK_MAPPER = HealthCheckServlet.class.getCanonicalName() + ".mapper"; -- public static final String HEALTH_CHECK_HTTP_STATUS_INDICATOR = HealthCheckServlet.class.getCanonicalName() + ".httpStatusIndicator"; -- -- private static final long serialVersionUID = -8432996484889177321L; -- private static final String CONTENT_TYPE = "application/json"; -- private static final String HTTP_STATUS_INDICATOR_PARAM = "httpStatusIndicator"; -- -- private transient HealthCheckRegistry registry; -- private transient ExecutorService executorService; -- private transient HealthCheckFilter filter; -- private transient ObjectMapper mapper; -- private transient boolean httpStatusIndicator; -- -- public HealthCheckServlet() { -- } -- -- public HealthCheckServlet(HealthCheckRegistry registry) { -- this.registry = registry; -+ public abstract static class ContextListener implements ServletContextListener { -+ /** -+ * @return the {@link HealthCheckRegistry} to inject into the servlet context. -+ */ -+ protected abstract HealthCheckRegistry getHealthCheckRegistry(); -+ -+ /** -+ * @return the {@link ExecutorService} to inject into the servlet context, or {@code null} if -+ * the health checks should be run in the servlet worker thread. -+ */ -+ protected ExecutorService getExecutorService() { -+ // don't use a thread pool by default -+ return null; - } + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); -- @Override -- public void init(ServletConfig config) throws ServletException { -- super.init(config); -- -- final ServletContext context = config.getServletContext(); -- if (null == registry) { -- final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); -- if (registryAttr instanceof HealthCheckRegistry) { -- this.registry = (HealthCheckRegistry) registryAttr; -- } else { -- throw new ServletException("Couldn't find a HealthCheckRegistry instance."); -- } -- } -- -- final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR); -- if (executorAttr instanceof ExecutorService) { -- this.executorService = (ExecutorService) executorAttr; -- } -- -- final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER); -- if (filterAttr instanceof HealthCheckFilter) { -- filter = (HealthCheckFilter) filterAttr; -- } -- if (filter == null) { -- filter = HealthCheckFilter.ALL; -- } -- -- final Object mapperAttr = context.getAttribute(HEALTH_CHECK_MAPPER); -- if (mapperAttr instanceof ObjectMapper) { -- this.mapper = (ObjectMapper) mapperAttr; -- } else { -- this.mapper = new ObjectMapper(); -- } -- this.mapper.registerModule(new HealthCheckModule()); -- -- final Object httpStatusIndicatorAttr = context.getAttribute(HEALTH_CHECK_HTTP_STATUS_INDICATOR); -- if (httpStatusIndicatorAttr instanceof Boolean) { -- this.httpStatusIndicator = (Boolean) httpStatusIndicatorAttr; -- } else { -- this.httpStatusIndicator = true; -- } -+ /** -+ * @return the {@link HealthCheckFilter} that shall be used to filter health checks, or {@link -+ * HealthCheckFilter#ALL} if the default should be used. -+ */ -+ protected HealthCheckFilter getHealthCheckFilter() { -+ return HealthCheckFilter.ALL; -+ } -+ -+ /** -+ * @return the {@link ObjectMapper} that shall be used to render health checks, or {@code null} -+ * if the default object mapper should be used. -+ */ -+ protected ObjectMapper getObjectMapper() { -+ // don't use an object mapper by default -+ return null; - } + @BeforeEach + void setUp() { +--- a/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java ++++ b/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java +@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; - @Override -- public void destroy() { -- super.destroy(); -- registry.shutdown(); -+ public void contextInitialized(ServletContextEvent event) { -+ final ServletContext context = event.getServletContext(); -+ context.setAttribute(HEALTH_CHECK_REGISTRY, getHealthCheckRegistry()); -+ context.setAttribute(HEALTH_CHECK_EXECUTOR, getExecutorService()); -+ context.setAttribute(HEALTH_CHECK_MAPPER, getObjectMapper()); - } +-public class InstrumentedAppenderTest { ++final class InstrumentedAppenderTest { - @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -- final SortedMap results = runHealthChecks(); -- resp.setContentType(CONTENT_TYPE); -- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -- if (results.isEmpty()) { -- resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); -- } else { -- final String reqParameter = req.getParameter(HTTP_STATUS_INDICATOR_PARAM); -- final boolean httpStatusIndicatorParam = Boolean.parseBoolean(reqParameter); -- final boolean useHttpStatusForHealthCheck = reqParameter == null ? httpStatusIndicator : httpStatusIndicatorParam; -- if (!useHttpStatusForHealthCheck || isAllHealthy(results)) { -- resp.setStatus(HttpServletResponse.SC_OK); -- } else { -- resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); -- } -- } -- -- try (OutputStream output = resp.getOutputStream()) { -- getWriter(req).writeValue(output, results); -- } -- } -- -- private ObjectWriter getWriter(HttpServletRequest request) { -- final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); -- if (prettyPrint) { -- return mapper.writerWithDefaultPrettyPrinter(); -- } -- return mapper.writer(); -- } -- -- private SortedMap runHealthChecks() { -- if (executorService == null) { -- return registry.runHealthChecks(filter); -- } -- return registry.runHealthChecks(executorService, filter); -- } -- -- private static boolean isAllHealthy(Map results) { -- for (HealthCheck.Result result : results.values()) { -- if (!result.isHealthy()) { -- return false; -- } -- } -- return true; -- } -- -- // visible for testing -- ObjectMapper getMapper() { -- return mapper; -+ public void contextDestroyed(ServletContextEvent event) { -+ // no-op -+ } -+ } -+ -+ public static final String HEALTH_CHECK_REGISTRY = -+ HealthCheckServlet.class.getCanonicalName() + ".registry"; -+ public static final String HEALTH_CHECK_EXECUTOR = -+ HealthCheckServlet.class.getCanonicalName() + ".executor"; -+ public static final String HEALTH_CHECK_FILTER = -+ HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter"; -+ public static final String HEALTH_CHECK_MAPPER = -+ HealthCheckServlet.class.getCanonicalName() + ".mapper"; -+ public static final String HEALTH_CHECK_HTTP_STATUS_INDICATOR = -+ HealthCheckServlet.class.getCanonicalName() + ".httpStatusIndicator"; -+ -+ private static final long serialVersionUID = -8432996484889177321L; -+ private static final String CONTENT_TYPE = "application/json"; -+ private static final String HTTP_STATUS_INDICATOR_PARAM = "httpStatusIndicator"; -+ -+ private transient HealthCheckRegistry registry; -+ private transient ExecutorService executorService; -+ private transient HealthCheckFilter filter; -+ private transient ObjectMapper mapper; -+ private transient boolean httpStatusIndicator; -+ -+ public HealthCheckServlet() {} -+ -+ public HealthCheckServlet(HealthCheckRegistry registry) { -+ this.registry = registry; -+ } -+ -+ @Override -+ public void init(ServletConfig config) throws ServletException { -+ super.init(config); -+ -+ final ServletContext context = config.getServletContext(); -+ if (registry == null) { -+ final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); -+ if (registryAttr instanceof HealthCheckRegistry) { -+ this.registry = (HealthCheckRegistry) registryAttr; -+ } else { -+ throw new ServletException("Couldn't find a HealthCheckRegistry instance."); -+ } -+ } -+ -+ final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR); -+ if (executorAttr instanceof ExecutorService) { -+ this.executorService = (ExecutorService) executorAttr; - } -+ -+ final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER); -+ if (filterAttr instanceof HealthCheckFilter) { -+ filter = (HealthCheckFilter) filterAttr; -+ } -+ if (filter == null) { -+ filter = HealthCheckFilter.ALL; -+ } -+ -+ final Object mapperAttr = context.getAttribute(HEALTH_CHECK_MAPPER); -+ if (mapperAttr instanceof ObjectMapper) { -+ this.mapper = (ObjectMapper) mapperAttr; -+ } else { -+ this.mapper = new ObjectMapper(); -+ } -+ this.mapper.registerModule(new HealthCheckModule()); -+ -+ final Object httpStatusIndicatorAttr = context.getAttribute(HEALTH_CHECK_HTTP_STATUS_INDICATOR); -+ if (httpStatusIndicatorAttr instanceof Boolean) { -+ this.httpStatusIndicator = (Boolean) httpStatusIndicatorAttr; -+ } else { -+ this.httpStatusIndicator = true; -+ } -+ } -+ -+ @Override -+ public void destroy() { -+ super.destroy(); -+ registry.shutdown(); -+ } -+ -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ final SortedMap results = runHealthChecks(); -+ resp.setContentType(CONTENT_TYPE); -+ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -+ if (results.isEmpty()) { -+ resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); -+ } else { -+ final String reqParameter = req.getParameter(HTTP_STATUS_INDICATOR_PARAM); -+ final boolean httpStatusIndicatorParam = Boolean.parseBoolean(reqParameter); -+ final boolean useHttpStatusForHealthCheck = -+ reqParameter == null ? httpStatusIndicator : httpStatusIndicatorParam; -+ if (!useHttpStatusForHealthCheck || isAllHealthy(results)) { -+ resp.setStatus(HttpServletResponse.SC_OK); -+ } else { -+ resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); -+ } -+ } -+ -+ try (OutputStream output = resp.getOutputStream()) { -+ getWriter(req).writeValue(output, results); -+ } -+ } -+ -+ private ObjectWriter getWriter(HttpServletRequest request) { -+ final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); -+ if (prettyPrint) { -+ return mapper.writerWithDefaultPrettyPrinter(); -+ } -+ return mapper.writer(); -+ } -+ -+ private SortedMap runHealthChecks() { -+ if (executorService == null) { -+ return registry.runHealthChecks(filter); -+ } -+ return registry.runHealthChecks(executorService, filter); -+ } -+ -+ private static boolean isAllHealthy(Map results) { -+ for (HealthCheck.Result result : results.values()) { -+ if (!result.isHealthy()) { -+ return false; -+ } -+ } -+ return true; -+ } -+ -+ // visible for testing -+ ObjectMapper getMapper() { -+ return mapper; -+ } - } ---- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -+++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -@@ -6,7 +6,10 @@ import com.fasterxml.jackson.databind.util.JSONPObject; - import io.dropwizard.metrics5.MetricFilter; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.json.MetricsModule; -- -+import java.io.IOException; -+import java.io.OutputStream; -+import java.util.Locale; -+import java.util.concurrent.TimeUnit; - import javax.servlet.ServletConfig; - import javax.servlet.ServletContext; - import javax.servlet.ServletContextEvent; -@@ -15,185 +18,182 @@ import javax.servlet.ServletException; - import javax.servlet.http.HttpServlet; - import javax.servlet.http.HttpServletRequest; - import javax.servlet.http.HttpServletResponse; --import java.io.IOException; --import java.io.OutputStream; --import java.util.Locale; --import java.util.concurrent.TimeUnit; + public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; - /** - * A servlet which returns the metrics in a given registry as an {@code application/json} response. - */ - public class MetricsServlet extends HttpServlet { -+ /** -+ * An abstract {@link ServletContextListener} which allows you to programmatically inject the -+ * {@link MetricRegistry}, rate and duration units, and allowed origin for {@link MetricsServlet}. -+ */ -+ public abstract static class ContextListener implements ServletContextListener { - /** -- * An abstract {@link ServletContextListener} which allows you to programmatically inject the -- * {@link MetricRegistry}, rate and duration units, and allowed origin for -- * {@link MetricsServlet}. -+ * @return the {@link MetricRegistry} to inject into the servlet context. - */ -- public static abstract class ContextListener implements ServletContextListener { -- /** -- * @return the {@link MetricRegistry} to inject into the servlet context. -- */ -- protected abstract MetricRegistry getMetricRegistry(); -- -- /** -- * @return the {@link TimeUnit} to which rates should be converted, or {@code null} if the -- * default should be used. -- */ -- protected TimeUnit getRateUnit() { -- // use the default -- return null; -- } -- -- /** -- * @return the {@link TimeUnit} to which durations should be converted, or {@code null} if -- * the default should be used. -- */ -- protected TimeUnit getDurationUnit() { -- // use the default -- return null; -- } -- -- /** -- * @return the {@code Access-Control-Allow-Origin} header value, if any. -- */ -- protected String getAllowedOrigin() { -- // use the default -- return null; -- } -- -- /** -- * Returns the name of the parameter used to specify the jsonp callback, if any. -- */ -- protected String getJsonpCallbackParameter() { -- return null; -- } -- -- /** -- * Returns the {@link MetricFilter} that shall be used to filter metrics, or {@link MetricFilter#ALL} if -- * the default should be used. -- */ -- protected MetricFilter getMetricFilter() { -- // use the default -- return MetricFilter.ALL; -- } -- -- @Override -- public void contextInitialized(ServletContextEvent event) { -- final ServletContext context = event.getServletContext(); -- context.setAttribute(METRICS_REGISTRY, getMetricRegistry()); -- context.setAttribute(METRIC_FILTER, getMetricFilter()); -- if (getDurationUnit() != null) { -- context.setInitParameter(MetricsServlet.DURATION_UNIT, getDurationUnit().toString()); -- } -- if (getRateUnit() != null) { -- context.setInitParameter(MetricsServlet.RATE_UNIT, getRateUnit().toString()); -- } -- if (getAllowedOrigin() != null) { -- context.setInitParameter(MetricsServlet.ALLOWED_ORIGIN, getAllowedOrigin()); -- } -- if (getJsonpCallbackParameter() != null) { -- context.setAttribute(CALLBACK_PARAM, getJsonpCallbackParameter()); -- } -- } -- -- @Override -- public void contextDestroyed(ServletContextEvent event) { -- // no-op -- } -- } -- -- public static final String RATE_UNIT = MetricsServlet.class.getCanonicalName() + ".rateUnit"; -- public static final String DURATION_UNIT = MetricsServlet.class.getCanonicalName() + ".durationUnit"; -- public static final String SHOW_SAMPLES = MetricsServlet.class.getCanonicalName() + ".showSamples"; -- public static final String METRICS_REGISTRY = MetricsServlet.class.getCanonicalName() + ".registry"; -- public static final String ALLOWED_ORIGIN = MetricsServlet.class.getCanonicalName() + ".allowedOrigin"; -- public static final String METRIC_FILTER = MetricsServlet.class.getCanonicalName() + ".metricFilter"; -- public static final String CALLBACK_PARAM = MetricsServlet.class.getCanonicalName() + ".jsonpCallback"; -+ protected abstract MetricRegistry getMetricRegistry(); - -- private static final long serialVersionUID = 1049773947734939602L; -- private static final String CONTENT_TYPE = "application/json"; -+ /** -+ * @return the {@link TimeUnit} to which rates should be converted, or {@code null} if the -+ * default should be used. -+ */ -+ protected TimeUnit getRateUnit() { -+ // use the default -+ return null; -+ } - -- protected String allowedOrigin; -- protected String jsonpParamName; -- protected transient MetricRegistry registry; -- protected transient ObjectMapper mapper; -+ /** -+ * @return the {@link TimeUnit} to which durations should be converted, or {@code null} if the -+ * default should be used. -+ */ -+ protected TimeUnit getDurationUnit() { -+ // use the default -+ return null; -+ } - -- public MetricsServlet() { -+ /** -+ * @return the {@code Access-Control-Allow-Origin} header value, if any. -+ */ -+ protected String getAllowedOrigin() { -+ // use the default -+ return null; - } + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); -- public MetricsServlet(MetricRegistry registry) { -- this.registry = registry; -+ /** Returns the name of the parameter used to specify the jsonp callback, if any. */ -+ protected String getJsonpCallbackParameter() { -+ return null; - } + @BeforeEach + void setUp() { +--- a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java ++++ b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.servlet; -- @Override -- public void init(ServletConfig config) throws ServletException { -- super.init(config); -- -- final ServletContext context = config.getServletContext(); -- if (null == registry) { -- final Object registryAttr = context.getAttribute(METRICS_REGISTRY); -- if (registryAttr instanceof MetricRegistry) { -- this.registry = (MetricRegistry) registryAttr; -- } else { -- throw new ServletException("Couldn't find a MetricRegistry instance."); -- } -- } -- this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); -- this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); -- -- setupMetricsModule(context); -+ /** -+ * Returns the {@link MetricFilter} that shall be used to filter metrics, or {@link -+ * MetricFilter#ALL} if the default should be used. -+ */ -+ protected MetricFilter getMetricFilter() { -+ // use the default -+ return MetricFilter.ALL; - } + import static io.dropwizard.metrics5.MetricRegistry.name; -- protected void setupMetricsModule(ServletContext context) { -- final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), -- TimeUnit.SECONDS); -- final TimeUnit durationUnit = parseTimeUnit(context.getInitParameter(DURATION_UNIT), -- TimeUnit.SECONDS); -- final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES)); -- MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER); -- if (filter == null) { -- filter = MetricFilter.ALL; -- } -- -- this.mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit, -- durationUnit, -- showSamples, -- filter)); -+ @Override -+ public void contextInitialized(ServletContextEvent event) { -+ final ServletContext context = event.getServletContext(); -+ context.setAttribute(METRICS_REGISTRY, getMetricRegistry()); -+ context.setAttribute(METRIC_FILTER, getMetricFilter()); -+ if (getDurationUnit() != null) { -+ context.setInitParameter(MetricsServlet.DURATION_UNIT, getDurationUnit().toString()); -+ } -+ if (getRateUnit() != null) { -+ context.setInitParameter(MetricsServlet.RATE_UNIT, getRateUnit().toString()); -+ } -+ if (getAllowedOrigin() != null) { -+ context.setInitParameter(MetricsServlet.ALLOWED_ORIGIN, getAllowedOrigin()); -+ } -+ if (getJsonpCallbackParameter() != null) { -+ context.setAttribute(CALLBACK_PARAM, getJsonpCallbackParameter()); -+ } - } ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -64,7 +65,7 @@ public abstract class AbstractInstrumentedFilter implements Filter { + final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); - @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -- resp.setContentType(CONTENT_TYPE); -- if (allowedOrigin != null) { -- resp.setHeader("Access-Control-Allow-Origin", allowedOrigin); -- } -- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -- resp.setStatus(HttpServletResponse.SC_OK); -- -- try (OutputStream output = resp.getOutputStream()) { -- if (jsonpParamName != null && req.getParameter(jsonpParamName) != null) { -- getWriter(req).writeValue(output, new JSONPObject(req.getParameter(jsonpParamName), registry)); -- } else { -- getWriter(req).writeValue(output, registry); -- } -- } -+ public void contextDestroyed(ServletContextEvent event) { -+ // no-op -+ } -+ } -+ -+ public static final String RATE_UNIT = MetricsServlet.class.getCanonicalName() + ".rateUnit"; -+ public static final String DURATION_UNIT = -+ MetricsServlet.class.getCanonicalName() + ".durationUnit"; -+ public static final String SHOW_SAMPLES = -+ MetricsServlet.class.getCanonicalName() + ".showSamples"; -+ public static final String METRICS_REGISTRY = -+ MetricsServlet.class.getCanonicalName() + ".registry"; -+ public static final String ALLOWED_ORIGIN = -+ MetricsServlet.class.getCanonicalName() + ".allowedOrigin"; -+ public static final String METRIC_FILTER = -+ MetricsServlet.class.getCanonicalName() + ".metricFilter"; -+ public static final String CALLBACK_PARAM = -+ MetricsServlet.class.getCanonicalName() + ".jsonpCallback"; -+ -+ private static final long serialVersionUID = 1049773947734939602L; -+ private static final String CONTENT_TYPE = "application/json"; -+ -+ protected String allowedOrigin; -+ protected String jsonpParamName; -+ protected transient MetricRegistry registry; -+ protected transient ObjectMapper mapper; -+ -+ public MetricsServlet() {} -+ -+ public MetricsServlet(MetricRegistry registry) { -+ this.registry = registry; -+ } -+ -+ @Override -+ public void init(ServletConfig config) throws ServletException { -+ super.init(config); -+ -+ final ServletContext context = config.getServletContext(); -+ if (registry == null) { -+ final Object registryAttr = context.getAttribute(METRICS_REGISTRY); -+ if (registryAttr instanceof MetricRegistry) { -+ this.registry = (MetricRegistry) registryAttr; -+ } else { -+ throw new ServletException("Couldn't find a MetricRegistry instance."); -+ } -+ } -+ this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); -+ this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); -+ -+ setupMetricsModule(context); -+ } -+ -+ protected void setupMetricsModule(ServletContext context) { -+ final TimeUnit rateUnit = parseTimeUnit(context.getInitParameter(RATE_UNIT), TimeUnit.SECONDS); -+ final TimeUnit durationUnit = -+ parseTimeUnit(context.getInitParameter(DURATION_UNIT), TimeUnit.SECONDS); -+ final boolean showSamples = Boolean.parseBoolean(context.getInitParameter(SHOW_SAMPLES)); -+ MetricFilter filter = (MetricFilter) context.getAttribute(METRIC_FILTER); -+ if (filter == null) { -+ filter = MetricFilter.ALL; + String metricName = filterConfig.getInitParameter(METRIC_PREFIX); +- if (metricName == null || metricName.isEmpty()) { ++ if (Strings.isNullOrEmpty(metricName)) { + metricName = getClass().getName(); } -- protected ObjectWriter getWriter(HttpServletRequest request) { -- final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); -- if (prettyPrint) { -- return mapper.writerWithDefaultPrettyPrinter(); -- } -- return mapper.writer(); -+ this.mapper = -+ new ObjectMapper() -+ .registerModule(new MetricsModule(rateUnit, durationUnit, showSamples, filter)); -+ } -+ -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ resp.setContentType(CONTENT_TYPE); -+ if (allowedOrigin != null) { -+ resp.setHeader("Access-Control-Allow-Origin", allowedOrigin); -+ } -+ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -+ resp.setStatus(HttpServletResponse.SC_OK); -+ -+ try (OutputStream output = resp.getOutputStream()) { -+ if (jsonpParamName != null && req.getParameter(jsonpParamName) != null) { -+ getWriter(req) -+ .writeValue(output, new JSONPObject(req.getParameter(jsonpParamName), registry)); -+ } else { -+ getWriter(req).writeValue(output, registry); -+ } - } -+ } - -- @SuppressWarnings("IdentityConversion") -- protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { -- try { -- return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); -- } catch (IllegalArgumentException e) { -- return defaultValue; -- } -+ protected ObjectWriter getWriter(HttpServletRequest request) { -+ final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty")); -+ if (prettyPrint) { -+ return mapper.writerWithDefaultPrettyPrinter(); -+ } -+ return mapper.writer(); -+ } -+ -+ @SuppressWarnings("IdentityConversion") -+ protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { -+ try { -+ return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); -+ } catch (IllegalArgumentException e) { -+ return defaultValue; - } -+ } - } ---- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/PingServlet.java -+++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/PingServlet.java -@@ -1,30 +1,28 @@ - package io.dropwizard.metrics5.servlets; +--- a/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +@@ -9,8 +9,8 @@ import javax.servlet.ServletContext; + import javax.servlet.ServletContextEvent; + import org.junit.jupiter.api.Test; -+import java.io.IOException; -+import java.io.PrintWriter; - import javax.servlet.ServletException; - import javax.servlet.http.HttpServlet; - import javax.servlet.http.HttpServletRequest; - import javax.servlet.http.HttpServletResponse; --import java.io.IOException; --import java.io.PrintWriter; - --/** -- * An HTTP servlets which outputs a {@code text/plain} {@code "pong"} response. -- */ -+/** An HTTP servlets which outputs a {@code text/plain} {@code "pong"} response. */ - public class PingServlet extends HttpServlet { -- private static final long serialVersionUID = 3772654177231086757L; -- private static final String CONTENT_TYPE = "text/plain"; -- private static final String CONTENT = "pong"; -- private static final String CACHE_CONTROL = "Cache-Control"; -- private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; -+ private static final long serialVersionUID = 3772654177231086757L; -+ private static final String CONTENT_TYPE = "text/plain"; -+ private static final String CONTENT = "pong"; -+ private static final String CACHE_CONTROL = "Cache-Control"; -+ private static final String NO_CACHE = "must-revalidate,no-cache,no-store"; - -- @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -- resp.setStatus(HttpServletResponse.SC_OK); -- resp.setHeader(CACHE_CONTROL, NO_CACHE); -- resp.setContentType(CONTENT_TYPE); -- try (PrintWriter writer = resp.getWriter()) { -- writer.println(CONTENT); -- } -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ resp.setStatus(HttpServletResponse.SC_OK); -+ resp.setHeader(CACHE_CONTROL, NO_CACHE); -+ resp.setContentType(CONTENT_TYPE); -+ try (PrintWriter writer = resp.getWriter()) { -+ writer.println(CONTENT); - } -+ } - } ---- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/ThreadDumpServlet.java -+++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/ThreadDumpServlet.java -@@ -1,55 +1,54 @@ - package io.dropwizard.metrics5.servlets; +-class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++final class InstrumentedFilterContextListenerTest { ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ class InstrumentedFilterContextListenerTest { - import io.dropwizard.metrics5.jvm.ThreadDump; -- -+import java.io.IOException; -+import java.io.OutputStream; -+import java.lang.management.ManagementFactory; - import javax.servlet.ServletException; - import javax.servlet.http.HttpServlet; - import javax.servlet.http.HttpServletRequest; - import javax.servlet.http.HttpServletResponse; --import java.io.IOException; --import java.io.OutputStream; --import java.lang.management.ManagementFactory; + @Test + void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); - /** -- * An HTTP servlets which outputs a {@code text/plain} dump of all threads in -- * the VM. Only responds to {@code GET} requests. -+ * An HTTP servlets which outputs a {@code text/plain} dump of all threads in the VM. Only responds -+ * to {@code GET} requests. - */ - public class ThreadDumpServlet extends HttpServlet { - -- private static final long serialVersionUID = -2690343532336103046L; -- private static final String CONTENT_TYPE = "text/plain"; -+ private static final long serialVersionUID = -2690343532336103046L; -+ private static final String CONTENT_TYPE = "text/plain"; - -- private transient ThreadDump threadDump; -+ private transient ThreadDump threadDump; - -- @Override -- public void init() throws ServletException { -- try { -- // Some PaaS like Google App Engine blacklist java.lang.managament -- this.threadDump = new ThreadDump(ManagementFactory.getThreadMXBean()); -- } catch (NoClassDefFoundError ncdfe) { -- this.threadDump = null; // we won't be able to provide thread dump -- } -+ @Override -+ public void init() throws ServletException { -+ try { -+ // Some PaaS like Google App Engine blacklist java.lang.managament -+ this.threadDump = new ThreadDump(ManagementFactory.getThreadMXBean()); -+ } catch (NoClassDefFoundError ncdfe) { -+ this.threadDump = null; // we won't be able to provide thread dump - } -- -- @Override -- protected void doGet(HttpServletRequest req, -- HttpServletResponse resp) throws ServletException, IOException { -- final boolean includeMonitors = getParam(req.getParameter("monitors"), true); -- final boolean includeSynchronizers = getParam(req.getParameter("synchronizers"), true); -- -- resp.setStatus(HttpServletResponse.SC_OK); -- resp.setContentType(CONTENT_TYPE); -- resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -- if (threadDump == null) { -- resp.getWriter().println("Sorry your runtime environment does not allow to dump threads."); -- return; -- } -- try (OutputStream output = resp.getOutputStream()) { -- threadDump.dump(includeMonitors, includeSynchronizers, output); -- } -+ } -+ -+ @Override -+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) -+ throws ServletException, IOException { -+ final boolean includeMonitors = getParam(req.getParameter("monitors"), true); -+ final boolean includeSynchronizers = getParam(req.getParameter("synchronizers"), true); -+ -+ resp.setStatus(HttpServletResponse.SC_OK); -+ resp.setContentType(CONTENT_TYPE); -+ resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); -+ if (threadDump == null) { -+ resp.getWriter().println("Sorry your runtime environment does not allow to dump threads."); -+ return; - } -- -- private static Boolean getParam(String initParam, boolean defaultValue) { -- return initParam == null ? defaultValue : Boolean.parseBoolean(initParam); -+ try (OutputStream output = resp.getOutputStream()) { -+ threadDump.dump(includeMonitors, includeSynchronizers, output); - } -+ } -+ -+ private static Boolean getParam(String initParam, boolean defaultValue) { -+ return initParam == null ? defaultValue : Boolean.parseBoolean(initParam); -+ } - } ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java -@@ -6,24 +6,24 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); - public abstract class AbstractServletTest { -- private final ServletTester tester = new ServletTester(); -- protected final HttpTester.Request request = HttpTester.newRequest(); -- protected HttpTester.Response response; -+ private final ServletTester tester = new ServletTester(); -+ protected final HttpTester.Request request = HttpTester.newRequest(); -+ protected HttpTester.Response response; - -- @BeforeEach -- public void setUpTester() throws Exception { -- setUp(tester); -- tester.start(); -- } -+ @BeforeEach -+ public void setUpTester() throws Exception { -+ setUp(tester); -+ tester.start(); -+ } - -- protected abstract void setUp(ServletTester tester); -+ protected abstract void setUp(ServletTester tester); - -- @AfterEach -- public void tearDownTester() throws Exception { -- tester.stop(); -- } -+ @AfterEach -+ public void tearDownTester() throws Exception { -+ tester.stop(); -+ } + listener.contextInitialized(event); +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java +@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { + super.init(config); -- protected void processRequest() throws Exception { -- this.response = HttpTester.parseResponse(tester.getResponses(request.generate())); -- } -+ protected void processRequest() throws Exception { -+ this.response = HttpTester.parseResponse(tester.getResponses(request.generate())); -+ } - } + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); + if (registryAttr instanceof HealthCheckRegistry) { + this.registry = (HealthCheckRegistry) registryAttr; +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(METRICS_REGISTRY); + if (registryAttr instanceof MetricRegistry) { + this.registry = (MetricRegistry) registryAttr; --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.health.HealthCheckRegistry; - import org.eclipse.jetty.http.HttpHeader; -@@ -7,56 +9,53 @@ import org.eclipse.jetty.servlet.ServletTester; +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; -- -class AdminServletTest extends AbstractServletTest { -- private final MetricRegistry registry = new MetricRegistry(); -- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -- -- @Override -- protected void setUp(ServletTester tester) { -- tester.setContextPath("/context"); -- -- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -- tester.addServlet(AdminServlet.class, "/admin"); -- } -- -- @BeforeEach -- void setUp() { -- request.setMethod("GET"); -- request.setURI("/context/admin"); -- request.setVersion("HTTP/1.0"); -- } -- -- @Test -- void returnsA200() throws Exception { -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.getContent()) -- .isEqualTo(String.format( -- "%n" + -- "%n" + -- "%n" + -- " Metrics%n" + -- "%n" + -- "%n" + -- "

    Operational Menu

    %n" + -- " %n" + -- "%n" + -- "%n" -- )); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("text/html;charset=UTF-8"); -- } +final class AdminServletTest extends AbstractServletTest { -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.setContextPath("/context"); -+ -+ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -+ tester.setAttribute( -+ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -+ tester.addServlet(AdminServlet.class, "/admin"); -+ } -+ -+ @BeforeEach -+ void setUp() { -+ request.setMethod("GET"); -+ request.setURI("/context/admin"); -+ request.setVersion("HTTP/1.0"); -+ } -+ -+ @Test -+ void returnsA200() throws Exception { -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "%n" -+ + "%n" -+ + "%n" -+ + " Metrics%n" -+ + "%n" -+ + "%n" -+ + "

    Operational Menu

    %n" -+ + " %n" -+ + "%n" -+ + "%n")); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); -+ } - } + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.health.HealthCheckRegistry; - import org.eclipse.jetty.http.HttpHeader; -@@ -7,61 +9,58 @@ import org.eclipse.jetty.servlet.ServletTester; +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; -- -class AdminServletUriTest extends AbstractServletTest { -- private final MetricRegistry registry = new MetricRegistry(); -- private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); +final class AdminServletUriTest extends AbstractServletTest { -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); - -- @Override -- protected void setUp(ServletTester tester) { -- tester.setContextPath("/context"); -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.setContextPath("/context"); - -- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -- tester.setAttribute("io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -- tester.setInitParameter("metrics-uri", "/metrics-test"); -- tester.setInitParameter("ping-uri", "/ping-test"); -- tester.setInitParameter("threads-uri", "/threads-test"); -- tester.setInitParameter("healthcheck-uri", "/healthcheck-test"); -- tester.setInitParameter("cpu-profile-uri", "/pprof-test"); -- tester.addServlet(AdminServlet.class, "/admin"); -- } -+ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -+ tester.setAttribute( -+ "io.dropwizard.metrics5.servlets.HealthCheckServlet.registry", healthCheckRegistry); -+ tester.setInitParameter("metrics-uri", "/metrics-test"); -+ tester.setInitParameter("ping-uri", "/ping-test"); -+ tester.setInitParameter("threads-uri", "/threads-test"); -+ tester.setInitParameter("healthcheck-uri", "/healthcheck-test"); -+ tester.setInitParameter("cpu-profile-uri", "/pprof-test"); -+ tester.addServlet(AdminServlet.class, "/admin"); -+ } - -- @BeforeEach -- void setUp() { -- request.setMethod("GET"); -- request.setURI("/context/admin"); -- request.setVersion("HTTP/1.0"); -- } -+ @BeforeEach -+ void setUp() { -+ request.setMethod("GET"); -+ request.setURI("/context/admin"); -+ request.setVersion("HTTP/1.0"); -+ } - -- @Test -- void returnsA200() throws Exception { -- processRequest(); -+ @Test -+ void returnsA200() throws Exception { -+ processRequest(); - -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.getContent()) -- .isEqualTo(String.format( -- "%n" + -- "%n" + -- "%n" + -- " Metrics%n" + -- "%n" + -- "%n" + -- "

    Operational Menu

    %n" + -- " %n" + -- "%n" + -- "%n" -- )); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("text/html;charset=UTF-8"); -- } -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "%n" -+ + "%n" -+ + "%n" -+ + " Metrics%n" -+ + "%n" -+ + "%n" -+ + "

    Operational Menu

    %n" -+ + " %n" -+ + "%n" -+ + "%n")); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/html;charset=UTF-8"); -+ } - } + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java -@@ -7,38 +7,35 @@ import org.eclipse.jetty.servlet.ServletTester; +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -class CpuProfileServletTest extends AbstractServletTest { -- -- @Override -- protected void setUp(ServletTester tester) { -- tester.addServlet(CpuProfileServlet.class, "/pprof"); -- } -- -- @BeforeEach -- void setUp() throws Exception { -- request.setMethod("GET"); -- request.setURI("/pprof?duration=1"); -- request.setVersion("HTTP/1.0"); -- -- processRequest(); -- } -- -- @Test -- void returns200OK() { -- assertThat(response.getStatus()) -- .isEqualTo(200); -- } -- -- @Test -- void returnsPprofRaw() { -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("pprof/raw"); -- } -- -- @Test -- void returnsUncacheable() { -- assertThat(response.get(HttpHeader.CACHE_CONTROL)) -- .isEqualTo("must-revalidate,no-cache,no-store"); -- -- } +final class CpuProfileServletTest extends AbstractServletTest { -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.addServlet(CpuProfileServlet.class, "/pprof"); -+ } -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ request.setMethod("GET"); -+ request.setURI("/pprof?duration=1"); -+ request.setVersion("HTTP/1.0"); -+ -+ processRequest(); -+ } -+ -+ @Test -+ void returns200OK() { -+ assertThat(response.getStatus()).isEqualTo(200); -+ } -+ -+ @Test -+ void returnsPprofRaw() { -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("pprof/raw"); -+ } -+ -+ @Test -+ void returnsUncacheable() { -+ assertThat(response.get(HttpHeader.CACHE_CONTROL)) -+ .isEqualTo("must-revalidate,no-cache,no-store"); -+ } - } + + @Override + protected void setUp(ServletTester tester) { --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -@@ -1,258 +1,269 @@ +@@ -1,10 +1,9 @@ package io.dropwizard.metrics5.servlets; -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.never; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import com.fasterxml.jackson.databind.ObjectMapper; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.health.HealthCheck; - import io.dropwizard.metrics5.health.HealthCheckFilter; - import io.dropwizard.metrics5.health.HealthCheckRegistry; --import org.eclipse.jetty.http.HttpHeader; --import org.eclipse.jetty.servlet.ServletTester; --import org.junit.jupiter.api.AfterEach; --import org.junit.jupiter.api.BeforeEach; --import org.junit.jupiter.api.Test; -- --import javax.servlet.ServletConfig; --import javax.servlet.ServletContext; --import javax.servlet.ServletException; - import java.time.ZonedDateTime; - import java.time.format.DateTimeFormatter; - import java.util.concurrent.Callable; - import java.util.concurrent.ExecutorService; - import java.util.concurrent.Executors; -+import javax.servlet.ServletConfig; -+import javax.servlet.ServletContext; -+import javax.servlet.ServletException; -+import org.eclipse.jetty.http.HttpHeader; -+import org.eclipse.jetty.servlet.ServletTester; -+import org.junit.jupiter.api.AfterEach; -+import org.junit.jupiter.api.BeforeEach; -+import org.junit.jupiter.api.Test; - --import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.never; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- --class HealthCheckServletTest extends AbstractServletTest { -+final class HealthCheckServletTest extends AbstractServletTest { - -- private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); -+ private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; -- private static final DateTimeFormatter DATE_TIME_FORMATTER = -- DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); -+ private static final DateTimeFormatter DATE_TIME_FORMATTER = -+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); +@@ -27,7 +26,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; -- private static final String EXPECTED_TIMESTAMP = DATE_TIME_FORMATTER.format(FIXED_TIME); -+ private static final String EXPECTED_TIMESTAMP = DATE_TIME_FORMATTER.format(FIXED_TIME); +-class HealthCheckServletTest extends AbstractServletTest { ++final class HealthCheckServletTest extends AbstractServletTest { -- private static final Clock FIXED_CLOCK = new Clock() { -+ private static final Clock FIXED_CLOCK = -+ new Clock() { - @Override - public long getTick() { -- return 0L; -+ return 0L; - } + private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); - @Override - public long getTime() { -- return FIXED_TIME.toInstant().toEpochMilli(); -+ return FIXED_TIME.toInstant().toEpochMilli(); - } -- }; -- -- private final HealthCheckRegistry registry = new HealthCheckRegistry(); -- private final ExecutorService threadPool = Executors.newCachedThreadPool(); -- private final ObjectMapper mapper = new ObjectMapper(); -- -- @Override -- protected void setUp(ServletTester tester) { -- tester.addServlet(HealthCheckServlet.class, "/healthchecks"); -- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", registry); -- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".executor", threadPool); -- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".mapper", mapper); -- tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter", -- (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); -- } -- -- @BeforeEach -- void setUp() { -- request.setMethod("GET"); -- request.setURI("/healthchecks"); -- request.setVersion("HTTP/1.0"); -- } -- -- @AfterEach -- void tearDown() { -- threadPool.shutdown(); -- } -- -- @Test -- void returns501IfNoHealthChecksAreRegistered() throws Exception { -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(501); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()).isEqualTo("{}"); -- } -- -- @Test -- void returnsA200IfAllHealthChecksAreHealthy() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()) -- .isEqualTo("{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + -- EXPECTED_TIMESTAMP + -- "\"}}"); -+ }; -+ -+ private final HealthCheckRegistry registry = new HealthCheckRegistry(); -+ private final ExecutorService threadPool = Executors.newCachedThreadPool(); -+ private final ObjectMapper mapper = new ObjectMapper(); -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.addServlet(HealthCheckServlet.class, "/healthchecks"); -+ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", registry); -+ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".executor", threadPool); -+ tester.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".mapper", mapper); -+ tester.setAttribute( -+ HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter", -+ (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); -+ } -+ -+ @BeforeEach -+ void setUp() { -+ request.setMethod("GET"); -+ request.setURI("/healthchecks"); -+ request.setVersion("HTTP/1.0"); -+ } -+ -+ @AfterEach -+ void tearDown() { -+ threadPool.shutdown(); -+ } -+ -+ @Test -+ void returns501IfNoHealthChecksAreRegistered() throws Exception { -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(501); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()).isEqualTo("{}"); -+ } -+ -+ @Test -+ void returnsA200IfAllHealthChecksAreHealthy() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .isEqualTo( +@@ -95,9 +94,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); + "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", + EXPECTED_TIMESTAMP); -+ } -+ -+ @Test -+ void returnsASubsetOfHealthChecksIfFiltered() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -+ registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .isEqualTo( + } + + @Test +@@ -111,9 +109,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); + "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", + EXPECTED_TIMESTAMP); -+ } -+ -+ @Test -+ void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -+ registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(500); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .contains( -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -+ + EXPECTED_TIMESTAMP -+ + "\"}", -+ ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -+ + EXPECTED_TIMESTAMP -+ + "\"}}"); -+ } -+ -+ @Test -+ void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -+ registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -+ request.setURI("/healthchecks?httpStatusIndicator=false"); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .contains( -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -+ + EXPECTED_TIMESTAMP -+ + "\"}", -+ ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -+ + EXPECTED_TIMESTAMP -+ + "\"}}"); -+ } -+ -+ @Test -+ void optionallyPrettyPrintsTheJson() throws Exception { -+ registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); -+ -+ request.setURI("/healthchecks?pretty=true"); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( + } + + @Test +@@ -168,15 +165,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getContent()) + .isEqualTo( + String.format( +- "{%n" +- + " \"fun\" : {%n" +- + " \"healthy\" : true,%n" +- + " \"message\" : \"foo bar 123\",%n" +- + " \"duration\" : 0,%n" +- + " \"timestamp\" : \"" +- + EXPECTED_TIMESTAMP +- + "\"" +- + "%n }%n}")); + "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", + EXPECTED_TIMESTAMP)); -+ } -+ -+ private static HealthCheck.Result healthyResultWithMessage(String message) { -+ return HealthCheck.Result.builder() -+ .healthy() -+ .withMessage(message) -+ .usingClock(FIXED_CLOCK) -+ .build(); -+ } -+ -+ private static HealthCheck.Result unhealthyResultWithMessage(String message) { -+ return HealthCheck.Result.builder() -+ .unhealthy() -+ .withMessage(message) -+ .usingClock(FIXED_CLOCK) -+ .build(); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); -+ healthCheckServlet.init(servletConfig); -+ -+ verify(servletConfig).getServletContext(); -+ verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { + } + + private static HealthCheck.Result healthyResultWithMessage(String message) { +@@ -197,23 +187,23 @@ class HealthCheckServletTest extends AbstractServletTest { + + @Test + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); + final HealthCheckRegistry healthCheckRegistry = mock(); + final ServletContext servletContext = mock(); + final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -+ .thenReturn(healthCheckRegistry); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -+ healthCheckServlet.init(servletConfig); -+ -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() -+ throws Exception { -+ assertThatThrownBy( -+ () -> { -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -+ .thenReturn("IRELLEVANT_STRING"); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -+ healthCheckServlet.init(servletConfig); -+ }) -+ .isInstanceOf(ServletException.class); -+ } -+ -+ @Test -+ void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() -+ throws Exception { -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -+ .thenReturn(registry); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_MAPPER)) -+ .thenReturn("IRELLEVANT_STRING"); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -+ healthCheckServlet.init(servletConfig); -+ -+ assertThat(healthCheckServlet.getMapper()).isNotNull().isInstanceOf(ObjectMapper.class); -+ } -+ -+ static class TestHealthCheck implements HealthCheck { -+ private final Callable check; -+ -+ public TestHealthCheck(Callable check) { -+ this.check = check; - } - -- @Test -- void returnsASubsetOfHealthChecksIfFiltered() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -- registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()) -- .isEqualTo("{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + -- EXPECTED_TIMESTAMP + -- "\"}}"); -- } -- -- @Test -- void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -- registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(500); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()).contains( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", -- ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); -- } -- -- @Test -- void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); -- registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); -- request.setURI("/healthchecks?httpStatusIndicator=false"); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()).contains( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", -- ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); -- } -- -- @Test -- void optionallyPrettyPrintsTheJson() throws Exception { -- registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); -- -- request.setURI("/healthchecks?pretty=true"); -- -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -- assertThat(response.getContent()) -- .isEqualTo(String.format("{%n" + -- " \"fun\" : {%n" + -- " \"healthy\" : true,%n" + -- " \"message\" : \"foo bar 123\",%n" + -- " \"duration\" : 0,%n" + -- " \"timestamp\" : \"" + EXPECTED_TIMESTAMP + "\"" + -- "%n }%n}")); -- } -- -- private static HealthCheck.Result healthyResultWithMessage(String message) { -- return HealthCheck.Result.builder() -- .healthy() -- .withMessage(message) -- .usingClock(FIXED_CLOCK) -- .build(); -- } -- -- private static HealthCheck.Result unhealthyResultWithMessage(String message) { -- return HealthCheck.Result.builder() -- .unhealthy() -- .withMessage(message) -- .usingClock(FIXED_CLOCK) -- .build(); -- } -- -- @Test -- void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); -- healthCheckServlet.init(servletConfig); -- -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -- } -- -- @Test -- void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -- .thenReturn(healthCheckRegistry); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -- healthCheckServlet.init(servletConfig); -- -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -- } -- -- @Test -- void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { -- assertThrows(ServletException.class, () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -- .thenReturn("IRELLEVANT_STRING"); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -- healthCheckServlet.init(servletConfig); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(healthCheckRegistry); +@@ -221,32 +211,32 @@ class HealthCheckServletTest extends AbstractServletTest { + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- assertThrows( +- ServletException.class, +- () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) +- .thenReturn("IRELLEVANT_STRING"); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); - }); -- } -- -- @Test -- void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)).thenReturn(registry); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_MAPPER)).thenReturn("IRELLEVANT_STRING"); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -- healthCheckServlet.init(servletConfig); -- -- assertThat(healthCheckServlet.getMapper()) -- .isNotNull() -- .isInstanceOf(ObjectMapper.class); -+ @Override -+ public Result check() throws Exception { -+ return check.call(); - } ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); + } -- static class TestHealthCheck implements HealthCheck { -- private final Callable check; -- -- public TestHealthCheck(Callable check) { -- this.check = check; -- } -- -- @Override -- public Result check() throws Exception { -- return check.call(); -- } -- -- @Override -- public Clock clock() { -- return FIXED_CLOCK; -- } -+ @Override -+ public Clock clock() { -+ return FIXED_CLOCK; - } --} -\ No newline at end of file -+ } -+} + @Test + void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(registry); --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Gauge; -@@ -7,166 +11,163 @@ import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -+import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; +@@ -17,8 +17,8 @@ import org.eclipse.jetty.servlet.ServletTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.when; -- -class MetricsServletContextListenerTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -- private final MetricRegistry registry = new MetricRegistry(); -- private final String allowedOrigin = "some.other.origin"; -- -- @Override -- protected void setUp(ServletTester tester) { -- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -- tester.addServlet(MetricsServlet.class, "/metrics"); -- tester.getContext().addEventListener(new MetricsServlet.ContextListener() { -- @Override -- protected MetricRegistry getMetricRegistry() { +- private final Clock clock = mock(Clock.class); +final class MetricsServletContextListenerTest extends AbstractServletTest { + private final Clock clock = mock(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private final String allowedOrigin = "some.other.origin"; -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -+ tester.addServlet(MetricsServlet.class, "/metrics"); -+ tester -+ .getContext() -+ .addEventListener( -+ new MetricsServlet.ContextListener() { -+ @Override -+ protected MetricRegistry getMetricRegistry() { - return registry; -- } -+ } - -- @Override -- protected TimeUnit getDurationUnit() { -+ @Override -+ protected TimeUnit getDurationUnit() { - return TimeUnit.MILLISECONDS; -- } -+ } - -- @Override -- protected TimeUnit getRateUnit() { -+ @Override -+ protected TimeUnit getRateUnit() { - return TimeUnit.MINUTES; -- } -+ } - -- @Override -- protected String getAllowedOrigin() { -+ @Override -+ protected String getAllowedOrigin() { - return allowedOrigin; -- } -- }); -- } -- -- @BeforeEach -- void setUp() { -- // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves -- // will call getTick again several times and always get the same value (the last specified here) -- when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); -- -- registry.register(MetricName.build("g1"), (Gauge) () -> 100L); -- registry.counter("c").inc(); -- registry.histogram("h").update(1); -- registry.register(MetricName.build("m"), new Meter(clock)).mark(); -- registry.register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) -- .update(1, TimeUnit.SECONDS); -- -- request.setMethod("GET"); -- request.setURI("/metrics"); -- request.setVersion("HTTP/1.0"); -- } -- -- @Test -- void returnsA200() throws Exception { -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo(allowedOrigin); -- assertThat(response.getContent()) -- .isEqualTo("{" + -- "\"version\":\"5.0.0\"," + -- "\"gauges\":{" + -- "\"g1\":{\"value\":100}" + -- "}," + -- "\"counters\":{" + -- "\"c\":{\"count\":1}" + -- "}," + -- "\"histograms\":{" + -- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + -- "}," + -- "\"meters\":{" + -- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":2.0E8,\"units\":\"events/minute\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1000.0,\"mean\":1000.0,\"min\":1000.0,\"p50\":1000.0,\"p75\":1000.0,\"p95\":1000.0,\"p98\":1000.0,\"p99\":1000.0,\"p999\":1000.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":6.0E8,\"duration_units\":\"milliseconds\",\"rate_units\":\"calls/minute\"}" + -- "}" + -- "}"); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void optionallyPrettyPrintsTheJson() throws Exception { -- request.setURI("/metrics?pretty=true"); -- -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo(allowedOrigin); -- assertThat(response.getContent()) -- .isEqualTo(String.format("{%n" + -- " \"version\" : \"5.0.0\",%n" + -- " \"gauges\" : {%n" + -- " \"g1\" : {%n" + -- " \"value\" : 100%n" + -- " }%n" + -- " },%n" + -- " \"counters\" : {%n" + -- " \"c\" : {%n" + -- " \"count\" : 1%n" + -- " }%n" + -- " },%n" + -- " \"histograms\" : {%n" + -- " \"h\" : {%n" + -- " \"count\" : 1,%n" + -- " \"max\" : 1,%n" + -- " \"mean\" : 1.0,%n" + -- " \"min\" : 1,%n" + -- " \"p50\" : 1.0,%n" + -- " \"p75\" : 1.0,%n" + -- " \"p95\" : 1.0,%n" + -- " \"p98\" : 1.0,%n" + -- " \"p99\" : 1.0,%n" + -- " \"p999\" : 1.0,%n" + -- " \"stddev\" : 0.0%n" + -- " }%n" + -- " },%n" + -- " \"meters\" : {%n" + -- " \"m\" : {%n" + -- " \"count\" : 1,%n" + -- " \"m15_rate\" : 0.0,%n" + -- " \"m1_rate\" : 0.0,%n" + -- " \"m5_rate\" : 0.0,%n" + -- " \"mean_rate\" : 2.0E8,%n" + -- " \"units\" : \"events/minute\"%n" + -- " }%n" + -- " },%n" + -- " \"timers\" : {%n" + -- " \"t\" : {%n" + -- " \"count\" : 1,%n" + -- " \"max\" : 1000.0,%n" + -- " \"mean\" : 1000.0,%n" + -- " \"min\" : 1000.0,%n" + -- " \"p50\" : 1000.0,%n" + -- " \"p75\" : 1000.0,%n" + -- " \"p95\" : 1000.0,%n" + -- " \"p98\" : 1000.0,%n" + -- " \"p99\" : 1000.0,%n" + -- " \"p999\" : 1000.0,%n" + -- " \"stddev\" : 0.0,%n" + -- " \"m15_rate\" : 0.0,%n" + -- " \"m1_rate\" : 0.0,%n" + -- " \"m5_rate\" : 0.0,%n" + -- " \"mean_rate\" : 6.0E8,%n" + -- " \"duration_units\" : \"milliseconds\",%n" + -- " \"rate_units\" : \"calls/minute\"%n" + -- " }%n" + -- " }%n" + -- "}")); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -+ } -+ }); -+ } -+ -+ @BeforeEach -+ void setUp() { -+ // provide ticks for the setup (calls getTick 6 times). The serialization in the tests -+ // themselves -+ // will call getTick again several times and always get the same value (the last specified here) -+ when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); -+ -+ registry.register(MetricName.build("g1"), (Gauge) () -> 100L); -+ registry.counter("c").inc(); -+ registry.histogram("h").update(1); -+ registry.register(MetricName.build("m"), new Meter(clock)).mark(); -+ registry -+ .register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) -+ .update(1, TimeUnit.SECONDS); -+ -+ request.setMethod("GET"); -+ request.setURI("/metrics"); -+ request.setVersion("HTTP/1.0"); -+ } -+ -+ @Test -+ void returnsA200() throws Exception { -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo(allowedOrigin); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ "{" -+ + "\"version\":\"5.0.0\"," -+ + "\"gauges\":{" -+ + "\"g1\":{\"value\":100}" -+ + "}," -+ + "\"counters\":{" -+ + "\"c\":{\"count\":1}" -+ + "}," -+ + "\"histograms\":{" -+ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -+ + "}," -+ + "\"meters\":{" -+ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":2.0E8,\"units\":\"events/minute\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1000.0,\"mean\":1000.0,\"min\":1000.0,\"p50\":1000.0,\"p75\":1000.0,\"p95\":1000.0,\"p98\":1000.0,\"p99\":1000.0,\"p999\":1000.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":6.0E8,\"duration_units\":\"milliseconds\",\"rate_units\":\"calls/minute\"}" -+ + "}" -+ + "}"); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void optionallyPrettyPrintsTheJson() throws Exception { -+ request.setURI("/metrics?pretty=true"); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo(allowedOrigin); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "{%n" -+ + " \"version\" : \"5.0.0\",%n" -+ + " \"gauges\" : {%n" -+ + " \"g1\" : {%n" -+ + " \"value\" : 100%n" -+ + " }%n" -+ + " },%n" -+ + " \"counters\" : {%n" -+ + " \"c\" : {%n" -+ + " \"count\" : 1%n" -+ + " }%n" -+ + " },%n" -+ + " \"histograms\" : {%n" -+ + " \"h\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"max\" : 1,%n" -+ + " \"mean\" : 1.0,%n" -+ + " \"min\" : 1,%n" -+ + " \"p50\" : 1.0,%n" -+ + " \"p75\" : 1.0,%n" -+ + " \"p95\" : 1.0,%n" -+ + " \"p98\" : 1.0,%n" -+ + " \"p99\" : 1.0,%n" -+ + " \"p999\" : 1.0,%n" -+ + " \"stddev\" : 0.0%n" -+ + " }%n" -+ + " },%n" -+ + " \"meters\" : {%n" -+ + " \"m\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"m15_rate\" : 0.0,%n" -+ + " \"m1_rate\" : 0.0,%n" -+ + " \"m5_rate\" : 0.0,%n" -+ + " \"mean_rate\" : 2.0E8,%n" -+ + " \"units\" : \"events/minute\"%n" -+ + " }%n" -+ + " },%n" -+ + " \"timers\" : {%n" -+ + " \"t\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"max\" : 1000.0,%n" -+ + " \"mean\" : 1000.0,%n" -+ + " \"min\" : 1000.0,%n" -+ + " \"p50\" : 1000.0,%n" -+ + " \"p75\" : 1000.0,%n" -+ + " \"p95\" : 1000.0,%n" -+ + " \"p98\" : 1000.0,%n" -+ + " \"p99\" : 1000.0,%n" -+ + " \"p999\" : 1000.0,%n" -+ + " \"stddev\" : 0.0,%n" -+ + " \"m15_rate\" : 0.0,%n" -+ + " \"m1_rate\" : 0.0,%n" -+ + " \"m5_rate\" : 0.0,%n" -+ + " \"mean_rate\" : 6.0E8,%n" -+ + " \"duration_units\" : \"milliseconds\",%n" -+ + " \"rate_units\" : \"calls/minute\"%n" -+ + " }%n" -+ + " }%n" -+ + "}")); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } - } + private final MetricRegistry registry = new MetricRegistry(); + private final String allowedOrigin = "some.other.origin"; + --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -@@ -1,5 +1,12 @@ +@@ -1,11 +1,9 @@ package io.dropwizard.metrics5.servlets; -+import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.mockito.ArgumentMatchers.eq; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.never; -+import static org.mockito.Mockito.verify; -+import static org.mockito.Mockito.when; -+ - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Gauge; -@@ -7,261 +14,241 @@ import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Timer; -+import java.util.concurrent.TimeUnit; -+import javax.servlet.ServletConfig; -+import javax.servlet.ServletContext; -+import javax.servlet.ServletException; - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -25,8 +23,8 @@ import org.eclipse.jetty.servlet.ServletTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import javax.servlet.ServletConfig; --import javax.servlet.ServletContext; --import javax.servlet.ServletException; --import java.util.concurrent.TimeUnit; -- --import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.mockito.ArgumentMatchers.eq; --import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; --import static org.mockito.Mockito.verify; --import static org.mockito.Mockito.when; -- -class MetricsServletTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -- private final MetricRegistry registry = new MetricRegistry(); -- private ServletTester tester; -- -- @Override -- protected void setUp(ServletTester tester) { -- this.tester = tester; -- tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -- tester.addServlet(MetricsServlet.class, "/metrics"); -- tester.getContext().setInitParameter("io.dropwizard.metrics5.servlets.MetricsServlet.allowedOrigin", "*"); -- } -- -- @BeforeEach -- void setUp() { -- // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves -- // will call getTick again several times and always get the same value (the last specified here) -- when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); -- -- registry.register(MetricName.build("g1"), (Gauge) () -> 100L); -- registry.counter("c").inc(); -- registry.histogram("h").update(1); -- registry.register(MetricName.build("m"), new Meter(clock)).mark(); -- registry.register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) -- .update(1, TimeUnit.SECONDS); -- -- request.setMethod("GET"); -- request.setURI("/metrics"); -- request.setVersion("HTTP/1.0"); -- } -- -- @Test -- void returnsA200() throws Exception { -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo("*"); -- assertThat(response.getContent()) -- .isEqualTo("{" + -- "\"version\":\"5.0.0\"," + -- "\"gauges\":{" + -- "\"g1\":{\"value\":100}" + -- "}," + -- "\"counters\":{" + -- "\"c\":{\"count\":1}" + -- "}," + -- "\"histograms\":{" + -- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + -- "}," + -- "\"meters\":{" + -- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + -- "}" + -- "}"); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void returnsJsonWhenJsonpInitParamNotSet() throws Exception { -- String callbackParamName = "callbackParam"; -- String callbackParamVal = "callbackParamVal"; -- request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo("*"); -- assertThat(response.getContent()) -- .isEqualTo("{" + -- "\"version\":\"5.0.0\"," + -- "\"gauges\":{" + -- "\"g1\":{\"value\":100}" + -- "}," + -- "\"counters\":{" + -- "\"c\":{\"count\":1}" + -- "}," + -- "\"histograms\":{" + -- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + -- "}," + -- "\"meters\":{" + -- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + -- "}" + -- "}"); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void returnsJsonpWhenInitParamSet() throws Exception { -- String callbackParamName = "callbackParam"; -- String callbackParamVal = "callbackParamVal"; -- request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); -- tester.getContext().setInitParameter("io.dropwizard.metrics5.servlets.MetricsServlet.jsonpCallback", callbackParamName); -- processRequest(); -- -- assertThat(response.getStatus()).isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo("*"); -- assertThat(response.getContent()) -- .isEqualTo(callbackParamVal + "({" + -- "\"version\":\"5.0.0\"," + -- "\"gauges\":{" + -- "\"g1\":{\"value\":100}" + -- "}," + -- "\"counters\":{" + -- "\"c\":{\"count\":1}" + -- "}," + -- "\"histograms\":{" + -- "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" + -- "}," + -- "\"meters\":{" + -- "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" + -- "}" + -- "})"); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void optionallyPrettyPrintsTheJson() throws Exception { -- request.setURI("/metrics?pretty=true"); -- -- processRequest(); -- -- assertThat(response.getStatus()) -- .isEqualTo(200); -- assertThat(response.get("Access-Control-Allow-Origin")) -- .isEqualTo("*"); -- assertThat(response.getContent()) -- .isEqualTo(String.format("{%n" + -- " \"version\" : \"5.0.0\",%n" + -- " \"gauges\" : {%n" + -- " \"g1\" : {%n" + -- " \"value\" : 100%n" + -- " }%n" + -- " },%n" + -- " \"counters\" : {%n" + -- " \"c\" : {%n" + -- " \"count\" : 1%n" + -- " }%n" + -- " },%n" + -- " \"histograms\" : {%n" + -- " \"h\" : {%n" + -- " \"count\" : 1,%n" + -- " \"max\" : 1,%n" + -- " \"mean\" : 1.0,%n" + -- " \"min\" : 1,%n" + -- " \"p50\" : 1.0,%n" + -- " \"p75\" : 1.0,%n" + -- " \"p95\" : 1.0,%n" + -- " \"p98\" : 1.0,%n" + -- " \"p99\" : 1.0,%n" + -- " \"p999\" : 1.0,%n" + -- " \"stddev\" : 0.0%n" + -- " }%n" + -- " },%n" + -- " \"meters\" : {%n" + -- " \"m\" : {%n" + -- " \"count\" : 1,%n" + -- " \"m15_rate\" : 0.0,%n" + -- " \"m1_rate\" : 0.0,%n" + -- " \"m5_rate\" : 0.0,%n" + -- " \"mean_rate\" : 3333333.3333333335,%n" + -- " \"units\" : \"events/second\"%n" + -- " }%n" + -- " },%n" + -- " \"timers\" : {%n" + -- " \"t\" : {%n" + -- " \"count\" : 1,%n" + -- " \"max\" : 1.0,%n" + -- " \"mean\" : 1.0,%n" + -- " \"min\" : 1.0,%n" + -- " \"p50\" : 1.0,%n" + -- " \"p75\" : 1.0,%n" + -- " \"p95\" : 1.0,%n" + -- " \"p98\" : 1.0,%n" + -- " \"p99\" : 1.0,%n" + -- " \"p999\" : 1.0,%n" + -- " \"stddev\" : 0.0,%n" + -- " \"m15_rate\" : 0.0,%n" + -- " \"m1_rate\" : 0.0,%n" + -- " \"m5_rate\" : 0.0,%n" + -- " \"mean_rate\" : 1.0E7,%n" + -- " \"duration_units\" : \"seconds\",%n" + -- " \"rate_units\" : \"calls/second\"%n" + -- " }%n" + -- " }%n" + -- "}")); -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("application/json"); -- } -- -- @Test -- void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- -- final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); -- metricsServlet.init(servletConfig); -- -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -- } -- -- @Test -- void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn(metricRegistry); -- -- final MetricsServlet metricsServlet = new MetricsServlet(null); -- metricsServlet.init(servletConfig); -- -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -- } -- -- @Test -- void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { -- assertThrows(ServletException.class, () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn("IRELLEVANT_STRING"); -- -- final MetricsServlet metricsServlet = new MetricsServlet(null); -- metricsServlet.init(servletConfig); -- }); -- } +- private final Clock clock = mock(Clock.class); +final class MetricsServletTest extends AbstractServletTest { + private final Clock clock = mock(); -+ private final MetricRegistry registry = new MetricRegistry(); -+ private ServletTester tester; -+ -+ @Override -+ protected void setUp(ServletTester tester) { -+ this.tester = tester; -+ tester.setAttribute("io.dropwizard.metrics5.servlets.MetricsServlet.registry", registry); -+ tester.addServlet(MetricsServlet.class, "/metrics"); -+ tester -+ .getContext() -+ .setInitParameter("io.dropwizard.metrics5.servlets.MetricsServlet.allowedOrigin", "*"); -+ } -+ -+ @BeforeEach -+ void setUp() { -+ // provide ticks for the setup (calls getTick 6 times). The serialization in the tests -+ // themselves -+ // will call getTick again several times and always get the same value (the last specified here) -+ when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); -+ -+ registry.register(MetricName.build("g1"), (Gauge) () -> 100L); -+ registry.counter("c").inc(); -+ registry.histogram("h").update(1); -+ registry.register(MetricName.build("m"), new Meter(clock)).mark(); -+ registry -+ .register(MetricName.build("t"), new Timer(new ExponentiallyDecayingReservoir(), clock)) -+ .update(1, TimeUnit.SECONDS); -+ -+ request.setMethod("GET"); -+ request.setURI("/metrics"); -+ request.setVersion("HTTP/1.0"); -+ } -+ -+ @Test -+ void returnsA200() throws Exception { -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ "{" -+ + "\"version\":\"5.0.0\"," -+ + "\"gauges\":{" -+ + "\"g1\":{\"value\":100}" -+ + "}," -+ + "\"counters\":{" -+ + "\"c\":{\"count\":1}" -+ + "}," -+ + "\"histograms\":{" -+ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -+ + "}," -+ + "\"meters\":{" -+ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -+ + "}" -+ + "}"); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void returnsJsonWhenJsonpInitParamNotSet() throws Exception { -+ String callbackParamName = "callbackParam"; -+ String callbackParamVal = "callbackParamVal"; -+ request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ "{" -+ + "\"version\":\"5.0.0\"," -+ + "\"gauges\":{" -+ + "\"g1\":{\"value\":100}" -+ + "}," -+ + "\"counters\":{" -+ + "\"c\":{\"count\":1}" -+ + "}," -+ + "\"histograms\":{" -+ + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -+ + "}," -+ + "\"meters\":{" -+ + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -+ + "}" -+ + "}"); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void returnsJsonpWhenInitParamSet() throws Exception { -+ String callbackParamName = "callbackParam"; -+ String callbackParamVal = "callbackParamVal"; -+ request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); -+ tester -+ .getContext() -+ .setInitParameter( -+ "io.dropwizard.metrics5.servlets.MetricsServlet.jsonpCallback", callbackParamName); -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); -+ assertThat(response.getContent()) -+ .isEqualTo( + private final MetricRegistry registry = new MetricRegistry(); + private ServletTester tester; + +@@ -130,22 +128,8 @@ class MetricsServletTest extends AbstractServletTest { + assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); + assertThat(response.getContent()) + .isEqualTo( +- callbackParamVal +- + "({" +- + "\"version\":\"5.0.0\"," +- + "\"gauges\":{" +- + "\"g1\":{\"value\":100}" +- + "}," +- + "\"counters\":{" +- + "\"c\":{\"count\":1}" +- + "}," +- + "\"histograms\":{" +- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" +- + "}," +- + "\"meters\":{" +- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" +- + "}" +- + "})"); + "%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", + callbackParamVal); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void optionallyPrettyPrintsTheJson() throws Exception { -+ request.setURI("/metrics?pretty=true"); -+ -+ processRequest(); -+ -+ assertThat(response.getStatus()).isEqualTo(200); -+ assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); -+ assertThat(response.getContent()) -+ .isEqualTo( -+ String.format( -+ "{%n" -+ + " \"version\" : \"5.0.0\",%n" -+ + " \"gauges\" : {%n" -+ + " \"g1\" : {%n" -+ + " \"value\" : 100%n" -+ + " }%n" -+ + " },%n" -+ + " \"counters\" : {%n" -+ + " \"c\" : {%n" -+ + " \"count\" : 1%n" -+ + " }%n" -+ + " },%n" -+ + " \"histograms\" : {%n" -+ + " \"h\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"max\" : 1,%n" -+ + " \"mean\" : 1.0,%n" -+ + " \"min\" : 1,%n" -+ + " \"p50\" : 1.0,%n" -+ + " \"p75\" : 1.0,%n" -+ + " \"p95\" : 1.0,%n" -+ + " \"p98\" : 1.0,%n" -+ + " \"p99\" : 1.0,%n" -+ + " \"p999\" : 1.0,%n" -+ + " \"stddev\" : 0.0%n" -+ + " }%n" -+ + " },%n" -+ + " \"meters\" : {%n" -+ + " \"m\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"m15_rate\" : 0.0,%n" -+ + " \"m1_rate\" : 0.0,%n" -+ + " \"m5_rate\" : 0.0,%n" -+ + " \"mean_rate\" : 3333333.3333333335,%n" -+ + " \"units\" : \"events/second\"%n" -+ + " }%n" -+ + " },%n" -+ + " \"timers\" : {%n" -+ + " \"t\" : {%n" -+ + " \"count\" : 1,%n" -+ + " \"max\" : 1.0,%n" -+ + " \"mean\" : 1.0,%n" -+ + " \"min\" : 1.0,%n" -+ + " \"p50\" : 1.0,%n" -+ + " \"p75\" : 1.0,%n" -+ + " \"p95\" : 1.0,%n" -+ + " \"p98\" : 1.0,%n" -+ + " \"p99\" : 1.0,%n" -+ + " \"p999\" : 1.0,%n" -+ + " \"stddev\" : 0.0,%n" -+ + " \"m15_rate\" : 0.0,%n" -+ + " \"m1_rate\" : 0.0,%n" -+ + " \"m5_rate\" : 0.0,%n" -+ + " \"mean_rate\" : 1.0E7,%n" -+ + " \"duration_units\" : \"seconds\",%n" -+ + " \"rate_units\" : \"calls/second\"%n" -+ + " }%n" -+ + " }%n" -+ + "}")); -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -224,48 +208,47 @@ class MetricsServletTest extends AbstractServletTest { + + @Test + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); + final MetricRegistry metricRegistry = mock(); + final ServletContext servletContext = mock(); + final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ -+ final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); -+ metricsServlet.init(servletConfig); -+ + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); + verify(servletConfig).getServletContext(); + verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); + final MetricRegistry metricRegistry = mock(); + final ServletContext servletContext = mock(); + final ServletConfig servletConfig = mock(); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn(metricRegistry); + when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); -+ -+ final MetricsServlet metricsServlet = new MetricsServlet(null); -+ metricsServlet.init(servletConfig); -+ + + final MetricsServlet metricsServlet = new MetricsServlet(null); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); + verify(servletConfig).getServletContext(); + verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); -+ } -+ -+ @Test -+ void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() -+ throws Exception { + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- assertThrows( +- ServletException.class, +- () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn("IRELLEVANT_STRING"); +- +- final MetricsServlet metricsServlet = new MetricsServlet(null); +- metricsServlet.init(servletConfig); +- }); + assertThatThrownBy( + () -> { + final ServletContext servletContext = mock(); @@ -86562,271 +11145,27 @@ + metricsServlet.init(servletConfig); + }) + .isInstanceOf(ServletException.class); -+ } + } } --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java -@@ -1,49 +1,45 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; -- -class PingServletTest extends AbstractServletTest { -- @Override -- protected void setUp(ServletTester tester) { -- tester.addServlet(PingServlet.class, "/ping"); -- } -- -- @BeforeEach -- void setUp() throws Exception { -- request.setMethod("GET"); -- request.setURI("/ping"); -- request.setVersion("HTTP/1.0"); -- -- processRequest(); -- } -- -- @Test -- void returns200OK() { -- assertThat(response.getStatus()) -- .isEqualTo(200); -- } -- -- @Test -- void returnsPong() { -- assertThat(response.getContent()) -- .isEqualTo(String.format("pong%n")); -- } -- -- @Test -- void returnsTextPlain() { -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("text/plain;charset=ISO-8859-1"); -- } -- -- @Test -- void returnsUncacheable() { -- assertThat(response.get(HttpHeader.CACHE_CONTROL)) -- .isEqualTo("must-revalidate,no-cache,no-store"); -- -- } +final class PingServletTest extends AbstractServletTest { -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.addServlet(PingServlet.class, "/ping"); -+ } -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ request.setMethod("GET"); -+ request.setURI("/ping"); -+ request.setVersion("HTTP/1.0"); -+ -+ processRequest(); -+ } -+ -+ @Test -+ void returns200OK() { -+ assertThat(response.getStatus()).isEqualTo(200); -+ } -+ -+ @Test -+ void returnsPong() { -+ assertThat(response.getContent()).isEqualTo(String.format("pong%n")); -+ } -+ -+ @Test -+ void returnsTextPlain() { -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/plain;charset=ISO-8859-1"); -+ } -+ -+ @Test -+ void returnsUncacheable() { -+ assertThat(response.get(HttpHeader.CACHE_CONTROL)) -+ .isEqualTo("must-revalidate,no-cache,no-store"); -+ } - } + @Override + protected void setUp(ServletTester tester) { + tester.addServlet(PingServlet.class, "/ping"); --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java -@@ -1,49 +1,45 @@ - package io.dropwizard.metrics5.servlets; - -+import static org.assertj.core.api.Assertions.assertThat; -+ - import org.eclipse.jetty.http.HttpHeader; - import org.eclipse.jetty.servlet.ServletTester; +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; --import static org.assertj.core.api.Assertions.assertThat; -- -class ThreadDumpServletTest extends AbstractServletTest { -- @Override -- protected void setUp(ServletTester tester) { -- tester.addServlet(ThreadDumpServlet.class, "/threads"); -- } -- -- @BeforeEach -- void setUp() throws Exception { -- request.setMethod("GET"); -- request.setURI("/threads"); -- request.setVersion("HTTP/1.0"); -- -- processRequest(); -- } -- -- @Test -- void returns200OK() { -- assertThat(response.getStatus()) -- .isEqualTo(200); -- } -- -- @Test -- void returnsAThreadDump() { -- assertThat(response.getContent()) -- .contains("Finalizer"); -- } -- -- @Test -- void returnsTextPlain() { -- assertThat(response.get(HttpHeader.CONTENT_TYPE)) -- .isEqualTo("text/plain"); -- } -- -- @Test -- void returnsUncacheable() { -- assertThat(response.get(HttpHeader.CACHE_CONTROL)) -- .isEqualTo("must-revalidate,no-cache,no-store"); -- -- } +final class ThreadDumpServletTest extends AbstractServletTest { -+ @Override -+ protected void setUp(ServletTester tester) { -+ tester.addServlet(ThreadDumpServlet.class, "/threads"); -+ } -+ -+ @BeforeEach -+ void setUp() throws Exception { -+ request.setMethod("GET"); -+ request.setURI("/threads"); -+ request.setVersion("HTTP/1.0"); -+ -+ processRequest(); -+ } -+ -+ @Test -+ void returns200OK() { -+ assertThat(response.getStatus()).isEqualTo(200); -+ } -+ -+ @Test -+ void returnsAThreadDump() { -+ assertThat(response.getContent()).contains("Finalizer"); -+ } -+ -+ @Test -+ void returnsTextPlain() { -+ assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("text/plain"); -+ } -+ -+ @Test -+ void returnsUncacheable() { -+ assertThat(response.get(HttpHeader.CACHE_CONTROL)) -+ .isEqualTo("must-revalidate,no-cache,no-store"); -+ } - } ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/experiments/ExampleServer.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/experiments/ExampleServer.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.servlets.experiments; - -+import static io.dropwizard.metrics5.MetricRegistry.name; -+ - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.MetricRegistry; -@@ -18,43 +20,48 @@ import org.eclipse.jetty.servlet.ServletContextHandler; - import org.eclipse.jetty.servlet.ServletHolder; - import org.eclipse.jetty.util.thread.ThreadPool; - --import static io.dropwizard.metrics5.MetricRegistry.name; -- - public class ExampleServer { -- private static final MetricRegistry REGISTRY = new MetricRegistry(); -- private static final Counter COUNTER_1 = REGISTRY.counter(name(ExampleServer.class, "wah", "doody")); -- private static final Counter COUNTER_2 = REGISTRY.counter(name(ExampleServer.class, "woo")); -+ private static final MetricRegistry REGISTRY = new MetricRegistry(); -+ private static final Counter COUNTER_1 = -+ REGISTRY.counter(name(ExampleServer.class, "wah", "doody")); -+ private static final Counter COUNTER_2 = REGISTRY.counter(name(ExampleServer.class, "woo")); - -- static { -- REGISTRY.register(name(ExampleServer.class, "boo"), (Gauge) () -> { -- throw new RuntimeException("asplode!"); -- }); -- } -+ static { -+ REGISTRY.register( -+ name(ExampleServer.class, "boo"), -+ (Gauge) -+ () -> { -+ throw new RuntimeException("asplode!"); -+ }); -+ } - -- public static void main(String[] args) throws Exception { -- COUNTER_1.inc(); -- COUNTER_2.inc(); -+ public static void main(String[] args) throws Exception { -+ COUNTER_1.inc(); -+ COUNTER_2.inc(); - -- final ThreadPool threadPool = new InstrumentedQueuedThreadPool(REGISTRY); -- final Server server = new Server(threadPool); -+ final ThreadPool threadPool = new InstrumentedQueuedThreadPool(REGISTRY); -+ final Server server = new Server(threadPool); - -- final Connector connector = new ServerConnector(server, new InstrumentedConnectionFactory( -+ final Connector connector = -+ new ServerConnector( -+ server, -+ new InstrumentedConnectionFactory( - new HttpConnectionFactory(), REGISTRY.timer("http.connection"))); -- server.addConnector(connector); -+ server.addConnector(connector); - -- final ServletContextHandler context = new ServletContextHandler(); -- context.setContextPath("/initial"); -- context.setAttribute(MetricsServlet.METRICS_REGISTRY, REGISTRY); -- context.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, new HealthCheckRegistry()); -+ final ServletContextHandler context = new ServletContextHandler(); -+ context.setContextPath("/initial"); -+ context.setAttribute(MetricsServlet.METRICS_REGISTRY, REGISTRY); -+ context.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, new HealthCheckRegistry()); - -- final ServletHolder holder = new ServletHolder(new AdminServlet()); -- context.addServlet(holder, "/dingo/*"); -+ final ServletHolder holder = new ServletHolder(new AdminServlet()); -+ context.addServlet(holder, "/dingo/*"); - -- final InstrumentedHandler handler = new InstrumentedHandler(REGISTRY); -- handler.setHandler(context); -- server.setHandler(handler); -+ final InstrumentedHandler handler = new InstrumentedHandler(REGISTRY); -+ handler.setHandler(context); -+ server.setHandler(handler); - -- server.start(); -- server.join(); -- } -+ server.start(); -+ server.join(); -+ } - } + @Override + protected void setUp(ServletTester tester) { + tester.addServlet(ThreadDumpServlet.class, "/threads"); diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index e69de29bb2..664cccfbf5 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -0,0 +1,94 @@ +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[11,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[12,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[16,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[17,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[6,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[7,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[11,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[12,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[16,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[17,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[6,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[7,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[11,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[12,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[16,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[17,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[6,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[7,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[11,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[12,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[16,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[17,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[6,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[7,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[11,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[12,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[16,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[17,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[6,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[7,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[164,12] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[169,11] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[175,17] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[200,8] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[203,21] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[206,11] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[250,36] [cast] redundant cast to ByteBuffer +metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method +metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement +metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement +metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[56,27] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[40,12] [removal] SecurityManager in java.lang has been deprecated and marked for removal +metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[40,38] [removal] getSecurityManager() in System has been deprecated and marked for removal +metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[270,32] [removal] getSecurityManager() in System has been deprecated and marked for removal +metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[270,6] [removal] SecurityManager in java.lang has been deprecated and marked for removal +metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java:[40,8] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java:[114,8] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[160,12] [deprecation] DefaultHttpClientConnectionOperator(Lookup,SchemePortResolver,DnsResolver) in DefaultHttpClientConnectionOperator has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[30,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[31,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[32,37] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[33,38] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[96,21] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java:[49,4] [deprecation] HttpRequestExecutor(Timeout,ConnectionReuseStrategy,Http1StreamListener) in HttpRequestExecutor has been deprecated +metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java:[189,31] [serial] non-transient instance field of a serializable class declared with a non-serializable type +metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast +metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast +metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast +metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[74,74] [unchecked] unchecked cast +metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[83,74] [unchecked] unchecked cast +metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[92,74] [unchecked] unchecked cast +metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[108,27] [rawtypes] found raw type: Gauge +metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[112,27] [rawtypes] found raw type: Gauge +metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,49] [rawtypes] found raw type: Gauge +metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,9] [rawtypes] found raw type: Gauge +metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[367,22] [rawtypes] found raw type: Gauge +metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[50,4] [rawtypes] found raw type: Gauge +metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type +metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index ae6ee84a8f..8ce67eb95e 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -9,6 +9,7 @@ repository='https://github.com/dropwizard/metrics.git' revision='v5.0.0-rc22' additional_build_flags='' additional_source_directories='${project.basedir}${file.separator}src${file.separator}it${file.separator}java,${project.basedir}${file.separator}src${file.separator}xdocs-examples${file.separator}java' +#additional_source_directories='' # XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Refaster rules # as they introduce changes that expect Guava to be on the classpath. #patch_error_prone_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!.*File).*" diff --git a/integration-tests/run-integration-test.sh b/integration-tests/run-integration-test.sh index 5a20345046..4ccf3ce823 100755 --- a/integration-tests/run-integration-test.sh +++ b/integration-tests/run-integration-test.sh @@ -136,8 +136,8 @@ git config user.name || git config user.name 'Integration Test' git clean -fdx git apply < "${integration_test_root}/${test_name}-init.patch" git commit -m 'dependency: Introduce Error Prone Support' . -#mvn ${shared_build_flags} "${format_goal}" -#git commit -m 'minor: Reformat using Google Java Format' . +mvn ${shared_build_flags} "${format_goal}" +git commit -m 'minor: Reformat using Google Java Format' . diff_base="$(git rev-parse HEAD)" # Apply Error Prone Support-suggested changes until a fixed point is reached. @@ -173,6 +173,8 @@ apply_patch '' echo "RUN ONE MORE FULL --------" +echo "Version $(mvn --version)" +echo "COMMANDO ${shared_build_flags} clean package -Derror-prone.configuration-args=${error_prone_validation_flags}. ${validation_build_flags} " # Run one more full build and log the output. # # By also running the tests, we validate that the (majority of) applied changes From 2876cf84ef38b231778a5f42683c89f4623b0837 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Fri, 15 Nov 2024 09:24:55 +0100 Subject: [PATCH 30/59] ExcludePaths generated_resources --- .../metrics-expected-warnings.txt | 30 ------------------- integration-tests/metrics.sh | 9 ++---- integration-tests/run-integration-test.sh | 2 +- 3 files changed, 4 insertions(+), 37 deletions(-) diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index 664cccfbf5..0007071c9b 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -1,33 +1,3 @@ -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[11,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[12,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[16,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[17,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[6,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CachedGaugeBenchmark_jmhType_B2.java:[7,83] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[11,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[12,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[16,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[17,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[6,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/CounterBenchmark_jmhType_B2.java:[7,79] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[11,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[12,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[16,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[17,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[6,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/MeterBenchmark_jmhType_B2.java:[7,77] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[11,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[12,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[16,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[17,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[6,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/ReservoirBenchmark_jmhType_B2.java:[7,81] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[11,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[12,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_ITERATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[16,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[17,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_INVOCATION_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[6,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'SETUP_TRIAL_MUTEX_UPDATER', though note that this is not a private constant -metrics-benchmarks/target/generated-sources/annotations/io/dropwizard/metrics5/benchmarks/jmh_generated/SlidingTimeWindowReservoirsBenchmark_jmhType_B2.java:[7,99] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention; consider renaming to 'TEAR_TRIAL_MUTEX_UPDATER', though note that this is not a private constant metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[164,12] [cast] redundant cast to ByteBuffer metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[169,11] [cast] redundant cast to ByteBuffer diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 8ce67eb95e..5d70f43da5 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -5,15 +5,12 @@ set -e -u -o pipefail test_name="$(basename "${0}" .sh)" project='metrics' repository='https://github.com/dropwizard/metrics.git' -#revision='v4.2.28' revision='v5.0.0-rc22' additional_build_flags='' additional_source_directories='${project.basedir}${file.separator}src${file.separator}it${file.separator}java,${project.basedir}${file.separator}src${file.separator}xdocs-examples${file.separator}java' -#additional_source_directories='' -# XXX: We exclude the `CollectorMutability` and the `Immutable*|Preconditions*|StringRules.StringIsNullOrEmpty` Refaster rules -# as they introduce changes that expect Guava to be on the classpath. -#patch_error_prone_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!.*File).*" -patch_error_prone_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*" +# XXX: These don't work... +#patch_error_prone_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*" +patch_error_prone_flags='' validation_error_prone_flags='' validation_build_flags='' diff --git a/integration-tests/run-integration-test.sh b/integration-tests/run-integration-test.sh index 4ccf3ce823..6f01c51a12 100755 --- a/integration-tests/run-integration-test.sh +++ b/integration-tests/run-integration-test.sh @@ -71,7 +71,7 @@ format_goal='com.spotify.fmt:fmt-maven-plugin:2.21.1:format' #error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' #error_prone_shared_flags="-XepExcludedPaths:.*[\\/]resources[\\/].*" -error_prone_shared_flags="" +error_prone_shared_flags="-XepExcludedPaths:.*/target/generated-sources/.*" error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( From 1a543bf8f087a2ae013ff2974f627c8d041b3ea8 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Fri, 15 Nov 2024 10:53:49 +0100 Subject: [PATCH 31/59] More cleanup, less init patch --- .../metrics-expected-warnings.txt | 21 +++++------------- integration-tests/metrics-init.patch | 22 ------------------- 2 files changed, 5 insertions(+), 38 deletions(-) diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index 0007071c9b..57884f7984 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -1,22 +1,11 @@ metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge -metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[164,12] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[169,11] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[175,17] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[200,8] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[203,21] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[206,11] [cast] redundant cast to ByteBuffer -metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[250,36] [cast] redundant cast to ByteBuffer metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[56,27] [this-escape] possible 'this' escape before subclass is fully initialized -metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[40,12] [removal] SecurityManager in java.lang has been deprecated and marked for removal -metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[40,38] [removal] getSecurityManager() in System has been deprecated and marked for removal metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[270,32] [removal] getSecurityManager() in System has been deprecated and marked for removal -metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[270,6] [removal] SecurityManager in java.lang has been deprecated and marked for removal metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java:[40,8] [this-escape] possible 'this' escape before subclass is fully initialized @@ -24,6 +13,9 @@ metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedH metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[14,40] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[15,40] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[16,37] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[160,12] [deprecation] DefaultHttpClientConnectionOperator(Lookup,SchemePortResolver,DnsResolver) in DefaultHttpClientConnectionOperator has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[30,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[31,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated @@ -35,13 +27,10 @@ metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/Instrumente metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type -metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone +metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java:[189,31] [serial] non-transient instance field of a serializable class declared with a non-serializable type metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index b4401ee861..1d027d9548 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -39,19 +39,6 @@ index 195619b..5584f91 100644 protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { try { return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); -diff --git a/metrics-jcstress/pom.xml b/metrics-jcstress/pom.xml -index b02832d..d9be879 100644 ---- a/metrics-jcstress/pom.xml -+++ b/metrics-jcstress/pom.xml -@@ -41,7 +41,7 @@ - -- 1.8 -+ 17 - - -- -- com.google.errorprone -- error_prone_core -- ${errorprone.version} -- -- -- -- -- -- -- -- jdk11 -- -- 11 -- -- -- -- -- org.apache.maven.plugins -- maven-compiler-plugin -- ${maven-compiler-plugin.version} -- -- 1.8 -- 1.8 -- true -- true -- -- -- -- -- - jdk17 - -@@ -218,7 +182,7 @@ + jdk8 +@@ -218,7 +243,7 @@ -Xlint:all -XDcompilePolicy=simple @@ -177,7 +106,7 @@ index 5318dac..709591f 100644 -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED -@@ -230,12 +194,22 @@ +@@ -230,12 +255,22 @@ -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED @@ -201,12 +130,12 @@ index 5318dac..709591f 100644 -@@ -418,7 +392,7 @@ - enforce - - -- -+ - - - +@@ -371,7 +406,7 @@ + + -Xlint:all + -XDcompilePolicy=simple +- -Xplugin:ErrorProne -XepExcludedPaths:.*/target/generated-sources/.* ++ ${error-prone-support.flags} + + + From aacdbc54f522579a6a3b9ce3f79e6834b900b1a0 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Fri, 15 Nov 2024 12:42:39 +0100 Subject: [PATCH 33/59] Drop unnecessary args --- integration-tests/metrics.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 5d70f43da5..c362fe410b 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -7,9 +7,9 @@ project='metrics' repository='https://github.com/dropwizard/metrics.git' revision='v5.0.0-rc22' additional_build_flags='' -additional_source_directories='${project.basedir}${file.separator}src${file.separator}it${file.separator}java,${project.basedir}${file.separator}src${file.separator}xdocs-examples${file.separator}java' +additional_source_directories='' # XXX: These don't work... -#patch_error_prone_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*" +#patch_error_prone_flags='-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*' patch_error_prone_flags='' validation_error_prone_flags='' validation_build_flags='' From 1b9f7354136b76e6d4a885f6a8e74deb5df1a3b9 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Mon, 18 Nov 2024 07:45:07 +0100 Subject: [PATCH 34/59] Update error_prone_shared_flags --- integration-tests/checkstyle.sh | 4 ++-- integration-tests/metrics.sh | 4 ++-- integration-tests/run-integration-test.sh | 7 ++----- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index e38cd21d28..a8e1436a7d 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -9,8 +9,8 @@ revision='checkstyle-10.14.0' # XXX: Configure Renovate to manage the AssertJ version declared here. additional_build_flags='-Perror-prone-compile,error-prone-test-compile -Dassertj.version=3.24.2 -Dmaven.compiler.failOnError=true' additional_source_directories='${project.basedir}${file.separator}src${file.separator}it${file.separator}java,${project.basedir}${file.separator}src${file.separator}xdocs-examples${file.separator}java' -patch_error_prone_flags='' -validation_error_prone_flags='' +patch_error_prone_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' +validation_error_prone_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' # Validation skips some tests: # - The `metadataFilesGenerationAllFiles` test is skipped because it makes line # number assertions that will fail when the code is formatted or patched. diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index c362fe410b..1dcfe8c4cc 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -10,8 +10,8 @@ additional_build_flags='' additional_source_directories='' # XXX: These don't work... #patch_error_prone_flags='-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*' -patch_error_prone_flags='' -validation_error_prone_flags='' +patch_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' +validation_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' validation_build_flags='' if [ "${#}" -gt 2 ] || ([ "${#}" = 2 ] && [ "${1:---sync}" != '--sync' ]); then diff --git a/integration-tests/run-integration-test.sh b/integration-tests/run-integration-test.sh index 19bd082f43..22f475fbaf 100755 --- a/integration-tests/run-integration-test.sh +++ b/integration-tests/run-integration-test.sh @@ -51,7 +51,6 @@ case "$(uname -s)" in ;; esac -# -Perror-prone-compile,error-prone-test-compile shared_build_flags=" -Derror-prone.version=$( mvn -f "${error_prone_support_root}" help:evaluate -Dexpression=version.error-prone -q -DforceStdout @@ -71,7 +70,8 @@ format_goal='com.spotify.fmt:fmt-maven-plugin:2.21.1:format' #error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' #error_prone_shared_flags="-XepExcludedPaths:.*[\\/]resources[\\/].*" -error_prone_shared_flags="-XepExcludedPaths:.*/target/generated-sources/.*" +#error_prone_shared_flags="-XepExcludedPaths:.*/target/generated-sources/.*" +error_prone_shared_flags="" error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( @@ -170,9 +170,6 @@ function apply_patch() { apply_patch '' -echo "RUN ONE MORE FULL --------" -echo "Version $(mvn --version)" -echo "COMMANDO ${shared_build_flags} clean package -Derror-prone.configuration-args=${error_prone_validation_flags}. ${validation_build_flags} " # Run one more full build and log the output. # # By also running the tests, we validate that the (majority of) applied changes From ffcca9c7c6cb5c33d3c0b57a78062a4207eafe7f Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Mon, 18 Nov 2024 16:03:17 +0100 Subject: [PATCH 35/59] Introduce `shared_error_prone_flags` --- integration-tests/checkstyle.sh | 8 +- integration-tests/metrics.sh | 7 +- integration-tests/run-integration-test.sh | 23 +- simple-metrics.txt | 26775 ++++++++++++++++++++ 4 files changed, 26793 insertions(+), 20 deletions(-) create mode 100644 simple-metrics.txt diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index a8e1436a7d..3825904bc9 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -8,9 +8,10 @@ repository='https://github.com/checkstyle/checkstyle.git' revision='checkstyle-10.14.0' # XXX: Configure Renovate to manage the AssertJ version declared here. additional_build_flags='-Perror-prone-compile,error-prone-test-compile -Dassertj.version=3.24.2 -Dmaven.compiler.failOnError=true' -additional_source_directories='${project.basedir}${file.separator}src${file.separator}it${file.separator}java,${project.basedir}${file.separator}src${file.separator}xdocs-examples${file.separator}java' -patch_error_prone_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' -validation_error_prone_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' +additional_source_directories="${project.basedir}${file.separator}src${file.separator}it${file.separator}java,${project.basedir}${file.separator}src${file.separator}xdocs-examples${file.separator}java" +shared_error_prone_flags="-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*" +patch_error_prone_flags='' +validation_error_prone_flags='' # Validation skips some tests: # - The `metadataFilesGenerationAllFiles` test is skipped because it makes line # number assertions that will fail when the code is formatted or patched. @@ -30,6 +31,7 @@ fi "${revision}" \ "${additional_build_flags}" \ "${additional_source_directories}" \ + "${shared_error_prone_flags}" \ "${patch_error_prone_flags}" \ "${validation_error_prone_flags}" \ "${validation_build_flags}" \ diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 1dcfe8c4cc..225f4f3140 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -8,10 +8,10 @@ repository='https://github.com/dropwizard/metrics.git' revision='v5.0.0-rc22' additional_build_flags='' additional_source_directories='' +shared_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' # XXX: These don't work... -#patch_error_prone_flags='-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*' -patch_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' -validation_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' +patch_error_prone_flags='-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*' +validation_error_prone_flags='' validation_build_flags='' if [ "${#}" -gt 2 ] || ([ "${#}" = 2 ] && [ "${1:---sync}" != '--sync' ]); then @@ -26,6 +26,7 @@ fi "${revision}" \ "${additional_build_flags}" \ "${additional_source_directories}" \ + "${shared_error_prone_flags}" \ "${patch_error_prone_flags}" \ "${validation_error_prone_flags}" \ "${validation_build_flags}" \ diff --git a/integration-tests/run-integration-test.sh b/integration-tests/run-integration-test.sh index 22f475fbaf..ccd49db43e 100755 --- a/integration-tests/run-integration-test.sh +++ b/integration-tests/run-integration-test.sh @@ -13,7 +13,7 @@ error_prone_support_root="${integration_test_root}/.." repos_root="${integration_test_root}/.repos" if [ "${#}" -lt 9 ] || [ "${#}" -gt 11 ] || ([ "${#}" = 11 ] && [ "${10:---sync}" != '--sync' ]); then - >&2 echo "Usage: $(basename "${0}") [--sync] []" + >&2 echo "Usage: $(basename "${0}") [--sync] []" exit 1 fi @@ -23,11 +23,12 @@ repository="${3}" revision="${4}" additional_build_flags="${5}" additional_source_directories="${6}" -patch_error_prone_flags="${7}" -validation_error_prone_flags="${8}" -validation_build_flags="${9}" -do_sync="$([ "${#}" = 9 ] || [ "${10:-}" != '--sync' ] || echo 1)" -report_directory="$([ "${#}" = 9 ] || ([ -z "${do_sync}" ] && echo "${10}") || ([ "${#}" = 10 ] || echo "${11}"))" +shared_error_prone_flags="${7}" +patch_error_prone_flags="${8}" +validation_error_prone_flags="${9}" +validation_build_flags="${10}" +do_sync="$([ "${#}" = 10 ] || [ "${11:-}" != '--sync' ] || echo 1)" +report_directory="$([ "${#}" = 10 ] || ([ -z "${do_sync}" ] && echo "${11}") || ([ "${#}" = 11 ] || echo "${12}"))" if [ -n "${report_directory}" ]; then mkdir -p "${report_directory}" @@ -68,13 +69,7 @@ shared_build_flags=" # `shared_build_flags`. format_goal='com.spotify.fmt:fmt-maven-plugin:2.21.1:format' -#error_prone_shared_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' -#error_prone_shared_flags="-XepExcludedPaths:.*[\\/]resources[\\/].*" -#error_prone_shared_flags="-XepExcludedPaths:.*/target/generated-sources/.*" -error_prone_shared_flags="" - - -error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( +error_prone_patch_flags="${shared_error_prone_flags} -XepPatchLocation:IN_PLACE -XepPatchChecks:$( find "${error_prone_support_root}" \ -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" \ -not -path "*/error-prone-experimental/*" \ @@ -84,7 +79,7 @@ error_prone_patch_flags="${error_prone_shared_flags} -XepPatchLocation:IN_PLACE | paste -s -d ',' - ) ${patch_error_prone_flags}" -error_prone_validation_flags="${error_prone_shared_flags} -XepDisableAllChecks $( +error_prone_validation_flags="${shared_error_prone_flags} -XepDisableAllChecks $( find "${error_prone_support_root}" \ -path "*/META-INF/services/com.google.errorprone.bugpatterns.BugChecker" \ -not -path "*/error-prone-experimental/*" \ diff --git a/simple-metrics.txt b/simple-metrics.txt new file mode 100644 index 0000000000..4c9b4099b5 --- /dev/null +++ b/simple-metrics.txt @@ -0,0 +1,26775 @@ +Shared build flags: + -Derror-prone.version=2.35.1 + -Derror-prone-support.version=0.19.2-SNAPSHOT + -DadditionalSourceDirectories= + + +Error Prone patch flags: -XepExcludedPaths:.*/target/generated-sources/.* -XepPatchLocation:IN_PLACE -XepPatchChecks:AmbiguousJsonCreator,AssertJIsNull,AutowiredConstructor,CanonicalAnnotationSyntax,CanonicalClassNameUsage,ClassCastLambdaUsage,CollectorMutability,ConstantNaming,DirectReturn,EmptyMethod,EmptyMonoZip,ExplicitEnumOrdering,FluxFlatMapUsage,FluxImplicitBlock,FormatStringConcatenation,IdentityConversion,ImmutablesSortedSetComparator,IsInstanceLambdaUsage,JUnitClassModifiers,JUnitMethodDeclaration,JUnitNullaryParameterizedTestDeclaration,JUnitValueSource,LexicographicalAnnotationAttributeListing,LexicographicalAnnotationListing,MockitoMockClassReference,MockitoStubbing,MongoDBTextFilterUsage,NestedOptionals,NestedPublishers,NonEmptyMono,NonStaticImport,OptionalOrElseGet,PrimitiveComparison,RedundantStringConversion,RequestMappingAnnotation,RequestParamType,Slf4jLogStatement,Slf4jLoggerDeclaration,SpringMvcAnnotation,StaticImport,StringJoin,TimeZoneUsage,Refaster -Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).* +Error Prone validation flags: -XepExcludedPaths:.*/target/generated-sources/.* -XepDisableAllChecks -Xep:AmbiguousJsonCreator:WARN -Xep:AssertJIsNull:WARN -Xep:AutowiredConstructor:WARN -Xep:CanonicalAnnotationSyntax:WARN -Xep:CanonicalClassNameUsage:WARN -Xep:ClassCastLambdaUsage:WARN -Xep:CollectorMutability:WARN -Xep:ConstantNaming:WARN -Xep:DirectReturn:WARN -Xep:EmptyMethod:WARN -Xep:EmptyMonoZip:WARN -Xep:ExplicitEnumOrdering:WARN -Xep:FluxFlatMapUsage:WARN -Xep:FluxImplicitBlock:WARN -Xep:FormatStringConcatenation:WARN -Xep:IdentityConversion:WARN -Xep:ImmutablesSortedSetComparator:WARN -Xep:IsInstanceLambdaUsage:WARN -Xep:JUnitClassModifiers:WARN -Xep:JUnitMethodDeclaration:WARN -Xep:JUnitNullaryParameterizedTestDeclaration:WARN -Xep:JUnitValueSource:WARN -Xep:LexicographicalAnnotationAttributeListing:WARN -Xep:LexicographicalAnnotationListing:WARN -Xep:MockitoMockClassReference:WARN -Xep:MockitoStubbing:WARN -Xep:MongoDBTextFilterUsage:WARN -Xep:NestedOptionals:WARN -Xep:NestedPublishers:WARN -Xep:NonEmptyMono:WARN -Xep:NonStaticImport:WARN -Xep:OptionalOrElseGet:WARN -Xep:PrimitiveComparison:WARN -Xep:RedundantStringConversion:WARN -Xep:RequestMappingAnnotation:WARN -Xep:RequestParamType:WARN -Xep:Slf4jLogStatement:WARN -Xep:Slf4jLoggerDeclaration:WARN -Xep:SpringMvcAnnotation:WARN -Xep:StaticImport:WARN -Xep:StringJoin:WARN -Xep:TimeZoneUsage:WARN -Xep:Refaster:WARN +~/repos/error-prone-support/integration-tests/.repos/metrics ~/repos/error-prone-support +rick.ossendrijver@gmail.com +Rick Ossendrijver +[detached HEAD d508418] dependency: Introduce Error Prone Support + 5 files changed, 48 insertions(+), 4 deletions(-) +[INFO] Scanning for projects... +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Build Order: +[INFO] +[INFO] Metrics5 Parent [pom] +[INFO] Metrics5 Documentation [jar] +[INFO] Metrics5 BOM [pom] +[INFO] Annotations for Metrics5 [bundle] +[INFO] Metrics5 Core [bundle] +[INFO] Benchmarks for Metrics5 [jar] +[INFO] Metrics Integration for Caffeine 3.x [bundle] +[INFO] Metrics Integration for Collectd [bundle] +[INFO] Metrics Integration for Ehcache [bundle] +[INFO] Graphite Integration for Metrics5 [bundle] +[INFO] InfluxDB integration for Metrics5 [bundle] +[INFO] JVM Integration for Metrics5 [bundle] +[INFO] Metrics5 Health Checks [bundle] +[INFO] Metrics Integration for Apache HttpClient [bundle] +[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] +[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] +[INFO] Metrics Integration for Jakarta Servlets [bundle] +[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] +[INFO] Jackson Integration for Metrics5 [bundle] +[INFO] Metrics Integration for Jetty 11.x and higher [bundle] +[INFO] Metrics5 Utility Jakarta Servlets [bundle] +[INFO] Metrics Integration for JCache [bundle] +[INFO] Metrics Integration for JDBI3 [bundle] +[INFO] Metrics Integration for Jersey 2.x [bundle] +[INFO] Metrics Integration for Jersey 3.0.x [bundle] +[INFO] Metrics Integration for Jersey 3.1.x [bundle] +[INFO] Metrics Integration for Jetty 10.x and higher [bundle] +[INFO] Metrics Integration for Log4j 2.x [bundle] +[INFO] Metrics Integration for Logback 1.3.x [bundle] +[INFO] Metrics Integration for Logback 1.4.x [bundle] +[INFO] Metrics Integration for Logback 1.5.x [bundle] +[INFO] Metrics Integration for Servlets [bundle] +[INFO] Metrics5 Utility Servlets [bundle] +[INFO] Metrics5 JCStress tests [jar] +[INFO] Metrics Integration with JMX [bundle] +[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] +[INFO] Metrics Integration for Jetty 12.x and higher [bundle] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- +[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] +[INFO] from pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- +[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] +[INFO] from docs/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- +[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. +[info] Processed 0 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- +[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] +[INFO] from metrics-bom/pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- +[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] +[INFO] from metrics-annotation/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. +[info] Processed 9 files (9 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- +[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] +[INFO] from metrics-core/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- +[info] Processed 87 files (87 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- +[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] +[INFO] from metrics-benchmarks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. +[info] Processed 5 files (5 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- +[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] +[INFO] from metrics-caffeine3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- +[info] Processed 2 files (2 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- +[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] +[INFO] from metrics-collectd/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- +[info] Processed 12 files (12 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- +[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] +[INFO] from metrics-ehcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- +[info] Processed 4 files (4 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- +[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] +[INFO] from metrics-graphite/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- +[info] Processed 13 files (13 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- +[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] +[INFO] from metrics-influxdb/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- +[info] Processed 8 files (8 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- +[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] +[INFO] from metrics-jvm/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- +[info] Processed 23 files (23 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- +[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] +[INFO] from metrics-healthchecks/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- +[info] Processed 14 files (14 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] +[INFO] from metrics-httpclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- +[info] Processed 8 files (8 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] +[INFO] from metrics-httpclient5/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- +[info] Processed 13 files (13 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- +[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] +[INFO] from metrics-httpasyncclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- +[info] Processed 5 files (5 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] +[INFO] from metrics-jakarta-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- +[info] Processed 4 files (4 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] +[INFO] from metrics-jakarta-servlet6/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- +[info] Processed 4 files (4 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- +[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] +[INFO] from metrics-json/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- +[info] Processed 4 files (4 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- +[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] +[INFO] from metrics-jetty11/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- +[info] Processed 8 files (8 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- +[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] +[INFO] from metrics-jakarta-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- +[info] Processed 17 files (17 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- +[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] +[INFO] from metrics-jcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- +[info] Processed 2 files (2 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- +[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] +[INFO] from metrics-jdbi3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- +[info] Processed 15 files (15 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- +[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] +[INFO] from metrics-jersey2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- +[info] Processed 24 files (24 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- +[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] +[INFO] from metrics-jersey3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- +[info] Processed 24 files (24 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- +[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] +[INFO] from metrics-jersey31/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- +[info] Processed 24 files (24 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- +[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] +[INFO] from metrics-jetty10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- +[info] Processed 8 files (8 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- +[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] +[INFO] from metrics-log4j2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- +[info] Processed 3 files (3 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- +[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] +[INFO] from metrics-logback13/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- +[info] Processed 2 files (2 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- +[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] +[INFO] from metrics-logback14/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- +[info] Processed 2 files (2 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- +[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] +[INFO] from metrics-logback15/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- +[info] Processed 2 files (2 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- +[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] +[INFO] from metrics-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- +[info] Processed 4 files (4 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- +[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] +[INFO] from metrics-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- +[info] Processed 16 files (16 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- +[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] +[INFO] from metrics-jcstress/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. +[info] Processed 3 files (3 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- +[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] +[INFO] from metrics-jmx/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- +[info] Processed 5 files (5 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ +[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] +[INFO] from metrics-legacy-adapter/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- +[info] Processed 60 files (60 reformatted). +[INFO] +[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- +[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] +[INFO] from metrics-legacy-adapter-healthchecks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. +[info] Processed 4 files (4 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] +[INFO] from metrics-jetty12/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- +[info] Processed 5 files (5 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] +[INFO] from metrics-jetty12-ee10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- +[info] Processed 2 files (2 reformatted). +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: +[INFO] +[INFO] Metrics5 Parent .................................... SUCCESS [ 0.130 s] +[INFO] Metrics5 Documentation ............................. SUCCESS [ 0.588 s] +[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.003 s] +[INFO] Annotations for Metrics5 ........................... SUCCESS [ 0.951 s] +[INFO] Metrics5 Core ...................................... SUCCESS [ 1.412 s] +[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 0.835 s] +[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 0.987 s] +[INFO] Metrics Integration for Collectd ................... SUCCESS [ 1.186 s] +[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 1.283 s] +[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 1.226 s] +[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 1.048 s] +[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 1.128 s] +[INFO] Metrics5 Health Checks ............................. SUCCESS [ 1.026 s] +[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 0.934 s] +[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 0.969 s] +[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 0.977 s] +[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 0.883 s] +[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 0.916 s] +[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 1.071 s] +[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 1.007 s] +[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 1.003 s] +[INFO] Metrics Integration for JCache ..................... SUCCESS [ 1.001 s] +[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 0.956 s] +[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 1.021 s] +[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 1.053 s] +[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 1.143 s] +[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 1.029 s] +[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 1.003 s] +[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 0.969 s] +[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 0.954 s] +[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 0.914 s] +[INFO] Metrics Integration for Servlets ................... SUCCESS [ 0.863 s] +[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 0.970 s] +[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 0.877 s] +[INFO] Metrics Integration with JMX ....................... SUCCESS [ 1.028 s] +[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 1.100 s] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 0.845 s] +[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 0.997 s] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 1.008 s] +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 38.095 s +[INFO] Finished at: 2024-11-18T12:45:04+01:00 +[INFO] ------------------------------------------------------------------------ +[detached HEAD b1e8ab8] minor: Reformat using Google Java Format + 445 files changed, 38272 insertions(+), 38032 deletions(-) +[INFO] Scanning for projects... +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Build Order: +[INFO] +[INFO] Metrics5 Parent [pom] +[INFO] Metrics5 Documentation [jar] +[INFO] Metrics5 BOM [pom] +[INFO] Annotations for Metrics5 [bundle] +[INFO] Metrics5 Core [bundle] +[INFO] Benchmarks for Metrics5 [jar] +[INFO] Metrics Integration for Caffeine 3.x [bundle] +[INFO] Metrics Integration for Collectd [bundle] +[INFO] Metrics Integration for Ehcache [bundle] +[INFO] Graphite Integration for Metrics5 [bundle] +[INFO] InfluxDB integration for Metrics5 [bundle] +[INFO] JVM Integration for Metrics5 [bundle] +[INFO] Metrics5 Health Checks [bundle] +[INFO] Metrics Integration for Apache HttpClient [bundle] +[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] +[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] +[INFO] Metrics Integration for Jakarta Servlets [bundle] +[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] +[INFO] Jackson Integration for Metrics5 [bundle] +[INFO] Metrics Integration for Jetty 11.x and higher [bundle] +[INFO] Metrics5 Utility Jakarta Servlets [bundle] +[INFO] Metrics Integration for JCache [bundle] +[INFO] Metrics Integration for JDBI3 [bundle] +[INFO] Metrics Integration for Jersey 2.x [bundle] +[INFO] Metrics Integration for Jersey 3.0.x [bundle] +[INFO] Metrics Integration for Jersey 3.1.x [bundle] +[INFO] Metrics Integration for Jetty 10.x and higher [bundle] +[INFO] Metrics Integration for Log4j 2.x [bundle] +[INFO] Metrics Integration for Logback 1.3.x [bundle] +[INFO] Metrics Integration for Logback 1.4.x [bundle] +[INFO] Metrics Integration for Logback 1.5.x [bundle] +[INFO] Metrics Integration for Servlets [bundle] +[INFO] Metrics5 Utility Servlets [bundle] +[INFO] Metrics5 JCStress tests [jar] +[INFO] Metrics Integration with JMX [bundle] +[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] +[INFO] Metrics Integration for Jetty 12.x and higher [bundle] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- +[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] +[INFO] from pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- +[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] +[INFO] from docs/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec +[INFO] +[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- +[INFO] +[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- +[INFO] Copying 72 resources from source to target/source +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- +[INFO] Copying 72 resources from source to target/classes +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ docs --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/docs-5.0.0-rc22.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- +[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. +[info] Processed 0 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- +[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] +[INFO] from metrics-bom/pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- +[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] +[INFO] from metrics-annotation/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- +[INFO] Recompiling the module because of changed source code. +[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. +[info] Processed 9 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- +[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] +[INFO] from metrics-core/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- +[INFO] Recompiling the module because of changed source code. +[INFO] Compiling 49 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java:[56,53] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'disabledMetricAttributes = ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java:[56,44] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'disabledMetricAttributes = emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[175,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(this.scheduledFuture == null, "Reporter already started");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[144,4] Note: [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#RequireNonNullWithMessageStatement) + Did you mean 'requireNonNull(registry, "registry == null");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[131,28] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'ImmutableSet.of());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[157,90] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'disabledMetricAttributes != null ? disabledMetricAttributes : ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[131,19] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'emptySet());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[157,81] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'disabledMetricAttributes != null ? disabledMetricAttributes : emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[188,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@Deprecated'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[52,27] [this-escape] possible 'this' escape before subclass is fully initialized +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[94,4] Note: [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#RequireNonNullWithMessageStatement) + Did you mean 'requireNonNull(metric, "metric == null");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[256,45] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Histogram;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[662,45] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Histogram;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[216,43] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Counter;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[649,43] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Counter;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[296,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Meter;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[331,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Timer;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[369,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Gauge;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[675,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Meter;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[688,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Timer;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[702,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) + Did you mean 'return metric instanceof Gauge;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[433,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableSortedSet(new TreeSet<>(metrics.keySet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[458,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableSortedMap(timers);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[565,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableSortedMap(timers);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[630,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(metrics);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[97,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(pairs.length % 2 == 0, "Argument count must be even");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[204,36] Note: [Refaster Rule] MapEntryRules.MapEntryComparingByKey: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MapEntryRules#MapEntryComparingByKey) + Did you mean '.sorted(comparingByKey())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[67,35] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean '.filter(s -> !Strings.isNullOrEmpty(s))'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[20,76] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean 'private static final Map EMPTY_TAGS = ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[66,47] Note: [Refaster Rule] StreamRules.StreamOfArray: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StreamRules#StreamOfArray) + Did you mean 'Stream.concat(Stream.of(key), Arrays.stream(parts))'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[20,67] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'private static final Map EMPTY_TAGS = emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[36,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.key = requireNonNull(key);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[68,31] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(joining(SEPARATOR));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[204,26] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.sorted(comparing(Map.Entry::getKey))'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[206,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(sorted);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[182,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(CsvReporter.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java:[20,30] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention + (see https://error-prone.picnic.tech/bugpatterns/ConstantNaming) + Did you mean 'private static final double MAX_TICK_ZERO_TARGET = 0.0001;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java:[22,27] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention + (see https://error-prone.picnic.tech/bugpatterns/ConstantNaming) + Did you mean 'private static final int MAX_TICKS;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java:[67,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), quantile + " is not in [0..1]");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java:[38,32] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'Arrays.sort(copy, comparingLong(w -> w.value));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[238,6] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: " + value);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[44,6] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention + (see https://error-prone.picnic.tech/bugpatterns/ConstantNaming) + Did you mean 'STATE_UPDATER ='? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[56,58] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention + (see https://error-prone.picnic.tech/bugpatterns/ConstantNaming) + Did you mean 'private static final AtomicIntegerFieldUpdater COUNT_UPDATER ='? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[129,15] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'requireNonNull(newValues.pollFirstEntry(), "Expected an entry");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[257,37] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[263,26] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.clock = requireNonNull(value, "clock is required");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[239,31] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean 'return ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[633,33] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'return ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[639,33] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'return ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[645,33] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'return ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[161,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedSet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[167,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[173,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[179,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[185,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[191,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[197,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[203,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[209,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[215,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[221,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[239,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[633,24] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[639,24] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[645,24] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java:[87,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) + Did you mean 'checkState(metricRegistry != null, "Default registry name has not been set.");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java:[7] Note: [NonStaticImport] Member should not be statically imported + (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java:[10] Note: [NonStaticImport] Member should not be statically imported + (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java:[84,58] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'this.disabledMetricAttributes = ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java:[84,49] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.disabledMetricAttributes = emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java:[189,9] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return adder.longValue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java:[50,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), quantile + " is not in [0..1]");'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 38 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[125,6] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatWithFailMessageStringIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatWithFailMessageStringIsTrue) + Did you mean 'assertThat(futures.get(i).get()).withFailMessage("Future " + i + " failed").isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[18] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CachedGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[19,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(CachedGaugeTest.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ChunkedAssociativeLongArrayTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java:[10,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void trim() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java:[7,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ClassMetadataTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java:[9,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void parameterMetadataIsAvailable() throws NoSuchMethodException {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java:[14,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java:[16,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ClockTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ConsoleReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[26,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistry registry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[27,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[77,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[96,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[100,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[141,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[170,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[178,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[242,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[286,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[294,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[352,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[356,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java:[12,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(counter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CounterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[20,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CsvReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[23,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistry registry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[24,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[56,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[66,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[70,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[108,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[116,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[140,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void csvFileProviderIsUsed() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[141,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'CsvFileProvider fileProvider = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[180,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[202,88] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'Files.readAllBytes(new File(dataDirectory, filename).toPath()), UTF_8);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class DefaultSettableGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class DerivativeGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[20,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[24,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[28,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[32,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[36,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[40,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[44,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[48,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[52,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[56,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[60,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[64,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[68,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[72,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[76,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[89,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[93,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[97,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[101,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[105,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[109,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[113,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[117,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[121,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[125,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[129,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[133,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[137,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[141,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[145,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[158,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[162,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[166,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[170,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[174,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[178,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[182,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[186,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[190,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[194,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[198,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[202,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[206,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[210,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[214,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[16,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[85,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[154,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class EWMATest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java:[10,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ExponentialMovingAveragesTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java:[12,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void maxTicks() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java:[13,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java:[14,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ExponentiallyDecayingReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java:[45,34] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableList());' or '.collect(toCollection(ArrayList::new));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java:[45,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toList());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java:[11,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class FixedNameCsvFileProviderTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java:[22,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getFile() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java:[30,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getFileSanitize() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[16,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(histogram.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[17,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(histogram.getSum()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HistogramTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[11,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Reservoir reservoir = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[28,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedExecutorServiceTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[24,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG ='? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[118,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("unchecked")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[183,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void reportsRejectedTasksForThreadPoolExecutor() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[210,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void removesMetricsAfterShutdownForThreadPoolExecutor() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[239,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("unchecked")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[294,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void removesMetricsAfterShutdownForForkJoinPool() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[46,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[60,65] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[75,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[89,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[103,65] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[120,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[134,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[150,65] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[167,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[181,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[197,65] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[216,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[230,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[282,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[47,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[61,60] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[76,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[90,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[104,60] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[121,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[135,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[151,60] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[168,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[182,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[198,60] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[217,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[231,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[283,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[48,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[62,59] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[77,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[91,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[105,59] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[122,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[136,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[152,59] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[169,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[183,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[199,59] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[218,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[232,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[284,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[45,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[59,57] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[74,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[88,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[133,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[149,57] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[166,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[180,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[229,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[267,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[281,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[39,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[42,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[56,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[82,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[85,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[96,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[99,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[112,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[127,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[130,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[146,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[174,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[177,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[190,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[193,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[208,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[223,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[226,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[238,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[260,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[275,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[278,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[290,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[313,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[43,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[57,52] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[86,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[100,52] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[131,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[147,52] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[178,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[194,52] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[227,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[279,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[41,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[69,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[84,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[114,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[129,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[161,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[176,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[210,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[225,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[262,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[277,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[315,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[16] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedScheduledExecutorServiceTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[17,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG ='? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[38,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void submitRunnable() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[81,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void scheduleRunnable() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[126,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void submitCallable() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[173,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void scheduleCallable() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[222,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void scheduleFixedRateCallable() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[274,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void scheduleFixedDelayCallable() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedThreadFactoryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java:[61,18] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getFifteenMinuteRate() * 60.0).isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java:[48,18] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getFiveMinuteRate() * 60.0).isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java:[35,18] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getOneMinuteRate() * 60.0).isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java:[12,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MeterApproximationTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[51,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[33,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[49,51] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[47,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[31,51] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[29,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[27,45] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[45,45] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[23,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[25,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getSum()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MeterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[13,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricFilterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[77,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[68,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[63,87] Note: [Refaster Rule] AssertJMapRules.AbstractMapAssertContainsExactlyInAnyOrderEntriesOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AbstractMapAssertContainsExactlyInAnyOrderEntriesOf) + Did you mean 'assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()).containsExactlyInAnyOrderEntriesOf(refTags);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[91,59] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(b.resolve("key").compareTo(b)).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[92,56] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) + Did you mean 'assertThat(b.compareTo(b.resolve("key"))).isNegative();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[100,56] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) + Did you mean 'assertThat(MetricName.EMPTY.compareTo(a)).isNegative();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[101,56] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) + Did you mean 'assertThat(MetricName.EMPTY.compareTo(b)).isNegative();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[14,4] Note: [Refaster Rule] AssertJStringRules.AbstractStringAssertStringIsEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJStringRules#AbstractStringAssertStringIsEmpty) + Did you mean 'assertThat(MetricName.EMPTY.getKey()).isEmpty();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[55,41] Note: [Refaster Rule] AssertJMapRules.AbstractMapAssertContainsExactlyInAnyOrderEntriesOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AbstractMapAssertContainsExactlyInAnyOrderEntriesOf) + Did you mean 'assertThat(test2.getTags()).containsExactlyInAnyOrderEntriesOf(refTags);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[52,40] Note: [Refaster Rule] AssertJMapRules.AbstractMapAssertContainsExactlyInAnyOrderEntriesOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AbstractMapAssertContainsExactlyInAnyOrderEntriesOf) + Did you mean 'assertThat(test.getTags()).containsExactlyInAnyOrderEntriesOf(refTags);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[90,44] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(b.compareTo(a)).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[103,44] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(b.compareTo(a)).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[89,41] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) + Did you mean 'assertThat(a.compareTo(b)).isNegative();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[102,41] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) + Did you mean 'assertThat(a.compareTo(b)).isNegative();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricNameTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void empty() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[21,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void emptyResolve() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[27,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void resolveToEmpty() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[33,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void resolve() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[39,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void resolveBothEmpty() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[45,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void addTagsVarious() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[59,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void taggedMoreArguments() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[67,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void taggedNotPairs() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[76,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void taggedNotPairs2() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[85,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void compareTo() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[96,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void compareTo2() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricRegistryListenerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[11,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[12,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[13,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[14,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[504,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) + Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[525,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) + Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[551,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) + Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[581,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) + Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[607,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) + Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[636,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) + Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[428,48] Note: [Refaster Rule] AssertJRules.AssertThatSetContainsExactlyOneElement: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetContainsExactlyOneElement) + Did you mean 'assertThat(registry.getNames()).containsExactly(MetricName.build("nested.gauge"));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[562,49] Note: [Refaster Rule] AssertJRules.AssertThatIterableHasSize: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatIterableHasSize) + Did you mean 'assertThat(deepChildMetrics).hasSize(3);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[649,49] Note: [Refaster Rule] AssertJRules.AssertThatIterableHasSize: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatIterableHasSize) + Did you mean 'assertThat(deepChildMetrics).hasSize(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[563,45] Note: [Refaster Rule] AssertJRules.AssertThatIterableHasSize: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatIterableHasSize) + Did you mean 'assertThat(childMetrics).hasSize(5);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[650,45] Note: [Refaster Rule] AssertJRules.AssertThatIterableHasSize: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatIterableHasSize) + Did you mean 'assertThat(childMetrics).hasSize(3);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[18] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricRegistryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[40,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistryListener listener = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[44,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[45,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[46,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[47,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[294,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistryListener other = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[507,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[507,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[528,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[528,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[554,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[554,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[560,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[560,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[584,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[584,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[610,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[610,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[639,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[639,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[645,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[645,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[496,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByNullPointerExceptionHasMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByNullPointerExceptionHasMessage) + Did you mean 'assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)).isInstanceOf(NullPointerException.class).hasMessage("metric == null");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class NoopMetricRegistryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[18,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistryListener listener = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[21,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[22,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[23,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[24,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[223,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("rawtypes")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[245,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistryListener other = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java:[12,42] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) + Did you mean 'assertThat(ratio).hasToString("100.0:200.0");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class RatioGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[205,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[195,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[185,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[110,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) + Did you mean 'Assertions.fail("NullPointerException must be thrown !!!");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[234,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) + Did you mean 'assertThat(customExecutor.isTerminated()).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[241,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsFalse: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsFalse) + Did you mean 'assertThat(mockExecutor.isTerminated()).isFalse();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[242,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsFalse: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsFalse) + Did you mean 'assertThat(mockExecutor.isShutdown()).isFalse();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[148,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockExecutor)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[309,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(reporter)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ScheduledReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[30,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[31,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[32,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[33,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[35,60] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ScheduledExecutorService mockExecutor = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java:[84,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) + Did you mean 'assertThat(exception.getMessage().contains("Default metric registry name is already set.")).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java:[63,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) + Did you mean 'assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java:[31,59] Note: [Refaster Rule] AssertJRules.AssertThatSetContainsExactlyOneElement: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetContainsExactlyOneElement) + Did you mean 'assertThat(SharedMetricRegistries.names()).containsExactly("one");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SharedMetricRegistriesTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SimpleSettableGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[6] Note: [NonStaticImport] Member should not be statically imported + (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class Slf4jReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[25,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Logger logger = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[26,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Marker marker = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[27,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistry registry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[82,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[90,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[107,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[110,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[127,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[137,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[102,55] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(clock.getTick() * 256).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SlidingTimeWindowArrayReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[19,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[33,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[85,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getTickOverflow() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java:[45,62] Note: [Refaster Rule] TimeRules.EpochInstant: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/TimeRules#EpochInstant) + Did you mean 'assertThat(stwm.calculateIndexOfTick(Instant.EPOCH)).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java:[63,79] Note: [Refaster Rule] TimeRules.EpochInstant: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/TimeRules#EpochInstant) + Did you mean 'assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.EPOCH);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SlidingTimeWindowMovingAveragesTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[75,55] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(clock.getTick() * 256).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SlidingTimeWindowReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[15,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[29,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[54,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getTickOverflow() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SlidingWindowReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[41,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[39,51] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[37,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[35,45] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[31,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[46,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[114,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[133,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[140,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[33,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(timer.getSum()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[47,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(timer.getSum()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[115,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(timer.getSum()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[141,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(timer.getSum()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class TimerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[16,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Reservoir reservoir = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[104,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java:[23,59] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNotNegative: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNotNegative) + Did you mean 'assertThat(i).isLessThan(1000).isNotNegative();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class UniformReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java:[8,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("unchecked")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[30,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[39,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[48,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[141,43] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) + Did you mean 'assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n"));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[82,55] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[62,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[67,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[72,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[77,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[161,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[20,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[25,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[57,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[196,53] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) + Did you mean 'assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[189,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) + Did you mean 'assertThat(emptySnapshot.getStdDev()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[182,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) + Did you mean 'assertThat(emptySnapshot.getMean()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[168,45] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(emptySnapshot.getMin()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[175,45] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(emptySnapshot.getMax()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class UniformSnapshotTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[21,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(values.length == weights.length, "Mismatched lengths: " + values.length + " vs " + weights.length);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[49,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[58,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[67,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[150,43] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) + Did you mean 'assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n"));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[101,55] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[81,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[86,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[91,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[96,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[170,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[39,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[44,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[76,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[210,53] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) + Did you mean 'assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[202,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) + Did you mean 'assertThat(emptySnapshot.getStdDev()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[194,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) + Did you mean 'assertThat(emptySnapshot.getMean()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[178,45] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(emptySnapshot.getMin()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[186,45] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(emptySnapshot.getMax()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class WeightedSnapshotTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[121,33] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.toArray(any(WeightedSample[].class));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[136,33] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.toArray(any(WeightedSample[].class));'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- +[info] Processed 87 files (22 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- +[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] +[INFO] from metrics-benchmarks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java:[45,13] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return slidingTime.getSnapshot();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java:[61,13] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return arrTime.getSnapshot();'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22.jar +[INFO] +[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. +[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. +[info] Processed 5 files (1 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- +[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] +[INFO] from metrics-caffeine3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- +[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] +[INFO] from metrics-collectd/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[311,57] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[7] Note: [NonStaticImport] Member should not be statically imported + (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[10] Note: [NonStaticImport] Member should not be statically imported + (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[153,8] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(!username.isEmpty(), "username is required for securityLevel: " + securityLevel);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[157,8] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(!password.isEmpty(), "password is required for securityLevel: " + securityLevel);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[84,80] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'private Set disabledMetricAttributes = ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[84,71] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'private Set disabledMetricAttributes = emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[305,14] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean 'LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java:[22,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) + Did you mean 'checkState(!isConnected(), "Already connected");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[239,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) + Did you mean 'checkState(iv.length == IV_LENGTH, "Bad initialization vector");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[264,6] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) + Did you mean 'checkState(output.length == SHA1_LENGTH, "Bad SHA1 hash");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[122,36] Note: [Refaster Rule] StringRules.StringIsEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsEmpty) + Did you mean 'if (val == null || val.isEmpty()) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[67,73] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.username = username != null ? username.getBytes(UTF_8) : null;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[68,73] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.password = password != null ? password.getBytes(UTF_8) : null;'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[127,44] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'buffer.put(val.getBytes(US_ASCII)).put(NULL);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[22,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalArgumentExceptionHasMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalArgumentExceptionHasMessage) + Did you mean 'assertThatThrownBy(() ->'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[35,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalArgumentExceptionHasMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalArgumentExceptionHasMessage) + Did you mean 'assertThatThrownBy(() ->'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CollectdReporterSecurityTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[13,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void unableSetSecurityLevelToSignWithoutUsername() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[26,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void unableSetSecurityLevelToSignWithoutPassword() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[248,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalArgumentExceptionHasMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalArgumentExceptionHasMessage) + Did you mean 'assertThatThrownBy(() ->'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[261,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalArgumentExceptionHasMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalArgumentExceptionHasMessage) + Did you mean 'assertThatThrownBy(() ->'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[269,59] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf1: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf1) + Did you mean 'final Map map = ImmutableMap.of(name, metric);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[292,52] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) + Did you mean 'return valueList == null ? ImmutableList.of() : valueList.getValues();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[28,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CollectdReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[99,26] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[114,22] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[133,30] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[134,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[157,22] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[158,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[198,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[205,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[239,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void unableSetSecurityLevelToSignWithoutUsername() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[252,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void unableSetSecurityLevelToSignWithoutPassword() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[265,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySortedMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[269,46] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'final Map map = singletonMap(name, metric);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[292,42] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return valueList == null ? emptyList() : valueList.getValues();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java:[193,75] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class PacketWriterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java:[31,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void signRequest() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java:[77,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void encryptRequest() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SanitizeTest {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- +[info] Processed 12 files (4 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- +[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] +[INFO] from metrics-ehcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedCacheDecoratorFactoryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java:[16] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedEhcacheTest {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- +[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] +[INFO] from metrics-graphite/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[66,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(hostname != null && !hostname.isEmpty(), "hostname must not be null or empty");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[70,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(port >= 0 && port <= 65535, "port must be a valid IP port (0-65535)");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[119,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) + Did you mean 'checkState(!isConnected(), "Already connected");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[32,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(Graphite.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java:[112,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) + Did you mean 'checkState(!isConnected(), "Already connected");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java:[136,53] Note: [RedundantStringConversion] Avoid redundant string conversions when possible + (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) + Did you mean 'sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n';'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[7] Note: [NonStaticImport] Member should not be statically imported + (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[10] Note: [NonStaticImport] Member should not be statically imported + (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[88,58] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'this.disabledMetricAttributes = ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[88,49] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.disabledMetricAttributes = emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[252,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(GraphiteReporter.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[433,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[438,19] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[451,20] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java:[46,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) + Did you mean 'checkState(!isConnected(), "Already connected");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java:[66,64] Note: [RedundantStringConversion] Avoid redundant string conversions when possible + (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) + Did you mean 'String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n';'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java:[176,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) + Did you mean 'checkState(!isConnected(), "Already connected");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java:[252,23] Note: [Refaster Rule] CollectionRules.CollectionIsEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/CollectionRules#CollectionIsEmpty) + Did you mean 'if (!metrics.isEmpty()) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java:[51,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(PickledGraphite.class);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[98,45] Note: [Refaster Rule] AssertJIntegerRules.AbstractIntegerAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJIntegerRules#AbstractIntegerAssertIsZero) + Did you mean 'assertThat(graphite.getFailures()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[111,45] Note: [Refaster Rule] AssertJIntegerRules.AbstractIntegerAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJIntegerRules#AbstractIntegerAssertIsZero) + Did you mean 'assertThat(graphite.getFailures()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[95,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(channel)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[108,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(channel)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class GraphiteRabbitMQTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[24,58] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ConnectionFactory connectionFactory = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[25,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Connection connection = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[26,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Channel channel = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[28,63] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ConnectionFactory bogusConnectionFactory = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[29,49] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Connection bogusConnection = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[30,43] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Channel bogusChannel = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[182,58] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[479,28] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'ImmutableSet.of(),'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[495,54] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[52,56] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[62,56] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[36] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class GraphiteReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[42,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[43,40] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Graphite graphite = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[44,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistry registry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[52,47] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.disabledMetricAttributes(emptySet())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[62,47] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.disabledMetricAttributes(emptySet())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[182,49] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.disabledMetricAttributes(emptySet())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[225,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[241,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[245,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[283,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[309,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[336,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[344,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[413,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[421,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[453,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[479,19] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'emptySet(),'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[495,45] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.disabledMetricAttributes(emptySet())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java:[6] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class GraphiteSanitizeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[87,47] Note: [Refaster Rule] AssertJIntegerRules.AbstractIntegerAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJIntegerRules#AbstractIntegerAssertIsZero) + Did you mean 'assertThat(graphite.getFailures()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[26] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class GraphiteTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[29,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final SocketFactory socketFactory = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[32,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Socket socket = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[33,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ByteArrayOutputStream output = spy();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class GraphiteUDPTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java:[33,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'DatagramChannel mockDatagramChannel = Mockito.mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java:[33,49] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'DatagramChannel mockDatagramChannel = mock(DatagramChannel.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java:[34] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class PickledGraphiteTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java:[35,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final SocketFactory socketFactory = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java:[39,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Socket socket = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java:[40,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ByteArrayOutputStream output = spy();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- +[info] Processed 13 files (5 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- +[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] +[INFO] from metrics-influxdb/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[81,58] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'this.disabledMetricAttributes = ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[81,49] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.disabledMetricAttributes = emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[199,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(InfluxDbReporter.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,19] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java:[45,26] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.address = requireNonNull(address);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InfluxDbLineBuilderAssumptionsTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[56,56] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[66,56] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[39] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InfluxDbReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[45,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[46,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final InfluxDbSender sender = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[48,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistry registry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[56,47] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.disabledMetricAttributes(emptySet())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[66,47] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.disabledMetricAttributes(emptySet())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[200,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[217,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[221,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[252,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[277,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[303,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[311,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[363,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[371,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java:[19] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InfluxDbUdpTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java:[25,62] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final DatagramChannel datagramChannel = Mockito.mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java:[25,57] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'private final DatagramChannel datagramChannel = mock(DatagramChannel.class);'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- +[info] Processed 8 files (4 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- +[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] +[INFO] from metrics-jvm/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 12 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java:[22,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(BufferPoolMetricSet.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java:[50,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(gauges);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java:[62,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(gauges);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[56,31] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'return ImmutableSet.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[43,44] Note: [RedundantStringConversion] Avoid redundant string conversions when possible + (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) + Did you mean 'stackTrace.append("\t at ").append(element).append(String.format("%n"));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[47,25] Note: [RedundantStringConversion] Avoid redundant string conversions when possible + (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) + Did you mean 'stackTrace));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[54,24] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableSet(deadlocks);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[56,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return emptySet();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java:[46,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(gauges);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java:[50,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(gauges);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java:[142,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(gauges);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[74,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[83,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[92,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[16] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class BufferPoolMetricSetTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[27,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MBeanServer mBeanServer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ClassLoadingGaugeSetTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java:[16,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ClassLoadingMXBean cl = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java:[21,44] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat((double) clockTick).isCloseTo(systemTick, offset(1000000.0));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java:[17,44] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat((double) clockTime).isCloseTo(systemTime, offset(200.0));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CpuTimeClockTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[37,31] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNotNegative: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNotNegative) + Did you mean 'Assertions.assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class FileDescriptorRatioGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[16,51] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final UnixOperatingSystemMXBean os = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[28,14] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(gauge.getValue()).isEqualTo(0.1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[36,14] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(new FileDescriptorRatioGauge().getValue())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[43,14] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[49,80] Note: [Refaster Rule] AssertJMapRules.AssertThatMapIsNotEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AssertThatMapIsNotEmpty) + Did you mean 'assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[18,61] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf1: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf1) + Did you mean 'new GarbageCollectorMetricSet(ImmutableList.of(gc));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class GarbageCollectorMetricSetTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[16,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final GarbageCollectorMXBean gc = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[18,47] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'new GarbageCollectorMetricSet(singletonList(gc));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java:[56,56] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat((Integer) gauge.getValue()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java:[16] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class JmxAttributeGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class JvmAttributeGaugeSetTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java:[15,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final RuntimeMXBean runtime = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[299,74] Note: [Refaster Rule] AssertJMapRules.AssertThatMapIsNotEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AssertThatMapIsNotEmpty) + Did you mean 'assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MemoryUsageGaugeSetTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[18,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MemoryUsage heap = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[19,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MemoryUsage nonHeap = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[20,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MemoryUsage pool = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[21,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MemoryUsage weirdPool = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[22,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MemoryUsage weirdCollection = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[23,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MemoryMXBean mxBean = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[24,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MemoryPoolMXBean memoryPool = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[25,55] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MemoryPoolMXBean weirdMemoryPool = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[162,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[241,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ThreadDeadlockDetectorTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java:[15,43] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadMXBean threads = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java:[27,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ThreadInfo thread1 = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java:[38,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ThreadInfo thread2 = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java:[43,18] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) + Did you mean 'assertThat(output).hasToString(String.format('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ThreadDumpTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java:[18,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadMXBean threadMXBean = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java:[21,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadInfo runnable = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ThreadStatesGaugeSetTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[18,43] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadMXBean threads = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[19,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadDeadlockDetector detector = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[23,43] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadInfo newThread = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[24,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadInfo runnableThread = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[25,47] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadInfo blockedThread = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[26,47] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadInfo waitingThread = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[27,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadInfo timedWaitingThread = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[28,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ThreadInfo terminatedThread = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[90,14] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1);'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- +[info] Processed 23 files (10 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- +[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] +[INFO] from metrics-healthchecks/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java:[80,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(expression, message);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java:[35,44] Note: [Refaster Rule] EqualityRules.EnumReferenceEquality: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/EqualityRules#EnumReferenceEquality) + Did you mean 'if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java:[32,41] Note: [Refaster Rule] EqualityRules.EnumReferenceEquality: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/EqualityRules#EnumReferenceEquality) + Did you mean 'Async.InitialState.HEALTHY == async.initialState()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java:[165,59] Note: [Refaster Rule] TimeRules.InstantAtZone: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/TimeRules#InstantAtZone) + Did you mean 'ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java:[126,57] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.details = details == null ? null : unmodifiableMap(details);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java:[221,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return PRIME * result + (Long.hashCode(time));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java:[240,55] Note: [RedundantStringConversion] Avoid redundant string conversions when possible + (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) + Did you mean 'builder.append(e.getKey()).append("=").append(e.getValue());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[95,6] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(!healthChecks.containsKey(name), "A health check named " + name + " already exists");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[30,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(HealthCheckRegistry.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[131,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[183,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableSortedMap(results);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[225,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableSortedMap(results);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[85,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[67,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[76,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[58,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[40,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[49,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[100,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockExecutorService)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[112,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockExecutorService)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[139,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockExecutorService)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[158,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockExecutorService)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[181,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockExecutorService)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[198,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockExecutorService)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[217,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockExecutorService)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[235,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockExecutorService)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[141,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(mockFuture).cancel(eq(true));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[19] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class AsyncHealthCheckDecoratorTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[32,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final HealthCheck mockHealthCheck = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[33,67] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ScheduledExecutorService mockExecutorService = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[36,49] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ScheduledFuture mockFuture = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[127,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("unchecked")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[141,39] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'verify(mockFuture, times(1)).cancel(true);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[144,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("unchecked")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[168,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("unchecked")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HealthCheckFilterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[77,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[26] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HealthCheckRegistryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[27,63] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ScheduledExecutorService executorService = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[29,59] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final HealthCheckRegistryListener listener = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[31,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final HealthCheck hc1 = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[32,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final HealthCheck hc2 = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[34,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final HealthCheck.Result r1 = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[35,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final HealthCheck.Result r2 = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[37,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final HealthCheck.Result ar = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[41,41] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ScheduledFuture af = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[104,47] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'HealthCheckRegistryListener listener = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[118,47] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'HealthCheckRegistryListener listener = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[184,59] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNotNegative: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNotNegative) + Did you mean 'assertThat(actual.getDuration()).isNotNegative();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HealthCheckTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[32,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final HealthCheck underlying = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[92,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final RuntimeException e = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[147,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final RuntimeException e = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[164,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final HealthCheck.Result result = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[174,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final RuntimeException e = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[88,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) + Did you mean 'assertThat(exception.getMessage().contains("Default health check registry is already set.")).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[100,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) + Did you mean 'assertThat(exception.getMessage().contains("Default health check registry is already set.")).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[61,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) + Did you mean 'assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[31,64] Note: [Refaster Rule] AssertJRules.AssertThatSetContainsExactlyOneElement: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetContainsExactlyOneElement) + Did you mean 'assertThat(SharedHealthCheckRegistries.names()).containsExactly("db");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SharedHealthCheckRegistriesTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[21,73] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) + Did you mean 'when(detector.getDeadlockedThreads()).thenReturn(ImmutableSet.of());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ThreadDeadlockHealthCheckTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[18,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ThreadDeadlockDetector detector = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[21,64] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'when(detector.getDeadlockedThreads()).thenReturn(emptySet());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[23,14] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(healthCheck.execute().isHealthy()).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[32,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ThreadDeadlockDetector detector = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[47,14] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(healthCheck.execute().isHealthy()).isTrue();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- +[info] Processed 14 files (6 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] +[INFO] from metrics-httpclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java:[114,8] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HttpClientMetricNameStrategiesTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[50,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) + Did you mean 'assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHttpClientConnectionManagerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[40,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistry registry = Mockito.mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[40,43] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'final MetricRegistry registry = mock(MetricRegistry.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[49,11] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[49,36] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'Mockito.verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[70,10] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) + Did you mean 'Assertions.fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHttpClientsTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[27,10] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[28,62] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistryListener registryListener = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- +[info] Processed 8 files (2 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] +[INFO] from metrics-httpclient5/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[14,40] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[15,40] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[16,37] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[30,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[31,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[32,37] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[33,38] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[96,21] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[160,12] [deprecation] DefaultHttpClientConnectionOperator(Lookup,SchemePortResolver,DnsResolver) in DefaultHttpClientConnectionOperator has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java:[49,4] [deprecation] HttpRequestExecutor(Timeout,ConnectionReuseStrategy,Http1StreamListener) in HttpRequestExecutor has been deprecated +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[47,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[69,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java:[19] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HttpClientMetricNameStrategiesTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[57,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) + Did you mean 'assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedAsyncClientConnectionManagerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[47,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistry registry = Mockito.mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[47,43] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'final MetricRegistry registry = mock(MetricRegistry.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[56,11] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[56,36] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'Mockito.verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[104,20] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) + Did you mean 'Assertions.fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[109,20] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) + Did you mean 'Assertions.fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[147,22] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) + Did you mean 'Assertions.fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[157,22] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) + Did you mean 'Assertions.fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[163,10] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) + Did you mean 'Assertions.fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[214,22] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) + Did you mean 'Assertions.fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[219,22] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) + Did you mean 'Assertions.fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[42] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHttpAsyncClientsTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[86,75] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'exchange.getResponseBody().write("TEST".getBytes(US_ASCII));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[196,77] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'exchange.getResponseBody().write("TEST".getBytes(US_ASCII));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[55,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) + Did you mean 'assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHttpClientConnectionManagerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[45,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistry registry = Mockito.mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[45,43] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'final MetricRegistry registry = mock(MetricRegistry.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[54,11] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[54,36] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'Mockito.verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[70,10] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) + Did you mean 'Assertions.fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHttpClientsTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[27,10] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[28,62] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistryListener registryListener = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- +[info] Processed 13 files (4 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- +[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] +[INFO] from metrics-httpasyncclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java:[40,8] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHttpClientsTest extends HttpClientTestBase {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[121,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) + Did you mean 'Assertions.fail("This should fail as the client should not be able to connect");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[32] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHttpClientsTimerTest extends HttpClientTestBase {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[49,22] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[75,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("unchecked")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[81,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'FutureCallback futureCallback = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[102,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("unchecked")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[109,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'FutureCallback futureCallback = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- +[info] Processed 5 files (1 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] +[INFO] from metrics-jakarta-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java:[67,27] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean 'if (Strings.isNullOrEmpty(metricName)) {'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedFilterContextListenerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[13,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistry registry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[24,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext context = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[26,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContextEvent event = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] +[INFO] from metrics-jakarta-servlet6/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java:[67,27] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean 'if (Strings.isNullOrEmpty(metricName)) {'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedFilterContextListenerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java:[13,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistry registry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java:[24,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext context = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java:[26,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContextEvent event = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- +[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] +[INFO] from metrics-json/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java:[189,31] [serial] non-transient instance field of a serializable class declared with a non-serializable type +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java:[83,55] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf1: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf1) + Did you mean 'new SimpleSerializers(ImmutableList.of(new HealthCheckResultSerializer())));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java:[83,41] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'new SimpleSerializers(singletonList(new HealthCheckResultSerializer())));'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[13] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HealthCheckModuleTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[20,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[28,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[43,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[62,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[90,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[131,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", result.getTimestamp());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[19] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricsModuleTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[45,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[53,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[56,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[110,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[130,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[137,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot snapshot = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- +[info] Processed 4 files (2 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- +[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] +[INFO] from metrics-jetty11/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[256,44] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) + Did you mean 'this.responses = ImmutableList.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[176,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean ': ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[176,25] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[191,21] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'unmodifiableList('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[256,34] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.responses = emptyList();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[146,35] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) + Did you mean ': ImmutableList.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[135,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean ': ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[135,25] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[138,25] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '? unmodifiableList('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[146,25] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyList();'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java:[24] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedConnectionFactoryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[161,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[165,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()).isPositive()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[153,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[31] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHandlerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[121,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[131,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[140,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@Disabled("flaky on virtual machines")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[228,91] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '"some content from the async\n".getBytes(UTF_8));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHttpChannelListenerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java:[191,89] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '"some content from the async".getBytes(UTF_8));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedQueuedThreadPoolTest {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- +[info] Processed 8 files (4 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- +[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] +[INFO] from metrics-jakarta-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java:[102,13] Note: [Refaster Rule] NullRules.IsNull: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/NullRules#IsNull) + Did you mean 'if (registry == null) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java:[134,13] Note: [Refaster Rule] NullRules.IsNull: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/NullRules#IsNull) + Did you mean 'if (registry == null) {'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class AdminServletExclusionTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class AdminServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class AdminServletUriTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CpuProfileServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[231,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[225,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[208,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletConfig).getServletContext();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[224,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletConfig).getServletContext();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[30] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HealthCheckServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[32,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[97,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", EXPECTED_TIMESTAMP);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[113,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", EXPECTED_TIMESTAMP);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[170,25] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", EXPECTED_TIMESTAMP));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[200,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final HealthCheckRegistry healthCheckRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[201,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[202,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[214,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final HealthCheckRegistry healthCheckRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[215,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[216,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[234,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[235,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[248,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[249,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricsServletContextListenerTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java:[21,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[258,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[252,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletContext).getAttribute(eq(MetricsServlet.METRICS_REGISTRY));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[235,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletConfig).getServletContext();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[251,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletConfig).getServletContext();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricsServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[29,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[132,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", callbackParamVal);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[227,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistry metricRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[228,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[229,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[236,48] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[241,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistry metricRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[242,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[243,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[245,36] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[252,49] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'verify(servletContext, times(1)).getAttribute(MetricsServlet.METRICS_REGISTRY);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[261,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[262,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[264,42] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class PingServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ThreadDumpServletTest extends AbstractServletTest {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- +[info] Processed 17 files (2 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- +[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] +[INFO] from metrics-jcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java:[36,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(JCacheGaugeSet.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java:[55,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(gauges);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[74,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat((Float) registry.getGauges().get(myCache.resolve("average-remove-time")).getValue()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[70,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat((Float) registry.getGauges().get(myCache.resolve("average-get-time")).getValue()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[72,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat((Float) registry.getGauges().get(myCache.resolve("average-put-time")).getValue()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class JCacheGaugeSetTest {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- +[info] Processed 2 files (2 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- +[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] +[INFO] from metrics-jdbi3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java:[16,28] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean 'return Strings.isNullOrEmpty(rawSql) ? MetricName.build("sql.empty") : null;'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class BasicSqlNameStrategyTest extends AbstractStrategyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedSqlLoggerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[18,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistry mockRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[19,55] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final StatementNameStrategy mockNameStrategy = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[22,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final StatementContext mockContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[23,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Timer mockTimer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[40,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistry mockRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[41,55] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final StatementNameStrategy mockNameStrategy = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[44,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final StatementContext mockContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[45,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Timer mockTimer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class NaiveNameStrategyTest extends AbstractStrategyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SmartNameStrategyTest extends AbstractStrategyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class TimedAnnotationNameStrategyTest extends AbstractStrategyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[47,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void annotationOnMethod() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[57,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void annotationOnMethodWithCustomName() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[67,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void annotationOnMethodWithCustomAbsoluteName() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[75,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void annotationOnClass() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[85,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void annotationOnMethodAndClassWithCustomNames() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[94,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void noAnnotations() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[101,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void noMethod() {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- +[info] Processed 15 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- +[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] +[INFO] from metrics-jersey2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[310,50] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) + Did you mean '&& metric.cause.isInstance(event.getException().getCause()))) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[308,43] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) + Did you mean 'if (metric.cause.isInstance(event.getException())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[546,29] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean 'if (!Strings.isNullOrEmpty(explicitName)) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[170,37] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) + Did you mean ': ImmutableList.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[174,36] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean ': ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[162,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '? unmodifiableList('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[170,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyList();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[174,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[421,31] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return new ChainedRequestEventListener('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[607,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return 31 * result + method.hashCode();'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CustomReservoirImplementationTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonFilterMetricsJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java:[37,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(new InstrumentedFilteredResource(testClock));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[53,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[78,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[37,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResourceExceptionMeteredPerClass.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[95,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[98,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter4xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[101,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter5xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[70,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[27] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[40,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResource.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[110,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void resourceNotFound() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java:[34,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResourceMeteredPerClass.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[112,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) + Did you mean 'Assertions.fail("expected RuntimeException");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[37,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(new TestExceptionMapper());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java:[34,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResourceTimedPerClass.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java:[20,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java:[28,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java:[36,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java:[52,4] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[23,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[37,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@ExceptionMetered(cause = IOException.class)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[48,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[56,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[64,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[72,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[79,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[86,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java:[12,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- +[info] Processed 24 files (7 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- +[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] +[INFO] from metrics-jersey3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[311,50] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) + Did you mean '&& metric.cause.isInstance(event.getException().getCause()))) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[309,43] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) + Did you mean 'if (metric.cause.isInstance(event.getException())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[547,29] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean 'if (!Strings.isNullOrEmpty(explicitName)) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[171,37] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) + Did you mean ': ImmutableList.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[175,36] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean ': ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[163,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '? unmodifiableList('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[171,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyList();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[175,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[422,31] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return new ChainedRequestEventListener('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[605,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return 31 * result + method.hashCode();'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CustomReservoirImplementationTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonFilterMetricsJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(new InstrumentedFilteredResource(testClock));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[54,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[79,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[24] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResourceExceptionMeteredPerClass.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[92,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[95,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter4xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[98,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter5xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[118,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[119,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[120,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter201.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[130,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[142,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[143,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[131,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[132,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter201.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[146,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[147,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[70,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[41,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResource.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[136,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void responseMeteredMethodsAreMeteredWithAllLevel() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[151,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void resourceNotFound() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java:[35,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResourceMeteredPerClass.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[143,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[144,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[157,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[158,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[113,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) + Did you mean 'Assertions.fail("expected RuntimeException");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(new TestExceptionMapper());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java:[35,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResourceTimedPerClass.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java:[20,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java:[28,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java:[36,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java:[52,4] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[23,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[37,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@ExceptionMetered(cause = IOException.class)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[48,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[56,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[64,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[72,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[79,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[86,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java:[12,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- +[info] Processed 24 files (7 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- +[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] +[INFO] from metrics-jersey31/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[311,50] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) + Did you mean '&& metric.cause.isInstance(event.getException().getCause()))) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[309,43] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) + Did you mean 'if (metric.cause.isInstance(event.getException())'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[547,29] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean 'if (!Strings.isNullOrEmpty(explicitName)) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[171,37] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) + Did you mean ': ImmutableList.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[175,36] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean ': ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[163,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '? unmodifiableList('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[171,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyList();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[175,27] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[422,31] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return new ChainedRequestEventListener('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[605,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return 31 * result + method.hashCode();'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CustomReservoirImplementationTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonFilterMetricsJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(new InstrumentedFilteredResource(testClock));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[54,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[79,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[24] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResourceExceptionMeteredPerClass.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[92,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[95,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter4xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[98,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter5xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[109,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[110,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[114,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[129,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[130,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[131,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter201.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[141,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[153,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[154,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[113,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[142,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[143,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter201.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[157,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[158,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[70,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[41,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResource.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[103,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void responseMeteredMethodsAreMeteredWithCoarseLevel() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[118,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void responseMeteredMethodsAreMeteredWithDetailedLevel() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[147,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void responseMeteredMethodsAreMeteredWithAllLevel() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[162,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void resourceNotFound() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java:[35,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResourceMeteredPerClass.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[143,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[144,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[149,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[150,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) + Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[113,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) + Did you mean 'Assertions.fail("expected RuntimeException");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(new TestExceptionMapper());'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java:[35,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return config.register(InstrumentedResourceTimedPerClass.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java:[20,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java:[28,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java:[36,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java:[52,4] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[23,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[37,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@ExceptionMetered(cause = IOException.class)'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[48,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[56,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[64,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[72,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[79,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[86,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java:[12,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@GET'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- +[info] Processed 24 files (7 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- +[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] +[INFO] from metrics-jetty10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[256,44] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) + Did you mean 'this.responses = ImmutableList.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[176,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean ': ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[176,25] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[191,21] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'unmodifiableList('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[256,34] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.responses = emptyList();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[146,35] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) + Did you mean ': ImmutableList.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[135,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean ': ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[135,25] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[138,25] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '? unmodifiableList('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[146,25] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyList();'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java:[24] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedConnectionFactoryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[161,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[165,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()).isPositive()'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[153,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[31] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHandlerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[121,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[131,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[140,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@Disabled("flaky on virtual machines")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[228,91] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '"some content from the async\n".getBytes(UTF_8));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedHttpChannelListenerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java:[191,89] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '"some content from the async".getBytes(UTF_8));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedQueuedThreadPoolTest {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- +[info] Processed 8 files (4 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- +[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] +[INFO] from metrics-log4j2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/apache/logging/log4j/log4j-core/2.24.1/log4j-core-2.24.1.jar(/org/apache/logging/log4j/core/LoggerContext.class): warning: Cannot find annotation method 'value()' in type 'SuppressFBWarnings': class file for edu.umd.cs.findbugs.annotations.SuppressFBWarnings not found +/home/rick/.m2/repository/org/apache/logging/log4j/log4j-core/2.24.1/log4j-core-2.24.1.jar(/org/apache/logging/log4j/core/LoggerContext.class): warning: Cannot find annotation method 'justification()' in type 'SuppressFBWarnings' +/home/rick/.m2/repository/org/apache/logging/log4j/log4j-core/2.24.1/log4j-core-2.24.1.jar(/org/apache/logging/log4j/core/config/ConfigurationSource.class): warning: Cannot find annotation method 'value()' in type 'SuppressFBWarnings' +/home/rick/.m2/repository/org/apache/logging/log4j/log4j-core/2.24.1/log4j-core-2.24.1.jar(/org/apache/logging/log4j/core/config/ConfigurationSource.class): warning: Cannot find annotation method 'justification()' in type 'SuppressFBWarnings' +/home/rick/.m2/repository/org/apache/logging/log4j/log4j-api/2.24.1/log4j-api-2.24.1.jar(/org/apache/logging/log4j/Level.class): warning: Cannot find annotation method 'value()' in type 'BaselineIgnore': class file for aQute.bnd.annotation.baseline.BaselineIgnore not found +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedAppenderConfigTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedAppenderTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java:[21,37] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final LogEvent event = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- +[info] Processed 3 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- +[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] +[INFO] from metrics-logback13/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedAppenderTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java:[21,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ILoggingEvent event = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- +[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] +[INFO] from metrics-logback14/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedAppenderTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java:[21,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ILoggingEvent event = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- +[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] +[INFO] from metrics-logback15/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedAppenderTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java:[21,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ILoggingEvent event = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- +[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] +[INFO] from metrics-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java:[67,27] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean 'if (Strings.isNullOrEmpty(metricName)) {'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedFilterContextListenerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[13,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final MetricRegistry registry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[24,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext context = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[26,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContextEvent event = mock();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- +[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] +[INFO] from metrics-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java:[102,13] Note: [Refaster Rule] NullRules.IsNull: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/NullRules#IsNull) + Did you mean 'if (registry == null) {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java:[134,13] Note: [Refaster Rule] NullRules.IsNull: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/NullRules#IsNull) + Did you mean 'if (registry == null) {'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 10 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class AdminServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class AdminServletUriTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CpuProfileServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[231,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[225,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[208,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletConfig).getServletContext();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[224,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletConfig).getServletContext();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[30] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HealthCheckServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[32,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[97,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", EXPECTED_TIMESTAMP);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[113,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", EXPECTED_TIMESTAMP);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[170,25] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", EXPECTED_TIMESTAMP));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[200,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final HealthCheckRegistry healthCheckRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[201,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[202,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[214,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final HealthCheckRegistry healthCheckRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[215,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[216,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[234,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[235,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[248,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[249,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricsServletContextListenerTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java:[21,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[258,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) + Did you mean 'assertThatThrownBy(() -> {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[252,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletContext).getAttribute(eq(MetricsServlet.METRICS_REGISTRY));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[235,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletConfig).getServletContext();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[251,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) + Did you mean 'verify(servletConfig).getServletContext();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricsServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[29,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Clock clock = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[132,18] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", callbackParamVal);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[227,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistry metricRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[228,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[229,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[236,48] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[241,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final MetricRegistry metricRegistry = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[242,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[243,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[245,36] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[252,49] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'verify(servletContext, times(1)).getAttribute(MetricsServlet.METRICS_REGISTRY);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[261,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[262,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[264,42] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class PingServletTest extends AbstractServletTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ThreadDumpServletTest extends AbstractServletTest {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- +[info] Processed 16 files (2 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- +[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] +[INFO] from metrics-jcstress/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22.jar +[INFO] +[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. +[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. +[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: +[WARNING] - META-INF/AL2.0 +[WARNING] - META-INF/LGPL2.1 +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. +[info] Processed 3 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- +[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] +[INFO] from metrics-jmx/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java:[13,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectNameFactory.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java:[41,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly + (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) + Did you mean 'return new ObjectName(domain, properties);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[91,6] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) + Did you mean 'checkArgument(onFactory != null, "null objectNameFactory");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[64,55] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean 'this.specificDurationUnits = ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[65,51] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean 'this.specificRateUnits = ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[64,46] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.specificDurationUnits = emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[65,42] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.specificRateUnits = emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[132,46] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.specificDurationUnits = unmodifiableMap(specificDurationUnits);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[143,42] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.specificRateUnits = unmodifiableMap(specificRateUnits);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[162,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) + Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(JmxReporter.class);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class DefaultObjectNameFactoryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[38] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class JmxReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[40,34] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'private final String name = randomUUID().toString().replaceAll("[{\\-}]", "");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[52,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Gauge gauge = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[53,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Counter counter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[54,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Histogram histogram = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[55,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Meter meter = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[56,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final Timer timer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[57,62] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private final ObjectNameFactory mockObjectNameFactory = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[69,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot hSnapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[98,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final Snapshot tSnapshot = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[288,40] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'MBeanServer mockedMBeanServer = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[313,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void jmxMetricNameWithAsterisk() {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- +[info] Processed 5 files (3 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ +[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] +[INFO] from metrics-legacy-adapter/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 36 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,49] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,9] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[110,27] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[114,27] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java:[118,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableSortedMap(items);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[107,31] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toCollection(TreeSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[163,22] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableSortedMap(items);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java:[27,26] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(items);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java:[51,24] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'return unmodifiableMap(items);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 24 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[50,4] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[367,22] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CachedGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void create() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java:[24,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createWothClock() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[13,45] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(clock.getTick()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[19,45] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(clock.getTick()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ClockTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[11,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void defaultClockCanBeUsed() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[17,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void userTimeClockCanBeUsed() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[23,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void customTimeClockCanBeUsed() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ConsoleReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java:[38,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createConsoleReporter() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java:[75,79] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(new String(byteArrayOutputStream.toByteArray(), UTF_8))'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class CounterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[14,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void incrementCounter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[21,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void incrementCounterOnManyPoints() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[28,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void decrementCounter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[35,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void decrementCounterOnManyPoints() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class DerivativeGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java:[11,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void calculate() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[25,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ExponentiallyDecayingReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createReservoir() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[25,60] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getStdDev()).isEqualTo(32.62, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[34,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createReservoirWithCustomSizeAndAlpha() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[41,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createReservoirWithCustomSizeAlphaAndClock() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java:[13] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class FixedNameCsvFileProviderTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class GaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java:[13,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getValue() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[26,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class HistogramTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void create() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[26,60] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getStdDev()).isEqualTo(32.62, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedExecutorServiceTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java:[15,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void create() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java:[13] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedScheduledExecutorServiceTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java:[22,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void create() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedThreadFactoryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java:[14,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void factory() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java:[12,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@SuppressWarnings("DoNotCall")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MeterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createMeteer() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java:[18,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createMeterWithCustomClock() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java:[31,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void mark() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class MetricRegistryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[19,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void registerMetric() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[26,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void registerAll() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[43,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void registerGauge() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[49,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createCustomGauge() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[55,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createCounter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[62,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createCustomCounter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[76,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createHistogram() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[86,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createCustomHistogram() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[98,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createMeter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[107,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createCustomMeter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[122,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createTimer() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[132,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createCustomTimer() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[148,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void removeMetric() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[159,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void removeMatching() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[171,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void addListenerForGauge() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[200,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void addListenerForCounter() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[228,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void addListenerForHistogram() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[257,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void addListenerForMeter() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[286,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void addListenerForTimer() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[315,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void removeListener() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[334,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getNames() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[345,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getGauges() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[372,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getGaugesWithFilter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[401,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getHistograms() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[414,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getHistogramsWithFilter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[427,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getCounters() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[440,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getCountersWithFilter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[453,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getMeters() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[467,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getMetersWithFilter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[481,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getTimers() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[494,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getTimersWithFilter() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[507,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getMetrics() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[21,58] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) + Did you mean 'assertThat(ratioGauge.getRatio()).hasToString("1.0:3.0");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class RatioGaugeTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[20,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void viewRatin() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[25,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void calculateRatio() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[26,60] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(ratioGauge.getValue()).isCloseTo(0.33, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[13] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class ScheduledReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[54,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void report() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[64,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void start() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[74,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void startWithoutDelay() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[52,48] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalStateException: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalStateException) + Did you mean 'assertThatThrownBy(SharedMetricRegistries::getDefault).isInstanceOf(IllegalStateException.class);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SharedMetricRegistriesTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[18,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getOrCreateMetricRegistry() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[26,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void addMetricRegistry() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[36,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void names() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[46,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void tryGetDefaultRegistry() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[51,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void getDefaultRegistry() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class Slf4jReporterTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java:[20,30] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private Logger logger = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java:[21,30] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'private Marker marker = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java:[34,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void report() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SlidingTimeWindowArrayReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[13,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createWithWindow() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[21,71] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[25,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createWithWindowAndClock() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[32,71] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SlidingTimeWindowReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[13,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createWithWindow() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[20,71] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[24,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createWithWindowAndClock() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[31,71] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SlidingWindowReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createWithBigWindow() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[19,71] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[23,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createWithLowWindow() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[31,71] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[23,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, Offset.offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[27,55] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get999thPercentile()).isCloseTo(5, Offset.offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[24,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get95thPercentile()).isCloseTo(5, Offset.offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[25,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get98thPercentile()).isCloseTo(5, Offset.offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[26,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.get99thPercentile()).isCloseTo(5, Offset.offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[21,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(1.58, Offset.offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[22,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getMedian()).isCloseTo(3, Offset.offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class SnapshotTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[14,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createSnapshot() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[21,59] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getStdDev()).isEqualTo(1.58, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[22,56] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[23,66] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[24,64] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get95thPercentile()).isEqualTo(5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[25,64] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get98thPercentile()).isEqualTo(5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[26,64] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get99thPercentile()).isEqualTo(5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[27,65] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get999thPercentile()).isEqualTo(5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class TimerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[29,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void create() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[38,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createWithCustomReservoir() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[47,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createWithCustomReservoirAndClock() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[56,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void timerContext() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[64,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void timerRunnable() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[75,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void timerCallable() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[85,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void timerSupplier() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[95,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void updateDuration() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[25,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(36.47, Offset.offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class UniformReservoirTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createReservoir() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[25,60] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getStdDev()).isEqualTo(36.47, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[34,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createReservoirWithCustomSize() {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/metrics-legacy-adapter-5.0.0-rc22.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- +[info] Processed 60 files (13 reformatted). +[INFO] +[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- +[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] +[INFO] from metrics-legacy-adapter-healthchecks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/metrics-legacy-adapter-healthchecks-5.0.0-rc22.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] +[INFO] from metrics-jetty12/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[247,44] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) + Did you mean 'this.responses = ImmutableList.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[167,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) + Did you mean ': ImmutableMap.of();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[167,25] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean ': emptyMap();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[182,21] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'unmodifiableList('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[247,34] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'this.responses = emptyList();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/12.0.14/jetty-server-12.0.14.jar(/org/eclipse/jetty/server/HttpConnectionFactory.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/12.0.14/jetty-server-12.0.14.jar(/org/eclipse/jetty/server/HttpConnectionFactory.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/12.0.14/jetty-server-12.0.14.jar(/org/eclipse/jetty/server/HttpConnectionFactory.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/12.0.14/jetty-server-12.0.14.jar(/org/eclipse/jetty/server/HttpConnectionFactory.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/ssl/SslContextFactory.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/ssl/SslContextFactory.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/ssl/SslContextFactory.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/ssl/SslContextFactory.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[22,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedConnectionFactoryTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[35,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void setUp() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[53,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void tearDown() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[59,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void instrumentsConnectionTimes() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[73,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void instrumentsActiveConnections() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java:[10,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedQueuedThreadPoolTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java:[17,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void setUp() {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java:[23,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void customMetricsPrefix() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java:[38,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void metricsPrefixBackwardCompatible() throws Exception {'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- +[info] Processed 5 files (1 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] +[INFO] from metrics-jetty12-ee10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/ee10/jetty-ee10-servlet/12.0.14/jetty-ee10-servlet-12.0.14.jar(/org/eclipse/jetty/ee10/servlet/DefaultServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/ee10/jetty-ee10-servlet/12.0.14/jetty-ee10-servlet-12.0.14.jar(/org/eclipse/jetty/ee10/servlet/ServletContextHandler.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/ee10/jetty-ee10-servlet/12.0.14/jetty-ee10-servlet-12.0.14.jar(/org/eclipse/jetty/ee10/servlet/ServletContextHandler.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[180,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[185,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat('? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[172,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(registry.getMeters().get(metricName().resolve(".200-responses")).getCount()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[170,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) + Did you mean 'assertThat(registry.getMeters().get(metricName().resolve("2xx-responses")).getCount()).isPositive();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[35,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final + (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) + Did you mean 'final class InstrumentedEE10HandlerTest {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[43,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void setUp() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[65,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void tearDown() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[71,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void hasAName() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[76,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void createsAndRemovesMetricsForTheHandler() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[120,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void responseTimesAreRecordedForBlockingResponses() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[118,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@Disabled("flaky on virtual machines")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[130,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void doStopDoesNotThrowNPE() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[138,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[148,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[159,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved + (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) + Did you mean 'void responseTimesAreRecordedForAsyncResponses() throws Exception {'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[157,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible + (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) + Did you mean '@Disabled("flaky on virtual machines")'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[253,91] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '"some content from the async\n".getBytes(UTF_8));'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- +[info] Processed 2 files (1 reformatted). +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: +[INFO] +[INFO] Metrics5 Parent .................................... SUCCESS [ 0.348 s] +[INFO] Metrics5 Documentation ............................. SUCCESS [ 1.412 s] +[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.009 s] +[INFO] Annotations for Metrics5 ........................... SUCCESS [ 4.564 s] +[INFO] Metrics5 Core ...................................... SUCCESS [ 27.676 s] +[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 5.998 s] +[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 8.001 s] +[INFO] Metrics Integration for Collectd ................... SUCCESS [ 14.076 s] +[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 8.093 s] +[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 14.205 s] +[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 11.589 s] +[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 11.988 s] +[INFO] Metrics5 Health Checks ............................. SUCCESS [ 11.640 s] +[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 9.543 s] +[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 10.951 s] +[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 8.025 s] +[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 7.862 s] +[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 7.217 s] +[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 8.924 s] +[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 11.442 s] +[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 11.180 s] +[INFO] Metrics Integration for JCache ..................... SUCCESS [ 7.736 s] +[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 9.524 s] +[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 12.614 s] +[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 14.470 s] +[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 16.701 s] +[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 13.086 s] +[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 7.669 s] +[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 7.401 s] +[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 7.500 s] +[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 9.950 s] +[INFO] Metrics Integration for Servlets ................... SUCCESS [ 7.850 s] +[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 11.958 s] +[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 5.342 s] +[INFO] Metrics Integration with JMX ....................... SUCCESS [ 10.732 s] +[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 15.020 s] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 4.963 s] +[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 9.111 s] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 8.927 s] +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 06:16 min +[INFO] Finished at: 2024-11-18T12:51:22+01:00 +[INFO] ------------------------------------------------------------------------ +diff --git a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java +index 72f85e8..13f3b2c 100644 +--- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java ++++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java +@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.benchmarks; + + import io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir; + import io.dropwizard.metrics5.SlidingTimeWindowReservoir; +-import io.dropwizard.metrics5.Snapshot; + import java.util.concurrent.TimeUnit; + import org.openjdk.jmh.annotations.Benchmark; + import org.openjdk.jmh.annotations.Group; +@@ -42,8 +41,7 @@ public class SlidingTimeWindowReservoirsBenchmark { + @Group("slidingTime") + @GroupThreads(1) + public Object slidingTimeRead() { +- Snapshot snapshot = slidingTime.getSnapshot(); +- return snapshot; ++ return slidingTime.getSnapshot(); + } + + @Benchmark +@@ -58,8 +56,7 @@ public class SlidingTimeWindowReservoirsBenchmark { + @Group("arrTime") + @GroupThreads(1) + public Object arrTimeRead() { +- Snapshot snapshot = arrTime.getSnapshot(); +- return snapshot; ++ return arrTime.getSnapshot(); + } + + public static void main(String[] args) throws RunnerException { +diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java +index 9ea691f..7b54d0b 100644 +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java +@@ -1,13 +1,12 @@ + package io.dropwizard.metrics5.collectd; + ++import static com.google.common.base.Preconditions.checkArgument; + import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MAX; + import static io.dropwizard.metrics5.MetricAttribute.MEAN; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P75; + import static io.dropwizard.metrics5.MetricAttribute.P95; +@@ -16,6 +15,7 @@ import static io.dropwizard.metrics5.MetricAttribute.P99; + import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; + ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -30,7 +30,6 @@ import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; + import java.io.IOException; + import java.net.InetAddress; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -81,7 +80,7 @@ public class CollectdReporter extends ScheduledReporter { + private SecurityLevel securityLevel = SecurityLevel.NONE; + private String username = ""; + private String password = ""; +- private Set disabledMetricAttributes = Collections.emptySet(); ++ private Set disabledMetricAttributes = ImmutableSet.of(); + private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; + + private Builder(MetricRegistry registry) { +@@ -150,14 +149,10 @@ public class CollectdReporter extends ScheduledReporter { + + public CollectdReporter build(Sender sender) { + if (securityLevel != SecurityLevel.NONE) { +- if (username.isEmpty()) { +- throw new IllegalArgumentException( +- "username is required for securityLevel: " + securityLevel); +- } +- if (password.isEmpty()) { +- throw new IllegalArgumentException( +- "password is required for securityLevel: " + securityLevel); +- } ++ checkArgument( ++ !username.isEmpty(), "username is required for securityLevel: " + securityLevel); ++ checkArgument( ++ !password.isEmpty(), "password is required for securityLevel: " + securityLevel); + } + return new CollectdReporter( + registry, +@@ -302,7 +297,7 @@ public class CollectdReporter extends ScheduledReporter { + try { + writer.write(metaData, value); + } catch (RuntimeException e) { +- LOG.warn("Failed to process metric '" + metaData.getPlugin() + "': " + e.getMessage()); ++ LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage()); + } catch (IOException e) { + LOG.error("Failed to send metric to collectd", e); + } +@@ -336,9 +331,9 @@ public class CollectdReporter extends ScheduledReporter { + private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { + final Snapshot snapshot = metric.getSnapshot(); + writeValue(metaData, COUNT, (double) metric.getCount()); +- writeValue(metaData, MAX, (double) snapshot.getMax()); ++ writeValue(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); + writeValue(metaData, MEAN, snapshot.getMean()); +- writeValue(metaData, MIN, (double) snapshot.getMin()); ++ writeValue(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); + writeValue(metaData, STDDEV, snapshot.getStdDev()); + writeValue(metaData, P50, snapshot.getMedian()); + writeValue(metaData, P75, snapshot.get75thPercentile()); +@@ -351,9 +346,9 @@ public class CollectdReporter extends ScheduledReporter { + private void serializeTimer(MetaData.Builder metaData, Timer metric) { + final Snapshot snapshot = metric.getSnapshot(); + writeValue(metaData, COUNT, (double) metric.getCount()); +- writeDuration(metaData, MAX, (double) snapshot.getMax()); ++ writeDuration(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); + writeDuration(metaData, MEAN, snapshot.getMean()); +- writeDuration(metaData, MIN, (double) snapshot.getMin()); ++ writeDuration(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); + writeDuration(metaData, STDDEV, snapshot.getStdDev()); + writeDuration(metaData, P50, snapshot.getMedian()); + writeDuration(metaData, P75, snapshot.get75thPercentile()); +diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java +index 4c5716e..764b5f8 100644 +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java +@@ -1,10 +1,13 @@ + package io.dropwizard.metrics5.collectd; + ++import static com.google.common.base.Preconditions.checkState; ++import static java.nio.charset.StandardCharsets.US_ASCII; ++import static java.nio.charset.StandardCharsets.UTF_8; ++ + import java.io.IOException; + import java.nio.BufferOverflowException; + import java.nio.ByteBuffer; + import java.nio.ByteOrder; +-import java.nio.charset.StandardCharsets; + import java.security.InvalidKeyException; + import java.security.MessageDigest; + import java.security.NoSuchAlgorithmException; +@@ -64,8 +67,8 @@ class PacketWriter { + PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { + this.sender = sender; + this.securityLevel = securityLevel; +- this.username = username != null ? username.getBytes(StandardCharsets.UTF_8) : null; +- this.password = password != null ? password.getBytes(StandardCharsets.UTF_8) : null; ++ this.username = username != null ? username.getBytes(UTF_8) : null; ++ this.password = password != null ? password.getBytes(UTF_8) : null; + } + + void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { +@@ -119,12 +122,12 @@ class PacketWriter { + } + + private void writeString(ByteBuffer buffer, int type, String val) { +- if (val == null || val.length() == 0) { ++ if (val == null || val.isEmpty()) { + return; + } + int len = HEADER_LEN + val.length() + 1; + writeHeader(buffer, type, len); +- buffer.put(val.getBytes(StandardCharsets.US_ASCII)).put(NULL); ++ buffer.put(val.getBytes(US_ASCII)).put(NULL); + } + + private void writeNumber(ByteBuffer buffer, int type, long val) { +@@ -236,9 +239,7 @@ class PacketWriter { + } catch (InvalidParameterSpecException e) { + throw new RuntimeException(e); + } +- if (iv.length != IV_LENGTH) { +- throw new IllegalStateException("Bad initialization vector"); +- } ++ checkState(iv.length == IV_LENGTH, "Bad initialization vector"); + final ByteBuffer output = ByteBuffer.allocate(input.remaining() * 2); + try { + cipher.doFinal(input, output); +@@ -261,9 +262,7 @@ class PacketWriter { + final MessageDigest digest = MessageDigest.getInstance(SHA_1_ALGORITHM); + digest.update(input); + final byte[] output = digest.digest(); +- if (output.length != SHA1_LENGTH) { +- throw new IllegalStateException("Bad SHA1 hash"); +- } ++ checkState(output.length == SHA1_LENGTH, "Bad SHA1 hash"); + return output; + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); +diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java +index 271e31b..4a99ab6 100644 +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.collectd; + ++import static com.google.common.base.Preconditions.checkState; ++ + import java.io.IOException; + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; +@@ -19,9 +21,7 @@ public class Sender { + } + + public void connect() throws IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); + if (host != null) { + address = new InetSocketAddress(host, port); + } +diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java +index 4d62df2..c666135 100644 +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java +@@ -1,37 +1,37 @@ + package io.dropwizard.metrics5.collectd; + +-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + + import io.dropwizard.metrics5.MetricRegistry; + import org.junit.jupiter.api.Test; + +-class CollectdReporterSecurityTest { ++final class CollectdReporterSecurityTest { + + private final MetricRegistry registry = new MetricRegistry(); + + @Test +- void testUnableSetSecurityLevelToSignWithoutUsername() { +- assertThatIllegalArgumentException() +- .isThrownBy( ++ void unableSetSecurityLevelToSignWithoutUsername() { ++ assertThatThrownBy( + () -> + CollectdReporter.forRegistry(registry) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withPassword("t1_g3r") + .build(new Sender("localhost", 25826))) +- .withMessage("username is required for securityLevel: SIGN"); ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("username is required for securityLevel: SIGN"); + } + + @Test +- void testUnableSetSecurityLevelToSignWithoutPassword() { +- assertThatIllegalArgumentException() +- .isThrownBy( ++ void unableSetSecurityLevelToSignWithoutPassword() { ++ assertThatThrownBy( + () -> + CollectdReporter.forRegistry(registry) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withUsername("scott") + .build(new Sender("localhost", 25826))) +- .withMessage("password is required for securityLevel: SIGN"); ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("password is required for securityLevel: SIGN"); + } + } +diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java +index 6213497..2dd98c8 100644 +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java +@@ -1,11 +1,14 @@ + package io.dropwizard.metrics5.collectd; + ++import static java.util.Collections.emptySortedMap; + import static java.util.concurrent.TimeUnit.MILLISECONDS; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Histogram; + import io.dropwizard.metrics5.Meter; +@@ -14,7 +17,6 @@ import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -25,7 +27,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.junit.jupiter.api.extension.RegisterExtension; + +-public class CollectdReporterTest { ++final class CollectdReporterTest { + @RegisterExtension public static Receiver receiver = new Receiver(25826); + + private final MetricRegistry registry = new MetricRegistry(); +@@ -96,7 +98,7 @@ public class CollectdReporterTest { + + @Test + void reportsCounters() throws Exception { +- Counter counter = mock(Counter.class); ++ Counter counter = mock(); + when(counter.getCount()).thenReturn(42L); + + reporter.report( +@@ -111,7 +113,7 @@ public class CollectdReporterTest { + + @Test + void reportsMeters() throws Exception { +- Meter meter = mock(Meter.class); ++ Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); +@@ -130,8 +132,8 @@ public class CollectdReporterTest { + + @Test + void reportsHistograms() throws Exception { +- Histogram histogram = mock(Histogram.class); +- Snapshot snapshot = mock(Snapshot.class); ++ Histogram histogram = mock(); ++ Snapshot snapshot = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSnapshot()).thenReturn(snapshot); + when(snapshot.getMax()).thenReturn(2L); +@@ -154,8 +156,8 @@ public class CollectdReporterTest { + + @Test + void reportsTimers() throws Exception { +- Timer timer = mock(Timer.class); +- Snapshot snapshot = mock(Snapshot.class); ++ Timer timer = mock(); ++ Snapshot snapshot = mock(); + when(timer.getSnapshot()).thenReturn(snapshot); + when(timer.getCount()).thenReturn(1L); + when(timer.getSnapshot()).thenReturn(snapshot); +@@ -195,14 +197,14 @@ public class CollectdReporterTest { + + @Test + void doesNotReportDisabledMetricAttributes() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getOneMinuteRate()).thenReturn(2.0); + when(meter.getFiveMinuteRate()).thenReturn(3.0); + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(11L); + + CollectdReporter reporter = +@@ -236,37 +238,37 @@ public class CollectdReporterTest { + } + + @Test +- void testUnableSetSecurityLevelToSignWithoutUsername() { +- assertThatIllegalArgumentException() +- .isThrownBy( ++ void unableSetSecurityLevelToSignWithoutUsername() { ++ assertThatThrownBy( + () -> + CollectdReporter.forRegistry(registry) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withPassword("t1_g3r") + .build(new Sender("localhost", 25826))) +- .withMessage("username is required for securityLevel: SIGN"); ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("username is required for securityLevel: SIGN"); + } + + @Test +- void testUnableSetSecurityLevelToSignWithoutPassword() { +- assertThatIllegalArgumentException() +- .isThrownBy( ++ void unableSetSecurityLevelToSignWithoutPassword() { ++ assertThatThrownBy( + () -> + CollectdReporter.forRegistry(registry) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withUsername("scott") + .build(new Sender("localhost", 25826))) +- .withMessage("password is required for securityLevel: SIGN"); ++ .isInstanceOf(IllegalArgumentException.class) ++ .hasMessage("password is required for securityLevel: SIGN"); + } + + private SortedMap map() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + private SortedMap map(MetricName name, T metric) { +- final Map map = Collections.singletonMap(name, metric); ++ final Map map = ImmutableMap.of(name, metric); + return new TreeMap<>(map); + } + +@@ -289,6 +291,6 @@ public class CollectdReporterTest { + + private List nextValues(Receiver receiver) throws Exception { + final ValueList valueList = receiver.next(); +- return valueList == null ? Collections.emptyList() : valueList.getValues(); ++ return valueList == null ? ImmutableList.of() : valueList.getValues(); + } + } +diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java +index 27d6b2f..53749ca 100644 +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java +@@ -17,7 +17,7 @@ import javax.crypto.spec.IvParameterSpec; + import javax.crypto.spec.SecretKeySpec; + import org.junit.jupiter.api.Test; + +-class PacketWriterTest { ++final class PacketWriterTest { + + private MetaData metaData = + new MetaData.Builder("nw-1.alpine.example.com", 1520961345L, 100) +@@ -28,7 +28,7 @@ class PacketWriterTest { + private String password = "t1_g$r"; + + @Test +- void testSignRequest() throws Exception { ++ void signRequest() throws Exception { + AtomicBoolean packetVerified = new AtomicBoolean(); + Sender sender = + new Sender("localhost", 4009) { +@@ -74,7 +74,7 @@ class PacketWriterTest { + } + + @Test +- void testEncryptRequest() throws Exception { ++ void encryptRequest() throws Exception { + AtomicBoolean packetVerified = new AtomicBoolean(); + Sender sender = + new Sender("localhost", 4009) { +@@ -190,6 +190,6 @@ class PacketWriterTest { + assertThat(amountOfValues).isEqualTo((short) 1); + byte dataType = packet.get(); + assertThat(dataType).isEqualTo((byte) 1); +- assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isEqualTo(42.0, offset(0.01)); ++ assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01)); + } + } +diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java +index 365d6bd..52ee6cc 100644 +--- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java ++++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-class SanitizeTest { ++final class SanitizeTest { + + private Sanitize sanitize = new Sanitize(Sanitize.DEFAULT_MAX_LENGTH); + +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java +index 22c8d4c..6e22c83 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java +@@ -1,8 +1,9 @@ + package io.dropwizard.metrics5; + ++ ++import com.google.common.collect.ImmutableSet; + import java.io.PrintStream; + import java.text.DateFormat; +-import java.util.Collections; + import java.util.Date; + import java.util.Locale; + import java.util.Map; +@@ -53,7 +54,7 @@ public class ConsoleReporter extends ScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- disabledMetricAttributes = Collections.emptySet(); ++ disabledMetricAttributes = ImmutableSet.of(); + } + + /** +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java +index cff228f..6f77ff9 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java +@@ -179,7 +179,7 @@ public class CsvReporter extends ScheduledReporter { + } + } + +- private static final Logger LOGGER = LoggerFactory.getLogger(CsvReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(CsvReporter.class); + + private final File directory; + private final Locale locale; +@@ -391,7 +391,7 @@ public class CsvReporter extends ScheduledReporter { + } + } + } catch (IOException e) { +- LOGGER.warn("Error writing to {}", name, e); ++ LOG.warn("Error writing to {}", name, e); + } + } + +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java b/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java +index 4770275..6e9741a 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java +@@ -17,9 +17,9 @@ public class ExponentialMovingAverages implements MovingAverages { + * If ticking would reduce even Long.MAX_VALUE in the 15 minute EWMA below this target then don't + * bother ticking in a loop and instead reset all the EWMAs. + */ +- private static final double maxTickZeroTarget = 0.0001; ++ private static final double MAX_TICK_ZERO_TARGET = 0.0001; + +- private static final int maxTicks; ++ private static final int MAX_TICKS; + private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5); + + static { +@@ -29,8 +29,8 @@ public class ExponentialMovingAverages implements MovingAverages { + do { + m3.tick(); + m3Ticks++; +- } while (m3.getRate(TimeUnit.SECONDS) > maxTickZeroTarget); +- maxTicks = m3Ticks; ++ } while (m3.getRate(TimeUnit.SECONDS) > MAX_TICK_ZERO_TARGET); ++ MAX_TICKS = m3Ticks; + } + + private final EWMA m1Rate = EWMA.oneMinuteEWMA(); +@@ -69,7 +69,7 @@ public class ExponentialMovingAverages implements MovingAverages { + if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) { + sum.add(age); + final long requiredTicks = age / TICK_INTERVAL; +- if (requiredTicks >= maxTicks) { ++ if (requiredTicks >= MAX_TICKS) { + m1Rate.reset(); + m5Rate.reset(); + m15Rate.reset(); +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java +index 6c0a2ff..43690af 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java +@@ -1,8 +1,10 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Objects.requireNonNull; ++ + import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; + import java.time.Duration; +-import java.util.Objects; + import java.util.concurrent.ConcurrentSkipListMap; + import java.util.concurrent.ThreadLocalRandom; + import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +@@ -41,7 +43,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + + private static final double SECONDS_PER_NANO = .000_000_001D; + private static final AtomicReferenceFieldUpdater +- stateUpdater = ++ STATE_UPDATER = + AtomicReferenceFieldUpdater.newUpdater( + LockFreeExponentiallyDecayingReservoir.class, State.class, "state"); + +@@ -53,7 +55,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + + private static final class State { + +- private static final AtomicIntegerFieldUpdater countUpdater = ++ private static final AtomicIntegerFieldUpdater COUNT_UPDATER = + AtomicIntegerFieldUpdater.newUpdater(State.class, "count"); + + private final double alphaNanos; +@@ -89,7 +91,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + private void addSample( + double priority, long value, double itemWeight, boolean bypassIncrement) { + if (values.putIfAbsent(priority, new WeightedSample(value, itemWeight)) == null +- && (bypassIncrement || countUpdater.incrementAndGet(this) > size)) { ++ && (bypassIncrement || COUNT_UPDATER.incrementAndGet(this) > size)) { + values.pollFirstEntry(); + } + } +@@ -126,7 +128,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + // It's possible that more values were added while the map was scanned, those with the + // minimum priorities are removed. + while (newCount > size) { +- Objects.requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); ++ requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); + newCount--; + } + return new State(alphaNanos, size, newTick, newCount, newValues); +@@ -193,7 +195,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + + private State doRescale(long currentTick, State stateSnapshot) { + State newState = stateSnapshot.rescale(currentTick); +- if (stateUpdater.compareAndSet(this, stateSnapshot, newState)) { ++ if (STATE_UPDATER.compareAndSet(this, stateSnapshot, newState)) { + // newState successfully installed + return newState; + } +@@ -235,10 +237,8 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + * are replaced (based on weight, with some amount of random jitter). + */ + public Builder size(int value) { +- if (value <= 0) { +- throw new IllegalArgumentException( +- "LockFreeExponentiallyDecayingReservoir size must be positive: " + value); +- } ++ checkArgument( ++ value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: " + value); + this.size = value; + return this; + } +@@ -254,13 +254,13 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + + /** Interval at which this reservoir is rescaled. */ + public Builder rescaleThreshold(Duration value) { +- this.rescaleThreshold = Objects.requireNonNull(value, "rescaleThreshold is required"); ++ this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required"); + return this; + } + + /** Clock instance used for decay. */ + public Builder clock(Clock value) { +- this.clock = Objects.requireNonNull(value, "clock is required"); ++ this.clock = requireNonNull(value, "clock is required"); + return this; + } + +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java +index 5779398..e3ac43a 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java +@@ -1,13 +1,19 @@ + package io.dropwizard.metrics5; + +-import java.util.Collections; +-import java.util.Comparator; ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Collections.unmodifiableMap; ++import static java.util.Map.Entry.comparingByKey; ++import static java.util.Objects.requireNonNull; ++import static java.util.stream.Collectors.joining; ++ ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableMap; ++import java.util.Arrays; + import java.util.HashMap; + import java.util.Iterator; + import java.util.LinkedHashMap; + import java.util.Map; + import java.util.Objects; +-import java.util.stream.Collectors; + import java.util.stream.Stream; + + /** +@@ -17,7 +23,7 @@ import java.util.stream.Stream; + public class MetricName implements Comparable { + + private static final String SEPARATOR = "."; +- private static final Map EMPTY_TAGS = Collections.emptyMap(); ++ private static final Map EMPTY_TAGS = ImmutableMap.of(); + static final MetricName EMPTY = new MetricName("", EMPTY_TAGS); + + /** +@@ -33,7 +39,7 @@ public class MetricName implements Comparable { + private final Map tags; + + public MetricName(String key, Map tags) { +- this.key = Objects.requireNonNull(key); ++ this.key = requireNonNull(key); + this.tags = tags.isEmpty() ? EMPTY_TAGS : unmodifiableSortedCopy(tags); + } + +@@ -63,9 +69,9 @@ public class MetricName implements Comparable { + } + + String newKey = +- Stream.concat(Stream.of(key), Stream.of(parts)) +- .filter(s -> s != null && !s.isEmpty()) +- .collect(Collectors.joining(SEPARATOR)); ++ Stream.concat(Stream.of(key), Arrays.stream(parts)) ++ .filter(s -> !Strings.isNullOrEmpty(s)) ++ .collect(joining(SEPARATOR)); + return new MetricName(newKey, tags); + } + +@@ -94,9 +100,7 @@ public class MetricName implements Comparable { + return this; + } + +- if (pairs.length % 2 != 0) { +- throw new IllegalArgumentException("Argument count must be even"); +- } ++ checkArgument(pairs.length % 2 == 0, "Argument count must be even"); + + final Map add = new HashMap<>(); + for (int i = 0; i < pairs.length; i += 2) { +@@ -201,8 +205,8 @@ public class MetricName implements Comparable { + private static , V> Map unmodifiableSortedCopy(Map map) { + LinkedHashMap sorted = new LinkedHashMap<>(); + map.entrySet().stream() +- .sorted(Comparator.comparing(Map.Entry::getKey)) ++ .sorted(comparingByKey()) + .forEach(e -> sorted.put(e.getKey(), e.getValue())); +- return Collections.unmodifiableMap(sorted); ++ return unmodifiableMap(sorted); + } + } +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java +index 806cef0..d30ac87 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java +@@ -1,6 +1,10 @@ + package io.dropwizard.metrics5; + +-import java.util.Collections; ++import static java.util.Collections.unmodifiableMap; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; ++import static java.util.Objects.requireNonNull; ++ + import java.util.List; + import java.util.Map; + import java.util.SortedMap; +@@ -91,9 +95,7 @@ public class MetricRegistry implements MetricSet { + * @throws IllegalArgumentException if the name is already registered or metric variable is null + */ + public T register(MetricName name, T metric) throws IllegalArgumentException { +- if (metric == null) { +- throw new NullPointerException("metric == null"); +- } ++ requireNonNull(metric, "metric == null"); + + if (metric instanceof MetricRegistry) { + final MetricRegistry childRegistry = (MetricRegistry) metric; +@@ -213,7 +215,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); ++ return metric instanceof Counter; + } + }); + } +@@ -253,7 +255,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); ++ return metric instanceof Histogram; + } + }); + } +@@ -293,7 +295,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); ++ return metric instanceof Meter; + } + }); + } +@@ -328,7 +330,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); ++ return metric instanceof Timer; + } + }); + } +@@ -366,7 +368,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Gauge.class.isInstance(metric); ++ return metric instanceof Gauge; + } + }); + } +@@ -430,7 +432,7 @@ public class MetricRegistry implements MetricSet { + * @return the names of all the metrics + */ + public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); ++ return unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); + } + + /** +@@ -455,7 +457,7 @@ public class MetricRegistry implements MetricSet { + timers.put(entry.getKey(), (Gauge) entry.getValue()); + } + } +- return Collections.unmodifiableSortedMap(timers); ++ return unmodifiableSortedMap(timers); + } + + /** +@@ -562,7 +564,7 @@ public class MetricRegistry implements MetricSet { + timers.put(entry.getKey(), (T) entry.getValue()); + } + } +- return Collections.unmodifiableSortedMap(timers); ++ return unmodifiableSortedMap(timers); + } + + private void onMetricAdded(MetricName name, Metric metric) { +@@ -627,7 +629,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public Map getMetrics() { +- return Collections.unmodifiableMap(metrics); ++ return unmodifiableMap(metrics); + } + + @FunctionalInterface +@@ -646,7 +648,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Counter.class.isInstance(metric); ++ return metric instanceof Counter; + } + }; + +@@ -659,7 +661,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Histogram.class.isInstance(metric); ++ return metric instanceof Histogram; + } + }; + +@@ -672,7 +674,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Meter.class.isInstance(metric); ++ return metric instanceof Meter; + } + }; + +@@ -685,7 +687,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Timer.class.isInstance(metric); ++ return metric instanceof Timer; + } + }; + +@@ -699,7 +701,7 @@ public class MetricRegistry implements MetricSet { + + @Override + public boolean isInstance(Metric metric) { +- return Gauge.class.isInstance(metric); ++ return metric instanceof Gauge; + } + }; + +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java b/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java +index 79d3683..7630290 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java +@@ -1,11 +1,14 @@ + package io.dropwizard.metrics5; + ++import static java.util.Collections.emptySortedMap; ++import static java.util.Collections.emptySortedSet; + import static java.util.Objects.requireNonNull; + ++import com.google.common.collect.ImmutableMap; ++import com.google.common.collect.ImmutableSet; + import java.io.OutputStream; + import java.time.Duration; + import java.util.Collection; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -158,67 +161,67 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public SortedSet getNames() { +- return Collections.emptySortedSet(); ++ return emptySortedSet(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap> getGauges() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap> getGauges(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getCounters() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getCounters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getHistograms() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getHistograms(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getMeters() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getMeters(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getTimers() { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ + @Override + public SortedMap getTimers(MetricFilter filter) { +- return Collections.emptySortedMap(); ++ return emptySortedMap(); + } + + /** {@inheritDoc} */ +@@ -236,7 +239,7 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public Map getMetrics() { +- return Collections.emptyMap(); ++ return ImmutableMap.of(); + } + + static final class NoopMetric implements Metric { +@@ -630,19 +633,19 @@ public final class NoopMetricRegistry extends MetricRegistry { + /** {@inheritDoc} */ + @Override + public Set keySet() { +- return Collections.emptySet(); ++ return ImmutableSet.of(); + } + + /** {@inheritDoc} */ + @Override + public Collection values() { +- return Collections.emptySet(); ++ return ImmutableSet.of(); + } + + /** {@inheritDoc} */ + @Override + public Set> entrySet() { +- return Collections.emptySet(); ++ return ImmutableSet.of(); + } + } + } +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java +index 9269921..0b6827d 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java +@@ -1,7 +1,10 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Objects.requireNonNull; ++ ++import com.google.common.collect.ImmutableSet; + import java.io.Closeable; +-import java.util.Collections; + import java.util.Locale; + import java.util.Set; + import java.util.SortedMap; +@@ -128,7 +131,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + durationUnit, + executor, + shutdownExecutorOnStop, +- Collections.emptySet()); ++ ImmutableSet.of()); + } + + protected ScheduledReporter( +@@ -141,9 +144,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + boolean shutdownExecutorOnStop, + Set disabledMetricAttributes) { + +- if (registry == null) { +- throw new NullPointerException("registry == null"); +- } ++ requireNonNull(registry, "registry == null"); + + this.registry = registry; + this.filter = filter; +@@ -154,7 +155,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + this.durationFactor = durationUnit.toNanos(1); + this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); + this.disabledMetricAttributes = +- disabledMetricAttributes != null ? disabledMetricAttributes : Collections.emptySet(); ++ disabledMetricAttributes != null ? disabledMetricAttributes : ImmutableSet.of(); + } + + /** +@@ -172,9 +173,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + * for testing. + */ + synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) { +- if (this.scheduledFuture != null) { +- throw new IllegalArgumentException("Reporter already started"); +- } ++ checkArgument(this.scheduledFuture == null, "Reporter already started"); + + this.scheduledFuture = getScheduledFuture(initialDelay, period, unit, runnable); + } +@@ -185,8 +184,8 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, + * ScheduledExecutorService)} instead. + */ +- @SuppressWarnings("DeprecatedIsStillUsed") + @Deprecated ++ @SuppressWarnings("DeprecatedIsStillUsed") + protected ScheduledFuture getScheduledFuture( + long initialDelay, long period, TimeUnit unit, Runnable runnable) { + return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java b/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java +index a36606a..9787356 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkState; ++ + import java.util.Set; + import java.util.concurrent.ConcurrentHashMap; + import java.util.concurrent.ConcurrentMap; +@@ -84,9 +86,7 @@ public class SharedMetricRegistries { + */ + public static MetricRegistry getDefault() { + MetricRegistry metricRegistry = tryGetDefault(); +- if (metricRegistry == null) { +- throw new IllegalStateException("Default registry name has not been set."); +- } ++ checkState(metricRegistry != null, "Default registry name has not been set."); + return metricRegistry; + } + +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java +index 9ab54ba..06dfa94 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java +@@ -4,10 +4,8 @@ import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MAX; + import static io.dropwizard.metrics5.MetricAttribute.MEAN; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P75; + import static io.dropwizard.metrics5.MetricAttribute.P95; +@@ -16,7 +14,7 @@ import static io.dropwizard.metrics5.MetricAttribute.P99; + import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; + +-import java.util.Collections; ++import com.google.common.collect.ImmutableSet; + import java.util.Map.Entry; + import java.util.Set; + import java.util.SortedMap; +@@ -81,7 +79,7 @@ public class Slf4jReporter extends ScheduledReporter { + this.loggingLevel = LoggingLevel.INFO; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = ImmutableSet.of(); + } + + /** +@@ -306,8 +304,8 @@ public class Slf4jReporter extends ScheduledReporter { + b.append("type=TIMER"); + append(b, "name", prefix(name)); + appendCountIfEnabled(b, timer); +- appendLongDurationIfEnabled(b, MIN, snapshot::getMin); +- appendLongDurationIfEnabled(b, MAX, snapshot::getMax); ++ appendLongDurationIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongDurationIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); + appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); + appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); + appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); +@@ -338,8 +336,8 @@ public class Slf4jReporter extends ScheduledReporter { + b.append("type=HISTOGRAM"); + append(b, "name", prefix(name)); + appendCountIfEnabled(b, histogram); +- appendLongIfEnabled(b, MIN, snapshot::getMin); +- appendLongIfEnabled(b, MAX, snapshot::getMax); ++ appendLongIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); ++ appendLongIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); + appendDoubleIfEnabled(b, MEAN, snapshot::getMean); + appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); + appendDoubleIfEnabled(b, P50, snapshot::getMedian); +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java +index e70b020..cccf48a 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java +@@ -186,8 +186,7 @@ public class SlidingTimeWindowMovingAverages implements MovingAverages { + buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); + buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); + } +- long retval = adder.longValue(); +- return retval; ++ return adder.longValue(); + } + + @Override +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java +index 3416ecf..28c6a60 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkArgument; + import static java.lang.Math.floor; + import static java.nio.charset.StandardCharsets.UTF_8; + +@@ -47,9 +48,9 @@ public class UniformSnapshot extends Snapshot { + */ + @Override + public double getValue(double quantile) { +- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { +- throw new IllegalArgumentException(quantile + " is not in [0..1]"); +- } ++ checkArgument( ++ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), ++ quantile + " is not in [0..1]"); + + if (values.length == 0) { + return 0.0; +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java +index 9ef6212..156bd3c 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java +@@ -1,13 +1,14 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkArgument; + import static java.nio.charset.StandardCharsets.UTF_8; ++import static java.util.Comparator.comparingLong; + + import java.io.OutputStream; + import java.io.OutputStreamWriter; + import java.io.PrintWriter; + import java.util.Arrays; + import java.util.Collection; +-import java.util.Comparator; + + /** A statistical snapshot of a {@link WeightedSnapshot}. */ + public class WeightedSnapshot extends Snapshot { +@@ -35,7 +36,7 @@ public class WeightedSnapshot extends Snapshot { + public WeightedSnapshot(Collection values) { + final WeightedSample[] copy = values.toArray(new WeightedSample[] {}); + +- Arrays.sort(copy, Comparator.comparingLong(w -> w.value)); ++ Arrays.sort(copy, comparingLong(w -> w.value)); + + this.values = new long[copy.length]; + this.normWeights = new double[copy.length]; +@@ -64,9 +65,9 @@ public class WeightedSnapshot extends Snapshot { + */ + @Override + public double getValue(double quantile) { +- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { +- throw new IllegalArgumentException(quantile + " is not in [0..1]"); +- } ++ checkArgument( ++ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), ++ quantile + " is not in [0..1]"); + + if (values.length == 0) { + return 0.0; +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java +index ba6975e..356b1a5 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertTrue; + + import java.util.ArrayList; + import java.util.List; +@@ -15,8 +14,8 @@ import org.junit.jupiter.api.Test; + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + +-class CachedGaugeTest { +- private static final Logger LOGGER = LoggerFactory.getLogger(CachedGaugeTest.class); ++final class CachedGaugeTest { ++ private static final Logger LOG = LoggerFactory.getLogger(CachedGaugeTest.class); + private static final int THREAD_COUNT = 10; + private static final long RUNNING_TIME_MILLIS = TimeUnit.SECONDS.toMillis(10); + +@@ -100,12 +99,12 @@ class CachedGaugeTest { + Integer newValue = shortTimeoutGauge.getValue(); + + if (newValue == null) { +- LOGGER.warn("Cached gauge returned null value"); ++ LOG.warn("Cached gauge returned null value"); + return false; + } + + if (newValue < lastValue) { +- LOGGER.error( ++ LOG.error( + "Cached gauge returned stale value, last: {}, new: {}", + lastValue, + newValue); +@@ -122,7 +121,7 @@ class CachedGaugeTest { + } + + for (int i = 0; i < futures.size(); i++) { +- assertTrue(futures.get(i).get(), "Future " + i + " failed"); ++ assertThat(futures.get(i).get()).withFailMessage("Future " + i + " failed").isTrue(); + } + + executor.shutdown(); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java +index 7b1f2a0..c95bb23 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java +@@ -4,10 +4,10 @@ import static org.assertj.core.api.BDDAssertions.then; + + import org.junit.jupiter.api.Test; + +-class ChunkedAssociativeLongArrayTest { ++final class ChunkedAssociativeLongArrayTest { + + @Test +- void testTrim() { ++ void trim() { + ChunkedAssociativeLongArray array = new ChunkedAssociativeLongArray(3); + array.put(-3, 3); + array.put(-2, 1); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java +index 0cf31e2..3f0840f 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java +@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-public class ClassMetadataTest { ++final class ClassMetadataTest { + @Test +- public void testParameterMetadataIsAvailable() throws NoSuchMethodException { ++ void parameterMetadataIsAvailable() throws NoSuchMethodException { + assertThat(DefaultSettableGauge.class.getConstructor(Object.class).getParameters()) + .allSatisfy(parameter -> assertThat(parameter.isNamePresent()).isTrue()); + } +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java +index 3d35a89..bb669f9 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java +@@ -5,15 +5,15 @@ import static org.assertj.core.api.Assertions.offset; + + import org.junit.jupiter.api.Test; + +-class ClockTest { ++final class ClockTest { + + @Test + void userTimeClock() { + final Clock.UserTimeClock clock = new Clock.UserTimeClock(); + +- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(100.0)); ++ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0)); + +- assertThat((double) clock.getTick()).isEqualTo(System.nanoTime(), offset(1000000.0)); ++ assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0)); + } + + @Test +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java +index 2544152..f6d1b2e 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java +@@ -19,12 +19,12 @@ import org.apache.commons.lang3.SystemUtils; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class ConsoleReporterTest { ++final class ConsoleReporterTest { + private final Locale locale = Locale.US; + private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); + +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); + private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + private final PrintStream output = new PrintStream(bytes); + private final ConsoleReporter reporter = +@@ -74,7 +74,7 @@ class ConsoleReporterTest { + + @Test + void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); +@@ -93,11 +93,11 @@ class ConsoleReporterTest { + + @Test + void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(4L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -138,7 +138,7 @@ class ConsoleReporterTest { + + @Test + void reportsMeterValues() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(3L); + when(meter.getMeanRate()).thenReturn(2.0); +@@ -167,7 +167,7 @@ class ConsoleReporterTest { + + @Test + void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(5)); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -175,7 +175,7 @@ class ConsoleReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -239,7 +239,7 @@ class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); + +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(5L); + when(meter.getMeanRate()).thenReturn(2.0); +@@ -283,7 +283,7 @@ class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); + +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -291,7 +291,7 @@ class ConsoleReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -349,11 +349,11 @@ class ConsoleReporterTest { + .disabledMetricAttributes(disabledMetricAttributes) + .build(); + +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(5L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java +index cbff53e..6f4778a 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java +@@ -4,12 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-class CounterTest { ++final class CounterTest { + private final Counter counter = new Counter(); + + @Test + void startsAtZero() { +- assertThat(counter.getCount()).isZero(); ++ assertThat(counter.getCount()).isEqualTo(0); + } + + @Test +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +index bebc00e..63b9baf 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5; + ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; +@@ -7,7 +8,6 @@ import static org.mockito.Mockito.when; + + import java.io.File; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.nio.file.Files; + import java.util.Locale; + import java.util.SortedMap; +@@ -17,11 +17,11 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.junit.jupiter.api.io.TempDir; + +-public class CsvReporterTest { ++final class CsvReporterTest { + @TempDir public File folder; + +- private final MetricRegistry registry = mock(MetricRegistry.class); +- private final Clock clock = mock(Clock.class); ++ private final MetricRegistry registry = mock(); ++ private final Clock clock = mock(); + + private File dataDirectory; + private CsvReporter reporter; +@@ -53,7 +53,7 @@ public class CsvReporterTest { + + @Test + void reportsCounterValues() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); +@@ -63,11 +63,11 @@ public class CsvReporterTest { + + @Test + void reportsHistogramValues() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(12L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -105,7 +105,7 @@ public class CsvReporterTest { + + @Test + void reportsTimerValues() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -113,7 +113,7 @@ public class CsvReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -137,8 +137,8 @@ public class CsvReporterTest { + } + + @Test +- void testCsvFileProviderIsUsed() { +- CsvFileProvider fileProvider = mock(CsvFileProvider.class); ++ void csvFileProviderIsUsed() { ++ CsvFileProvider fileProvider = mock(); + when(fileProvider.getFile(dataDirectory, "gauge")) + .thenReturn(new File(dataDirectory, "guage.csv")); + +@@ -177,7 +177,7 @@ public class CsvReporterTest { + } + + private Meter mockMeter() { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getMeanRate()).thenReturn(2.0); +@@ -198,8 +198,7 @@ public class CsvReporterTest { + + @SuppressWarnings("FilesReadStringWithCharset") + private String fileContents(String filename) throws IOException { +- return new String( +- Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); ++ return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), UTF_8); + } + + private SortedMap map() { +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java +index d5fdf29..70b5c03 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-class DefaultSettableGaugeTest { ++final class DefaultSettableGaugeTest { + @Test + void newSettableGaugeWithoutDefaultReturnsNull() { + DefaultSettableGauge gauge = new DefaultSettableGauge<>(); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java +index 9b09b3c..557ac5c 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-class DerivativeGaugeTest { ++final class DerivativeGaugeTest { + private final Gauge gauge1 = () -> "woo"; + private final Gauge gauge2 = + new DerivativeGauge(gauge1) { +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java +index a373839..e4318b9 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java +@@ -6,74 +6,74 @@ import static org.assertj.core.api.Assertions.offset; + import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + +-class EWMATest { ++final class EWMATest { + @Test + void aOneMinuteEWMAWithAValueOfThree() { + final EWMA ewma = EWMA.oneMinuteEWMA(); + ewma.update(3); + ewma.tick(); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.01098938, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00404277, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00148725, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00054713, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00020128, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00007405, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00002724, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00001002, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000369, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000136, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000050, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000018, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001)); + } + + @Test +@@ -82,67 +82,67 @@ class EWMATest { + ewma.update(3); + ewma.tick(); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.18071653, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.14795818, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.12113791, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.09917933, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.06648190, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.05443077, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.04456415, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.03648604, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); + } + + @Test +@@ -151,67 +151,67 @@ class EWMATest { + ewma.update(3); + ewma.tick(); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.56130419, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.52510399, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.45955700, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.42991879, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.37625345, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.35198773, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.30805027, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.28818318, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.25221023, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.23594443, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001)); + + elapseMinute(ewma); + +- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); ++ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); + } + + private void elapseMinute(EWMA ewma) { +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java +index 2a21820..c1f8a8c 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java +@@ -7,10 +7,10 @@ import static org.mockito.Mockito.when; + import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + +-public class ExponentialMovingAveragesTest { ++final class ExponentialMovingAveragesTest { + @Test +- public void testMaxTicks() { +- final Clock clock = mock(Clock.class); ++ void maxTicks() { ++ final Clock clock = mock(); + when(clock.getTick()).thenReturn(0L, Long.MAX_VALUE); + final ExponentialMovingAverages ema = new ExponentialMovingAverages(clock); + ema.update(Long.MAX_VALUE); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java +index 5985e81..151ccbc 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.collect.ImmutableList.toImmutableList; + import static org.assertj.core.api.Assertions.assertThat; + + import java.util.Arrays; +@@ -7,11 +8,10 @@ import java.util.Collection; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicBoolean; + import java.util.concurrent.atomic.AtomicInteger; +-import java.util.stream.Collectors; + import org.junit.jupiter.params.ParameterizedTest; + import org.junit.jupiter.params.provider.MethodSource; + +-public class ExponentiallyDecayingReservoirTest { ++final class ExponentiallyDecayingReservoirTest { + + public enum ReservoirFactory { + EXPONENTIALLY_DECAYING() { +@@ -42,7 +42,7 @@ public class ExponentiallyDecayingReservoirTest { + public static Collection reservoirs() { + return Arrays.stream(ReservoirFactory.values()) + .map(value -> new Object[] {value}) +- .collect(Collectors.toList()); ++ .collect(toImmutableList()); + } + + private ReservoirFactory reservoirFactory; +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java +index c0a9f6b..5b003df 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java +@@ -8,7 +8,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.junit.jupiter.api.io.TempDir; + +-public class FixedNameCsvFileProviderTest { ++final class FixedNameCsvFileProviderTest { + @TempDir public File folder; + + private File dataDirectory; +@@ -19,7 +19,7 @@ public class FixedNameCsvFileProviderTest { + } + + @Test +- void testGetFile() { ++ void getFile() { + FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); + File file = provider.getFile(dataDirectory, "test"); + assertThat(file.getParentFile()).isEqualTo(dataDirectory); +@@ -27,7 +27,7 @@ public class FixedNameCsvFileProviderTest { + } + + @Test +- void testGetFileSanitize() { ++ void getFileSanitize() { + FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); + File file = provider.getFile(dataDirectory, "/myfake/uri"); + assertThat(file.getParentFile()).isEqualTo(dataDirectory); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java +index 770c53a..ec2901f 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java +@@ -7,14 +7,14 @@ import static org.mockito.Mockito.when; + + import org.junit.jupiter.api.Test; + +-class HistogramTest { +- private final Reservoir reservoir = mock(Reservoir.class); ++final class HistogramTest { ++ private final Reservoir reservoir = mock(); + private final Histogram histogram = new Histogram(reservoir); + + @Test + void updatesTheCountAndSumOnUpdates() { +- assertThat(histogram.getCount()).isZero(); +- assertThat(histogram.getSum()).isZero(); ++ assertThat(histogram.getCount()).isEqualTo(0); ++ assertThat(histogram.getSum()).isEqualTo(0); + + histogram.update(1); + histogram.update(5); +@@ -25,7 +25,7 @@ class HistogramTest { + + @Test + void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(reservoir.getSnapshot()).thenReturn(snapshot); + + assertThat(histogram.getSnapshot()).isEqualTo(snapshot); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java +index 46d7690..cfb2386 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java +@@ -19,10 +19,9 @@ import org.junit.jupiter.api.Test; + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + +-class InstrumentedExecutorServiceTest { ++final class InstrumentedExecutorServiceTest { + +- private static final Logger LOGGER = +- LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); ++ private static final Logger LOG = LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); + private ExecutorService executor; + private MetricRegistry registry; + private InstrumentedExecutorService instrumentedExecutorService; +@@ -48,7 +47,7 @@ class InstrumentedExecutorServiceTest { + void tearDown() throws Exception { + instrumentedExecutorService.shutdown(); + if (!instrumentedExecutorService.awaitTermination(2, TimeUnit.SECONDS)) { +- LOGGER.error("InstrumentedExecutorService did not terminate."); ++ LOG.error("InstrumentedExecutorService did not terminate."); + } + } + +@@ -115,8 +114,8 @@ class InstrumentedExecutorServiceTest { + assertThat(idle.getSnapshot().size()).isEqualTo(1); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + void reportsTasksInformationForThreadPoolExecutor() throws Exception { + executor = + new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); +@@ -180,7 +179,7 @@ class InstrumentedExecutorServiceTest { + } + + @Test +- public void reportsRejectedTasksForThreadPoolExecutor() throws Exception { ++ void reportsRejectedTasksForThreadPoolExecutor() throws Exception { + executor = + new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1)); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); +@@ -207,7 +206,7 @@ class InstrumentedExecutorServiceTest { + } + + @Test +- public void removesMetricsAfterShutdownForThreadPoolExecutor() { ++ void removesMetricsAfterShutdownForThreadPoolExecutor() { + executor = + new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "stp"); +@@ -236,8 +235,8 @@ class InstrumentedExecutorServiceTest { + MetricRegistry.name("stp", "tasks.capacity")); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + void reportsTasksInformationForForkJoinPool() throws Exception { + executor = Executors.newWorkStealingPool(4); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); +@@ -291,7 +290,7 @@ class InstrumentedExecutorServiceTest { + } + + @Test +- public void removesMetricsAfterShutdownForForkJoinPool() { ++ void removesMetricsAfterShutdownForForkJoinPool() { + executor = Executors.newWorkStealingPool(4); + instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "sfjp"); + +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java +index fb9cbe9..b85071b 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java +@@ -13,8 +13,8 @@ import org.junit.jupiter.api.Test; + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + +-class InstrumentedScheduledExecutorServiceTest { +- private static final Logger LOGGER = ++final class InstrumentedScheduledExecutorServiceTest { ++ private static final Logger LOG = + LoggerFactory.getLogger(InstrumentedScheduledExecutorServiceTest.class); + + private final ScheduledExecutorService scheduledExecutor = +@@ -35,17 +35,17 @@ class InstrumentedScheduledExecutorServiceTest { + private final Histogram percentOfPeriod = registry.histogram("xs.scheduled.percent-of-period"); + + @Test +- void testSubmitRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void submitRunnable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + Future theFuture = + instrumentedScheduledExecutor.submit( +@@ -53,87 +53,87 @@ class InstrumentedScheduledExecutorServiceTest { + assertThat(submitted.getCount()).isEqualTo(1); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + }); + + theFuture.get(); + + assertThat(submitted.getCount()).isEqualTo(1); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test +- void testScheduleRunnable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void scheduleRunnable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + ScheduledFuture theFuture = + instrumentedScheduledExecutor.schedule( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + }, + 10L, + TimeUnit.MILLISECONDS); + + theFuture.get(); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test +- void testSubmitCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void submitCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + final Object obj = new Object(); + +@@ -143,13 +143,13 @@ class InstrumentedScheduledExecutorServiceTest { + assertThat(submitted.getCount()).isEqualTo(1); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + return obj; + }); +@@ -158,45 +158,45 @@ class InstrumentedScheduledExecutorServiceTest { + + assertThat(submitted.getCount()).isEqualTo(1); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test +- void testScheduleCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void scheduleCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + final Object obj = new Object(); + + ScheduledFuture theFuture = + instrumentedScheduledExecutor.schedule( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + return obj; + }, +@@ -205,37 +205,37 @@ class InstrumentedScheduledExecutorServiceTest { + + assertThat(theFuture.get()).isEqualTo(obj); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isEqualTo(1); + assertThat(duration.getCount()).isEqualTo(1); + assertThat(duration.getSnapshot().size()).isEqualTo(1); + + assertThat(scheduledOnce.getCount()).isEqualTo(1); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + } + + @Test +- void testScheduleFixedRateCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void scheduleFixedRateCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + CountDownLatch countDownLatch = new CountDownLatch(1); + ScheduledFuture theFuture = + instrumentedScheduledExecutor.scheduleAtFixedRate( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); + +@@ -257,37 +257,37 @@ class InstrumentedScheduledExecutorServiceTest { + theFuture.cancel(true); + TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isNotEqualTo(0); + assertThat(duration.getCount()).isNotEqualTo(0); + assertThat(duration.getSnapshot().size()).isNotEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); + assertThat(scheduledRepetitively.getCount()).isEqualTo(1); + assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); + assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); + } + + @Test +- void testScheduleFixedDelayCallable() throws Exception { +- assertThat(submitted.getCount()).isZero(); ++ void scheduleFixedDelayCallable() throws Exception { ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); +- assertThat(completed.getCount()).isZero(); +- assertThat(duration.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); ++ assertThat(completed.getCount()).isEqualTo(0); ++ assertThat(duration.getCount()).isEqualTo(0); + +- assertThat(scheduledOnce.getCount()).isZero(); +- assertThat(scheduledRepetitively.getCount()).isZero(); +- assertThat(scheduledOverrun.getCount()).isZero(); +- assertThat(percentOfPeriod.getCount()).isZero(); ++ assertThat(scheduledOnce.getCount()).isEqualTo(0); ++ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); ++ assertThat(scheduledOverrun.getCount()).isEqualTo(0); ++ assertThat(percentOfPeriod.getCount()).isEqualTo(0); + + CountDownLatch countDownLatch = new CountDownLatch(1); + ScheduledFuture theFuture = + instrumentedScheduledExecutor.scheduleWithFixedDelay( + () -> { +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + + assertThat(running.getCount()).isEqualTo(1); + +@@ -310,9 +310,9 @@ class InstrumentedScheduledExecutorServiceTest { + theFuture.cancel(true); + TimeUnit.MILLISECONDS.sleep(200); + +- assertThat(submitted.getCount()).isZero(); ++ assertThat(submitted.getCount()).isEqualTo(0); + +- assertThat(running.getCount()).isZero(); ++ assertThat(running.getCount()).isEqualTo(0); + assertThat(completed.getCount()).isNotEqualTo(0); + assertThat(duration.getCount()).isNotEqualTo(0); + assertThat(duration.getSnapshot().size()).isNotEqualTo(0); +@@ -322,7 +322,7 @@ class InstrumentedScheduledExecutorServiceTest { + void tearDown() throws Exception { + instrumentedScheduledExecutor.shutdown(); + if (!instrumentedScheduledExecutor.awaitTermination(2, TimeUnit.SECONDS)) { +- LOGGER.error("InstrumentedScheduledExecutorService did not terminate."); ++ LOG.error("InstrumentedScheduledExecutorService did not terminate."); + } + } + } +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java +index fcd3736..1228864 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java +@@ -11,7 +11,7 @@ import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.Test; + +-class InstrumentedThreadFactoryTest { ++final class InstrumentedThreadFactoryTest { + private static final int THREAD_COUNT = 10; + + private final ThreadFactory factory = Executors.defaultThreadFactory(); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java +index 32c2380..e2fe1d8 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java +@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.params.ParameterizedTest; + import org.junit.jupiter.params.provider.MethodSource; + +-public class MeterApproximationTest { ++final class MeterApproximationTest { + + public static Collection ratesPerMinute() { + Object[][] data = new Object[][] {{15}, {60}, {600}, {6000}}; +@@ -32,7 +32,7 @@ public class MeterApproximationTest { + 3, TimeUnit.MINUTES); + + assertThat(meter.getOneMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } + + @MethodSource("ratesPerMinute") +@@ -45,7 +45,7 @@ public class MeterApproximationTest { + 13, TimeUnit.MINUTES); + + assertThat(meter.getFiveMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } + + @MethodSource("ratesPerMinute") +@@ -58,7 +58,7 @@ public class MeterApproximationTest { + 38, TimeUnit.MINUTES); + + assertThat(meter.getFifteenMinuteRate() * 60.0) +- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); ++ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); + } + + private Meter simulateMetronome( +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java +index afddef9..f589811 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java +@@ -9,8 +9,8 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class MeterTest { +- private final Clock clock = mock(Clock.class); ++final class MeterTest { ++ private final Clock clock = mock(); + private final Meter meter = new Meter(clock); + + @BeforeEach +@@ -20,17 +20,17 @@ class MeterTest { + + @Test + void startsOutWithNoRatesOrCount() { +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + +- assertThat(meter.getSum()).isZero(); ++ assertThat(meter.getSum()).isEqualTo(0); + +- assertThat(meter.getMeanRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); + } + + @Test +@@ -42,12 +42,12 @@ class MeterTest { + + assertThat(meter.getSum()).isEqualTo(10000000000L); + +- assertThat(meter.getMeanRate()).isEqualTo(0.3, offset(0.001)); ++ assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001)); + +- assertThat(meter.getOneMinuteRate()).isEqualTo(0.1840, offset(0.001)); ++ assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001)); + +- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.1966, offset(0.001)); ++ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001)); + +- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.1988, offset(0.001)); ++ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001)); + } + } +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java +index 6152bde..53dfece 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java +@@ -5,7 +5,7 @@ import static org.mockito.Mockito.mock; + + import org.junit.jupiter.api.Test; + +-class MetricFilterTest { ++final class MetricFilterTest { + @Test + void theAllFilterMatchesAllMetrics() { + assertThat(MetricFilter.ALL.matches(MetricName.build(""), mock(Metric.class))).isTrue(); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java +index 490c830..35860d7 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java +@@ -1,105 +1,106 @@ + package io.dropwizard.metrics5; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + + import java.util.HashMap; + import java.util.Map; + import org.junit.jupiter.api.Test; + +-class MetricNameTest { ++final class MetricNameTest { + @Test +- void testEmpty() { ++ void empty() { + assertThat(MetricName.EMPTY.getTags()).isEmpty(); +- assertThat(MetricName.EMPTY.getKey()).isEqualTo(""); ++ assertThat(MetricName.EMPTY.getKey()).isEmpty(); + + assertThat(MetricName.build()).isEqualTo(MetricName.EMPTY); + assertThat(MetricName.EMPTY.resolve((String) null)).isEqualTo(MetricName.EMPTY); + } + + @Test +- void testEmptyResolve() { ++ void emptyResolve() { + final MetricName name = MetricName.build(); + assertThat(name.resolve("foo")).isEqualTo(MetricName.build("foo")); + } + + @Test +- void testResolveToEmpty() { ++ void resolveToEmpty() { + final MetricName name = MetricName.build("foo"); + assertThat(name.resolve((String) null)).isEqualTo(MetricName.build("foo")); + } + + @Test +- void testResolve() { ++ void resolve() { + final MetricName name = MetricName.build("foo"); + assertThat(name.resolve("bar")).isEqualTo(MetricName.build("foo.bar")); + } + + @Test +- void testResolveBothEmpty() { ++ void resolveBothEmpty() { + final MetricName name = MetricName.build(); + assertThat(name.resolve((String) null)).isEqualTo(MetricName.EMPTY); + } + + @Test +- void testAddTagsVarious() { ++ void addTagsVarious() { + final Map refTags = new HashMap(); + refTags.put("foo", "bar"); + final MetricName test = MetricName.EMPTY.tagged("foo", "bar"); + final MetricName test2 = MetricName.EMPTY.tagged(refTags); + + assertThat(test).isEqualTo(new MetricName("", refTags)); +- assertThat(test.getTags()).isEqualTo(refTags); ++ assertThat(test.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); + + assertThat(test2).isEqualTo(new MetricName("", refTags)); +- assertThat(test2.getTags()).isEqualTo(refTags); ++ assertThat(test2.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); + } + + @Test +- void testTaggedMoreArguments() { ++ void taggedMoreArguments() { + final Map refTags = new HashMap(); + refTags.put("foo", "bar"); + refTags.put("baz", "biz"); +- assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()).isEqualTo(refTags); ++ assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()) ++ .containsExactlyInAnyOrderEntriesOf(refTags); + } + + @Test +- void testTaggedNotPairs() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- MetricName.EMPTY.tagged("foo"); +- }); ++ void taggedNotPairs() { ++ assertThatThrownBy( ++ () -> { ++ MetricName.EMPTY.tagged("foo"); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test +- void testTaggedNotPairs2() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- MetricName.EMPTY.tagged("foo", "bar", "baz"); +- }); ++ void taggedNotPairs2() { ++ assertThatThrownBy( ++ () -> { ++ MetricName.EMPTY.tagged("foo", "bar", "baz"); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test +- void testCompareTo() { ++ void compareTo() { + final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); + final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); + +- assertThat(a.compareTo(b)).isLessThan(0); +- assertThat(b.compareTo(a)).isGreaterThan(0); +- assertThat(b.resolve("key").compareTo(b)).isGreaterThan(0); +- assertThat(b.compareTo(b.resolve("key"))).isLessThan(0); ++ assertThat(a.compareTo(b)).isNegative(); ++ assertThat(b.compareTo(a)).isPositive(); ++ assertThat(b.resolve("key").compareTo(b)).isPositive(); ++ assertThat(b.compareTo(b.resolve("key"))).isNegative(); + } + + @Test +- void testCompareTo2() { ++ void compareTo2() { + final MetricName a = MetricName.EMPTY.tagged("a", "x"); + final MetricName b = MetricName.EMPTY.tagged("b", "x"); + +- assertThat(MetricName.EMPTY.compareTo(a)).isLessThan(0); +- assertThat(MetricName.EMPTY.compareTo(b)).isLessThan(0); +- assertThat(a.compareTo(b)).isLessThan(0); +- assertThat(b.compareTo(a)).isGreaterThan(0); ++ assertThat(MetricName.EMPTY.compareTo(a)).isNegative(); ++ assertThat(MetricName.EMPTY.compareTo(b)).isNegative(); ++ assertThat(a.compareTo(b)).isNegative(); ++ assertThat(b.compareTo(a)).isPositive(); + } + } +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java +index 3f9b427..a32294b 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java +@@ -5,13 +5,13 @@ import static org.mockito.Mockito.verifyNoInteractions; + + import org.junit.jupiter.api.Test; + +-class MetricRegistryListenerTest { ++final class MetricRegistryListenerTest { + private static final MetricName BLAH = MetricName.build("blah"); + +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + private final MetricRegistryListener listener = new MetricRegistryListener.Base() {}; + + @Test +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java +index 865dfca..d79a191 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.collect.ImmutableSet.toImmutableSet; + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatThrownBy; +@@ -15,7 +16,7 @@ import java.util.stream.Collectors; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class MetricRegistryTest { ++final class MetricRegistryTest { + + private static class CustomCounter extends Counter { + +@@ -37,14 +38,14 @@ class MetricRegistryTest { + private static final MetricName GAUGE2 = MetricName.build("gauge2"); + private static final MetricName SETTABLE_GAUGE = MetricName.build("settable-gauge"); + private static final MetricName THING = MetricName.build("thing"); +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); ++ private final MetricRegistryListener listener = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final Gauge gauge = () -> ""; + private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + + @BeforeEach + void setUp() { +@@ -291,7 +292,7 @@ class MetricRegistryTest { + registry.register(METER2, meter); + registry.register(TIMER2, timer); + +- final MetricRegistryListener other = mock(MetricRegistryListener.class); ++ final MetricRegistryListener other = mock(); + registry.addListener(other); + + verify(other).onGaugeAdded(GAUGE2, gauge); +@@ -425,7 +426,7 @@ class MetricRegistryTest { + MetricRegistry other = new MetricRegistry(); + other.register(GAUGE, gauge); + registry.register(MetricName.build("nested"), other); +- assertThat(registry.getNames()).containsOnly(MetricName.build("nested.gauge")); ++ assertThat(registry.getNames()).containsExactly(MetricName.build("nested.gauge")); + } + + @Test +@@ -501,7 +502,7 @@ class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) + .collect(Collectors.toSet())); +@@ -522,7 +523,7 @@ class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) + .collect(Collectors.toSet())); +@@ -548,7 +549,7 @@ class MetricRegistryTest { + Set deepChildMetrics = deepChild.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) + .collect(Collectors.toSet())); +@@ -557,10 +558,10 @@ class MetricRegistryTest { + .containsAll( + deepChildMetrics.stream() + .map(m -> MetricName.build("deep-child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + +- assertThat(deepChildMetrics.size()).isEqualTo(3); +- assertThat(childMetrics.size()).isEqualTo(5); ++ assertThat(deepChildMetrics).hasSize(3); ++ assertThat(childMetrics).hasSize(5); + } + + @Test +@@ -578,7 +579,7 @@ class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) + .collect(Collectors.toSet())); +@@ -604,7 +605,7 @@ class MetricRegistryTest { + Set childMetrics = child.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) + .collect(Collectors.toSet())); +@@ -633,7 +634,7 @@ class MetricRegistryTest { + Set deepChildMetrics = deepChild.getMetrics().keySet(); + + assertThat(parentMetrics) +- .isEqualTo( ++ .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) + .collect(Collectors.toSet())); +@@ -642,12 +643,12 @@ class MetricRegistryTest { + .containsAll( + deepChildMetrics.stream() + .map(m -> MetricName.build("deep-child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(deepChildMetrics).doesNotContain(MetricName.build("test-2")); + +- assertThat(deepChildMetrics.size()).isEqualTo(1); +- assertThat(childMetrics.size()).isEqualTo(3); ++ assertThat(deepChildMetrics).hasSize(1); ++ assertThat(childMetrics).hasSize(3); + } + + @Test +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java +index 657462d..0dc6e29 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java +@@ -1,7 +1,7 @@ + package io.dropwizard.metrics5; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatNullPointerException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; + import static org.mockito.Mockito.verify; +@@ -12,16 +12,16 @@ import java.util.Set; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class NoopMetricRegistryTest { ++final class NoopMetricRegistryTest { + private static final MetricName METRIC_THING = MetricName.build("thing"); + +- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); ++ private final MetricRegistryListener listener = mock(); + private final NoopMetricRegistry registry = new NoopMetricRegistry(); + private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + + @BeforeEach + void setUp() { +@@ -220,8 +220,8 @@ class NoopMetricRegistryTest { + verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); + } + +- @Test + @SuppressWarnings("rawtypes") ++ @Test + void accessingACustomGaugeRegistersAndReusesIt() { + final MetricRegistry.MetricSupplier> supplier = () -> gauge; + final Gauge gauge1 = registry.gauge(METRIC_THING, supplier); +@@ -242,7 +242,7 @@ class NoopMetricRegistryTest { + registry.register(MetricName.build("meter"), meter); + registry.register(MetricName.build("timer"), timer); + +- final MetricRegistryListener other = mock(MetricRegistryListener.class); ++ final MetricRegistryListener other = mock(); + registry.addListener(other); + + verify(other, never()).onGaugeAdded(MetricName.build("gauge"), gauge); +@@ -491,8 +491,8 @@ class NoopMetricRegistryTest { + @Test + void registerNullMetric() { + MetricRegistry registry = new NoopMetricRegistry(); +- assertThatNullPointerException() +- .isThrownBy(() -> registry.register(MetricName.build("any_name"), null)) +- .withMessage("metric == null"); ++ assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)) ++ .isInstanceOf(NullPointerException.class) ++ .hasMessage("metric == null"); + } + } +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java +index 15ea461..e181635 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java +@@ -4,12 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-class RatioGaugeTest { ++final class RatioGaugeTest { + @Test + void ratiosAreHumanReadable() { + final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); + +- assertThat(ratio.toString()).isEqualTo("100.0:200.0"); ++ assertThat(ratio).hasToString("100.0:200.0"); + } + + @Test +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java +index 5f2f8ad..a3e7329 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java +@@ -1,10 +1,8 @@ + package io.dropwizard.metrics5; + ++import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertFalse; +-import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.junit.jupiter.api.Assertions.assertTrue; +-import static org.junit.jupiter.api.Assertions.fail; + import static org.mockito.Mockito.any; + import static org.mockito.Mockito.eq; + import static org.mockito.Mockito.mock; +@@ -21,18 +19,19 @@ import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.TimeoutException; + import java.util.concurrent.atomic.AtomicInteger; ++import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class ScheduledReporterTest { ++final class ScheduledReporterTest { + private final Gauge gauge = () -> ""; +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); + +- private final ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); ++ private final ScheduledExecutorService mockExecutor = mock(); + private final ScheduledExecutorService customExecutor = + Executors.newSingleThreadScheduledExecutor(); + private final ScheduledExecutorService externalExecutor = +@@ -107,7 +106,7 @@ class ScheduledReporterTest { + r = + new DummyReporter( + null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); +- fail("NullPointerException must be thrown !!!"); ++ Assertions.fail("NullPointerException must be thrown !!!"); + } catch (NullPointerException e) { + assertEquals("registry == null", e.getMessage()); + } finally { +@@ -145,7 +144,7 @@ class ScheduledReporterTest { + void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { + reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); + +- verify(mockExecutor, times(1)) ++ verify(mockExecutor) + .scheduleWithFixedDelay(any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS)); + } + +@@ -182,32 +181,32 @@ class ScheduledReporterTest { + + @Test + void shouldDisallowToStartReportingMultiple() throws Exception { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- reporter.start(200, TimeUnit.MILLISECONDS); +- reporter.start(200, TimeUnit.MILLISECONDS); +- }); ++ assertThatThrownBy( ++ () -> { ++ reporter.start(200, TimeUnit.MILLISECONDS); ++ reporter.start(200, TimeUnit.MILLISECONDS); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); +- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); +- }); ++ assertThatThrownBy( ++ () -> { ++ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); ++ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void shouldDisallowToStartReportingMultipleTimesOnExternallyManagedExecutor() throws Exception { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); +- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); +- }); ++ assertThatThrownBy( ++ () -> { ++ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); ++ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test +@@ -231,15 +230,15 @@ class ScheduledReporterTest { + void shouldShutdownExecutorOnStopByDefault() { + reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); + reporterWithCustomExecutor.stop(); +- assertTrue(customExecutor.isTerminated()); ++ assertThat(customExecutor.isTerminated()).isTrue(); + } + + @Test + void shouldNotShutdownExternallyManagedExecutorOnStop() { + reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); + reporterWithExternallyManagedExecutor.stop(); +- assertFalse(mockExecutor.isTerminated()); +- assertFalse(mockExecutor.isShutdown()); ++ assertThat(mockExecutor.isTerminated()).isFalse(); ++ assertThat(mockExecutor.isShutdown()).isFalse(); + } + + @Test +@@ -306,7 +305,7 @@ class ScheduledReporterTest { + + Thread.sleep(1_000); + +- verify(reporter, times(1)) ++ verify(reporter) + .report( + map(MetricName.build("gauge"), gauge), + map(MetricName.build("counter"), counter), +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java +index 9bdc888..9d0a08b 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java +@@ -2,13 +2,12 @@ package io.dropwizard.metrics5; + + import static org.assertj.core.api.Assertions.assertThat; + import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.junit.jupiter.api.Assertions.assertTrue; + + import java.util.concurrent.atomic.AtomicReference; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class SharedMetricRegistriesTest { ++final class SharedMetricRegistriesTest { + + @BeforeEach + void setUp() { +@@ -28,7 +27,7 @@ class SharedMetricRegistriesTest { + void hasASetOfNames() { + SharedMetricRegistries.getOrCreate("one"); + +- assertThat(SharedMetricRegistries.names()).containsOnly("one"); ++ assertThat(SharedMetricRegistries.names()).containsExactly("one"); + } + + @Test +@@ -60,7 +59,7 @@ class SharedMetricRegistriesTest { + () -> { + SharedMetricRegistries.getDefault(); + }); +- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); ++ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); + } + + @Test +@@ -81,7 +80,8 @@ class SharedMetricRegistriesTest { + SharedMetricRegistries.setDefault("foobah"); + SharedMetricRegistries.setDefault("borg"); + }); +- assertTrue(exception.getMessage().contains("Default metric registry name is already set.")); ++ assertThat(exception.getMessage().contains("Default metric registry name is already set.")) ++ .isTrue(); + } + + @Test +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java +index 78e54ea..d95e9c8 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-class SimpleSettableGaugeTest { ++final class SimpleSettableGaugeTest { + + @Test + void defaultValue() { +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java +index cd5f781..1aa7767 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java +@@ -3,7 +3,6 @@ package io.dropwizard.metrics5; + import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; +@@ -20,11 +19,11 @@ import org.junit.jupiter.api.Test; + import org.slf4j.Logger; + import org.slf4j.Marker; + +-class Slf4jReporterTest { ++final class Slf4jReporterTest { + +- private final Logger logger = mock(Logger.class); +- private final Marker marker = mock(Marker.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final Logger logger = mock(); ++ private final Marker marker = mock(); ++ private final MetricRegistry registry = mock(); + + /** + * The set of disabled metric attributes to pass to the Slf4jReporter builder in the default +@@ -79,7 +78,7 @@ class Slf4jReporterTest { + } + + private Timer timer() { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + + when(timer.getMeanRate()).thenReturn(2.0); +@@ -87,7 +86,7 @@ class Slf4jReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -104,10 +103,10 @@ class Slf4jReporterTest { + } + + private Histogram histogram() { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -124,7 +123,7 @@ class Slf4jReporterTest { + } + + private Meter meter() { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(3.0); +@@ -134,7 +133,7 @@ class Slf4jReporterTest { + } + + private Counter counter() { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + return counter; + } +@@ -168,7 +167,7 @@ class Slf4jReporterTest { + + @Test + void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); ++ disabledMetricAttributes = EnumSet.of(COUNT, MetricAttribute.MIN, P50); + reportsHistogramValuesAtError( + "type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " + + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); +@@ -192,7 +191,7 @@ class Slf4jReporterTest { + + @Test + void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, P50, M1_RATE); + reportsMeterValuesAtError( + "type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " + + "mean_rate=2.0, rate_unit=events/second"); +@@ -218,7 +217,7 @@ class Slf4jReporterTest { + + @Test + void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { +- disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); ++ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, STDDEV, P999, MEAN_RATE); + reportsTimerValuesAtError( + "type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " + + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java +index 3063fe2..c6a8b49 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java +@@ -12,11 +12,11 @@ import java.util.concurrent.atomic.AtomicLong; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("Duplicates") +-class SlidingTimeWindowArrayReservoirTest { ++final class SlidingTimeWindowArrayReservoirTest { + + @Test + void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); + +@@ -30,7 +30,7 @@ class SlidingTimeWindowArrayReservoirTest { + + @Test + void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); + +@@ -82,7 +82,7 @@ class SlidingTimeWindowArrayReservoirTest { + } + + @Test +- void testGetTickOverflow() { ++ void getTickOverflow() { + final Random random = new Random(0); + final int window = 128; + AtomicLong counter = new AtomicLong(0L); +@@ -99,7 +99,7 @@ class SlidingTimeWindowArrayReservoirTest { + // Set the clock to overflow in (2*window+1)ns + final ManualClock clock = new ManualClock(); + clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); ++ assertThat(clock.getTick() * 256).isPositive(); + + // Create the reservoir + final SlidingTimeWindowArrayReservoir reservoir = +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java +index 1dc69b9..748536b 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java +@@ -7,7 +7,7 @@ import java.time.Instant; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class SlidingTimeWindowMovingAveragesTest { ++final class SlidingTimeWindowMovingAveragesTest { + + private ManualClock clock; + private SlidingTimeWindowMovingAverages movingAverages; +@@ -42,7 +42,7 @@ class SlidingTimeWindowMovingAveragesTest { + + SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); + +- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(0L))).isEqualTo(0); ++ assertThat(stwm.calculateIndexOfTick(Instant.EPOCH)).isEqualTo(0); + assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L))).isEqualTo(1); + } + +@@ -60,7 +60,7 @@ class SlidingTimeWindowMovingAveragesTest { + } + + // verify that no cleanup happened yet +- assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.ofEpochSecond(0L)); ++ assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.EPOCH); + + assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); + assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java +index 3677975..0817849 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java +@@ -9,10 +9,10 @@ import java.util.Arrays; + import java.util.Random; + import org.junit.jupiter.api.Test; + +-class SlidingTimeWindowReservoirTest { ++final class SlidingTimeWindowReservoirTest { + @Test + void storesMeasurementsWithDuplicateTicks() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + final SlidingTimeWindowReservoir reservoir = + new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); + +@@ -26,7 +26,7 @@ class SlidingTimeWindowReservoirTest { + + @Test + void boundsMeasurementsToATimeWindow() { +- final Clock clock = mock(Clock.class); ++ final Clock clock = mock(); + when(clock.getTick()).thenReturn(0L); + + final SlidingTimeWindowReservoir reservoir = +@@ -51,7 +51,7 @@ class SlidingTimeWindowReservoirTest { + } + + @Test +- void testGetTickOverflow() { ++ void getTickOverflow() { + final Random random = new Random(0); + final int window = 128; + +@@ -72,7 +72,7 @@ class SlidingTimeWindowReservoirTest { + + // Set the clock to overflow in (2*window+1)ns + clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); +- assertThat(clock.getTick() * 256).isGreaterThan(0); ++ assertThat(clock.getTick() * 256).isPositive(); + + int updatesAfterThreshold = 0; + while (true) { +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java +index 2f6bbd0..122e7d5 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java +@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-class SlidingWindowReservoirTest { ++final class SlidingWindowReservoirTest { + private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); + + @Test +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java +index 55eb3e3..7281be4 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java +@@ -12,8 +12,8 @@ import java.util.concurrent.TimeUnit; + import java.util.concurrent.atomic.AtomicBoolean; + import org.junit.jupiter.api.Test; + +-class TimerTest { +- private final Reservoir reservoir = mock(Reservoir.class); ++final class TimerTest { ++ private final Reservoir reservoir = mock(); + private final Clock clock = + new Clock() { + // a mock clock that increments its ticker by 50msec per call +@@ -28,23 +28,23 @@ class TimerTest { + + @Test + void hasRates() { +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + +- assertThat(timer.getSum()).isZero(); ++ assertThat(timer.getSum()).isEqualTo(0); + +- assertThat(timer.getMeanRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); + +- assertThat(timer.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); ++ assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); + } + + @Test + void updatesTheCountAndSumOnUpdates() { +- assertThat(timer.getCount()).isZero(); +- assertThat(timer.getSum()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); ++ assertThat(timer.getSum()).isEqualTo(0); + + timer.update(1, TimeUnit.SECONDS); + timer.update(5, TimeUnit.SECONDS); +@@ -101,7 +101,7 @@ class TimerTest { + + @Test + void returnsTheSnapshotFromTheReservoir() { +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(reservoir.getSnapshot()).thenReturn(snapshot); + + assertThat(timer.getSnapshot()).isEqualTo(snapshot); +@@ -111,8 +111,8 @@ class TimerTest { + void ignoresNegativeValues() { + timer.update(-1, TimeUnit.SECONDS); + +- assertThat(timer.getCount()).isZero(); +- assertThat(timer.getSum()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); ++ assertThat(timer.getSum()).isEqualTo(0); + + verifyNoInteractions(reservoir); + } +@@ -130,15 +130,15 @@ class TimerTest { + void java8NegativeDuration() { + timer.update(Duration.ofMillis(-5678)); + +- assertThat(timer.getCount()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); + + verifyNoInteractions(reservoir); + } + + @Test + void tryWithResourcesWork() { +- assertThat(timer.getCount()).isZero(); +- assertThat(timer.getSum()).isZero(); ++ assertThat(timer.getCount()).isEqualTo(0); ++ assertThat(timer.getSum()).isEqualTo(0); + + int dummy = 0; + try (Timer.Context context = timer.time()) { +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java +index fbab25c..50c682e 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java +@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat; + + import org.junit.jupiter.api.Test; + +-class UniformReservoirTest { +- @Test ++final class UniformReservoirTest { + @SuppressWarnings("unchecked") ++ @Test + void aReservoirOf100OutOf1000Elements() { + final UniformReservoir reservoir = new UniformReservoir(100); + for (int i = 0; i < 1000; i++) { +@@ -20,7 +20,7 @@ class UniformReservoirTest { + assertThat(snapshot.size()).isEqualTo(100); + + for (double i : snapshot.getValues()) { +- assertThat(i).isLessThan(1000).isGreaterThanOrEqualTo(0); ++ assertThat(i).isLessThan(1000).isNotNegative(); + } + } + } +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java +index 34ffc56..5db094c 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java +@@ -2,8 +2,8 @@ package io.dropwizard.metrics5; + + import static java.util.Arrays.asList; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.assertj.core.api.Assertions.offset; +-import static org.junit.jupiter.api.Assertions.assertThrows; + + import java.io.ByteArrayOutputStream; + import java.util.Random; +@@ -12,74 +12,74 @@ import java.util.concurrent.CountDownLatch; + import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + +-class UniformSnapshotTest { ++final class UniformSnapshotTest { + private final Snapshot snapshot = new UniformSnapshot(new long[] {5, 1, 2, 3, 4}); + + @Test + void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)).isEqualTo(1, offset(0.1)); ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1)); + } + + @Test + void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)).isEqualTo(5, offset(0.1)); ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1)); + } + + @Test + void disallowsNotANumberQuantile() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(Double.NaN); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(Double.NaN); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disallowsNegativeQuantile() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(-0.5); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(-0.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disallowsQuantileOverOne() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(1.5); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(1.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); ++ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1)); + } + + @Test + void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1)); + } + + @Test + void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test +@@ -138,7 +138,7 @@ class UniformSnapshotTest { + + snapshot.dump(output); + +- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); + } + + @Test +@@ -158,41 +158,41 @@ class UniformSnapshotTest { + + @Test + void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()).isEqualTo(1.5811, offset(0.0001)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001)); + } + + @Test + void calculatesAMinOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMin()).isZero(); ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); + } + + @Test + void calculatesAMaxOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMax()).isZero(); ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); + } + + @Test + void calculatesAMeanOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getMean()).isZero(); ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); + } + + @Test + void calculatesAStdDevOfZeroForAnEmptySnapshot() { + final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); + +- assertThat(emptySnapshot.getStdDev()).isZero(); ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); + } + + @Test + void calculatesAStdDevOfZeroForASingletonSnapshot() { + final Snapshot singleItemSnapshot = new UniformSnapshot(new long[] {1}); + +- assertThat(singleItemSnapshot.getStdDev()).isZero(); ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); + } + } +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java +index f53854f..052948c 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java +@@ -1,8 +1,10 @@ + package io.dropwizard.metrics5; + ++import static com.google.common.base.Preconditions.checkArgument; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.assertj.core.api.Assertions.offset; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.mockito.ArgumentMatchers.any; + import static org.mockito.Mockito.doReturn; + import static org.mockito.Mockito.spy; + import static org.mockito.Mockito.when; +@@ -12,16 +14,14 @@ import java.io.ByteArrayOutputStream; + import java.util.ArrayList; + import java.util.List; + import org.junit.jupiter.api.Test; +-import org.mockito.ArgumentMatchers; + +-class WeightedSnapshotTest { ++final class WeightedSnapshotTest { + + private static List weightedArray( + long[] values, double[] weights) { +- if (values.length != weights.length) { +- throw new IllegalArgumentException( +- "Mismatched lengths: " + values.length + " vs " + weights.length); +- } ++ checkArgument( ++ values.length == weights.length, ++ "Mismatched lengths: " + values.length + " vs " + weights.length); + + final List samples = new ArrayList<>(); + for (int i = 0; i < values.length; i++) { +@@ -36,69 +36,69 @@ class WeightedSnapshotTest { + + @Test + void smallQuantilesAreTheFirstValue() { +- assertThat(snapshot.getValue(0.0)).isEqualTo(1.0, offset(0.1)); ++ assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1)); + } + + @Test + void bigQuantilesAreTheLastValue() { +- assertThat(snapshot.getValue(1.0)).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1)); + } + + @Test + void disallowsNotANumberQuantile() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(Double.NaN); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(Double.NaN); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disallowsNegativeQuantile() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(-0.5); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(-0.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disallowsQuantileOverOne() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- snapshot.getValue(1.5); +- }); ++ assertThatThrownBy( ++ () -> { ++ snapshot.getValue(1.5); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void hasAMedian() { +- assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); ++ assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1)); + } + + @Test + void hasAp75() { +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1)); + } + + @Test + void hasAp95() { +- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp98() { +- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp99() { +- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test + void hasAp999() { +- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); + } + + @Test +@@ -118,7 +118,7 @@ class WeightedSnapshotTest { + final List spyItems = spy(originalItems); + doReturn(originalItems.toArray(new WeightedSample[] {})) + .when(spyItems) +- .toArray(ArgumentMatchers.any(WeightedSample[].class)); ++ .toArray(any(WeightedSample[].class)); + when(spyItems.size()).thenReturn(4, 5); + + final Snapshot other = new WeightedSnapshot(spyItems); +@@ -133,7 +133,7 @@ class WeightedSnapshotTest { + final List spyItems = spy(originalItems); + doReturn(originalItems.toArray(new WeightedSample[] {})) + .when(spyItems) +- .toArray(ArgumentMatchers.any(WeightedSample[].class)); ++ .toArray(any(WeightedSample[].class)); + when(spyItems.size()).thenReturn(6, 5); + + final Snapshot other = new WeightedSnapshot(spyItems); +@@ -147,7 +147,7 @@ class WeightedSnapshotTest { + + snapshot.dump(output); + +- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); ++ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); + } + + @Test +@@ -167,7 +167,7 @@ class WeightedSnapshotTest { + + @Test + void calculatesTheStdDev() { +- assertThat(snapshot.getStdDev()).isEqualTo(1.2688, offset(0.0001)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001)); + } + + @Test +@@ -175,7 +175,7 @@ class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getMin()).isZero(); ++ assertThat(emptySnapshot.getMin()).isEqualTo(0); + } + + @Test +@@ -183,7 +183,7 @@ class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getMax()).isZero(); ++ assertThat(emptySnapshot.getMax()).isEqualTo(0); + } + + @Test +@@ -191,7 +191,7 @@ class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getMean()).isZero(); ++ assertThat(emptySnapshot.getMean()).isEqualTo(0); + } + + @Test +@@ -199,7 +199,7 @@ class WeightedSnapshotTest { + final Snapshot emptySnapshot = + new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); + +- assertThat(emptySnapshot.getStdDev()).isZero(); ++ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); + } + + @Test +@@ -207,7 +207,7 @@ class WeightedSnapshotTest { + final Snapshot singleItemSnapshot = + new WeightedSnapshot(weightedArray(new long[] {1}, new double[] {1.0})); + +- assertThat(singleItemSnapshot.getStdDev()).isZero(); ++ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); + } + + @Test +diff --git a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java +index f53b4c2..531ff9e 100644 +--- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java ++++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java +@@ -12,7 +12,7 @@ import net.sf.ehcache.Element; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedCacheDecoratorFactoryTest { ++final class InstrumentedCacheDecoratorFactoryTest { + private static final CacheManager MANAGER = CacheManager.create(); + + private MetricRegistry registry; +diff --git a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java +index 58bca0c..340cd66 100644 +--- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java ++++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java +@@ -13,7 +13,7 @@ import net.sf.ehcache.config.CacheConfiguration; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedEhcacheTest { ++final class InstrumentedEhcacheTest { + private static final CacheManager MANAGER = CacheManager.create(); + + private final MetricRegistry registry = new MetricRegistry(); +diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java +index bab371a..8dfe5cf 100644 +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.graphite; + ++import static com.google.common.base.Preconditions.checkArgument; ++import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.UTF_8; + import static java.util.Objects.requireNonNull; + +@@ -29,7 +31,7 @@ public class Graphite implements GraphiteSender { + private Writer writer; + private int failures; + +- private static final Logger LOGGER = LoggerFactory.getLogger(Graphite.class); ++ private static final Logger LOG = LoggerFactory.getLogger(Graphite.class); + + /** + * Creates a new client which connects to the given address using the default {@link +@@ -63,13 +65,9 @@ public class Graphite implements GraphiteSender { + * @param charset the character set used by the server + */ + public Graphite(String hostname, int port, SocketFactory socketFactory, Charset charset) { +- if (hostname == null || hostname.isEmpty()) { +- throw new IllegalArgumentException("hostname must not be null or empty"); +- } ++ checkArgument(hostname != null && !hostname.isEmpty(), "hostname must not be null or empty"); + +- if (port < 0 || port > 65535) { +- throw new IllegalArgumentException("port must be a valid IP port (0-65535)"); +- } ++ checkArgument(port >= 0 && port <= 65535, "port must be a valid IP port (0-65535)"); + + this.hostname = hostname; + this.port = port; +@@ -116,9 +114,7 @@ public class Graphite implements GraphiteSender { + + @Override + public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); + InetSocketAddress address = this.address; + // the previous dns retry logic did not work, as address.getAddress would always return the + // cached value +@@ -178,7 +174,7 @@ public class Graphite implements GraphiteSender { + writer.close(); + } + } catch (IOException ex) { +- LOGGER.debug("Error closing writer", ex); ++ LOG.debug("Error closing writer", ex); + } finally { + this.writer = null; + } +@@ -188,7 +184,7 @@ public class Graphite implements GraphiteSender { + socket.close(); + } + } catch (IOException ex) { +- LOGGER.debug("Error closing socket", ex); ++ LOG.debug("Error closing socket", ex); + } finally { + this.socket = null; + } +diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java +index fd9ee5f..7532a9f 100644 +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.graphite; + ++import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.UTF_8; + + import com.rabbitmq.client.Channel; +@@ -109,9 +110,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { + + @Override + public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); + + try { + connection = connectionFactory.newConnection(); +@@ -132,8 +131,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { + final String sanitizedName = sanitize(name); + final String sanitizedValue = sanitize(value); + +- final String message = +- sanitizedName + ' ' + sanitizedValue + ' ' + Long.toString(timestamp) + '\n'; ++ final String message = sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n'; + channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); + } catch (IOException e) { + failures++; +diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java +index 1e14d15..f189ad7 100644 +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java +@@ -4,10 +4,8 @@ import static io.dropwizard.metrics5.MetricAttribute.COUNT; + import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; + import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MAX; + import static io.dropwizard.metrics5.MetricAttribute.MEAN; + import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; +-import static io.dropwizard.metrics5.MetricAttribute.MIN; + import static io.dropwizard.metrics5.MetricAttribute.P50; + import static io.dropwizard.metrics5.MetricAttribute.P75; + import static io.dropwizard.metrics5.MetricAttribute.P95; +@@ -17,6 +15,7 @@ import static io.dropwizard.metrics5.MetricAttribute.P999; + import static io.dropwizard.metrics5.MetricAttribute.STDDEV; + import static io.dropwizard.metrics5.MetricAttribute.SUM; + ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -31,7 +30,6 @@ import io.dropwizard.metrics5.ScheduledReporter; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; + import java.io.IOException; +-import java.util.Collections; + import java.util.Locale; + import java.util.Map; + import java.util.Set; +@@ -85,7 +83,7 @@ public class GraphiteReporter extends ScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = ImmutableSet.of(); + this.addMetricAttributesAsTags = false; + this.floatingPointFormatter = DEFAULT_FP_FORMATTER; + } +@@ -249,7 +247,7 @@ public class GraphiteReporter extends ScheduledReporter { + } + } + +- private static final Logger LOGGER = LoggerFactory.getLogger(GraphiteReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(GraphiteReporter.class); + // the Carbon plaintext format is pretty underspecified, but it seems like it just wants + // US-formatted digits + private static final DoubleFunction DEFAULT_FP_FORMATTER = +@@ -430,12 +428,12 @@ public class GraphiteReporter extends ScheduledReporter { + } + graphite.flush(); + } catch (IOException e) { +- LOGGER.warn("Unable to report to Graphite", graphite, e); ++ LOG.warn("Unable to report to Graphite", graphite, e); + } finally { + try { + graphite.close(); + } catch (IOException e1) { +- LOGGER.warn("Error closing Graphite", graphite, e1); ++ LOG.warn("Error closing Graphite", graphite, e1); + } + } + } +@@ -448,16 +446,16 @@ public class GraphiteReporter extends ScheduledReporter { + try { + graphite.close(); + } catch (IOException e) { +- LOGGER.debug("Error disconnecting from Graphite", graphite, e); ++ LOG.debug("Error disconnecting from Graphite", graphite, e); + } + } + } + + private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { + final Snapshot snapshot = timer.getSnapshot(); +- sendIfEnabled(MAX, name, convertDuration(snapshot.getMax()), timestamp); ++ sendIfEnabled(MetricAttribute.MAX, name, convertDuration(snapshot.getMax()), timestamp); + sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); +- sendIfEnabled(MIN, name, convertDuration(snapshot.getMin()), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, convertDuration(snapshot.getMin()), timestamp); + sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); + sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); + sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); +@@ -484,9 +482,9 @@ public class GraphiteReporter extends ScheduledReporter { + final Snapshot snapshot = histogram.getSnapshot(); + sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); + sendIfEnabled(SUM, name, histogram.getSum(), timestamp); +- sendIfEnabled(MAX, name, snapshot.getMax(), timestamp); ++ sendIfEnabled(MetricAttribute.MAX, name, snapshot.getMax(), timestamp); + sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); +- sendIfEnabled(MIN, name, snapshot.getMin(), timestamp); ++ sendIfEnabled(MetricAttribute.MIN, name, snapshot.getMin(), timestamp); + sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); + sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); + sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); +diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java +index fc3560d..0466527 100644 +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.graphite; + ++import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.UTF_8; + + import java.io.IOException; +@@ -43,9 +44,7 @@ public class GraphiteUDP implements GraphiteSender { + + @Override + public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); + + // Resolve hostname + if (hostname != null) { +@@ -63,7 +62,7 @@ public class GraphiteUDP implements GraphiteSender { + @Override + public void send(String name, String value, long timestamp) throws IOException { + try { +- String str = sanitize(name) + ' ' + sanitize(value) + ' ' + Long.toString(timestamp) + '\n'; ++ String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n'; + ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); + datagramChannel.send(byteBuffer, address); + this.failures = 0; +diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java +index 42e72e5..6312111 100644 +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.graphite; + ++import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.UTF_8; + + import java.io.BufferedWriter; +@@ -48,7 +49,7 @@ public class PickledGraphite implements GraphiteSender { + QUOTE = '\'', + LF = '\n'; + +- private static final Logger LOGGER = LoggerFactory.getLogger(PickledGraphite.class); ++ private static final Logger LOG = LoggerFactory.getLogger(PickledGraphite.class); + private static final int DEFAULT_BATCH_SIZE = 100; + + private int batchSize; +@@ -173,9 +174,7 @@ public class PickledGraphite implements GraphiteSender { + + @Override + public void connect() throws IllegalStateException, IOException { +- if (isConnected()) { +- throw new IllegalStateException("Already connected"); +- } ++ checkState(!isConnected(), "Already connected"); + InetSocketAddress address = this.address; + if (address == null) { + address = new InetSocketAddress(hostname, port); +@@ -249,7 +248,7 @@ public class PickledGraphite implements GraphiteSender { + * message to graphite 3. Clear out the list of metrics + */ + private void writeMetrics() throws IOException { +- if (metrics.size() > 0) { ++ if (!metrics.isEmpty()) { + try { + byte[] payload = pickleMetrics(metrics); + byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); +@@ -260,8 +259,8 @@ public class PickledGraphite implements GraphiteSender { + outputStream.write(payload); + outputStream.flush(); + +- if (LOGGER.isDebugEnabled()) { +- LOGGER.debug("Wrote {} metrics", metrics.size()); ++ if (LOG.isDebugEnabled()) { ++ LOG.debug("Wrote {} metrics", metrics.size()); + } + } catch (IOException e) { + this.failures++; +diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java +index f7f01d6..29eb9ed 100755 +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java +@@ -8,7 +8,6 @@ import static org.mockito.Mockito.anyString; + import static org.mockito.Mockito.atMost; + import static org.mockito.Mockito.doThrow; + import static org.mockito.Mockito.mock; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -20,14 +19,14 @@ import java.net.UnknownHostException; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class GraphiteRabbitMQTest { +- private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); +- private final Connection connection = mock(Connection.class); +- private final Channel channel = mock(Channel.class); ++final class GraphiteRabbitMQTest { ++ private final ConnectionFactory connectionFactory = mock(); ++ private final Connection connection = mock(); ++ private final Channel channel = mock(); + +- private final ConnectionFactory bogusConnectionFactory = mock(ConnectionFactory.class); +- private final Connection bogusConnection = mock(Connection.class); +- private final Channel bogusChannel = mock(Channel.class); ++ private final ConnectionFactory bogusConnectionFactory = mock(); ++ private final Connection bogusConnection = mock(); ++ private final Channel bogusChannel = mock(); + + private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); + +@@ -92,10 +91,9 @@ class GraphiteRabbitMQTest { + + String expectedMessage = "name value 100\n"; + +- verify(channel, times(1)) +- .basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); ++ verify(channel).basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); + +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } + + @Test +@@ -105,10 +103,10 @@ class GraphiteRabbitMQTest { + + String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; + +- verify(channel, times(1)) ++ verify(channel) + .basicPublish("graphite", "name-to-sanitize", null, expectedMessage.getBytes(UTF_8)); + +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } + + @Test +diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java +index 934c6a9..0302ddc 100644 +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java +@@ -8,6 +8,7 @@ import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verifyNoMoreInteractions; + import static org.mockito.Mockito.when; + ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -22,7 +23,6 @@ import io.dropwizard.metrics5.Timer; + import java.net.UnknownHostException; + import java.text.DecimalFormat; + import java.text.DecimalFormatSymbols; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.Locale; + import java.util.Set; +@@ -33,15 +33,15 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.mockito.InOrder; + +-class GraphiteReporterTest { ++final class GraphiteReporterTest { + private static final MetricName GAUGE = MetricName.build("gauge"); + private static final MetricName METER = MetricName.build("meter"); + private static final MetricName COUNTER = MetricName.build("counter"); + + private final long timestamp = 1000198; +- private final Clock clock = mock(Clock.class); +- private final Graphite graphite = mock(Graphite.class); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final Clock clock = mock(); ++ private final Graphite graphite = mock(); ++ private final MetricRegistry registry = mock(); + private final GraphiteReporter reporter = + GraphiteReporter.forRegistry(registry) + .withClock(clock) +@@ -49,7 +49,7 @@ class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .build(graphite); + + private final GraphiteReporter minuteRateReporter = +@@ -59,7 +59,7 @@ class GraphiteReporterTest { + .convertRatesTo(TimeUnit.MINUTES) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .build(graphite); + + @BeforeEach +@@ -179,7 +179,7 @@ class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .withFloatingPointFormatter(formatter::format) + .build(graphite)) { + reportGaugeValue(graphiteReporter, 0.000045322); +@@ -222,7 +222,7 @@ class GraphiteReporterTest { + + @Test + void reportsCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map(COUNTER, counter), map(), map(), map()); +@@ -238,11 +238,11 @@ class GraphiteReporterTest { + + @Test + void reportsHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(12L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -280,7 +280,7 @@ class GraphiteReporterTest { + + @Test + void reportsMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -306,7 +306,7 @@ class GraphiteReporterTest { + + @Test + void reportsMetersInMinutes() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -333,7 +333,7 @@ class GraphiteReporterTest { + + @Test + void reportsTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -341,7 +341,7 @@ class GraphiteReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -410,7 +410,7 @@ class GraphiteReporterTest { + + @Test + void disabledMetricsAttribute() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -418,7 +418,7 @@ class GraphiteReporterTest { + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(11L); + + Set disabledMetricAttributes = +@@ -450,7 +450,7 @@ class GraphiteReporterTest { + + @Test + void sendsMetricAttributesAsTagsIfEnabled() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + getReporterThatSendsMetricAttributesAsTags() +@@ -476,7 +476,7 @@ class GraphiteReporterTest { + MetricFilter.ALL, + null, + false, +- Collections.emptySet(), ++ ImmutableSet.of(), + false) { + @Override + protected String format(double v) { +@@ -492,7 +492,7 @@ class GraphiteReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .addMetricAttributesAsTags(true) + .build(graphite); + } +diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java +index 9cbadb6..edca420 100644 +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java +@@ -3,7 +3,7 @@ package io.dropwizard.metrics5.graphite; + import org.assertj.core.api.SoftAssertions; + import org.junit.jupiter.api.Test; + +-class GraphiteSanitizeTest { ++final class GraphiteSanitizeTest { + @Test + void sanitizeGraphiteValues() { + SoftAssertions softly = new SoftAssertions(); +diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java +index 575ff2e..80e19d6 100644 +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java +@@ -23,14 +23,14 @@ import javax.net.SocketFactory; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class GraphiteTest { ++final class GraphiteTest { + private final String host = "example.com"; + private final int port = 1234; +- private final SocketFactory socketFactory = mock(SocketFactory.class); ++ private final SocketFactory socketFactory = mock(); + private final InetSocketAddress address = new InetSocketAddress(host, port); + +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); + + @BeforeEach + void setUp() throws Exception { +@@ -84,7 +84,7 @@ class GraphiteTest { + @Test + void measuresFailures() throws IOException { + try (Graphite graphite = new Graphite(address, socketFactory)) { +- assertThat(graphite.getFailures()).isZero(); ++ assertThat(graphite.getFailures()).isEqualTo(0); + } + } + +diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java +index a293305..5a8828e 100644 +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java +@@ -1,15 +1,15 @@ + package io.dropwizard.metrics5.graphite; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; + + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; + import java.nio.channels.DatagramChannel; + import org.junit.jupiter.api.Test; +-import org.mockito.Mockito; + +-class GraphiteUDPTest { ++final class GraphiteUDPTest { + + private final String host = "example.com"; + private final int port = 1234; +@@ -30,7 +30,7 @@ class GraphiteUDPTest { + @Test + void writesValue() throws Exception { + graphiteUDP = new GraphiteUDP(host, port); +- DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); ++ DatagramChannel mockDatagramChannel = mock(); + graphiteUDP.setDatagramChannel(mockDatagramChannel); + graphiteUDP.setAddress(new InetSocketAddress(host, port)); + +diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java +index 6bb1d9c..50567d0 100644 +--- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java ++++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java +@@ -31,13 +31,13 @@ import org.junit.jupiter.api.Test; + import org.python.core.PyList; + import org.python.core.PyTuple; + +-class PickledGraphiteTest { +- private final SocketFactory socketFactory = mock(SocketFactory.class); ++final class PickledGraphiteTest { ++ private final SocketFactory socketFactory = mock(); + private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); + private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); + +- private final Socket socket = mock(Socket.class); +- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); ++ private final Socket socket = mock(); ++ private final ByteArrayOutputStream output = spy(); + + private CompiledScript unpickleScript; + +diff --git a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java +index f34fc4a..81e0265 100644 +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.health; + ++import static com.google.common.base.Preconditions.checkArgument; ++ + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.health.annotation.Async; + import java.util.concurrent.ScheduledExecutorService; +@@ -29,10 +31,10 @@ public class AsyncHealthCheckDecorator implements HealthCheck, Runnable { + this.healthyTtl = + async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); + result = +- Async.InitialState.HEALTHY.equals(async.initialState()) ++ Async.InitialState.HEALTHY == async.initialState() + ? Result.healthy(NO_RESULT_YET_MESSAGE) + : Result.unhealthy(NO_RESULT_YET_MESSAGE); +- if (Async.ScheduleType.FIXED_RATE.equals(async.scheduleType())) { ++ if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) { + future = + executorService.scheduleAtFixedRate( + this, async.initialDelay(), async.period(), async.unit()); +@@ -77,8 +79,6 @@ public class AsyncHealthCheckDecorator implements HealthCheck, Runnable { + } + + private static void check(boolean expression, String message) { +- if (!expression) { +- throw new IllegalArgumentException(message); +- } ++ checkArgument(expression, message); + } + } +diff --git a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java +index 017ab9c..e7c8eae 100644 +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java +@@ -1,11 +1,12 @@ + package io.dropwizard.metrics5.health; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Clock; + import java.time.Instant; + import java.time.ZoneId; + import java.time.ZonedDateTime; + import java.time.format.DateTimeFormatter; +-import java.util.Collections; + import java.util.LinkedHashMap; + import java.util.Map; + import java.util.concurrent.TimeUnit; +@@ -123,7 +124,7 @@ public interface HealthCheck { + this.healthy = isHealthy; + this.message = message; + this.error = error; +- this.details = details == null ? null : Collections.unmodifiableMap(details); ++ this.details = details == null ? null : unmodifiableMap(details); + this.time = clock.getTime(); + } + +@@ -162,7 +163,7 @@ public interface HealthCheck { + */ + public String getTimestamp() { + Instant currentInstant = Instant.ofEpochMilli(time); +- ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(currentInstant, ZoneId.systemDefault()); ++ ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault()); + return DATE_FORMAT_PATTERN.format(zonedDateTime); + } + +@@ -218,8 +219,7 @@ public interface HealthCheck { + int result = healthy ? 1 : 0; + result = PRIME * result + (message != null ? message.hashCode() : 0); + result = PRIME * result + (error != null ? error.hashCode() : 0); +- result = PRIME * result + (Long.hashCode(time)); +- return result; ++ return PRIME * result + (Long.hashCode(time)); + } + + @Override +@@ -237,7 +237,7 @@ public interface HealthCheck { + if (details != null) { + for (Map.Entry e : details.entrySet()) { + builder.append(", "); +- builder.append(e.getKey()).append("=").append(String.valueOf(e.getValue())); ++ builder.append(e.getKey()).append("=").append(e.getValue()); + } + } + builder.append('}'); +diff --git a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java +index b920a9d..77b1e1e 100644 +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java +@@ -1,9 +1,11 @@ + package io.dropwizard.metrics5.health; + ++import static com.google.common.base.Preconditions.checkArgument; + import static io.dropwizard.metrics5.health.HealthCheck.Result; ++import static java.util.Collections.unmodifiableSortedMap; ++import static java.util.Collections.unmodifiableSortedSet; + + import io.dropwizard.metrics5.health.annotation.Async; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -27,7 +29,7 @@ import org.slf4j.LoggerFactory; + + /** A registry for health checks. */ + public class HealthCheckRegistry { +- private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckRegistry.class); ++ private static final Logger LOG = LoggerFactory.getLogger(HealthCheckRegistry.class); + private static final int ASYNC_EXECUTOR_POOL_SIZE = 2; + + private final ConcurrentMap healthChecks; +@@ -92,9 +94,8 @@ public class HealthCheckRegistry { + public void register(String name, HealthCheck healthCheck) { + HealthCheck registered; + synchronized (lock) { +- if (healthChecks.containsKey(name)) { +- throw new IllegalArgumentException("A health check named " + name + " already exists"); +- } ++ checkArgument( ++ !healthChecks.containsKey(name), "A health check named " + name + " already exists"); + registered = healthCheck; + if (healthCheck.getClass().isAnnotationPresent(Async.class)) { + registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); +@@ -128,7 +129,7 @@ public class HealthCheckRegistry { + * @return the names of all registered health checks + */ + public SortedSet getNames() { +- return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); ++ return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); + } + + /** +@@ -180,7 +181,7 @@ public class HealthCheckRegistry { + results.put(entry.getKey(), result); + } + } +- return Collections.unmodifiableSortedMap(results); ++ return unmodifiableSortedMap(results); + } + + /** +@@ -217,12 +218,12 @@ public class HealthCheckRegistry { + try { + results.put(entry.getKey(), entry.getValue().get()); + } catch (Exception e) { +- LOGGER.warn("Error executing health check {}", entry.getKey(), e); ++ LOG.warn("Error executing health check {}", entry.getKey(), e); + results.put(entry.getKey(), HealthCheck.Result.unhealthy(e)); + } + } + +- return Collections.unmodifiableSortedMap(results); ++ return unmodifiableSortedMap(results); + } + + private void onHealthCheckAdded(String name, HealthCheck healthCheck) { +diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java +index 209aede..83f8daa 100644 +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java +@@ -1,11 +1,12 @@ + package io.dropwizard.metrics5.health; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.ArgumentCaptor.forClass; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.*; ++import static org.mockito.Mockito.verify; + + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.health.annotation.Async; +@@ -16,7 +17,7 @@ import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; + + /** Unit tests for {@link AsyncHealthCheckDecorator}. */ +-class AsyncHealthCheckDecoratorTest { ++final class AsyncHealthCheckDecoratorTest { + + private static final long CURRENT_TIME = 1551002401000L; + +@@ -29,65 +30,66 @@ class AsyncHealthCheckDecoratorTest { + .withMessage("Result was healthy but it expired 1 milliseconds ago") + .build(); + +- private final HealthCheck mockHealthCheck = mock(HealthCheck.class); +- private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); ++ private final HealthCheck mockHealthCheck = mock(); ++ private final ScheduledExecutorService mockExecutorService = mock(); + + @SuppressWarnings("rawtypes") +- private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); ++ private final ScheduledFuture mockFuture = mock(); + + @Test + void nullHealthCheckTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(null, mockExecutorService); +- }); ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(null, mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void nullExecutorServiceTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(mockHealthCheck, null); +- }); ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(mockHealthCheck, null); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void nonAsyncHealthCheckTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); +- }); ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void negativePeriodTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(new NegativePeriodAsyncHealthCheck(), mockExecutorService); +- }); ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator( ++ new NegativePeriodAsyncHealthCheck(), mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void zeroPeriodTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); +- }); ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void negativeInitialValueTriggersInstantiationFailure() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- new AsyncHealthCheckDecorator( +- new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); +- }); ++ assertThatThrownBy( ++ () -> { ++ new AsyncHealthCheckDecorator( ++ new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test +@@ -97,7 +99,7 @@ class AsyncHealthCheckDecoratorTest { + AsyncHealthCheckDecorator asyncDecorator = + new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); + assertThat(asyncDecorator.check().isHealthy()).isTrue(); +@@ -109,7 +111,7 @@ class AsyncHealthCheckDecoratorTest { + AsyncHealthCheckDecorator asyncDecorator = + new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); + } +@@ -124,8 +126,8 @@ class AsyncHealthCheckDecoratorTest { + assertThat(asyncDecorator.check().isHealthy()).isFalse(); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + void tearDownTriggersCancellation() throws Exception { + when(mockExecutorService.scheduleAtFixedRate( + any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) +@@ -136,13 +138,13 @@ class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); + asyncDecorator.tearDown(); + +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); +- verify(mockFuture, times(1)).cancel(eq(true)); ++ verify(mockFuture).cancel(true); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { + HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); + when(mockExecutorService.scheduleAtFixedRate( +@@ -155,7 +157,7 @@ class AsyncHealthCheckDecoratorTest { + HealthCheck.Result initialResult = asyncDecorator.check(); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +@@ -165,8 +167,8 @@ class AsyncHealthCheckDecoratorTest { + assertThat(actualResult).isNotEqualTo(initialResult); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { + Exception exception = new Exception("TestException"); + when(mockExecutorService.scheduleAtFixedRate( +@@ -178,7 +180,7 @@ class AsyncHealthCheckDecoratorTest { + new ConfigurableAsyncHealthCheck(exception), mockExecutorService); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +@@ -195,7 +197,7 @@ class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate( + runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); +@@ -214,7 +216,7 @@ class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate( + runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); +@@ -232,7 +234,7 @@ class AsyncHealthCheckDecoratorTest { + new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); + + ArgumentCaptor runnableCaptor = forClass(Runnable.class); +- verify(mockExecutorService, times(1)) ++ verify(mockExecutorService) + .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); + Runnable capturedRunnable = runnableCaptor.getValue(); + capturedRunnable.run(); +diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java +index 1177c7b..31a20bc 100644 +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java +@@ -5,7 +5,7 @@ import static org.mockito.Mockito.mock; + + import org.junit.jupiter.api.Test; + +-class HealthCheckFilterTest { ++final class HealthCheckFilterTest { + + @Test + void theAllFilterMatchesAllHealthChecks() { +diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java +index 236b355..c099cc7 100644 +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java +@@ -1,9 +1,9 @@ + package io.dropwizard.metrics5.health; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.assertj.core.api.Assertions.entry; + import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +-import static org.junit.jupiter.api.Assertions.assertThrows; + import static org.mockito.ArgumentCaptor.forClass; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; +@@ -23,22 +23,22 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; + +-class HealthCheckRegistryTest { +- private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); ++final class HealthCheckRegistryTest { ++ private final ScheduledExecutorService executorService = mock(); + private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); +- private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ private final HealthCheckRegistryListener listener = mock(); + +- private final HealthCheck hc1 = mock(HealthCheck.class); +- private final HealthCheck hc2 = mock(HealthCheck.class); ++ private final HealthCheck hc1 = mock(); ++ private final HealthCheck hc2 = mock(); + +- private final HealthCheck.Result r1 = mock(HealthCheck.Result.class); +- private final HealthCheck.Result r2 = mock(HealthCheck.Result.class); ++ private final HealthCheck.Result r1 = mock(); ++ private final HealthCheck.Result r2 = mock(); + +- private final HealthCheck.Result ar = mock(HealthCheck.Result.class); ++ private final HealthCheck.Result ar = mock(); + private final HealthCheck ahc = new TestAsyncHealthCheck(ar); + + @SuppressWarnings("rawtypes") +- private final ScheduledFuture af = mock(ScheduledFuture.class); ++ private final ScheduledFuture af = mock(); + + @BeforeEach + @SuppressWarnings("unchecked") +@@ -74,11 +74,11 @@ class HealthCheckRegistryTest { + + @Test + void registeringHealthCheckTwiceThrowsException() { +- assertThrows( +- IllegalArgumentException.class, +- () -> { +- registry.register("hc1", hc1); +- }); ++ assertThatThrownBy( ++ () -> { ++ registry.register("hc1", hc1); ++ }) ++ .isInstanceOf(IllegalArgumentException.class); + } + + @Test +@@ -101,7 +101,7 @@ class HealthCheckRegistryTest { + + @Test + void addingListenerCatchesExistingHealthChecks() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ HealthCheckRegistryListener listener = mock(); + HealthCheckRegistry registry = new HealthCheckRegistry(); + registry.register("hc1", hc1); + registry.register("hc2", hc2); +@@ -115,7 +115,7 @@ class HealthCheckRegistryTest { + + @Test + void removedListenerDoesNotReceiveUpdates() { +- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); ++ HealthCheckRegistryListener listener = mock(); + HealthCheckRegistry registry = new HealthCheckRegistry(); + registry.addListener(listener); + registry.register("hc1", hc1); +diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java +index b64faa4..62df29b 100644 +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java +@@ -11,7 +11,7 @@ import java.time.ZonedDateTime; + import java.time.format.DateTimeFormatter; + import org.junit.jupiter.api.Test; + +-class HealthCheckTest { ++final class HealthCheckTest { + + private static final DateTimeFormatter DATE_TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); +@@ -29,7 +29,7 @@ class HealthCheckTest { + } + } + +- private final HealthCheck underlying = mock(HealthCheck.class); ++ private final HealthCheck underlying = mock(); + private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); + + @Test +@@ -89,7 +89,7 @@ class HealthCheckTest { + + @Test + void canHaveUnhealthyResultsWithExceptions() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); +@@ -144,7 +144,7 @@ class HealthCheckTest { + + @Test + void canHaveUnHealthyBuilderWithDetailAndError() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + final HealthCheck.Result result = +@@ -161,7 +161,7 @@ class HealthCheckTest { + + @Test + void returnsResultsWhenExecuted() { +- final HealthCheck.Result result = mock(HealthCheck.Result.class); ++ final HealthCheck.Result result = mock(); + when(underlying.execute()).thenReturn(result); + + assertThat(healthCheck.execute()).isEqualTo(result); +@@ -171,7 +171,7 @@ class HealthCheckTest { + + @Test + void wrapsExceptionsWhenExecuted() { +- final RuntimeException e = mock(RuntimeException.class); ++ final RuntimeException e = mock(); + when(e.getMessage()).thenReturn("oh noes"); + + when(underlying.execute()).thenThrow(e); +@@ -181,7 +181,7 @@ class HealthCheckTest { + assertThat(actual.getMessage()).isEqualTo("oh noes"); + assertThat(actual.getError()).isEqualTo(e); + assertThat(actual.getDetails()).isNull(); +- assertThat(actual.getDuration()).isGreaterThanOrEqualTo(0); ++ assertThat(actual.getDuration()).isNotNegative(); + } + + @Test +diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java +index 1578e44..08071b6 100644 +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java +@@ -2,13 +2,12 @@ package io.dropwizard.metrics5.health; + + import static org.assertj.core.api.Assertions.assertThat; + import static org.junit.jupiter.api.Assertions.assertThrows; +-import static org.junit.jupiter.api.Assertions.assertTrue; + + import java.util.concurrent.atomic.AtomicReference; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class SharedHealthCheckRegistriesTest { ++final class SharedHealthCheckRegistriesTest { + + @BeforeEach + void setUp() { +@@ -28,7 +27,7 @@ class SharedHealthCheckRegistriesTest { + void returnsSetOfCreatedRegistries() { + SharedHealthCheckRegistries.getOrCreate("db"); + +- assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); ++ assertThat(SharedHealthCheckRegistries.names()).containsExactly("db"); + } + + @Test +@@ -58,7 +57,7 @@ class SharedHealthCheckRegistriesTest { + () -> { + SharedHealthCheckRegistries.getDefault(); + }); +- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); ++ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); + } + + @Test +@@ -85,7 +84,8 @@ class SharedHealthCheckRegistriesTest { + SharedHealthCheckRegistries.setDefault("default"); + SharedHealthCheckRegistries.setDefault("default"); + }); +- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); ++ assertThat(exception.getMessage().contains("Default health check registry is already set.")) ++ .isTrue(); + } + + @Test +@@ -97,6 +97,7 @@ class SharedHealthCheckRegistriesTest { + SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); + SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); + }); +- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); ++ assertThat(exception.getMessage().contains("Default health check registry is already set.")) ++ .isTrue(); + } + } +diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java +index 948152a..7829d74 100644 +--- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java ++++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java +@@ -4,23 +4,22 @@ import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.health.HealthCheck; + import io.dropwizard.metrics5.jvm.ThreadDeadlockDetector; +-import java.util.Collections; + import java.util.Set; + import java.util.TreeSet; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.Test; + +-class ThreadDeadlockHealthCheckTest { ++final class ThreadDeadlockHealthCheckTest { + @Test + void isHealthyIfNoThreadsAreDeadlocked() { +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ final ThreadDeadlockDetector detector = mock(); + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); + +- when(detector.getDeadlockedThreads()).thenReturn(Collections.emptySet()); ++ when(detector.getDeadlockedThreads()).thenReturn(ImmutableSet.of()); + +- Assertions.assertThat(healthCheck.execute().isHealthy()).isTrue(); ++ assertThat(healthCheck.execute().isHealthy()).isTrue(); + } + + @Test +@@ -29,7 +28,7 @@ class ThreadDeadlockHealthCheckTest { + threads.add("one"); + threads.add("two"); + +- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++ final ThreadDeadlockDetector detector = mock(); + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); + + when(detector.getDeadlockedThreads()).thenReturn(threads); +@@ -44,6 +43,6 @@ class ThreadDeadlockHealthCheckTest { + @Test + void automaticallyUsesThePlatformThreadBeans() { + final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(); +- Assertions.assertThat(healthCheck.execute().isHealthy()).isTrue(); ++ assertThat(healthCheck.execute().isHealthy()).isTrue(); + } + } +diff --git a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java +index ece43e4..3c22974 100644 +--- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java ++++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java +@@ -22,7 +22,7 @@ import org.mockito.Mock; + import org.mockito.junit.jupiter.MockitoExtension; + + @ExtendWith(MockitoExtension.class) +-class InstrumentedHttpClientsTest extends HttpClientTestBase { ++final class InstrumentedHttpClientsTest extends HttpClientTestBase { + + private final MetricRegistry metricRegistry = new MetricRegistry(); + +diff --git a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java +index 55e5785..44f52fa 100644 +--- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java ++++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.httpasyncclient; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +@@ -20,6 +19,7 @@ import org.apache.http.client.methods.HttpGet; + import org.apache.http.concurrent.FutureCallback; + import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; + import org.apache.http.nio.client.HttpAsyncClient; ++import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; +@@ -29,7 +29,7 @@ import org.mockito.junit.jupiter.MockitoExtension; + + @ExtendWith(MockitoExtension.class) + @Disabled("The tests are flaky") +-class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { ++final class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + + private HttpAsyncClient asyncHttpClient; + +@@ -46,7 +46,7 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + chac.start(); + asyncHttpClient = chac; + +- Timer timer = mock(Timer.class); ++ Timer timer = mock(); + when(timer.time()).thenReturn(context); + when(metricRegistry.timer(MetricName.build("test"))).thenReturn(timer); + } +@@ -72,13 +72,13 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + verify(context, timeout(200).times(1)).stop(); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { + HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); + HttpGet get = new HttpGet("/?q=something"); + +- FutureCallback futureCallback = mock(FutureCallback.class); ++ FutureCallback futureCallback = mock(); + + // Timer hasn't been stopped prior to executing the request + verify(context, never()).stop(); +@@ -99,14 +99,14 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + verify(context, timeout(200).times(1)).stop(); + } + +- @Test + @SuppressWarnings("unchecked") ++ @Test + void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { + // There should be nothing listening on this port + HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); + HttpGet get = new HttpGet("/?q=something"); + +- FutureCallback futureCallback = mock(FutureCallback.class); ++ FutureCallback futureCallback = mock(); + + // Timer hasn't been stopped prior to executing the request + verify(context, never()).stop(); +@@ -118,7 +118,7 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + + try { + responseFuture.get(20, TimeUnit.SECONDS); +- fail("This should fail as the client should not be able to connect"); ++ Assertions.fail("This should fail as the client should not be able to connect"); + } catch (Exception e) { + // Ignore + } +diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java +index 2e09143..ed7927a 100644 +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java +@@ -17,7 +17,7 @@ import org.apache.http.client.methods.HttpRequestWrapper; + import org.apache.http.client.utils.URIUtils; + import org.junit.jupiter.api.Test; + +-class HttpClientMetricNameStrategiesTest { ++final class HttpClientMetricNameStrategiesTest { + + @Test + void methodOnlyWithName() { +diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java +index 5e33b2f..b4570e8 100644 +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java +@@ -3,16 +3,17 @@ package io.dropwizard.metrics5.httpclient; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertTrue; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; + +-class InstrumentedHttpClientConnectionManagerTest { ++final class InstrumentedHttpClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); + + @Test +@@ -37,7 +38,7 @@ class InstrumentedHttpClientConnectionManagerTest { + + @Test + void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); + + InstrumentedHttpClientConnectionManager.builder(registry) + .name("some-name") +@@ -46,7 +47,7 @@ class InstrumentedHttpClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); +- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); + } + } +diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java +index abaa84b..e5c7259 100644 +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.httpclient; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; +@@ -19,13 +18,13 @@ import org.apache.http.HttpRequest; + import org.apache.http.NoHttpResponseException; + import org.apache.http.client.HttpClient; + import org.apache.http.client.methods.HttpGet; ++import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); ++final class InstrumentedHttpClientsTest { ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); + private final MetricRegistry metricRegistry = new MetricRegistry(); + private final HttpClient client = + InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) +@@ -67,7 +66,7 @@ class InstrumentedHttpClientsTest { + + try { + client.execute(get); +- fail(); ++ Assertions.fail(); + } catch (NoHttpResponseException expected) { + assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); + } finally { +diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java +index 848b025..67741ec 100644 +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java +@@ -16,7 +16,7 @@ import org.apache.hc.core5.http.message.HttpRequestWrapper; + import org.apache.hc.core5.net.URIBuilder; + import org.junit.jupiter.api.Test; + +-class HttpClientMetricNameStrategiesTest { ++final class HttpClientMetricNameStrategiesTest { + + @Test + void methodOnlyWithName() { +diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java +index 78095dc..24fa03b 100644 +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java +@@ -3,16 +3,17 @@ package io.dropwizard.metrics5.httpclient5; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertTrue; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; + +-class InstrumentedAsyncClientConnectionManagerTest { ++final class InstrumentedAsyncClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); + + @Test +@@ -44,7 +45,7 @@ class InstrumentedAsyncClientConnectionManagerTest { + + @Test + void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); + + InstrumentedAsyncClientConnectionManager.builder(registry) + .name("some-name") +@@ -53,7 +54,7 @@ class InstrumentedAsyncClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); +- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); + } + } +diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java +index ebabd69..b67225a 100644 +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java +@@ -1,8 +1,8 @@ + package io.dropwizard.metrics5.httpclient5; + ++import static java.nio.charset.StandardCharsets.US_ASCII; + import static org.assertj.core.api.Assertions.assertThat; + import static org.awaitility.Awaitility.await; +-import static org.junit.jupiter.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.atLeastOnce; +@@ -18,7 +18,6 @@ import io.dropwizard.metrics5.MetricRegistryListener; + import io.dropwizard.metrics5.Timer; + import java.io.IOException; + import java.net.InetSocketAddress; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.ExecutionException; + import java.util.concurrent.Future; +@@ -31,6 +30,7 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; + import org.apache.hc.core5.concurrent.FutureCallback; + import org.apache.hc.core5.http.ConnectionClosedException; + import org.apache.hc.core5.http.HttpRequest; ++import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; +@@ -39,7 +39,7 @@ import org.mockito.Mock; + import org.mockito.junit.jupiter.MockitoExtension; + + @ExtendWith(MockitoExtension.class) +-class InstrumentedHttpAsyncClientsTest { ++final class InstrumentedHttpAsyncClientsTest { + + @Mock private HttpClientMetricNameStrategy metricNameStrategy; + @Mock private MetricRegistryListener registryListener; +@@ -83,7 +83,7 @@ class InstrumentedHttpAsyncClientsTest { + exchange -> { + exchange.sendResponseHeaders(200, 0L); + exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); + exchange.close(); + }); + httpServer.start(); +@@ -101,12 +101,12 @@ class InstrumentedHttpAsyncClientsTest { + + @Override + public void failed(Exception ex) { +- fail(); ++ Assertions.fail(); + } + + @Override + public void cancelled() { +- fail(); ++ Assertions.fail(); + } + }); + responseFuture.get(1L, TimeUnit.SECONDS); +@@ -144,7 +144,7 @@ class InstrumentedHttpAsyncClientsTest { + new FutureCallback() { + @Override + public void completed(SimpleHttpResponse result) { +- fail(); ++ Assertions.fail(); + } + + @Override +@@ -154,13 +154,13 @@ class InstrumentedHttpAsyncClientsTest { + + @Override + public void cancelled() { +- fail(); ++ Assertions.fail(); + } + }); + countDownLatch.await(5, TimeUnit.SECONDS); + responseFuture.get(5, TimeUnit.SECONDS); + +- fail(); ++ Assertions.fail(); + } catch (ExecutionException e) { + assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class); + await() +@@ -193,7 +193,7 @@ class InstrumentedHttpAsyncClientsTest { + exchange -> { + exchange.sendResponseHeaders(200, 0L); + exchange.setStreams(null, null); +- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); ++ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); + exchange.close(); + }); + httpServer.start(); +@@ -211,12 +211,12 @@ class InstrumentedHttpAsyncClientsTest { + + @Override + public void failed(Exception ex) { +- fail(); ++ Assertions.fail(); + } + + @Override + public void cancelled() { +- fail(); ++ Assertions.fail(); + } + }); + responseFuture.get(1L, TimeUnit.SECONDS); +diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java +index bddad25..4f63d65 100644 +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java +@@ -3,16 +3,17 @@ package io.dropwizard.metrics5.httpclient5; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.junit.jupiter.api.Assertions.assertEquals; +-import static org.junit.jupiter.api.Assertions.assertTrue; + import static org.mockito.ArgumentMatchers.any; ++import static org.mockito.Mockito.atLeast; ++import static org.mockito.Mockito.mock; ++import static org.mockito.Mockito.verify; + + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.junit.jupiter.api.Test; + import org.mockito.ArgumentCaptor; +-import org.mockito.Mockito; + +-class InstrumentedHttpClientConnectionManagerTest { ++final class InstrumentedHttpClientConnectionManagerTest { + private final MetricRegistry metricRegistry = new MetricRegistry(); + + @Test +@@ -42,7 +43,7 @@ class InstrumentedHttpClientConnectionManagerTest { + + @Test + void configurableViaBuilder() { +- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); ++ final MetricRegistry registry = mock(); + + InstrumentedHttpClientConnectionManager.builder(registry) + .name("some-name") +@@ -51,7 +52,7 @@ class InstrumentedHttpClientConnectionManagerTest { + .close(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); +- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); +- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); ++ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); ++ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); + } + } +diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java +index 86a450e..46cdc5e 100644 +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.httpclient5; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; +@@ -19,13 +18,13 @@ import org.apache.hc.client5.http.classic.HttpClient; + import org.apache.hc.client5.http.classic.methods.HttpGet; + import org.apache.hc.core5.http.HttpRequest; + import org.apache.hc.core5.http.NoHttpResponseException; ++import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedHttpClientsTest { +- private final HttpClientMetricNameStrategy metricNameStrategy = +- mock(HttpClientMetricNameStrategy.class); +- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); ++final class InstrumentedHttpClientsTest { ++ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); ++ private final MetricRegistryListener registryListener = mock(); + private final MetricRegistry metricRegistry = new MetricRegistry(); + private final HttpClient client = + InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) +@@ -67,7 +66,7 @@ class InstrumentedHttpClientsTest { + + try { + client.execute(get); +- fail(); ++ Assertions.fail(); + } catch (NoHttpResponseException expected) { + assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); + } finally { +diff --git a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java +index 3d674ce..1e2cf3a 100644 +--- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java ++++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.influxdb; + + import static io.dropwizard.metrics5.MetricAttribute.*; + ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -15,7 +16,6 @@ import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.Snapshot; + import io.dropwizard.metrics5.Timer; + import java.io.IOException; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -78,7 +78,7 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { + this.filter = MetricFilter.ALL; + this.executor = null; + this.shutdownExecutorOnStop = true; +- this.disabledMetricAttributes = Collections.emptySet(); ++ this.disabledMetricAttributes = ImmutableSet.of(); + } + + /** +@@ -196,7 +196,7 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { + } + } + +- private static final Logger LOGGER = LoggerFactory.getLogger(InfluxDbReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(InfluxDbReporter.class); + private static final String VALUE = "value"; + + private final Clock clock; +@@ -279,12 +279,12 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { + } + sender.flush(); + } catch (IOException e) { +- LOGGER.warn("Unable to report to InfluxDb", sender, e); ++ LOG.warn("Unable to report to InfluxDb", sender, e); + } finally { + try { + sender.disconnect(); + } catch (IOException e) { +- LOGGER.warn("Error disconnecting InfluxDb", sender, e); ++ LOG.warn("Error disconnecting InfluxDb", sender, e); + } + } + } +@@ -297,7 +297,7 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { + try { + sender.close(); + } catch (IOException e) { +- LOGGER.debug("Error disconnecting from InfluxDb", e); ++ LOG.debug("Error disconnecting from InfluxDb", e); + } + } + } +diff --git a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java +index 77be29b..0a75252 100644 +--- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java ++++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.influxdb; + ++import static java.util.Objects.requireNonNull; ++ + import java.io.IOException; + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; +@@ -9,7 +11,6 @@ import java.nio.charset.Charset; + import java.nio.charset.CharsetEncoder; + import java.nio.charset.CoderResult; + import java.nio.charset.CodingErrorAction; +-import java.util.Objects; + + public class InfluxDbUdpSender implements InfluxDbSender { + +@@ -42,7 +43,7 @@ public class InfluxDbUdpSender implements InfluxDbSender { + * @param address the address of the InfluxDb server + */ + public InfluxDbUdpSender(InetSocketAddress address) { +- this.address = Objects.requireNonNull(address); ++ this.address = requireNonNull(address); + charBuf = CharBuffer.allocate(mtu * 2); + byteBuf = ByteBuffer.allocate(mtu * 2); + } +diff --git a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java +index 75af4ca..3cb0035 100644 +--- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java ++++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java +@@ -5,7 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; + import io.dropwizard.metrics5.MetricAttribute; + import org.junit.jupiter.api.Test; + +-class InfluxDbLineBuilderAssumptionsTest { ++final class InfluxDbLineBuilderAssumptionsTest { + + @Test + void ensureMetricAttributeCodesAreSafeFieldKeys() { +diff --git a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java +index d50c1fa..98f5c99 100644 +--- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java ++++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java +@@ -11,6 +11,7 @@ import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.verifyNoMoreInteractions; + import static org.mockito.Mockito.when; + ++import com.google.common.collect.ImmutableSet; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; +@@ -25,7 +26,6 @@ import io.dropwizard.metrics5.Timer; + import java.io.IOException; + import java.net.UnknownHostException; + import java.util.ArrayList; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Set; +@@ -36,16 +36,16 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + import org.mockito.InOrder; + +-class InfluxDbReporterTest { ++final class InfluxDbReporterTest { + private static final MetricName GAUGE = MetricName.build("gauge"); + private static final MetricName METER = MetricName.build("meter"); + private static final MetricName COUNTER = MetricName.build("counter"); + + private final long timestamp = 1000198; +- private final Clock clock = mock(Clock.class); +- private final InfluxDbSender sender = mock(InfluxDbSender.class); ++ private final Clock clock = mock(); ++ private final InfluxDbSender sender = mock(); + private final List send = new ArrayList<>(); +- private final MetricRegistry registry = mock(MetricRegistry.class); ++ private final MetricRegistry registry = mock(); + private final InfluxDbReporter reporter = + InfluxDbReporter.forRegistry(registry) + .withClock(clock) +@@ -53,7 +53,7 @@ class InfluxDbReporterTest { + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .build(sender); + + private final InfluxDbReporter minuteRateReporter = +@@ -63,7 +63,7 @@ class InfluxDbReporterTest { + .convertRatesTo(TimeUnit.MINUTES) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) +- .disabledMetricAttributes(Collections.emptySet()) ++ .disabledMetricAttributes(ImmutableSet.of()) + .build(sender); + + @BeforeEach +@@ -197,7 +197,7 @@ class InfluxDbReporterTest { + + @Test + void reportsCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + reporter.report(map(), map(COUNTER, counter), map(), map(), map()); +@@ -214,11 +214,11 @@ class InfluxDbReporterTest { + + @Test + void reportsHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(12L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -249,7 +249,7 @@ class InfluxDbReporterTest { + + @Test + void reportsMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -274,7 +274,7 @@ class InfluxDbReporterTest { + + @Test + void reportsMetersInMinutes() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -300,7 +300,7 @@ class InfluxDbReporterTest { + + @Test + void reportsTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getSum()).thenReturn(6L); + when(timer.getMeanRate()).thenReturn(2.0); +@@ -308,7 +308,7 @@ class InfluxDbReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -360,7 +360,7 @@ class InfluxDbReporterTest { + + @Test + void disabledMetricsAttribute() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getSum()).thenReturn(6L); + when(meter.getOneMinuteRate()).thenReturn(2.0); +@@ -368,7 +368,7 @@ class InfluxDbReporterTest { + when(meter.getFifteenMinuteRate()).thenReturn(4.0); + when(meter.getMeanRate()).thenReturn(5.0); + +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(11L); + + Set disabledMetricAttributes = +diff --git a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java +index 29d4ddf..1f5a23a 100644 +--- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java ++++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java +@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.influxdb; + import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.any; + import static org.mockito.Mockito.doAnswer; ++import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + +@@ -14,15 +15,14 @@ import java.util.ArrayList; + import java.util.List; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; +-import org.mockito.Mockito; + +-class InfluxDbUdpTest { ++final class InfluxDbUdpTest { + + private final String host = "example.com"; + private final int port = 1234; + + private InfluxDbUdpSender influxdbUdp; +- private final DatagramChannel datagramChannel = Mockito.mock(DatagramChannel.class); ++ private final DatagramChannel datagramChannel = mock(); + private final List sent = new ArrayList<>(); + + @BeforeEach +diff --git a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java +index 3a776cc..459acf7 100644 +--- a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java ++++ b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.servlet; + + import static io.dropwizard.metrics5.MetricRegistry.name; + ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -64,7 +65,7 @@ public abstract class AbstractInstrumentedFilter implements Filter { + final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); + + String metricName = filterConfig.getInitParameter(METRIC_PREFIX); +- if (metricName == null || metricName.isEmpty()) { ++ if (Strings.isNullOrEmpty(metricName)) { + metricName = getClass().getName(); + } + +diff --git a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +index d6768d4..163e420 100644 +--- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +@@ -9,8 +9,8 @@ import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletContextEvent; + import org.junit.jupiter.api.Test; + +-class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++final class InstrumentedFilterContextListenerTest { ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ class InstrumentedFilterContextListenerTest { + + @Test + void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); + + listener.contextInitialized(event); +diff --git a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java +index 7473d89..8057b76 100644 +--- a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java ++++ b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.servlet6; + + import static io.dropwizard.metrics5.MetricRegistry.name; + ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -64,7 +65,7 @@ public abstract class AbstractInstrumentedFilter implements Filter { + final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); + + String metricName = filterConfig.getInitParameter(METRIC_PREFIX); +- if (metricName == null || metricName.isEmpty()) { ++ if (Strings.isNullOrEmpty(metricName)) { + metricName = getClass().getName(); + } + +diff --git a/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java b/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java +index af9fc44..0f00187 100644 +--- a/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java ++++ b/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java +@@ -9,8 +9,8 @@ import jakarta.servlet.ServletContext; + import jakarta.servlet.ServletContextEvent; + import org.junit.jupiter.api.Test; + +-class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++final class InstrumentedFilterContextListenerTest { ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ class InstrumentedFilterContextListenerTest { + + @Test + void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); + + listener.contextInitialized(event); +diff --git a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java +index a6081a8..440debd 100644 +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java +@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); + if (registryAttr instanceof HealthCheckRegistry) { + this.registry = (HealthCheckRegistry) registryAttr; +diff --git a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +index b8a0e3c..a365885 100644 +--- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java ++++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(METRICS_REGISTRY); + if (registryAttr instanceof MetricRegistry) { + this.registry = (MetricRegistry) registryAttr; +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java +index b71f2fa..92530f2 100755 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class AdminServletExclusionTest extends AbstractServletTest { ++final class AdminServletExclusionTest extends AbstractServletTest { + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +index 8fcdf8a..77b50ba 100755 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class AdminServletTest extends AbstractServletTest { ++final class AdminServletTest extends AbstractServletTest { + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +index ebe2c81..424a05e 100755 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class AdminServletUriTest extends AbstractServletTest { ++final class AdminServletUriTest extends AbstractServletTest { + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +index 1c63a41..2df4050 100644 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class CpuProfileServletTest extends AbstractServletTest { ++final class CpuProfileServletTest extends AbstractServletTest { + + @Override + protected void setUp(ServletTester tester) { +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +index f8f0a87..e8208b0 100644 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +@@ -1,10 +1,9 @@ + package io.dropwizard.metrics5.servlets; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -27,7 +26,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class HealthCheckServletTest extends AbstractServletTest { ++final class HealthCheckServletTest extends AbstractServletTest { + + private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); + +@@ -95,9 +94,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } + + @Test +@@ -111,9 +109,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } + + @Test +@@ -168,15 +165,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getContent()) + .isEqualTo( + String.format( +- "{%n" +- + " \"fun\" : {%n" +- + " \"healthy\" : true,%n" +- + " \"message\" : \"foo bar 123\",%n" +- + " \"duration\" : 0,%n" +- + " \"timestamp\" : \"" +- + EXPECTED_TIMESTAMP +- + "\"" +- + "%n }%n}")); ++ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", ++ EXPECTED_TIMESTAMP)); + } + + private static HealthCheck.Result healthyResultWithMessage(String message) { +@@ -197,23 +187,23 @@ class HealthCheckServletTest extends AbstractServletTest { + + @Test + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(healthCheckRegistry); +@@ -221,32 +211,32 @@ class HealthCheckServletTest extends AbstractServletTest { + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- assertThrows( +- ServletException.class, +- () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) +- .thenReturn("IRELLEVANT_STRING"); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); +- }); ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(ServletContext.class); ++ final ServletConfig servletConfig = mock(ServletConfig.class); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); + } + + @Test + void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(registry); +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +index 2e1d334..f30c0b9 100644 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +@@ -17,8 +17,8 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class MetricsServletContextListenerTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++final class MetricsServletContextListenerTest extends AbstractServletTest { ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final String allowedOrigin = "some.other.origin"; + +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +index 08d39bc..d74900f 100644 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +@@ -1,11 +1,10 @@ + package io.dropwizard.metrics5.servlets; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -25,8 +24,8 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class MetricsServletTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++final class MetricsServletTest extends AbstractServletTest { ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private ServletTester tester; + +@@ -130,22 +129,8 @@ class MetricsServletTest extends AbstractServletTest { + assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); + assertThat(response.getContent()) + .isEqualTo( +- callbackParamVal +- + "({" +- + "\"version\":\"5.0.0\"," +- + "\"gauges\":{" +- + "\"g1\":{\"value\":100}" +- + "}," +- + "\"counters\":{" +- + "\"c\":{\"count\":1}" +- + "}," +- + "\"histograms\":{" +- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" +- + "}," +- + "\"meters\":{" +- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" +- + "}" +- + "})"); ++ "%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", ++ callbackParamVal); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -224,48 +209,47 @@ class MetricsServletTest extends AbstractServletTest { + + @Test + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn(metricRegistry); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); + + final MetricsServlet metricsServlet = new MetricsServlet(null); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- assertThrows( +- ServletException.class, +- () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn("IRELLEVANT_STRING"); +- +- final MetricsServlet metricsServlet = new MetricsServlet(null); +- metricsServlet.init(servletConfig); +- }); ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(ServletContext.class); ++ final ServletConfig servletConfig = mock(ServletConfig.class); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final MetricsServlet metricsServlet = new MetricsServlet(null); ++ metricsServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); + } + } +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +index 72e4d9f..56bb1ee 100644 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class PingServletTest extends AbstractServletTest { ++final class PingServletTest extends AbstractServletTest { + @Override + protected void setUp(ServletTester tester) { + tester.addServlet(PingServlet.class, "/ping"); +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +index 3b92675..5bbb7b1 100644 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class ThreadDumpServletTest extends AbstractServletTest { ++final class ThreadDumpServletTest extends AbstractServletTest { + @Override + protected void setUp(ServletTester tester) { + tester.addServlet(ThreadDumpServlet.class, "/threads"); +diff --git a/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java b/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java +index 946c66f..9810386 100644 +--- a/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java ++++ b/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics5.jcache; + + import static io.dropwizard.metrics5.MetricRegistry.name; ++import static java.util.Collections.unmodifiableMap; + + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; +@@ -9,7 +10,6 @@ import io.dropwizard.metrics5.jvm.JmxAttributeGauge; + import java.lang.management.ManagementFactory; + import java.lang.reflect.Method; + import java.util.ArrayList; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Locale; +@@ -33,7 +33,7 @@ public class JCacheGaugeSet implements MetricSet { + private static final String M_BEAN_COORDINATES = + "javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"; + +- private static final Logger LOGGER = LoggerFactory.getLogger(JCacheGaugeSet.class); ++ private static final Logger LOG = LoggerFactory.getLogger(JCacheGaugeSet.class); + + @Override + public Map getMetrics() { +@@ -52,7 +52,7 @@ public class JCacheGaugeSet implements MetricSet { + } + } + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + + private Set getCacheBeans() { +@@ -60,7 +60,7 @@ public class JCacheGaugeSet implements MetricSet { + return ManagementFactory.getPlatformMBeanServer() + .queryMBeans(ObjectName.getInstance(M_BEAN_COORDINATES), null); + } catch (MalformedObjectNameException e) { +- LOGGER.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); ++ LOG.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); + throw new RuntimeException(e); + } + } +diff --git a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java +index cf3e28d..cf0f223 100644 +--- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java ++++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java +@@ -11,7 +11,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class JCacheGaugeSetTest { ++final class JCacheGaugeSetTest { + + private MetricRegistry registry; + private Cache myCache; +@@ -67,11 +67,11 @@ class JCacheGaugeSetTest { + + this.myCache.remove("woo2"); + assertThat((Float) registry.getGauges().get(myCache.resolve("average-get-time")).getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + assertThat((Float) registry.getGauges().get(myCache.resolve("average-put-time")).getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + assertThat((Float) registry.getGauges().get(myCache.resolve("average-remove-time")).getValue()) +- .isGreaterThan(0.0f); ++ .isPositive(); + } + + @AfterEach +diff --git a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java +index 5f67c62..ceea60d 100644 +--- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java ++++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.jdbi3.strategies; + ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import org.jdbi.v3.core.extension.ExtensionMethod; +@@ -13,7 +14,7 @@ public enum DefaultNameStrategy implements StatementNameStrategy { + @Override + public MetricName getStatementName(StatementContext statementContext) { + final String rawSql = statementContext.getRawSql(); +- return rawSql == null || rawSql.isEmpty() ? MetricName.build("sql.empty") : null; ++ return Strings.isNullOrEmpty(rawSql) ? MetricName.build("sql.empty") : null; + } + }, + +diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java +index 4588a32..5378df0 100644 +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java +@@ -8,7 +8,7 @@ import io.dropwizard.metrics5.MetricName; + import org.jdbi.v3.core.extension.ExtensionMethod; + import org.junit.jupiter.api.Test; + +-class BasicSqlNameStrategyTest extends AbstractStrategyTest { ++final class BasicSqlNameStrategyTest extends AbstractStrategyTest { + + private final BasicSqlNameStrategy basicSqlNameStrategy = new BasicSqlNameStrategy(); + +diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java +index b8cf361..c8f74aa 100755 +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java +@@ -12,15 +12,15 @@ import java.util.concurrent.TimeUnit; + import org.jdbi.v3.core.statement.StatementContext; + import org.junit.jupiter.api.Test; + +-class InstrumentedSqlLoggerTest { ++final class InstrumentedSqlLoggerTest { + @Test + void logsExecutionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); + final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); + +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); + + final MetricName statementName = MetricName.build("my-fake-name"); + final long fakeElapsed = 1234L; +@@ -37,12 +37,12 @@ class InstrumentedSqlLoggerTest { + + @Test + void logsExceptionTime() { +- final MetricRegistry mockRegistry = mock(MetricRegistry.class); +- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); ++ final MetricRegistry mockRegistry = mock(); ++ final StatementNameStrategy mockNameStrategy = mock(); + final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); + +- final StatementContext mockContext = mock(StatementContext.class); +- final Timer mockTimer = mock(Timer.class); ++ final StatementContext mockContext = mock(); ++ final Timer mockTimer = mock(); + + final MetricName statementName = MetricName.build("my-fake-name"); + final long fakeElapsed = 1234L; +diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java +index 7d8d115..8175106 100644 +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java +@@ -5,7 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; + import io.dropwizard.metrics5.MetricName; + import org.junit.jupiter.api.Test; + +-class NaiveNameStrategyTest extends AbstractStrategyTest { ++final class NaiveNameStrategyTest extends AbstractStrategyTest { + + private final NaiveNameStrategy naiveNameStrategy = new NaiveNameStrategy(); + +diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java +index efca9da..b9f4c6a 100644 +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java +@@ -12,7 +12,7 @@ import org.jdbi.v3.core.extension.ExtensionMethod; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class SmartNameStrategyTest extends AbstractStrategyTest { ++final class SmartNameStrategyTest extends AbstractStrategyTest { + + private final StatementNameStrategy smartNameStrategy = new SmartNameStrategy(); + private InstrumentedTimingCollector collector; +diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java +index 20cd360..b380772 100644 +--- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java ++++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java +@@ -8,7 +8,7 @@ import io.dropwizard.metrics5.annotation.Timed; + import org.jdbi.v3.core.extension.ExtensionMethod; + import org.junit.jupiter.api.Test; + +-class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { ++final class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + + private final TimedAnnotationNameStrategy timedAnnotationNameStrategy = + new TimedAnnotationNameStrategy(); +@@ -44,7 +44,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } + + @Test +- void testAnnotationOnMethod() throws Exception { ++ void annotationOnMethod() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("update"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +@@ -54,7 +54,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } + + @Test +- void testAnnotationOnMethodWithCustomName() throws Exception { ++ void annotationOnMethodWithCustomName() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("customUpdate"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +@@ -64,7 +64,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } + + @Test +- void testAnnotationOnMethodWithCustomAbsoluteName() throws Exception { ++ void annotationOnMethodWithCustomAbsoluteName() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("absoluteUpdate"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +@@ -72,7 +72,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } + + @Test +- void testAnnotationOnClass() throws Exception { ++ void annotationOnClass() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Bar.class, Bar.class.getMethod("update"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) +@@ -82,7 +82,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } + + @Test +- void testAnnotationOnMethodAndClassWithCustomNames() throws Exception { ++ void annotationOnMethodAndClassWithCustomNames() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn( + new ExtensionMethod(CustomBar.class, CustomBar.class.getMethod("find", String.class))); +@@ -91,14 +91,14 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { + } + + @Test +- void testNoAnnotations() throws Exception { ++ void noAnnotations() throws Exception { + when(ctx.getExtensionMethod()) + .thenReturn(new ExtensionMethod(Dummy.class, Dummy.class.getMethod("show"))); + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); + } + + @Test +- void testNoMethod() { ++ void noMethod() { + assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); + } + } +diff --git a/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java b/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java +index 7116636..0d33048 100644 +--- a/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java +@@ -3,7 +3,11 @@ package io.dropwizard.metrics5.jersey2; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Meter; +@@ -19,7 +23,6 @@ import io.dropwizard.metrics5.annotation.Timed; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -159,7 +162,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(metricName.resolve("1xx-responses")), // 1xx + registry.meter(metricName.resolve("2xx-responses")), // 2xx +@@ -167,11 +170,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(metricName.resolve("4xx-responses")), // 4xx + registry.meter(metricName.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); + this.metricRegistry = registry; + } + +@@ -305,9 +306,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -418,14 +419,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -543,7 +541,7 @@ public class InstrumentedResourceMethodApplicationListener + final String... suffixes) { + final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + MetricName metricName; +- if (explicitName != null && !explicitName.isEmpty()) { ++ if (!Strings.isNullOrEmpty(explicitName)) { + metricName = + absolute + ? MetricRegistry.name(explicitName) +@@ -604,8 +602,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); + } + } + } +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java +index d077730..9252eec 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java +@@ -14,7 +14,7 @@ import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-class CustomReservoirImplementationTest extends JerseyTest { ++final class CustomReservoirImplementationTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java +index b96f71a..47ae1ce 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} with filter tracking + */ +-class SingletonFilterMetricsJerseyTest extends JerseyTest { ++final class SingletonFilterMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -34,8 +34,7 @@ class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @BeforeEach +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +index 4258938..db81836 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -34,9 +34,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } + + @Test +@@ -50,7 +48,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -75,7 +73,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java +index 2aeb6ef..e79e200 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java +@@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link org.glassfish.jersey.server.ResourceConfig} + */ +-class SingletonMetricsJerseyTest extends JerseyTest { ++final class SingletonMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -37,9 +37,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -92,13 +90,13 @@ class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + MetricRegistry.name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); + +- assertThat(meter2xx.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); + assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter4xx.getCount()).isZero(); ++ assertThat(meter4xx.getCount()).isEqualTo(0); + assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); + +- assertThat(meter5xx.getCount()).isZero(); ++ assertThat(meter5xx.getCount()).isEqualTo(0); + assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); + + assertThat(meter2xx.getCount()).isEqualTo(1); +@@ -107,7 +105,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + } + + @Test +- void testResourceNotFound() { ++ void resourceNotFound() { + final Response response = target().path("not-found").request().get(); + assertThat(response.getStatus()).isEqualTo(404); + +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java +index 561a942..ce3e94f 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -31,9 +31,7 @@ class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java +index bc36e7a..eeec0da 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -1,7 +1,6 @@ + package io.dropwizard.metrics5.jersey2; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; + + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -11,6 +10,7 @@ import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceResponseM + import java.util.logging.Level; + import java.util.logging.Logger; + import javax.ws.rs.core.Application; ++import org.assertj.core.api.Assertions; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; +@@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -34,9 +34,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +@@ -109,7 +107,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { + try { + target("responseMeteredRuntimeExceptionPerClass").request().get(); +- fail("expected RuntimeException"); ++ Assertions.fail("expected RuntimeException"); + } catch (Exception e) { + assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + } +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java +index c8a6468..cd7c883 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java +@@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -31,9 +31,7 @@ class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } + + @Test +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java +index b1a48cc..6173844 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } + + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } + + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java +index a74a5c8..566fef8 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import javax.ws.rs.core.Response; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,46 +46,46 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered + @Path("/response-2xx-metered") ++ @ResponseMetered + public Response response2xxMetered() { + return Response.ok().build(); + } + + @GET +- @ResponseMetered + @Path("/response-4xx-metered") ++ @ResponseMetered + public Response response4xxMetered() { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + + @GET +- @ResponseMetered + @Path("/response-5xx-metered") ++ @ResponseMetered + public Response response5xxMetered() { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java +index 32fffd6..b99a6cf 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import javax.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +diff --git a/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java b/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java +index dc0e1bb..4298701 100644 +--- a/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java +@@ -4,7 +4,11 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Meter; +@@ -22,7 +26,6 @@ import jakarta.ws.rs.ext.Provider; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -160,7 +163,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(metricName.resolve("1xx-responses")), // 1xx + registry.meter(metricName.resolve("2xx-responses")), // 2xx +@@ -168,11 +171,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(metricName.resolve("4xx-responses")), // 4xx + registry.meter(metricName.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); + this.metricRegistry = registry; + } + +@@ -306,9 +307,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -419,14 +420,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -544,7 +542,7 @@ public class InstrumentedResourceMethodApplicationListener + final String... suffixes) { + final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + MetricName metricName; +- if (explicitName != null && !explicitName.isEmpty()) { ++ if (!Strings.isNullOrEmpty(explicitName)) { + metricName = + absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); + } else { +@@ -602,8 +600,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); + } + } + } +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java +index a3ac358..c512f1e 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java +@@ -14,7 +14,7 @@ import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-class CustomReservoirImplementationTest extends JerseyTest { ++final class CustomReservoirImplementationTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java +index a95000f..59b42a3 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java +@@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} with filter tracking + */ +-class SingletonFilterMetricsJerseyTest extends JerseyTest { ++final class SingletonFilterMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,8 +35,7 @@ class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @BeforeEach +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +index 80d90a6..023155e 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,9 +35,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } + + @Test +@@ -51,7 +49,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java +index f507662..9dca17f 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java +@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link org.glassfish.jersey.server.ResourceConfig} + */ +-class SingletonMetricsJerseyTest extends JerseyTest { ++final class SingletonMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -38,9 +38,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -89,13 +87,13 @@ class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter5xx = + registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); + +- assertThat(meter2xx.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); + assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter4xx.getCount()).isZero(); ++ assertThat(meter4xx.getCount()).isEqualTo(0); + assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); + +- assertThat(meter5xx.getCount()).isZero(); ++ assertThat(meter5xx.getCount()).isEqualTo(0); + assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); + + assertThat(meter2xx.getCount()).isEqualTo(1); +@@ -115,9 +113,9 @@ class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -127,28 +125,28 @@ class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } + + @Test +- public void responseMeteredMethodsAreMeteredWithAllLevel() { ++ void responseMeteredMethodsAreMeteredWithAllLevel() { + final Meter meter2xx = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + + @Test +- void testResourceNotFound() { ++ void resourceNotFound() { + final Response response = target().path("not-found").request().get(); + assertThat(response.getStatus()).isEqualTo(404); + +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java +index f9a9aaf..18c0712 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -32,9 +32,7 @@ class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java +index 9e3e887..00e401f 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.jersey3; + + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; + + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -12,6 +11,7 @@ import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceResponseM + import jakarta.ws.rs.core.Application; + import java.util.logging.Level; + import java.util.logging.Logger; ++import org.assertj.core.api.Assertions; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; +@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,9 +35,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +@@ -110,7 +108,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { + try { + target("responseMeteredRuntimeExceptionPerClass").request().get(); +- fail("expected RuntimeException"); ++ Assertions.fail("expected RuntimeException"); + } catch (Exception e) { + assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + } +@@ -140,8 +138,8 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); +@@ -154,7 +152,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + "2xx-responses")); + assertThat(meter.getCount()).isEqualTo(1); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java +index 96977e6..edcb12d 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -32,9 +32,7 @@ class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } + + @Test +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java +index 76fdaa4..7514cf6 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } + + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } + + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java +index f865db2..9e4d521 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,46 +46,46 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered + @Path("/response-2xx-metered") ++ @ResponseMetered + public Response response2xxMetered() { + return Response.ok().build(); + } + + @GET +- @ResponseMetered + @Path("/response-4xx-metered") ++ @ResponseMetered + public Response response4xxMetered() { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + + @GET +- @ResponseMetered + @Path("/response-5xx-metered") ++ @ResponseMetered + public Response response5xxMetered() { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java +index 5df3fc5..98e889d 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +diff --git a/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java b/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java +index 830d052..ff2dea3 100644 +--- a/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java ++++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java +@@ -4,7 +4,11 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.base.Strings; ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Clock; + import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; + import io.dropwizard.metrics5.Meter; +@@ -22,7 +26,6 @@ import jakarta.ws.rs.ext.Provider; + import java.lang.annotation.Annotation; + import java.lang.reflect.Method; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -160,7 +163,7 @@ public class InstrumentedResourceMethodApplicationListener + this.level = responseMetered.level(); + this.meters = + COARSE_METER_LEVELS.contains(level) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(metricName.resolve("1xx-responses")), // 1xx + registry.meter(metricName.resolve("2xx-responses")), // 2xx +@@ -168,11 +171,9 @@ public class InstrumentedResourceMethodApplicationListener + registry.meter(metricName.resolve("4xx-responses")), // 4xx + registry.meter(metricName.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); + this.responseCodeMeters = +- DETAILED_METER_LEVELS.contains(level) +- ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); + this.metricRegistry = registry; + } + +@@ -306,9 +307,9 @@ public class InstrumentedResourceMethodApplicationListener + : null; + + if (metric != null) { +- if (metric.cause.isAssignableFrom(event.getException().getClass()) ++ if (metric.cause.isInstance(event.getException()) + || (event.getException().getCause() != null +- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { ++ && metric.cause.isInstance(event.getException().getCause()))) { + metric.meter.mark(); + } + } +@@ -419,14 +420,11 @@ public class InstrumentedResourceMethodApplicationListener + + @Override + public RequestEventListener onRequest(final RequestEvent event) { +- final RequestEventListener listener = +- new ChainedRequestEventListener( +- new TimerRequestEventListener(timers, clock), +- new MeterRequestEventListener(meters), +- new ExceptionMeterRequestEventListener(exceptionMeters), +- new ResponseMeterRequestEventListener(responseMeters)); +- +- return listener; ++ return new ChainedRequestEventListener( ++ new TimerRequestEventListener(timers, clock), ++ new MeterRequestEventListener(meters), ++ new ExceptionMeterRequestEventListener(exceptionMeters), ++ new ResponseMeterRequestEventListener(responseMeters)); + } + + private T getClassLevelAnnotation( +@@ -544,7 +542,7 @@ public class InstrumentedResourceMethodApplicationListener + final String... suffixes) { + final Method definitionMethod = method.getInvocable().getDefinitionMethod(); + MetricName metricName; +- if (explicitName != null && !explicitName.isEmpty()) { ++ if (!Strings.isNullOrEmpty(explicitName)) { + metricName = + absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); + } else { +@@ -602,8 +600,7 @@ public class InstrumentedResourceMethodApplicationListener + @Override + public int hashCode() { + int result = type.hashCode(); +- result = 31 * result + method.hashCode(); +- return result; ++ return 31 * result + method.hashCode(); + } + } + } +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java +index 46996eb..6aaa268 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java +@@ -14,7 +14,7 @@ import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; + +-class CustomReservoirImplementationTest extends JerseyTest { ++final class CustomReservoirImplementationTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java +index b93ab95..546f28b 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java +@@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} with filter tracking + */ +-class SingletonFilterMetricsJerseyTest extends JerseyTest { ++final class SingletonFilterMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,8 +35,7 @@ class SingletonFilterMetricsJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry, testClock, true)); + config = config.register(new TestRequestFilter(testClock)); +- config = config.register(new InstrumentedFilteredResource(testClock)); +- return config; ++ return config.register(new InstrumentedFilteredResource(testClock)); + } + + @BeforeEach +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +index f67f1d0..32d2dde 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +@@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,9 +35,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); + } + + @Test +@@ -51,7 +49,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -76,7 +74,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { + assertThat(target("subresource/exception-metered").request().get(String.class)) + .isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("subresource/exception-metered") +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java +index aa0251c..3b35f93 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java +@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsJerseyTest extends JerseyTest { ++final class SingletonMetricsJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -38,9 +38,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + + ResourceConfig config = new ResourceConfig(); + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResource.class); +- +- return config; ++ return config.register(InstrumentedResource.class); + } + + @Test +@@ -67,7 +65,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { + + assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); + +- assertThat(meter.getCount()).isZero(); ++ assertThat(meter.getCount()).isEqualTo(0); + + try { + target("exception-metered").queryParam("splode", true).request().get(String.class); +@@ -89,33 +87,33 @@ class SingletonMetricsJerseyTest extends JerseyTest { + final Meter meter5xx = + registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); + +- assertThat(meter2xx.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); + assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter4xx.getCount()).isZero(); ++ assertThat(meter4xx.getCount()).isEqualTo(0); + assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); + +- assertThat(meter5xx.getCount()).isZero(); ++ assertThat(meter5xx.getCount()).isEqualTo(0); + assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); + } + + @Test +- public void responseMeteredMethodsAreMeteredWithCoarseLevel() { ++ void responseMeteredMethodsAreMeteredWithCoarseLevel() { + final Meter meter2xx = + registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "2xx-responses")); + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(0); + } + + @Test +- public void responseMeteredMethodsAreMeteredWithDetailedLevel() { ++ void responseMeteredMethodsAreMeteredWithDetailedLevel() { + final Meter meter2xx = + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "2xx-responses")); +@@ -126,9 +124,9 @@ class SingletonMetricsJerseyTest extends JerseyTest { + registry.meter( + name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); +- assertThat(meter201.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); ++ assertThat(meter201.getCount()).isEqualTo(0); + assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); + assertThat( + target("response-metered-detailed") +@@ -138,28 +136,28 @@ class SingletonMetricsJerseyTest extends JerseyTest { + .getStatus()) + .isEqualTo(201); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isOne(); +- assertThat(meter201.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(1); ++ assertThat(meter201.getCount()).isEqualTo(1); + } + + @Test +- public void responseMeteredMethodsAreMeteredWithAllLevel() { ++ void responseMeteredMethodsAreMeteredWithAllLevel() { + final Meter meter2xx = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); + final Meter meter200 = + registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + + @Test +- void testResourceNotFound() { ++ void resourceNotFound() { + final Response response = target().path("not-found").request().get(); + assertThat(response.getStatus()).isEqualTo(404); + +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java +index a661f5d..9a90095 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -32,9 +32,7 @@ class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceMeteredPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceMeteredPerClass.class); + } + + @Test +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java +index 1d68658..fdd0440 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.jersey31; + + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.fail; + + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -12,6 +11,7 @@ import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceResponse + import jakarta.ws.rs.core.Application; + import java.util.logging.Level; + import java.util.logging.Logger; ++import org.assertj.core.api.Assertions; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; +@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -35,9 +35,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + + config = config.register(new MetricsFeature(this.registry)); + config = config.register(InstrumentedResourceResponseMeteredPerClass.class); +- config = config.register(new TestExceptionMapper()); +- +- return config; ++ return config.register(new TestExceptionMapper()); + } + + @Test +@@ -110,7 +108,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { + try { + target("responseMeteredRuntimeExceptionPerClass").request().get(); +- fail("expected RuntimeException"); ++ Assertions.fail("expected RuntimeException"); + } catch (Exception e) { + assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + } +@@ -140,13 +138,13 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { + "responseMeteredPerClass", + "200-responses")); + +- assertThat(meter2xx.getCount()).isZero(); +- assertThat(meter200.getCount()).isZero(); ++ assertThat(meter2xx.getCount()).isEqualTo(0); ++ assertThat(meter200.getCount()).isEqualTo(0); + + assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) + .isEqualTo(200); + +- assertThat(meter2xx.getCount()).isOne(); +- assertThat(meter200.getCount()).isOne(); ++ assertThat(meter2xx.getCount()).isEqualTo(1); ++ assertThat(meter200.getCount()).isEqualTo(1); + } + } +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java +index 2258ea8..ca5dd87 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java +@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; + * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a + * Jersey {@link ResourceConfig} + */ +-class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { ++final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + static { + Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); + } +@@ -32,9 +32,7 @@ class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { + ResourceConfig config = new ResourceConfig(); + + config = config.register(new MetricsFeature(this.registry)); +- config = config.register(InstrumentedResourceTimedPerClass.class); +- +- return config; ++ return config.register(InstrumentedResourceTimedPerClass.class); + } + + @Test +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java +index 08d974e..17d8a5b 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java +@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { + } + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick++; + return "yay"; + } + + @GET +- @Timed(name = "fancyName") + @Path("/named") ++ @Timed(name = "fancyName") + public String named() { + testClock.tick++; + return "fancy"; + } + + @GET +- @Timed(name = "absolutelyFancy", absolute = true) + @Path("/absolute") ++ @Timed(name = "absolutelyFancy", absolute = true) + public String absolute() { + testClock.tick++; + return "absolute"; +@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { + public class InstrumentedFilteredSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + testClock.tick += 2; + return "yay"; +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java +index 20cc56a..6befce2 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java +@@ -21,8 +21,8 @@ import java.io.IOException; + @Produces(MediaType.TEXT_PLAIN) + public class InstrumentedResource { + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +@@ -34,8 +34,8 @@ public class InstrumentedResource { + return "woo"; + } + +- @GET + @ExceptionMetered(cause = IOException.class) ++ @GET + @Path("/exception-metered") + public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) + throws IOException { +@@ -46,46 +46,46 @@ public class InstrumentedResource { + } + + @GET +- @ResponseMetered(level = DETAILED) + @Path("/response-metered-detailed") ++ @ResponseMetered(level = DETAILED) + public Response responseMeteredDetailed( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = COARSE) + @Path("/response-metered-coarse") ++ @ResponseMetered(level = COARSE) + public Response responseMeteredCoarse( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered(level = ALL) + @Path("/response-metered-all") ++ @ResponseMetered(level = ALL) + public Response responseMeteredAll( + @QueryParam("status_code") @DefaultValue("200") int statusCode) { + return Response.status(Response.Status.fromStatusCode(statusCode)).build(); + } + + @GET +- @ResponseMetered + @Path("/response-2xx-metered") ++ @ResponseMetered + public Response response2xxMetered() { + return Response.ok().build(); + } + + @GET +- @ResponseMetered + @Path("/response-4xx-metered") ++ @ResponseMetered + public Response response4xxMetered() { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + + @GET +- @ResponseMetered + @Path("/response-5xx-metered") ++ @ResponseMetered + public Response response5xxMetered() { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java +index 3db3c9f..2efa31f 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java +@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; + public class InstrumentedSubResource { + + @GET +- @Timed + @Path("/timed") ++ @Timed + public String timed() { + return "yay"; + } +diff --git a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java +index 847cc4c..a75a1d4 100644 +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java +@@ -4,7 +4,10 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -14,7 +17,6 @@ import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -173,7 +175,7 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); + + this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); +@@ -188,7 +190,7 @@ public class InstrumentedHandler extends HandlerWrapper { + + if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { + this.responses = +- Collections.unmodifiableList( ++ unmodifiableList( + Arrays.asList( + metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx +@@ -253,7 +255,7 @@ public class InstrumentedHandler extends HandlerWrapper { + } + }); + } else { +- this.responses = Collections.emptyList(); ++ this.responses = ImmutableList.of(); + } + + this.listener = new AsyncAttachingListener(); +diff --git a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java +index bddd2b9..29e9004 100644 +--- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java +@@ -3,7 +3,10 @@ package io.dropwizard.metrics5.jetty10; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -14,7 +17,6 @@ import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(prefix.resolve("1xx-responses")), // 1xx + registry.meter(prefix.resolve("2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(prefix.resolve("4xx-responses")), // 4xx + registry.meter(prefix.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); + + this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); + this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); +diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java +index 9a3d31c..fa1f566 100644 +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java +@@ -21,7 +21,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedConnectionFactoryTest { ++final class InstrumentedConnectionFactoryTest { + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); + private final ServerConnector connector = +diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java +index 771f5a4..337c76a 100644 +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java +@@ -3,13 +3,13 @@ package io.dropwizard.metrics5.jetty10; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; + + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import javax.servlet.AsyncContext; + import javax.servlet.ServletException; +@@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + +-class InstrumentedHandlerTest { ++final class InstrumentedHandlerTest { + private final HttpClient client = new HttpClient(); + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); +@@ -118,7 +118,7 @@ class InstrumentedHandlerTest { + } + + @Test +- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { ++ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { + InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -128,7 +128,7 @@ class InstrumentedHandlerTest { + } + + @Test +- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { ++ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { + InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -137,8 +137,8 @@ class InstrumentedHandlerTest { + .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); + } + +- @Test + @Disabled("flaky on virtual machines") ++ @Test + void responseTimesAreRecordedForAsyncResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/async")); +@@ -150,7 +150,7 @@ class InstrumentedHandlerTest { + + private void assertResponseTimesValid() { + assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) +- .isGreaterThan(0L); ++ .isPositive(); + + assertThat( + registry +@@ -158,11 +158,11 @@ class InstrumentedHandlerTest { + .get(metricName().resolve("get-requests")) + .getSnapshot() + .getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -225,7 +225,7 @@ class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } + +diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java +index 295894d..aee388a 100644 +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java +@@ -1,12 +1,12 @@ + package io.dropwizard.metrics5.jetty10; + + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import javax.servlet.AsyncContext; + import javax.servlet.ServletOutputStream; + import javax.servlet.WriteListener; +@@ -22,7 +22,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedHttpChannelListenerTest { ++final class InstrumentedHttpChannelListenerTest { + private final HttpClient client = new HttpClient(); + private final Server server = new Server(); + private final ServerConnector connector = new ServerConnector(server); +@@ -188,7 +188,7 @@ class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } + +diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java +index 2d97f27..73ba784 100644 +--- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java ++++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java +@@ -8,7 +8,7 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedQueuedThreadPoolTest { ++final class InstrumentedQueuedThreadPoolTest { + private static final String PREFIX = "prefix"; + + private MetricRegistry metricRegistry; +diff --git a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java +index 19987c1..b5a43cb 100644 +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java +@@ -4,7 +4,10 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -19,7 +22,6 @@ import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -173,7 +175,7 @@ public class InstrumentedHandler extends HandlerWrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); + + this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); +@@ -188,7 +190,7 @@ public class InstrumentedHandler extends HandlerWrapper { + + if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { + this.responses = +- Collections.unmodifiableList( ++ unmodifiableList( + Arrays.asList( + metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx +@@ -253,7 +255,7 @@ public class InstrumentedHandler extends HandlerWrapper { + } + }); + } else { +- this.responses = Collections.emptyList(); ++ this.responses = ImmutableList.of(); + } + + this.listener = new AsyncAttachingListener(); +diff --git a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java +index a423590..e0d710f 100644 +--- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java ++++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java +@@ -3,7 +3,10 @@ package io.dropwizard.metrics5.jetty11; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; + import java.nio.ByteBuffer; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); + this.responses = + COARSE_METER_LEVELS.contains(responseMeteredLevel) +- ? Collections.unmodifiableList( ++ ? unmodifiableList( + Arrays.asList( + registry.meter(prefix.resolve("1xx-responses")), // 1xx + registry.meter(prefix.resolve("2xx-responses")), // 2xx +@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { + registry.meter(prefix.resolve("4xx-responses")), // 4xx + registry.meter(prefix.resolve("5xx-responses")) // 5xx + )) +- : Collections.emptyList(); ++ : ImmutableList.of(); + + this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); + this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); +diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java +index e1ae763..b810aef 100644 +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java +@@ -21,7 +21,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedConnectionFactoryTest { ++final class InstrumentedConnectionFactoryTest { + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); + private final ServerConnector connector = +diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java +index 74d5d78..743c45c 100644 +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java +@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.jetty11; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; + +@@ -15,7 +16,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; +@@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + +-class InstrumentedHandlerTest { ++final class InstrumentedHandlerTest { + private final HttpClient client = new HttpClient(); + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); +@@ -118,7 +118,7 @@ class InstrumentedHandlerTest { + } + + @Test +- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { ++ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { + InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -128,7 +128,7 @@ class InstrumentedHandlerTest { + } + + @Test +- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { ++ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { + InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -137,8 +137,8 @@ class InstrumentedHandlerTest { + .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); + } + +- @Test + @Disabled("flaky on virtual machines") ++ @Test + void responseTimesAreRecordedForAsyncResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/async")); +@@ -150,7 +150,7 @@ class InstrumentedHandlerTest { + + private void assertResponseTimesValid() { + assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) +- .isGreaterThan(0L); ++ .isPositive(); + + assertThat( + registry +@@ -158,11 +158,11 @@ class InstrumentedHandlerTest { + .get(metricName().resolve("get-requests")) + .getSnapshot() + .getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -225,7 +225,7 @@ class InstrumentedHandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + } + +diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java +index aab3f77..4120921 100644 +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics5.jetty11; + + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import io.dropwizard.metrics5.MetricName; +@@ -11,7 +12,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import org.eclipse.jetty.client.HttpClient; + import org.eclipse.jetty.client.api.ContentResponse; + import org.eclipse.jetty.server.Request; +@@ -22,7 +22,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedHttpChannelListenerTest { ++final class InstrumentedHttpChannelListenerTest { + private final HttpClient client = new HttpClient(); + private final Server server = new Server(); + private final ServerConnector connector = new ServerConnector(server); +@@ -188,7 +188,7 @@ class InstrumentedHttpChannelListenerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async".getBytes(UTF_8)); + context.complete(); + } + +diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java +index 464abd2..27d0872 100644 +--- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java ++++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java +@@ -8,7 +8,7 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class InstrumentedQueuedThreadPoolTest { ++final class InstrumentedQueuedThreadPoolTest { + private static final String PREFIX = "prefix"; + + private MetricRegistry metricRegistry; +diff --git a/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java b/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java +index 0e556df..20760f9 100644 +--- a/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java ++++ b/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java +@@ -3,6 +3,7 @@ package io.dropwizard.metrics.jetty12.ee10; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatCode; + +@@ -14,7 +15,6 @@ import jakarta.servlet.WriteListener; + import jakarta.servlet.http.HttpServletRequest; + import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; +-import java.nio.charset.StandardCharsets; + import java.util.concurrent.TimeUnit; + import org.eclipse.jetty.client.ContentResponse; + import org.eclipse.jetty.client.HttpClient; +@@ -32,7 +32,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + +-public class InstrumentedEE10HandlerTest { ++final class InstrumentedEE10HandlerTest { + private final HttpClient client = new HttpClient(); + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); +@@ -40,7 +40,7 @@ public class InstrumentedEE10HandlerTest { + private final InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); + + @BeforeEach +- public void setUp() throws Exception { ++ void setUp() throws Exception { + handler.setName("handler"); + + TestHandler testHandler = new TestHandler(); +@@ -62,18 +62,18 @@ public class InstrumentedEE10HandlerTest { + } + + @AfterEach +- public void tearDown() throws Exception { ++ void tearDown() throws Exception { + server.stop(); + client.stop(); + } + + @Test +- public void hasAName() throws Exception { ++ void hasAName() throws Exception { + assertThat(handler.getName()).isEqualTo("handler"); + } + + @Test +- public void createsAndRemovesMetricsForTheHandler() throws Exception { ++ void createsAndRemovesMetricsForTheHandler() throws Exception { + final ContentResponse response = client.GET(uri("/hello")); + + assertThat(response.getStatus()).isEqualTo(404); +@@ -115,9 +115,9 @@ public class InstrumentedEE10HandlerTest { + assertThat(registry.getNames()).isEmpty(); + } + +- @Test + @Disabled("flaky on virtual machines") +- public void responseTimesAreRecordedForBlockingResponses() throws Exception { ++ @Test ++ void responseTimesAreRecordedForBlockingResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/blocking")); + +@@ -127,7 +127,7 @@ public class InstrumentedEE10HandlerTest { + } + + @Test +- public void doStopDoesNotThrowNPE() throws Exception { ++ void doStopDoesNotThrowNPE() throws Exception { + InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); + handler.setHandler(new TestHandler()); + +@@ -135,7 +135,7 @@ public class InstrumentedEE10HandlerTest { + } + + @Test +- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { ++ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { + InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "coarse", COARSE); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -145,7 +145,7 @@ public class InstrumentedEE10HandlerTest { + } + + @Test +- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { ++ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { + InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "detailed", DETAILED); + handler.setHandler(new TestHandler()); + handler.setName("handler"); +@@ -154,9 +154,9 @@ public class InstrumentedEE10HandlerTest { + .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); + } + +- @Test + @Disabled("flaky on virtual machines") +- public void responseTimesAreRecordedForAsyncResponses() throws Exception { ++ @Test ++ void responseTimesAreRecordedForAsyncResponses() throws Exception { + + final ContentResponse response = client.GET(uri("/async")); + +@@ -167,9 +167,9 @@ public class InstrumentedEE10HandlerTest { + + private void assertResponseTimesValid() { + assertThat(registry.getMeters().get(metricName().resolve("2xx-responses")).getCount()) +- .isGreaterThan(0L); ++ .isPositive(); + assertThat(registry.getMeters().get(metricName().resolve(".200-responses")).getCount()) +- .isGreaterThan(0L); ++ .isPositive(); + + assertThat( + registry +@@ -177,12 +177,12 @@ public class InstrumentedEE10HandlerTest { + .get(metricName().resolve(".get-requests")) + .getSnapshot() + .getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + + assertThat( + registry.getTimers().get(metricName().resolve(".requests")).getSnapshot().getMedian()) +- .isGreaterThan(0.0) ++ .isPositive() + .isLessThan(TimeUnit.SECONDS.toNanos(1)); + } + +@@ -250,7 +250,7 @@ public class InstrumentedEE10HandlerTest { + @Override + public void onWritePossible() throws IOException { + servletOutputStream.write( +- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); ++ "some content from the async\n".getBytes(UTF_8)); + context.complete(); + servletContextRequest.getServletChannel().handle(); + } +diff --git a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java +index e8e513f..8a7229d 100644 +--- a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java ++++ b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java +@@ -4,7 +4,10 @@ import static io.dropwizard.metrics5.MetricRegistry.name; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; + import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; ++import static java.util.Collections.unmodifiableList; + ++import com.google.common.collect.ImmutableList; ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricName; +@@ -13,7 +16,6 @@ import io.dropwizard.metrics5.RatioGauge; + import io.dropwizard.metrics5.Timer; + import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; + import java.util.Arrays; +-import java.util.Collections; + import java.util.EnumSet; + import java.util.List; + import java.util.Map; +@@ -164,7 +166,7 @@ public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { + this.responseCodeMeters = + DETAILED_METER_LEVELS.contains(responseMeteredLevel) + ? new ConcurrentHashMap<>() +- : Collections.emptyMap(); ++ : ImmutableMap.of(); + + this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); + this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); +@@ -179,7 +181,7 @@ public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { + + if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { + this.responses = +- Collections.unmodifiableList( ++ unmodifiableList( + Arrays.asList( + metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx + metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx +@@ -244,7 +246,7 @@ public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { + } + }); + } else { +- this.responses = Collections.emptyList(); ++ this.responses = ImmutableList.of(); + } + } + +diff --git a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java +index 1ec7ffc..cf26f20 100644 +--- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java ++++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java +@@ -19,7 +19,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-public class InstrumentedConnectionFactoryTest { ++final class InstrumentedConnectionFactoryTest { + private final MetricRegistry registry = new MetricRegistry(); + private final Server server = new Server(); + private final ServerConnector connector = +@@ -32,7 +32,7 @@ public class InstrumentedConnectionFactoryTest { + private final HttpClient client = new HttpClient(); + + @BeforeEach +- public void setUp() throws Exception { ++ void setUp() throws Exception { + server.setHandler( + new Handler.Abstract() { + @Override +@@ -50,13 +50,13 @@ public class InstrumentedConnectionFactoryTest { + } + + @AfterEach +- public void tearDown() throws Exception { ++ void tearDown() throws Exception { + server.stop(); + client.stop(); + } + + @Test +- public void instrumentsConnectionTimes() throws Exception { ++ void instrumentsConnectionTimes() throws Exception { + final ContentResponse response = + client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); + assertThat(response.getStatus()).isEqualTo(200); +@@ -70,7 +70,7 @@ public class InstrumentedConnectionFactoryTest { + } + + @Test +- public void instrumentsActiveConnections() throws Exception { ++ void instrumentsActiveConnections() throws Exception { + final Counter counter = registry.counter("http.active-connections"); + + final ContentResponse response = +diff --git a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java +index a69021b..9fa9616 100644 +--- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java ++++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java +@@ -7,20 +7,20 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-public class InstrumentedQueuedThreadPoolTest { ++final class InstrumentedQueuedThreadPoolTest { + private static final String PREFIX = "prefix"; + + private MetricRegistry metricRegistry; + private InstrumentedQueuedThreadPool iqtp; + + @BeforeEach +- public void setUp() { ++ void setUp() { + metricRegistry = new MetricRegistry(); + iqtp = new InstrumentedQueuedThreadPool(metricRegistry); + } + + @Test +- public void customMetricsPrefix() throws Exception { ++ void customMetricsPrefix() throws Exception { + iqtp.setPrefix(PREFIX); + iqtp.start(); + +@@ -35,7 +35,7 @@ public class InstrumentedQueuedThreadPoolTest { + } + + @Test +- public void metricsPrefixBackwardCompatible() throws Exception { ++ void metricsPrefixBackwardCompatible() throws Exception { + iqtp.start(); + assertThat(metricRegistry.getNames()) + .overridingErrorMessage("The default metrics prefix was changed") +diff --git a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java +index 4b72b5d..642fd3a 100644 +--- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java ++++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java +@@ -10,7 +10,7 @@ import org.slf4j.LoggerFactory; + public class DefaultObjectNameFactory implements ObjectNameFactory { + + private static final char[] QUOTABLE_CHARS = new char[] {',', '=', ':', '"'}; +- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectNameFactory.class); + + @Override + public ObjectName createName(String type, String domain, MetricName name) { +@@ -38,14 +38,13 @@ public class DefaultObjectNameFactory implements ObjectNameFactory { + || shouldQuote(objectName.getKeyProperty("type"))) { + properties.put("type", ObjectName.quote(type)); + } +- objectName = new ObjectName(domain, properties); ++ return new ObjectName(domain, properties); + +- return objectName; + } catch (MalformedObjectNameException e) { + try { + return new ObjectName(domain, "name", ObjectName.quote(name.getKey())); + } catch (MalformedObjectNameException e1) { +- LOGGER.warn("Unable to register {} {}", type, name, e1); ++ LOG.warn("Unable to register {} {}", type, name, e1); + throw new RuntimeException(e1); + } + } +diff --git a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java +index 085b4ef..d7c7b50 100644 +--- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java ++++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java +@@ -1,5 +1,9 @@ + package io.dropwizard.metrics5.jmx; + ++import static com.google.common.base.Preconditions.checkArgument; ++import static java.util.Collections.unmodifiableMap; ++ ++import com.google.common.collect.ImmutableMap; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Histogram; +@@ -13,7 +17,6 @@ import io.dropwizard.metrics5.Reporter; + import io.dropwizard.metrics5.Timer; + import java.io.Closeable; + import java.lang.management.ManagementFactory; +-import java.util.Collections; + import java.util.Locale; + import java.util.Map; + import java.util.concurrent.ConcurrentHashMap; +@@ -61,8 +64,8 @@ public class JmxReporter implements Reporter, Closeable { + this.durationUnit = TimeUnit.MILLISECONDS; + this.domain = "metrics"; + this.objectNameFactory = new DefaultObjectNameFactory(); +- this.specificDurationUnits = Collections.emptyMap(); +- this.specificRateUnits = Collections.emptyMap(); ++ this.specificDurationUnits = ImmutableMap.of(); ++ this.specificRateUnits = ImmutableMap.of(); + } + + /** +@@ -88,9 +91,7 @@ public class JmxReporter implements Reporter, Closeable { + } + + public Builder createsObjectNamesWith(ObjectNameFactory onFactory) { +- if (onFactory == null) { +- throw new IllegalArgumentException("null objectNameFactory"); +- } ++ checkArgument(onFactory != null, "null objectNameFactory"); + this.objectNameFactory = onFactory; + return this; + } +@@ -129,7 +130,7 @@ public class JmxReporter implements Reporter, Closeable { + * @return {@code this} + */ + public Builder specificDurationUnits(Map specificDurationUnits) { +- this.specificDurationUnits = Collections.unmodifiableMap(specificDurationUnits); ++ this.specificDurationUnits = unmodifiableMap(specificDurationUnits); + return this; + } + +@@ -140,7 +141,7 @@ public class JmxReporter implements Reporter, Closeable { + * @return {@code this} + */ + public Builder specificRateUnits(Map specificRateUnits) { +- this.specificRateUnits = Collections.unmodifiableMap(specificRateUnits); ++ this.specificRateUnits = unmodifiableMap(specificRateUnits); + return this; + } + +@@ -159,7 +160,7 @@ public class JmxReporter implements Reporter, Closeable { + } + } + +- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); ++ private static final Logger LOG = LoggerFactory.getLogger(JmxReporter.class); + + @SuppressWarnings("UnusedDeclaration") + public interface MetricMBean { +@@ -570,9 +571,9 @@ public class JmxReporter implements Reporter, Closeable { + registerMBean(new JmxGauge(gauge, objectName), objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register gauge", e); ++ LOG.debug("Unable to register gauge", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register gauge", e); ++ LOG.warn("Unable to register gauge", e); + } + } + +@@ -582,9 +583,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("gauges", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister gauge", e); ++ LOG.debug("Unable to unregister gauge", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister gauge", e); ++ LOG.warn("Unable to unregister gauge", e); + } + } + +@@ -596,9 +597,9 @@ public class JmxReporter implements Reporter, Closeable { + registerMBean(new JmxCounter(counter, objectName), objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register counter", e); ++ LOG.debug("Unable to register counter", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register counter", e); ++ LOG.warn("Unable to register counter", e); + } + } + +@@ -608,9 +609,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("counters", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister counter", e); ++ LOG.debug("Unable to unregister counter", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister counter", e); ++ LOG.warn("Unable to unregister counter", e); + } + } + +@@ -622,9 +623,9 @@ public class JmxReporter implements Reporter, Closeable { + registerMBean(new JmxHistogram(histogram, objectName), objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register histogram", e); ++ LOG.debug("Unable to register histogram", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register histogram", e); ++ LOG.warn("Unable to register histogram", e); + } + } + +@@ -634,9 +635,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("histograms", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister histogram", e); ++ LOG.debug("Unable to unregister histogram", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister histogram", e); ++ LOG.warn("Unable to unregister histogram", e); + } + } + +@@ -649,9 +650,9 @@ public class JmxReporter implements Reporter, Closeable { + new JmxMeter(meter, objectName, timeUnits.rateFor(name.getKey())), objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register meter", e); ++ LOG.debug("Unable to register meter", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register meter", e); ++ LOG.warn("Unable to register meter", e); + } + } + +@@ -661,9 +662,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("meters", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister meter", e); ++ LOG.debug("Unable to unregister meter", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister meter", e); ++ LOG.warn("Unable to unregister meter", e); + } + } + +@@ -681,9 +682,9 @@ public class JmxReporter implements Reporter, Closeable { + objectName); + } + } catch (InstanceAlreadyExistsException e) { +- LOGGER.debug("Unable to register timer", e); ++ LOG.debug("Unable to register timer", e); + } catch (JMException e) { +- LOGGER.warn("Unable to register timer", e); ++ LOG.warn("Unable to register timer", e); + } + } + +@@ -693,9 +694,9 @@ public class JmxReporter implements Reporter, Closeable { + final ObjectName objectName = createName("timers", name); + unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister timer", e); ++ LOG.debug("Unable to unregister timer", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister timer", e); ++ LOG.warn("Unable to unregister timer", e); + } + } + +@@ -708,9 +709,9 @@ public class JmxReporter implements Reporter, Closeable { + try { + unregisterMBean(name); + } catch (InstanceNotFoundException e) { +- LOGGER.debug("Unable to unregister metric", e); ++ LOG.debug("Unable to unregister metric", e); + } catch (MBeanRegistrationException e) { +- LOGGER.warn("Unable to unregister metric", e); ++ LOG.warn("Unable to unregister metric", e); + } + } + registered.clear(); +diff --git a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java +index 5fa8ffd..407c905 100644 +--- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java ++++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java +@@ -7,7 +7,7 @@ import io.dropwizard.metrics5.MetricName; + import javax.management.ObjectName; + import org.junit.jupiter.api.Test; + +-class DefaultObjectNameFactoryTest { ++final class DefaultObjectNameFactoryTest { + + @Test + void createsObjectNameWithDomainInInput() { +diff --git a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java +index cd5cc55..b32b472 100644 +--- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java ++++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.jmx; + ++import static java.util.UUID.randomUUID; + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.entry; + import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +@@ -21,7 +22,6 @@ import io.dropwizard.metrics5.Timer; + import java.lang.management.ManagementFactory; + import java.util.SortedMap; + import java.util.TreeMap; +-import java.util.UUID; + import java.util.concurrent.TimeUnit; + import javax.management.Attribute; + import javax.management.AttributeList; +@@ -35,9 +35,9 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("rawtypes") +-class JmxReporterTest { ++final class JmxReporterTest { + private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); +- private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); ++ private final String name = randomUUID().toString().replaceAll("[{\\-}]", ""); + private final MetricRegistry registry = new MetricRegistry(); + + private final JmxReporter reporter = +@@ -49,12 +49,12 @@ class JmxReporterTest { + .filter(MetricFilter.ALL) + .build(); + +- private final Gauge gauge = mock(Gauge.class); +- private final Counter counter = mock(Counter.class); +- private final Histogram histogram = mock(Histogram.class); +- private final Meter meter = mock(Meter.class); +- private final Timer timer = mock(Timer.class); +- private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); ++ private final Gauge gauge = mock(); ++ private final Counter counter = mock(); ++ private final Histogram histogram = mock(); ++ private final Meter meter = mock(); ++ private final Timer timer = mock(); ++ private final ObjectNameFactory mockObjectNameFactory = mock(); + private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); + + @BeforeEach +@@ -66,7 +66,7 @@ class JmxReporterTest { + when(histogram.getCount()).thenReturn(1L); + when(histogram.getSum()).thenReturn(12L); + +- final Snapshot hSnapshot = mock(Snapshot.class); ++ final Snapshot hSnapshot = mock(); + when(hSnapshot.getMax()).thenReturn(2L); + when(hSnapshot.getMean()).thenReturn(3.0); + when(hSnapshot.getMin()).thenReturn(4L); +@@ -95,7 +95,7 @@ class JmxReporterTest { + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot tSnapshot = mock(Snapshot.class); ++ final Snapshot tSnapshot = mock(); + when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +@@ -285,7 +285,7 @@ class JmxReporterTest { + + @Test + void objectNameModifyingMBeanServer() throws Exception { +- MBeanServer mockedMBeanServer = mock(MBeanServer.class); ++ MBeanServer mockedMBeanServer = mock(); + + // overwrite the objectName + when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))) +@@ -310,7 +310,7 @@ class JmxReporterTest { + } + + @Test +- void testJmxMetricNameWithAsterisk() { ++ void jmxMetricNameWithAsterisk() { + MetricRegistry metricRegistry = new MetricRegistry(); + JmxReporter.forRegistry(metricRegistry).build().start(); + metricRegistry.counter("test*"); +diff --git a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java +index 69ee5d1..0c6cfcf 100644 +--- a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java ++++ b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java +@@ -1,14 +1,15 @@ + package io.dropwizard.metrics5.json; + ++ + import com.fasterxml.jackson.core.JsonGenerator; + import com.fasterxml.jackson.core.Version; + import com.fasterxml.jackson.databind.Module; + import com.fasterxml.jackson.databind.SerializerProvider; + import com.fasterxml.jackson.databind.module.SimpleSerializers; + import com.fasterxml.jackson.databind.ser.std.StdSerializer; ++import com.google.common.collect.ImmutableList; + import io.dropwizard.metrics5.health.HealthCheck; + import java.io.IOException; +-import java.util.Collections; + import java.util.Map; + + public class HealthCheckModule extends Module { +@@ -80,6 +81,6 @@ public class HealthCheckModule extends Module { + @Override + public void setupModule(SetupContext context) { + context.addSerializers( +- new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer()))); ++ new SimpleSerializers(ImmutableList.of(new HealthCheckResultSerializer()))); + } + } +diff --git a/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java b/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java +index 0f8c76b..fad833a 100644 +--- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java ++++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java +@@ -10,15 +10,14 @@ import java.util.LinkedHashMap; + import java.util.Map; + import org.junit.jupiter.api.Test; + +-class HealthCheckModuleTest { ++final class HealthCheckModuleTest { + private final ObjectMapper mapper = new ObjectMapper().registerModule(new HealthCheckModule()); + + @Test + void serializesAHealthyResult() throws Exception { + HealthCheck.Result result = HealthCheck.Result.healthy(); + assertThat(mapper.writeValueAsString(result)) +- .isEqualTo( +- "{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); ++ .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp()); + } + + @Test +@@ -26,14 +25,8 @@ class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":true," +- + "\"message\":\"yay for me\"," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -41,14 +34,8 @@ class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"boo\"," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -60,19 +47,8 @@ class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy(e); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"oh no\"," +- + "\"error\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh no\"," +- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" +- + "}," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -88,24 +64,8 @@ class HealthCheckModuleTest { + HealthCheck.Result result = HealthCheck.Result.unhealthy(b); + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":false," +- + "\"message\":\"oh well\"," +- + "\"error\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh well\"," +- + "\"stack\":[\"Blah.blee(Blah.java:150)\"]," +- + "\"cause\":{" +- + "\"type\":\"java.lang.RuntimeException\"," +- + "\"message\":\"oh no\"," +- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" +- + "}" +- + "}," +- + "\"duration\":0," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + + @Test +@@ -129,23 +89,7 @@ class HealthCheckModuleTest { + + assertThat(mapper.writeValueAsString(result)) + .isEqualTo( +- "{" +- + "\"healthy\":true," +- + "\"duration\":0," +- + "\"boolean\":true," +- + "\"integer\":1," +- + "\"long\":2," +- + "\"float\":3.546," +- + "\"double\":4.567," +- + "\"BigInteger\":12345," +- + "\"BigDecimal\":12345.56789," +- + "\"String\":\"string\"," +- + "\"complex\":{" +- + "\"field\":\"value\"" +- + "}," +- + "\"timestamp\":\"" +- + result.getTimestamp() +- + "\"" +- + "}"); ++ "{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", ++ result.getTimestamp()); + } + } +diff --git a/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java b/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java +index 8fe2c7d..401a8f3 100644 +--- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java ++++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java +@@ -16,7 +16,7 @@ import io.dropwizard.metrics5.Timer; + import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + +-class MetricsModuleTest { ++final class MetricsModuleTest { + private final ObjectMapper mapper = + new ObjectMapper() + .registerModule( +@@ -42,7 +42,7 @@ class MetricsModuleTest { + + @Test + void serializesCounters() throws Exception { +- final Counter counter = mock(Counter.class); ++ final Counter counter = mock(); + when(counter.getCount()).thenReturn(100L); + + assertThat(mapper.writeValueAsString(counter)).isEqualTo("{\"count\":100}"); +@@ -50,10 +50,10 @@ class MetricsModuleTest { + + @Test + void serializesHistograms() throws Exception { +- final Histogram histogram = mock(Histogram.class); ++ final Histogram histogram = mock(); + when(histogram.getCount()).thenReturn(1L); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(2L); + when(snapshot.getMean()).thenReturn(3.0); + when(snapshot.getMin()).thenReturn(4L); +@@ -107,7 +107,7 @@ class MetricsModuleTest { + + @Test + void serializesMeters() throws Exception { +- final Meter meter = mock(Meter.class); ++ final Meter meter = mock(); + when(meter.getCount()).thenReturn(1L); + when(meter.getMeanRate()).thenReturn(2.0); + when(meter.getOneMinuteRate()).thenReturn(5.0); +@@ -127,14 +127,14 @@ class MetricsModuleTest { + + @Test + void serializesTimers() throws Exception { +- final Timer timer = mock(Timer.class); ++ final Timer timer = mock(); + when(timer.getCount()).thenReturn(1L); + when(timer.getMeanRate()).thenReturn(2.0); + when(timer.getOneMinuteRate()).thenReturn(3.0); + when(timer.getFiveMinuteRate()).thenReturn(4.0); + when(timer.getFifteenMinuteRate()).thenReturn(5.0); + +- final Snapshot snapshot = mock(Snapshot.class); ++ final Snapshot snapshot = mock(); + when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); + when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); + when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); +diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java +index d90d7d8..2bce9f4 100644 +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java +@@ -1,10 +1,11 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricRegistry; + import io.dropwizard.metrics5.MetricSet; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + import javax.management.JMException; +@@ -19,7 +20,7 @@ import org.slf4j.LoggerFactory; + *

    These JMX objects are only available on Java 7 and above. + */ + public class BufferPoolMetricSet implements MetricSet { +- private static final Logger LOGGER = LoggerFactory.getLogger(BufferPoolMetricSet.class); ++ private static final Logger LOG = LoggerFactory.getLogger(BufferPoolMetricSet.class); + private static final String[] ATTRIBUTES = {"Count", "MemoryUsed", "TotalCapacity"}; + private static final String[] NAMES = {"count", "used", "capacity"}; + private static final String[] POOLS = {"direct", "mapped"}; +@@ -43,10 +44,10 @@ public class BufferPoolMetricSet implements MetricSet { + gauges.put( + MetricRegistry.name(pool, name), new JmxAttributeGauge(mBeanServer, on, attribute)); + } catch (JMException ignored) { +- LOGGER.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); ++ LOG.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); + } + } + } +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java +index 35a031e..63792f9 100644 +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; +@@ -9,7 +11,6 @@ import java.lang.management.GarbageCollectorMXBean; + import java.lang.management.ManagementFactory; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -43,6 +44,6 @@ public class GarbageCollectorMetricSet implements MetricSet { + gauges.put(MetricRegistry.name(name, "count"), (Gauge) gc::getCollectionCount); + gauges.put(MetricRegistry.name(name, "time"), (Gauge) gc::getCollectionTime); + } +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java +index 3a19d83..67a16e9 100644 +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java +@@ -1,12 +1,13 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; + import io.dropwizard.metrics5.MetricSet; + import java.lang.management.ManagementFactory; + import java.lang.management.RuntimeMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Locale; + import java.util.Map; +@@ -47,6 +48,6 @@ public class JvmAttributeGaugeSet implements MetricSet { + runtime.getSpecVersion())); + gauges.put(MetricName.build("uptime"), (Gauge) runtime::getUptime); + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java +index 60a2772..0c7ce49 100644 +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; +@@ -12,7 +14,6 @@ import java.lang.management.MemoryPoolMXBean; + import java.lang.management.MemoryUsage; + import java.util.ArrayList; + import java.util.Collection; +-import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; +@@ -139,6 +140,6 @@ public class MemoryUsageGaugeSet implements MetricSet { + MetricRegistry.name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); + } + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + } +diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java +index 40dc851..c973272 100644 +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java +@@ -1,9 +1,11 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableSet; ++ ++import com.google.common.collect.ImmutableSet; + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashSet; + import java.util.Set; + +@@ -40,19 +42,16 @@ public class ThreadDeadlockDetector { + for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { + final StringBuilder stackTrace = new StringBuilder(); + for (StackTraceElement element : info.getStackTrace()) { +- stackTrace.append("\t at ").append(element.toString()).append(String.format("%n")); ++ stackTrace.append("\t at ").append(element).append(String.format("%n")); + } + + deadlocks.add( + String.format( + "%s locked on %s (owned by %s):%n%s", +- info.getThreadName(), +- info.getLockName(), +- info.getLockOwnerName(), +- stackTrace.toString())); ++ info.getThreadName(), info.getLockName(), info.getLockOwnerName(), stackTrace)); + } +- return Collections.unmodifiableSet(deadlocks); ++ return unmodifiableSet(deadlocks); + } +- return Collections.emptySet(); ++ return ImmutableSet.of(); + } + } +diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java +index 2d12960..1db9950 100644 +--- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java ++++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java +@@ -1,5 +1,7 @@ + package io.dropwizard.metrics5.jvm; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.Metric; + import io.dropwizard.metrics5.MetricName; +@@ -8,7 +10,6 @@ import io.dropwizard.metrics5.MetricSet; + import java.lang.management.ManagementFactory; + import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + import java.util.Set; +@@ -59,7 +60,7 @@ public class ThreadStatesGaugeSet implements MetricSet { + gauges.put( + MetricName.build("deadlocks"), (Gauge>) deadlockDetector::getDeadlockedThreads); + +- return Collections.unmodifiableMap(gauges); ++ return unmodifiableMap(gauges); + } + + private int getThreadCount(Thread.State state) { +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java +index f622832..c497fc3 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java +@@ -13,7 +13,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("rawtypes") +-class BufferPoolMetricSetTest { ++final class BufferPoolMetricSetTest { + + private static final MetricName DIRECT = MetricName.build("direct"); + private static final MetricName MAPPED = MetricName.build("mapped"); +@@ -24,7 +24,7 @@ class BufferPoolMetricSetTest { + private static final MetricName MAPPED_CAPACITY = MAPPED.resolve("capacity"); + private static final MetricName MAPPED_USED = MAPPED.resolve("used"); + +- private final MBeanServer mBeanServer = mock(MBeanServer.class); ++ private final MBeanServer mBeanServer = mock(); + private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); + + private ObjectName mapped; +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java +index acefde0..24412e2 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java +@@ -11,9 +11,9 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("rawtypes") +-class ClassLoadingGaugeSetTest { ++final class ClassLoadingGaugeSetTest { + +- private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); ++ private final ClassLoadingMXBean cl = mock(); + private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); + + @BeforeEach +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java +index db5d8f8..9b633ad 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java +@@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.offset; + import java.lang.management.ManagementFactory; + import org.junit.jupiter.api.Test; + +-class CpuTimeClockTest { ++final class CpuTimeClockTest { + + @Test + void cpuTimeClock() { +@@ -14,10 +14,10 @@ class CpuTimeClockTest { + + final long clockTime = clock.getTime(); + final long systemTime = System.currentTimeMillis(); +- assertThat((double) clockTime).isEqualTo(systemTime, offset(200.0)); ++ assertThat((double) clockTime).isCloseTo(systemTime, offset(200.0)); + + final long clockTick = clock.getTick(); + final long systemTick = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(); +- assertThat((double) clockTick).isEqualTo(systemTick, offset(1000000.0)); ++ assertThat((double) clockTick).isCloseTo(systemTick, offset(1000000.0)); + } + } +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java +index 5e9db15..019d29c 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java +@@ -1,5 +1,6 @@ + package io.dropwizard.metrics5.jvm; + ++import static org.assertj.core.api.Assertions.assertThat; + import static org.junit.jupiter.api.Assumptions.assumeTrue; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; +@@ -12,8 +13,8 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("UnusedDeclaration") +-class FileDescriptorRatioGaugeTest { +- private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); ++final class FileDescriptorRatioGaugeTest { ++ private final UnixOperatingSystemMXBean os = mock(); + + private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); + +@@ -25,7 +26,7 @@ class FileDescriptorRatioGaugeTest { + + @Test + void calculatesTheRatioOfUsedToTotalFileDescriptors() { +- Assertions.assertThat(gauge.getValue()).isEqualTo(0.1); ++ assertThat(gauge.getValue()).isEqualTo(0.1); + } + + @Test +@@ -34,14 +35,12 @@ class FileDescriptorRatioGaugeTest { + assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); + + Assertions.assertThat(new FileDescriptorRatioGauge().getValue()) +- .isGreaterThanOrEqualTo(0.0) ++ .isNotNegative() + .isLessThanOrEqualTo(1.0); + } + + @Test + void returnsNaNWhenTheInformationIsUnavailable() { +- Assertions.assertThat( +- new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()) +- .isNaN(); ++ assertThat(new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()).isNaN(); + } + } +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java +index 5e7f1bd..c32dccb 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java +@@ -4,18 +4,18 @@ import static org.assertj.core.api.Assertions.assertThat; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.when; + ++import com.google.common.collect.ImmutableList; + import io.dropwizard.metrics5.Gauge; + import io.dropwizard.metrics5.MetricName; + import java.lang.management.GarbageCollectorMXBean; +-import java.util.Collections; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("unchecked") +-class GarbageCollectorMetricSetTest { +- private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); ++final class GarbageCollectorMetricSetTest { ++ private final GarbageCollectorMXBean gc = mock(); + private final GarbageCollectorMetricSet metrics = +- new GarbageCollectorMetricSet(Collections.singletonList(gc)); ++ new GarbageCollectorMetricSet(ImmutableList.of(gc)); + + private static final MetricName PS_OLDGEN_TIME = MetricName.build("PS-OldGen.time"); + private static final MetricName PS_OLDGEN_COUNT = MetricName.build("PS-OldGen.count"); +@@ -46,6 +46,6 @@ class GarbageCollectorMetricSetTest { + + @Test + void autoDiscoversGCs() { +- assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()).isNotEmpty(); ++ assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty(); + } + } +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java +index 9e7e876..dec09ab 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java +@@ -13,7 +13,7 @@ import org.junit.jupiter.api.AfterAll; + import org.junit.jupiter.api.BeforeAll; + import org.junit.jupiter.api.Test; + +-class JmxAttributeGaugeTest { ++final class JmxAttributeGaugeTest { + + private static MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + +@@ -53,7 +53,7 @@ class JmxAttributeGaugeTest { + JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); + + assertThat(gauge.getValue()).isInstanceOf(Integer.class); +- assertThat((Integer) gauge.getValue()).isGreaterThan(0); ++ assertThat((Integer) gauge.getValue()).isPositive(); + } + + @Test +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java +index 3a50f92..d56cf8b 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java +@@ -11,8 +11,8 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("unchecked") +-class JvmAttributeGaugeSetTest { +- private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); ++final class JvmAttributeGaugeSetTest { ++ private final RuntimeMXBean runtime = mock(); + private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); + + @BeforeEach +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java +index 9ebceed..96c5879 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java +@@ -14,15 +14,15 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("rawtypes") +-class MemoryUsageGaugeSetTest { +- private final MemoryUsage heap = mock(MemoryUsage.class); +- private final MemoryUsage nonHeap = mock(MemoryUsage.class); +- private final MemoryUsage pool = mock(MemoryUsage.class); +- private final MemoryUsage weirdPool = mock(MemoryUsage.class); +- private final MemoryUsage weirdCollection = mock(MemoryUsage.class); +- private final MemoryMXBean mxBean = mock(MemoryMXBean.class); +- private final MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); +- private final MemoryPoolMXBean weirdMemoryPool = mock(MemoryPoolMXBean.class); ++final class MemoryUsageGaugeSetTest { ++ private final MemoryUsage heap = mock(); ++ private final MemoryUsage nonHeap = mock(); ++ private final MemoryUsage pool = mock(); ++ private final MemoryUsage weirdPool = mock(); ++ private final MemoryUsage weirdCollection = mock(); ++ private final MemoryMXBean mxBean = mock(); ++ private final MemoryPoolMXBean memoryPool = mock(); ++ private final MemoryPoolMXBean weirdMemoryPool = mock(); + + private final MemoryUsageGaugeSet gauges = + new MemoryUsageGaugeSet(mxBean, Arrays.asList(memoryPool, weirdMemoryPool)); +@@ -159,7 +159,7 @@ class MemoryUsageGaugeSetTest { + } + + @Test +- public void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { ++ void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { + when(nonHeap.getMax()).thenReturn(-1L); + + final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); +@@ -238,7 +238,7 @@ class MemoryUsageGaugeSetTest { + } + + @Test +- public void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { ++ void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { + when(nonHeap.getMax()).thenReturn(-1L); + final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); + +@@ -296,6 +296,6 @@ class MemoryUsageGaugeSetTest { + + @Test + void autoDetectsMemoryUsageBeanAndMemoryPools() { +- assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()).isNotEmpty(); ++ assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty(); + } + } +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java +index 98850d7..4367c03 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java +@@ -11,8 +11,8 @@ import java.lang.management.ThreadMXBean; + import java.util.Locale; + import org.junit.jupiter.api.Test; + +-class ThreadDeadlockDetectorTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); ++final class ThreadDeadlockDetectorTest { ++ private final ThreadMXBean threads = mock(); + private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); + + @Test +@@ -24,7 +24,7 @@ class ThreadDeadlockDetectorTest { + + @Test + void returnsASetOfThreadsIfAnyAreDeadlocked() { +- final ThreadInfo thread1 = mock(ThreadInfo.class); ++ final ThreadInfo thread1 = mock(); + when(thread1.getThreadName()).thenReturn("thread1"); + when(thread1.getLockName()).thenReturn("lock2"); + when(thread1.getLockOwnerName()).thenReturn("thread2"); +@@ -35,7 +35,7 @@ class ThreadDeadlockDetectorTest { + new StackTraceElement("Blah", "blee", "Blah.java", 100) + }); + +- final ThreadInfo thread2 = mock(ThreadInfo.class); ++ final ThreadInfo thread2 = mock(); + when(thread2.getThreadName()).thenReturn("thread2"); + when(thread2.getLockName()).thenReturn("lock1"); + when(thread2.getLockOwnerName()).thenReturn("thread1"); +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java +index c89c824..1eeac39 100755 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java +@@ -14,11 +14,11 @@ import org.junit.jupiter.api.Test; + + // TODO: 3/12/13 -- improve test coverage for ThreadDump + +-class ThreadDumpTest { +- private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); ++final class ThreadDumpTest { ++ private final ThreadMXBean threadMXBean = mock(); + private final ThreadDump threadDump = new ThreadDump(threadMXBean); + +- private final ThreadInfo runnable = mock(ThreadInfo.class); ++ private final ThreadInfo runnable = mock(); + + @BeforeEach + void setUp() { +@@ -39,8 +39,8 @@ class ThreadDumpTest { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + threadDump.dump(output); + +- assertThat(output.toString()) +- .isEqualTo( ++ assertThat(output) ++ .hasToString( + String.format( + "\"runnable\" id=100 state=RUNNABLE%n" + + " at Blah.blee(Blah.java:100)%n" +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java +index d5896e7..8d20493 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java +@@ -10,22 +10,21 @@ import java.lang.management.ThreadInfo; + import java.lang.management.ThreadMXBean; + import java.util.HashSet; + import java.util.Set; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class ThreadStatesGaugeSetTest { +- private final ThreadMXBean threads = mock(ThreadMXBean.class); +- private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); ++final class ThreadStatesGaugeSetTest { ++ private final ThreadMXBean threads = mock(); ++ private final ThreadDeadlockDetector detector = mock(); + private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); + private final long[] ids = new long[] {1, 2, 3}; + +- private final ThreadInfo newThread = mock(ThreadInfo.class); +- private final ThreadInfo runnableThread = mock(ThreadInfo.class); +- private final ThreadInfo blockedThread = mock(ThreadInfo.class); +- private final ThreadInfo waitingThread = mock(ThreadInfo.class); +- private final ThreadInfo timedWaitingThread = mock(ThreadInfo.class); +- private final ThreadInfo terminatedThread = mock(ThreadInfo.class); ++ private final ThreadInfo newThread = mock(); ++ private final ThreadInfo runnableThread = mock(); ++ private final ThreadInfo blockedThread = mock(); ++ private final ThreadInfo waitingThread = mock(); ++ private final ThreadInfo timedWaitingThread = mock(); ++ private final ThreadInfo terminatedThread = mock(); + + private final Set deadlocks = new HashSet<>(); + +@@ -87,7 +86,7 @@ class ThreadStatesGaugeSetTest { + + @Test + void hasAGaugeForEachThreadState() { +- Assertions.assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1); ++ assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1); + + assertThat(((Gauge) gauges.getMetrics().get(RUNNABLE_COUNT)).getValue()).isEqualTo(1); + +diff --git a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java +index b176fb3..3c16b02 100644 +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java +@@ -1,16 +1,16 @@ + package com.codahale.metrics; + ++import static java.util.Collections.unmodifiableSortedMap; + import static java.util.Collections.unmodifiableSortedSet; + import static java.util.Objects.requireNonNull; ++import static java.util.stream.Collectors.toCollection; + + import io.dropwizard.metrics5.MetricName; +-import java.util.Collections; + import java.util.Map; + import java.util.SortedMap; + import java.util.SortedSet; + import java.util.TreeMap; + import java.util.TreeSet; +-import java.util.stream.Collectors; + + @Deprecated + public class MetricRegistry implements MetricSet { +@@ -102,9 +102,7 @@ public class MetricRegistry implements MetricSet { + + public SortedSet getNames() { + return unmodifiableSortedSet( +- delegate.getNames().stream() +- .map(MetricName::getKey) +- .collect(Collectors.toCollection(TreeSet::new))); ++ delegate.getNames().stream().map(MetricName::getKey).collect(toCollection(TreeSet::new))); + } + + public SortedMap getGauges() { +@@ -160,7 +158,7 @@ public class MetricRegistry implements MetricSet { + metrics.entrySet()) { + items.put(entry.getKey().getKey(), (T) Metric.of(entry.getValue())); + } +- return Collections.unmodifiableSortedMap(items); ++ return unmodifiableSortedMap(items); + } + + @Override +diff --git a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java +index a3c8c09..913df5b 100644 +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java +@@ -1,7 +1,8 @@ + package com.codahale.metrics; + ++import static java.util.Collections.unmodifiableMap; ++ + import io.dropwizard.metrics5.MetricName; +-import java.util.Collections; + import java.util.HashMap; + import java.util.Map; + +@@ -24,7 +25,7 @@ public interface MetricSet extends Metric { + original.getMetrics().entrySet()) { + items.put(entry.getKey().getKey(), Metric.of(entry.getValue())); + } +- return Collections.unmodifiableMap(items); ++ return unmodifiableMap(items); + } + + @Override +@@ -48,7 +49,7 @@ public interface MetricSet extends Metric { + for (Map.Entry entry : delegate.getMetrics().entrySet()) { + items.put(MetricName.build(entry.getKey()), entry.getValue().getDelegate()); + } +- return Collections.unmodifiableMap(items); ++ return unmodifiableMap(items); + } + } + } +diff --git a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java +index 498b258..6005e7e 100644 +--- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java ++++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java +@@ -1,10 +1,10 @@ + package com.codahale.metrics; + ++import static java.util.Collections.unmodifiableSortedMap; + import static java.util.Objects.requireNonNull; + + import io.dropwizard.metrics5.MetricName; + import java.io.Closeable; +-import java.util.Collections; + import java.util.Map; + import java.util.Set; + import java.util.SortedMap; +@@ -115,7 +115,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { + for (Map.Entry entry : metrics.entrySet()) { + items.put(MetricName.build(entry.getKey()), (T) entry.getValue().getDelegate()); + } +- return Collections.unmodifiableSortedMap(items); ++ return unmodifiableSortedMap(items); + } + + protected String getRateUnit() { +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java +index 223ecc1..8c49b13 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java +@@ -6,10 +6,10 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class CachedGaugeTest { ++final class CachedGaugeTest { + + @Test +- void testCreate() { ++ void create() { + CachedGauge cachedGauge = + new CachedGauge(100, TimeUnit.MILLISECONDS) { + @Override +@@ -21,7 +21,7 @@ class CachedGaugeTest { + } + + @Test +- void testCreateWothClock() { ++ void createWothClock() { + CachedGauge cachedGauge = + new CachedGauge(new Clock.UserTimeClock(), 100, TimeUnit.MILLISECONDS) { + @Override +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java +index 23f627f..392918b 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java +@@ -5,22 +5,22 @@ import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class ClockTest { ++final class ClockTest { + + @Test +- void testDefaultClockCanBeUsed() { ++ void defaultClockCanBeUsed() { + Clock clock = Clock.defaultClock(); +- assertThat(clock.getTick()).isGreaterThan(0); ++ assertThat(clock.getTick()).isPositive(); + } + + @Test +- void testUserTimeClockCanBeUsed() { ++ void userTimeClockCanBeUsed() { + Clock clock = new Clock.UserTimeClock(); +- assertThat(clock.getTick()).isGreaterThan(0); ++ assertThat(clock.getTick()).isPositive(); + } + + @Test +- void testCustomTimeClockCanBeUsed() { ++ void customTimeClockCanBeUsed() { + Clock clock = + new Clock() { + @Override +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java +index e828f0a..bf94dc6 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java +@@ -1,10 +1,10 @@ + package com.codahale.metrics; + ++import static java.nio.charset.StandardCharsets.UTF_8; + import static org.assertj.core.api.Assertions.assertThat; + + import java.io.ByteArrayOutputStream; + import java.io.PrintStream; +-import java.nio.charset.StandardCharsets; + import java.util.EnumSet; + import java.util.Locale; + import java.util.TimeZone; +@@ -17,7 +17,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class ConsoleReporterTest { ++final class ConsoleReporterTest { + + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + private final String dateHeader = +@@ -35,7 +35,7 @@ class ConsoleReporterTest { + } + + @Test +- void testCreateConsoleReporter() throws Exception { ++ void createConsoleReporter() throws Exception { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + + MetricRegistry metricRegistry = new MetricRegistry(); +@@ -72,7 +72,7 @@ class ConsoleReporterTest { + .build(); + consoleReporter.report(); + +- assertThat(new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8)) ++ assertThat(new String(byteArrayOutputStream.toByteArray(), UTF_8)) + .isEqualToNormalizingNewlines( + dateHeader + + "\n" +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java +index 2c6540e..a17564f 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java +@@ -6,33 +6,33 @@ import io.dropwizard.metrics5.Counter; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class CounterTest { ++final class CounterTest { + + private Counter counter = new Counter(); + + @Test +- void testIncrementCounter() { ++ void incrementCounter() { + counter.inc(); + + assertThat(counter.getCount()).isEqualTo(1); + } + + @Test +- void testIncrementCounterOnManyPoints() { ++ void incrementCounterOnManyPoints() { + counter.inc(5); + + assertThat(counter.getCount()).isEqualTo(5); + } + + @Test +- void testDecrementCounter() { ++ void decrementCounter() { + counter.dec(); + + assertThat(counter.getCount()).isEqualTo(-1); + } + + @Test +- void testDecrementCounterOnManyPoints() { ++ void decrementCounterOnManyPoints() { + counter.dec(5); + + assertThat(counter.getCount()).isEqualTo(-5); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java +index b3e7ad8..63bdd10 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java +@@ -5,10 +5,10 @@ import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class DerivativeGaugeTest { ++final class DerivativeGaugeTest { + + @Test +- void testCalculate() { ++ void calculate() { + DerivativeGauge derivativeGauge = + new DerivativeGauge(() -> "23") { + @Override +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java +index c598fe4..39c5242 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java +@@ -6,10 +6,10 @@ import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class ExponentiallyDecayingReservoirTest { ++final class ExponentiallyDecayingReservoirTest { + + @Test +- void testCreateReservoir() { ++ void createReservoir() { + ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(); + reservoir.update(120); + reservoir.update(190); +@@ -22,7 +22,7 @@ class ExponentiallyDecayingReservoirTest { + assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); + assertThat(snapshot.getMin()).isEqualTo(120); + assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); ++ assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1)); + assertThat(snapshot.get75thPercentile()).isEqualTo(190); + assertThat(snapshot.get95thPercentile()).isEqualTo(200); + assertThat(snapshot.get98thPercentile()).isEqualTo(200); +@@ -31,14 +31,14 @@ class ExponentiallyDecayingReservoirTest { + } + + @Test +- void testCreateReservoirWithCustomSizeAndAlpha() { ++ void createReservoirWithCustomSizeAndAlpha() { + ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01); + reservoir.update(100); + assertThat(reservoir.size()).isEqualTo(1); + } + + @Test +- void testCreateReservoirWithCustomSizeAlphaAndClock() { ++ void createReservoirWithCustomSizeAlphaAndClock() { + ExponentiallyDecayingReservoir reservoir = + new ExponentiallyDecayingReservoir( + 512, +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java +index 8696ad6..9dcbc16 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java +@@ -10,7 +10,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class FixedNameCsvFileProviderTest { ++final class FixedNameCsvFileProviderTest { + + private Path tempDirectory; + private FixedNameCsvFileProvider fixedNameCsvFileProvider = new FixedNameCsvFileProvider(); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java +index 22ad432..41a4073 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java +@@ -5,12 +5,12 @@ import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class GaugeTest { ++final class GaugeTest { + + private Gauge gauge = () -> 83; + + @Test +- void testGetValue() { ++ void getValue() { + assertThat(gauge.getValue()).isEqualTo(83); + } + } +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java +index 86e24c7..a141c70 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java +@@ -6,10 +6,10 @@ import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class HistogramTest { ++final class HistogramTest { + + @Test +- void testCreate() { ++ void create() { + Histogram histogram = new Histogram(new ExponentiallyDecayingReservoir()); + histogram.update(120); + histogram.update(190); +@@ -23,7 +23,7 @@ class HistogramTest { + assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); + assertThat(snapshot.getMin()).isEqualTo(120); + assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); ++ assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1)); + assertThat(snapshot.get75thPercentile()).isEqualTo(190); + assertThat(snapshot.get95thPercentile()).isEqualTo(200); + assertThat(snapshot.get98thPercentile()).isEqualTo(200); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java +index 2b18cb6..994061d 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java +@@ -9,10 +9,10 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class InstrumentedExecutorServiceTest { ++final class InstrumentedExecutorServiceTest { + + @Test +- void testCreate() throws Exception { ++ void create() throws Exception { + ExecutorService executorService = Executors.newSingleThreadExecutor(); + MetricRegistry registry = new MetricRegistry(); + InstrumentedExecutorService instrumentedExecutorService = +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java +index caf4bbb..d0e4130 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java +@@ -10,7 +10,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class InstrumentedScheduledExecutorServiceTest { ++final class InstrumentedScheduledExecutorServiceTest { + private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + + @AfterEach +@@ -19,7 +19,7 @@ class InstrumentedScheduledExecutorServiceTest { + } + + @Test +- void testCreate() throws Exception { ++ void create() throws Exception { + MetricRegistry registry = new MetricRegistry(); + InstrumentedScheduledExecutorService instrumentedExecutorService = + new InstrumentedScheduledExecutorService( +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java +index c947556..0355cfd 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java +@@ -7,11 +7,11 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class InstrumentedThreadFactoryTest { ++final class InstrumentedThreadFactoryTest { + +- @Test + @SuppressWarnings("DoNotCall") +- void testFactory() throws Exception { ++ @Test ++ void factory() throws Exception { + MetricRegistry registry = new MetricRegistry(); + InstrumentedThreadFactory threadFactory = + new InstrumentedThreadFactory(Thread::new, registry, "test-instrumented-thread-factory"); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java +index 0fee61f..a32fa5e 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java +@@ -6,16 +6,16 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class MeterTest { ++final class MeterTest { + + @Test +- void testCreateMeteer() { ++ void createMeteer() { + Meter meter = new Meter(); + assertThat(meter.getCount()).isEqualTo(0); + } + + @Test +- void testCreateMeterWithCustomClock() { ++ void createMeterWithCustomClock() { + Meter meter = + new Meter( + new Clock() { +@@ -28,7 +28,7 @@ class MeterTest { + } + + @Test +- void testMark() { ++ void mark() { + Meter meter = + new Meter( + new Clock() { +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java +index 7a5b056..80bd9f1 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java +@@ -11,19 +11,19 @@ import java.util.concurrent.TimeUnit; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class MetricRegistryTest { ++final class MetricRegistryTest { + + private MetricRegistry metricRegistry = new MetricRegistry(); + + @Test +- void testRegisterMetric() { ++ void registerMetric() { + Counter counter = metricRegistry.register("test-counter", new Counter()); + counter.inc(42); + assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); + } + + @Test +- void testRegisterAll() { ++ void registerAll() { + metricRegistry.registerAll( + () -> { + Map map = new HashMap<>(); +@@ -40,26 +40,26 @@ class MetricRegistryTest { + } + + @Test +- void testRegisterGauge() { ++ void registerGauge() { + metricRegistry.registerGauge("test-gauge", () -> 42); + assertThat(metricRegistry.getGauges().get("test-gauge").getValue()).isEqualTo(42); + } + + @Test +- void testCreateCustomGauge() { ++ void createCustomGauge() { + Gauge gauge = metricRegistry.gauge("test-gauge-supplier", () -> () -> 42); + assertThat(gauge.getValue()).isEqualTo(42); + } + + @Test +- void testCreateCounter() { ++ void createCounter() { + Counter counter = metricRegistry.counter("test-counter"); + counter.inc(42); + assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); + } + + @Test +- void testCreateCustomCounter() { ++ void createCustomCounter() { + Counter counter = + metricRegistry.counter( + "test-custom-counter", +@@ -73,7 +73,7 @@ class MetricRegistryTest { + } + + @Test +- void testCreateHistogram() { ++ void createHistogram() { + Histogram histogram = metricRegistry.histogram("test-histogram"); + histogram.update(100); + histogram.update(200); +@@ -83,7 +83,7 @@ class MetricRegistryTest { + } + + @Test +- void testCreateCustomHistogram() { ++ void createCustomHistogram() { + Histogram histogram = + metricRegistry.histogram( + "test-custom-histogram", () -> new Histogram(new SlidingWindowReservoir(2))); +@@ -95,7 +95,7 @@ class MetricRegistryTest { + } + + @Test +- void testCreateMeter() { ++ void createMeter() { + Meter meter = metricRegistry.meter("test-meter"); + meter.mark(); + meter.mark(2); +@@ -104,7 +104,7 @@ class MetricRegistryTest { + } + + @Test +- void testCreateCustomMeter() { ++ void createCustomMeter() { + Meter meter = + metricRegistry.meter( + "test-custom-meter", +@@ -119,7 +119,7 @@ class MetricRegistryTest { + } + + @Test +- void testCreateTimer() { ++ void createTimer() { + Timer timer = metricRegistry.timer("test-timer"); + timer.update(100, TimeUnit.MILLISECONDS); + timer.update(200, TimeUnit.MILLISECONDS); +@@ -129,7 +129,7 @@ class MetricRegistryTest { + } + + @Test +- void testCreateCustomTimer() { ++ void createCustomTimer() { + Timer timer = + metricRegistry.timer( + "custom-test-timer", +@@ -145,7 +145,7 @@ class MetricRegistryTest { + } + + @Test +- void testRemoveMetric() { ++ void removeMetric() { + metricRegistry.timer("test-timer"); + metricRegistry.counter("test-counter"); + metricRegistry.meter("test-meter"); +@@ -156,7 +156,7 @@ class MetricRegistryTest { + } + + @Test +- void testRemoveMatching() { ++ void removeMatching() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.timer("test-custom-timer"); +@@ -168,7 +168,7 @@ class MetricRegistryTest { + } + + @Test +- void testAddListenerForGauge() throws Exception { ++ void addListenerForGauge() throws Exception { + CountDownLatch gaugeAddedLatch = new CountDownLatch(1); + CountDownLatch gaugeRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -197,7 +197,7 @@ class MetricRegistryTest { + } + + @Test +- void testAddListenerForCounter() throws Exception { ++ void addListenerForCounter() throws Exception { + CountDownLatch counterAddedLatch = new CountDownLatch(1); + CountDownLatch counterRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -225,7 +225,7 @@ class MetricRegistryTest { + } + + @Test +- void testAddListenerForHistogram() throws Exception { ++ void addListenerForHistogram() throws Exception { + CountDownLatch histogramAddedLatch = new CountDownLatch(1); + CountDownLatch histogramRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -254,7 +254,7 @@ class MetricRegistryTest { + } + + @Test +- void testAddListenerForMeter() throws Exception { ++ void addListenerForMeter() throws Exception { + CountDownLatch meterAddedLatch = new CountDownLatch(1); + CountDownLatch meterRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -283,7 +283,7 @@ class MetricRegistryTest { + } + + @Test +- void testAddListenerForTimer() throws Exception { ++ void addListenerForTimer() throws Exception { + CountDownLatch timerAddedLatch = new CountDownLatch(1); + CountDownLatch timerRemovedLatch = new CountDownLatch(1); + metricRegistry.addListener( +@@ -312,7 +312,7 @@ class MetricRegistryTest { + } + + @Test +- void testRemoveListener() throws Exception { ++ void removeListener() throws Exception { + CountDownLatch gaugeAddedLatch = new CountDownLatch(1); + MetricRegistryListener listener = + new MetricRegistryListener.Base() { +@@ -331,7 +331,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetNames() { ++ void getNames() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.timer("test-custom-timer"); +@@ -342,7 +342,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetGauges() { ++ void getGauges() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -369,7 +369,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetGaugesWithFilter() { ++ void getGaugesWithFilter() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -398,7 +398,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetHistograms() { ++ void getHistograms() { + metricRegistry.counter("test-counter"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -411,7 +411,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetHistogramsWithFilter() { ++ void getHistogramsWithFilter() { + metricRegistry.counter("sw-counter"); + metricRegistry.timer("sw-timer"); + metricRegistry.meter("sw-meter"); +@@ -424,7 +424,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetCounters() { ++ void getCounters() { + metricRegistry.histogram("test-histogram"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -437,7 +437,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetCountersWithFilter() { ++ void getCountersWithFilter() { + metricRegistry.histogram("test-histogram"); + metricRegistry.timer("test-timer"); + metricRegistry.meter("test-meter"); +@@ -450,7 +450,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetMeters() { ++ void getMeters() { + metricRegistry.register("test-gauge", (Gauge) () -> 42); + metricRegistry.histogram("test-histogram"); + metricRegistry.timer("test-timer"); +@@ -464,7 +464,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetMetersWithFilter() { ++ void getMetersWithFilter() { + metricRegistry.register("sw-gauge", (Gauge) () -> 42); + metricRegistry.histogram("sw-histogram"); + metricRegistry.timer("sw-timer"); +@@ -478,7 +478,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetTimers() { ++ void getTimers() { + metricRegistry.histogram("test-histogram"); + metricRegistry.meter("test-meter"); + metricRegistry.counter("test-counter"); +@@ -491,7 +491,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetTimersWithFilter() { ++ void getTimersWithFilter() { + metricRegistry.histogram("test-histogram-2"); + metricRegistry.meter("test-meter-2"); + metricRegistry.counter("test-counter-2"); +@@ -504,7 +504,7 @@ class MetricRegistryTest { + } + + @Test +- void testGetMetrics() { ++ void getMetrics() { + metricRegistry.register( + "test-text-gauge-2", + new CachedGauge(1, TimeUnit.MINUTES) { +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java +index e593421..acd78e9 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java +@@ -1,12 +1,12 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class RatioGaugeTest { ++final class RatioGaugeTest { + + private RatioGauge ratioGauge = + new RatioGauge() { +@@ -17,12 +17,12 @@ class RatioGaugeTest { + }; + + @Test +- void testViewRatin() { +- assertThat(ratioGauge.getRatio().toString()).isEqualTo("1.0:3.0"); ++ void viewRatin() { ++ assertThat(ratioGauge.getRatio()).hasToString("1.0:3.0"); + } + + @Test +- void testCalculateRatio() { +- assertThat(ratioGauge.getValue()).isCloseTo(0.33, Offset.offset(0.01)); ++ void calculateRatio() { ++ assertThat(ratioGauge.getValue()).isCloseTo(0.33, offset(0.01)); + } + } +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java +index b483a4c..8f6f103 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java +@@ -10,7 +10,7 @@ import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class ScheduledReporterTest { ++final class ScheduledReporterTest { + + private MetricRegistry metricRegistry = new MetricRegistry(); + private ScheduledReporter scheduledReporter; +@@ -51,7 +51,7 @@ class ScheduledReporterTest { + } + + @Test +- void testReport() throws Exception { ++ void report() throws Exception { + CountDownLatch latch = new CountDownLatch(1); + scheduledReporter = createScheduledReporter(latch); + scheduledReporter.report(); +@@ -61,7 +61,7 @@ class ScheduledReporterTest { + } + + @Test +- void testStart() throws Exception { ++ void start() throws Exception { + CountDownLatch latch = new CountDownLatch(2); + scheduledReporter = createScheduledReporter(latch); + scheduledReporter.start(10, TimeUnit.MILLISECONDS); +@@ -71,7 +71,7 @@ class ScheduledReporterTest { + } + + @Test +- void testStartWithoutDelay() throws Exception { ++ void startWithoutDelay() throws Exception { + CountDownLatch latch = new CountDownLatch(2); + scheduledReporter = createScheduledReporter(latch); + scheduledReporter.start(0, 10, TimeUnit.MILLISECONDS); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java +index c2340f2..232c473 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java +@@ -1,13 +1,13 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.assertj.core.api.Assertions.assertThatIllegalStateException; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class SharedMetricRegistriesTest { ++final class SharedMetricRegistriesTest { + + @AfterEach + void tearDown() throws Exception { +@@ -15,7 +15,7 @@ class SharedMetricRegistriesTest { + } + + @Test +- void testGetOrCreateMetricRegistry() { ++ void getOrCreateMetricRegistry() { + SharedMetricRegistries.getOrCreate("get-or-create").counter("test-counter"); + + assertThat(SharedMetricRegistries.getOrCreate("get-or-create").getCounters()) +@@ -23,7 +23,7 @@ class SharedMetricRegistriesTest { + } + + @Test +- void testAddMetricRegistry() { ++ void addMetricRegistry() { + MetricRegistry metricRegistry = new MetricRegistry(); + metricRegistry.histogram("test-histogram"); + SharedMetricRegistries.add("add", metricRegistry); +@@ -33,7 +33,7 @@ class SharedMetricRegistriesTest { + } + + @Test +- void testNames() { ++ void names() { + SharedMetricRegistries.add("registry-1", new MetricRegistry()); + SharedMetricRegistries.add("registry-2", new MetricRegistry()); + SharedMetricRegistries.add("registry-3", new MetricRegistry()); +@@ -43,12 +43,13 @@ class SharedMetricRegistriesTest { + } + + @Test +- void testTryGetDefaultRegistry() { ++ void tryGetDefaultRegistry() { + assertThat(SharedMetricRegistries.tryGetDefault()).isNull(); + } + + @Test +- void testGetDefaultRegistry() { +- assertThatIllegalStateException().isThrownBy(SharedMetricRegistries::getDefault); ++ void getDefaultRegistry() { ++ assertThatThrownBy(SharedMetricRegistries::getDefault) ++ .isInstanceOf(IllegalStateException.class); + } + } +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java +index 55d05fe..984ceb1 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java +@@ -14,11 +14,11 @@ import org.slf4j.Logger; + import org.slf4j.Marker; + + @SuppressWarnings("deprecation") +-class Slf4jReporterTest { ++final class Slf4jReporterTest { + + private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); +- private Logger logger = mock(Logger.class); +- private Marker marker = mock(Marker.class); ++ private Logger logger = mock(); ++ private Marker marker = mock(); + + @BeforeEach + void setUp() throws Exception { +@@ -31,7 +31,7 @@ class Slf4jReporterTest { + } + + @Test +- void testReport() throws Exception { ++ void report() throws Exception { + MetricRegistry metricRegistry = new MetricRegistry(); + metricRegistry.counter("test-counter").inc(100); + +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java +index 95228fa..9e48141 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java +@@ -1,16 +1,16 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + + import java.util.concurrent.TimeUnit; +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class SlidingTimeWindowArrayReservoirTest { ++final class SlidingTimeWindowArrayReservoirTest { + + @Test +- void testCreateWithWindow() { ++ void createWithWindow() { + SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS); + reservoir.update(100); +@@ -18,17 +18,17 @@ class SlidingTimeWindowArrayReservoirTest { + reservoir.update(30); + + assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); + } + + @Test +- void testCreateWithWindowAndClock() { ++ void createWithWindowAndClock() { + SlidingTimeWindowArrayReservoir reservoir = + new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); + reservoir.update(400); + reservoir.update(300); + + assertThat(reservoir.size()).isEqualTo(2); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); + } + } +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java +index c80dcee..dcd9b61 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java +@@ -1,33 +1,33 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + + import java.util.concurrent.TimeUnit; +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class SlidingTimeWindowReservoirTest { ++final class SlidingTimeWindowReservoirTest { + + @Test +- void testCreateWithWindow() { ++ void createWithWindow() { + SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS); + reservoir.update(100); + reservoir.update(200); + reservoir.update(30); + + assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); + } + + @Test +- void testCreateWithWindowAndClock() { ++ void createWithWindowAndClock() { + SlidingTimeWindowReservoir reservoir = + new SlidingTimeWindowReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); + reservoir.update(400); + reservoir.update(300); + + assertThat(reservoir.size()).isEqualTo(2); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); + } + } +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java +index bebb55e..37cca6a 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java +@@ -1,26 +1,26 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class SlidingWindowReservoirTest { ++final class SlidingWindowReservoirTest { + + @Test +- void testCreateWithBigWindow() { ++ void createWithBigWindow() { + SlidingWindowReservoir reservoir = new SlidingWindowReservoir(100); + reservoir.update(100); + reservoir.update(220); + reservoir.update(130); + + assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, offset(0.1)); + } + + @Test +- void testCreateWithLowWindow() { ++ void createWithLowWindow() { + SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); + reservoir.update(500); + reservoir.update(220); +@@ -28,6 +28,6 @@ class SlidingWindowReservoirTest { + reservoir.update(40); + + assertThat(reservoir.size()).isEqualTo(3); +- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, Offset.offset(0.1)); ++ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, offset(0.1)); + } + } +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java +index 6c24eaa..24a6ae0 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java +@@ -8,23 +8,23 @@ import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class SnapshotTest { ++final class SnapshotTest { + + @Test +- void testCreateSnapshot() throws Exception { ++ void createSnapshot() throws Exception { + Snapshot snapshot = Snapshot.of(new UniformSnapshot(new long[] {5, 1, 2, 3, 4})); + + assertThat(snapshot.getValues()).isEqualTo(new long[] {1, 2, 3, 4, 5}); + assertThat(snapshot.size()).isEqualTo(5); + assertThat(snapshot.getMin()).isEqualTo(1); + assertThat(snapshot.getMax()).isEqualTo(5); +- assertThat(snapshot.getStdDev()).isEqualTo(1.58, Offset.offset(0.01)); +- assertThat(snapshot.getMedian()).isEqualTo(3, Offset.offset(0.01)); +- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, Offset.offset(0.01)); +- assertThat(snapshot.get95thPercentile()).isEqualTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get98thPercentile()).isEqualTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get99thPercentile()).isEqualTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get999thPercentile()).isEqualTo(5, Offset.offset(0.01)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.58, Offset.offset(0.01)); ++ assertThat(snapshot.getMedian()).isCloseTo(3, Offset.offset(0.01)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, Offset.offset(0.01)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5, Offset.offset(0.01)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5, Offset.offset(0.01)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5, Offset.offset(0.01)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5, Offset.offset(0.01)); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + snapshot.dump(baos); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java +index c2bd51c..d9764ee 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java +@@ -8,7 +8,7 @@ import java.util.concurrent.atomic.AtomicInteger; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class TimerTest { ++final class TimerTest { + + private static class ManualClock extends Clock { + +@@ -26,7 +26,7 @@ class TimerTest { + } + + @Test +- void testCreate() { ++ void create() { + Timer timer = new Timer(); + timer.update(100, TimeUnit.MILLISECONDS); + timer.update(200, TimeUnit.MILLISECONDS); +@@ -35,7 +35,7 @@ class TimerTest { + } + + @Test +- void testCreateWithCustomReservoir() { ++ void createWithCustomReservoir() { + Timer timer = new Timer(new SlidingWindowReservoir(100)); + timer.update(100, TimeUnit.MILLISECONDS); + timer.update(200, TimeUnit.MILLISECONDS); +@@ -44,7 +44,7 @@ class TimerTest { + } + + @Test +- void testCreateWithCustomReservoirAndClock() { ++ void createWithCustomReservoirAndClock() { + Timer timer = new Timer(new SlidingWindowReservoir(100), new Clock.UserTimeClock()); + timer.update(100, TimeUnit.MILLISECONDS); + timer.update(200, TimeUnit.MILLISECONDS); +@@ -53,7 +53,7 @@ class TimerTest { + } + + @Test +- void testTimerContext() { ++ void timerContext() { + Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + timer.time().stop(); + +@@ -61,7 +61,7 @@ class TimerTest { + } + + @Test +- void testTimerRunnable() { ++ void timerRunnable() { + Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + + AtomicInteger counter = new AtomicInteger(); +@@ -72,7 +72,7 @@ class TimerTest { + } + + @Test +- void testTimerCallable() throws Exception { ++ void timerCallable() throws Exception { + Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + + String message = timer.time(() -> "SUCCESS"); +@@ -82,7 +82,7 @@ class TimerTest { + } + + @Test +- void testTimerSupplier() throws Exception { ++ void timerSupplier() throws Exception { + Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); + + Integer result = timer.timeSupplier(() -> 42); +@@ -92,7 +92,7 @@ class TimerTest { + } + + @Test +- void testUpdateDuration() { ++ void updateDuration() { + Timer timer = new Timer(); + timer.update(Duration.ofMillis(100)); + timer.update(Duration.ofMillis(200)); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java +index f125498..0668c1e 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java +@@ -6,10 +6,10 @@ import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +-class UniformReservoirTest { ++final class UniformReservoirTest { + + @Test +- void testCreateReservoir() { ++ void createReservoir() { + UniformReservoir reservoir = new UniformReservoir(); + reservoir.update(120); + reservoir.update(190); +@@ -22,7 +22,7 @@ class UniformReservoirTest { + assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); + assertThat(snapshot.getMin()).isEqualTo(120); + assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isEqualTo(36.47, Offset.offset(0.1)); ++ assertThat(snapshot.getStdDev()).isCloseTo(36.47, Offset.offset(0.1)); + assertThat(snapshot.get75thPercentile()).isEqualTo(195); + assertThat(snapshot.get95thPercentile()).isEqualTo(200); + assertThat(snapshot.get98thPercentile()).isEqualTo(200); +@@ -31,7 +31,7 @@ class UniformReservoirTest { + } + + @Test +- void testCreateReservoirWithCustomSize() { ++ void createReservoirWithCustomSize() { + UniformReservoir reservoir = new UniformReservoir(128); + reservoir.update(440); + reservoir.update(250); +diff --git a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java +index a4e9cee..b93cf21 100644 +--- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java ++++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java +@@ -12,7 +12,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-public class InstrumentedAppenderConfigTest { ++final class InstrumentedAppenderConfigTest { + public static final String METRIC_NAME_PREFIX = "metrics"; + public static final String REGISTRY_NAME = "shared-metrics-registry"; + +diff --git a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java +index ce0bae1..ea2f261 100644 +--- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java ++++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java +@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-public class InstrumentedAppenderTest { ++final class InstrumentedAppenderTest { + + public static final String METRIC_NAME_PREFIX = "org.apache.logging.log4j.core.Appender"; + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final LogEvent event = mock(LogEvent.class); ++ private final LogEvent event = mock(); + + @BeforeEach + void setUp() { +diff --git a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java +index 81a0e1b..9adaef7 100644 +--- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java ++++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java +@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-public class InstrumentedAppenderTest { ++final class InstrumentedAppenderTest { + + public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); + + @BeforeEach + void setUp() { +diff --git a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java +index e29f84a..b83ae22 100644 +--- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java ++++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java +@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-public class InstrumentedAppenderTest { ++final class InstrumentedAppenderTest { + + public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); + + @BeforeEach + void setUp() { +diff --git a/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java b/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java +index 2891ce4..9f1e279 100644 +--- a/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java ++++ b/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java +@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-public class InstrumentedAppenderTest { ++final class InstrumentedAppenderTest { + + public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; + + private final MetricRegistry registry = new MetricRegistry(); + private final InstrumentedAppender appender = new InstrumentedAppender(registry); +- private final ILoggingEvent event = mock(ILoggingEvent.class); ++ private final ILoggingEvent event = mock(); + + @BeforeEach + void setUp() { +diff --git a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java +index dcc19dd..84c04d4 100644 +--- a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java ++++ b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.servlet; + + import static io.dropwizard.metrics5.MetricRegistry.name; + ++import com.google.common.base.Strings; + import io.dropwizard.metrics5.Counter; + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -64,7 +65,7 @@ public abstract class AbstractInstrumentedFilter implements Filter { + final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); + + String metricName = filterConfig.getInitParameter(METRIC_PREFIX); +- if (metricName == null || metricName.isEmpty()) { ++ if (Strings.isNullOrEmpty(metricName)) { + metricName = getClass().getName(); + } + +diff --git a/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java b/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +index 1a0bd8e..d7ceae8 100644 +--- a/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java ++++ b/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +@@ -9,8 +9,8 @@ import javax.servlet.ServletContext; + import javax.servlet.ServletContextEvent; + import org.junit.jupiter.api.Test; + +-class InstrumentedFilterContextListenerTest { +- private final MetricRegistry registry = mock(MetricRegistry.class); ++final class InstrumentedFilterContextListenerTest { ++ private final MetricRegistry registry = mock(); + private final InstrumentedFilterContextListener listener = + new InstrumentedFilterContextListener() { + @Override +@@ -21,9 +21,9 @@ class InstrumentedFilterContextListenerTest { + + @Test + void injectsTheMetricRegistryIntoTheServletContext() { +- final ServletContext context = mock(ServletContext.class); ++ final ServletContext context = mock(); + +- final ServletContextEvent event = mock(ServletContextEvent.class); ++ final ServletContextEvent event = mock(); + when(event.getServletContext()).thenReturn(context); + + listener.contextInitialized(event); +diff --git a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java +index 88cd1fa..8685484 100644 +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java +@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); + if (registryAttr instanceof HealthCheckRegistry) { + this.registry = (HealthCheckRegistry) registryAttr; +diff --git a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +index 3efdc27..cc16683 100644 +--- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java ++++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { + super.init(config); + + final ServletContext context = config.getServletContext(); +- if (null == registry) { ++ if (registry == null) { + final Object registryAttr = context.getAttribute(METRICS_REGISTRY); + if (registryAttr instanceof MetricRegistry) { + this.registry = (MetricRegistry) registryAttr; +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +index 8fcdf8a..77b50ba 100755 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class AdminServletTest extends AbstractServletTest { ++final class AdminServletTest extends AbstractServletTest { + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +index ebe2c81..424a05e 100755 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class AdminServletUriTest extends AbstractServletTest { ++final class AdminServletUriTest extends AbstractServletTest { + private final MetricRegistry registry = new MetricRegistry(); + private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); + +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +index 1c63a41..2df4050 100644 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class CpuProfileServletTest extends AbstractServletTest { ++final class CpuProfileServletTest extends AbstractServletTest { + + @Override + protected void setUp(ServletTester tester) { +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +index e7bc067..80b40f1 100644 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +@@ -1,10 +1,9 @@ + package io.dropwizard.metrics5.servlets; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -27,7 +26,7 @@ import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class HealthCheckServletTest extends AbstractServletTest { ++final class HealthCheckServletTest extends AbstractServletTest { + + private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); + +@@ -95,9 +94,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } + + @Test +@@ -111,9 +109,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getContent()) + .isEqualTo( +- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" +- + EXPECTED_TIMESTAMP +- + "\"}}"); ++ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", ++ EXPECTED_TIMESTAMP); + } + + @Test +@@ -168,15 +165,8 @@ class HealthCheckServletTest extends AbstractServletTest { + assertThat(response.getContent()) + .isEqualTo( + String.format( +- "{%n" +- + " \"fun\" : {%n" +- + " \"healthy\" : true,%n" +- + " \"message\" : \"foo bar 123\",%n" +- + " \"duration\" : 0,%n" +- + " \"timestamp\" : \"" +- + EXPECTED_TIMESTAMP +- + "\"" +- + "%n }%n}")); ++ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", ++ EXPECTED_TIMESTAMP)); + } + + private static HealthCheck.Result healthyResultWithMessage(String message) { +@@ -197,23 +187,23 @@ class HealthCheckServletTest extends AbstractServletTest { + + @Test + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); ++ verify(servletConfig).getServletContext(); + verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final HealthCheckRegistry healthCheckRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(healthCheckRegistry); +@@ -221,32 +211,32 @@ class HealthCheckServletTest extends AbstractServletTest { + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- assertThrows( +- ServletException.class, +- () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) +- .thenReturn("IRELLEVANT_STRING"); +- +- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); +- healthCheckServlet.init(servletConfig); +- }); ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(ServletContext.class); ++ final ServletConfig servletConfig = mock(ServletConfig.class); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); ++ healthCheckServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); + } + + @Test + void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn(registry); +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +index 5cd3578..101f79d 100644 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +@@ -17,8 +17,8 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class MetricsServletContextListenerTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++final class MetricsServletContextListenerTest extends AbstractServletTest { ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private final String allowedOrigin = "some.other.origin"; + +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +index ee72291..78086f5 100644 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +@@ -1,11 +1,10 @@ + package io.dropwizard.metrics5.servlets; + + import static org.assertj.core.api.Assertions.assertThat; +-import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.assertj.core.api.Assertions.assertThatThrownBy; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +-import static org.mockito.Mockito.times; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.when; + +@@ -25,8 +24,8 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class MetricsServletTest extends AbstractServletTest { +- private final Clock clock = mock(Clock.class); ++final class MetricsServletTest extends AbstractServletTest { ++ private final Clock clock = mock(); + private final MetricRegistry registry = new MetricRegistry(); + private ServletTester tester; + +@@ -130,22 +129,8 @@ class MetricsServletTest extends AbstractServletTest { + assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); + assertThat(response.getContent()) + .isEqualTo( +- callbackParamVal +- + "({" +- + "\"version\":\"5.0.0\"," +- + "\"gauges\":{" +- + "\"g1\":{\"value\":100}" +- + "}," +- + "\"counters\":{" +- + "\"c\":{\"count\":1}" +- + "}," +- + "\"histograms\":{" +- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" +- + "}," +- + "\"meters\":{" +- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" +- + "}" +- + "})"); ++ "%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", ++ callbackParamVal); + assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); + } + +@@ -224,48 +209,47 @@ class MetricsServletTest extends AbstractServletTest { + + @Test + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + + final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { +- final MetricRegistry metricRegistry = mock(MetricRegistry.class); +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final MetricRegistry metricRegistry = mock(); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn(metricRegistry); ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); + + final MetricsServlet metricsServlet = new MetricsServlet(null); + metricsServlet.init(servletConfig); + +- verify(servletConfig, times(1)).getServletContext(); +- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); ++ verify(servletConfig).getServletContext(); ++ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); + } + + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() + throws Exception { +- assertThrows( +- ServletException.class, +- () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); +- when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) +- .thenReturn("IRELLEVANT_STRING"); +- +- final MetricsServlet metricsServlet = new MetricsServlet(null); +- metricsServlet.init(servletConfig); +- }); ++ assertThatThrownBy( ++ () -> { ++ final ServletContext servletContext = mock(ServletContext.class); ++ final ServletConfig servletConfig = mock(ServletConfig.class); ++ when(servletConfig.getServletContext()).thenReturn(servletContext); ++ when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) ++ .thenReturn("IRELLEVANT_STRING"); ++ ++ final MetricsServlet metricsServlet = new MetricsServlet(null); ++ metricsServlet.init(servletConfig); ++ }) ++ .isInstanceOf(ServletException.class); + } + } +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +index 72e4d9f..56bb1ee 100644 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class PingServletTest extends AbstractServletTest { ++final class PingServletTest extends AbstractServletTest { + @Override + protected void setUp(ServletTester tester) { + tester.addServlet(PingServlet.class, "/ping"); +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +index 3b92675..5bbb7b1 100644 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +-class ThreadDumpServletTest extends AbstractServletTest { ++final class ThreadDumpServletTest extends AbstractServletTest { + @Override + protected void setUp(ServletTester tester) { + tester.addServlet(ThreadDumpServlet.class, "/threads"); +[detached HEAD 05c4a97] minor: Apply patches + 235 files changed, 1678 insertions(+), 1820 deletions(-) +[INFO] Scanning for projects... +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Build Order: +[INFO] +[INFO] Metrics5 Parent [pom] +[INFO] Metrics5 Documentation [jar] +[INFO] Metrics5 BOM [pom] +[INFO] Annotations for Metrics5 [bundle] +[INFO] Metrics5 Core [bundle] +[INFO] Benchmarks for Metrics5 [jar] +[INFO] Metrics Integration for Caffeine 3.x [bundle] +[INFO] Metrics Integration for Collectd [bundle] +[INFO] Metrics Integration for Ehcache [bundle] +[INFO] Graphite Integration for Metrics5 [bundle] +[INFO] InfluxDB integration for Metrics5 [bundle] +[INFO] JVM Integration for Metrics5 [bundle] +[INFO] Metrics5 Health Checks [bundle] +[INFO] Metrics Integration for Apache HttpClient [bundle] +[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] +[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] +[INFO] Metrics Integration for Jakarta Servlets [bundle] +[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] +[INFO] Jackson Integration for Metrics5 [bundle] +[INFO] Metrics Integration for Jetty 11.x and higher [bundle] +[INFO] Metrics5 Utility Jakarta Servlets [bundle] +[INFO] Metrics Integration for JCache [bundle] +[INFO] Metrics Integration for JDBI3 [bundle] +[INFO] Metrics Integration for Jersey 2.x [bundle] +[INFO] Metrics Integration for Jersey 3.0.x [bundle] +[INFO] Metrics Integration for Jersey 3.1.x [bundle] +[INFO] Metrics Integration for Jetty 10.x and higher [bundle] +[INFO] Metrics Integration for Log4j 2.x [bundle] +[INFO] Metrics Integration for Logback 1.3.x [bundle] +[INFO] Metrics Integration for Logback 1.4.x [bundle] +[INFO] Metrics Integration for Logback 1.5.x [bundle] +[INFO] Metrics Integration for Servlets [bundle] +[INFO] Metrics5 Utility Servlets [bundle] +[INFO] Metrics5 JCStress tests [jar] +[INFO] Metrics Integration with JMX [bundle] +[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] +[INFO] Metrics Integration for Jetty 12.x and higher [bundle] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- +[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] +[INFO] from pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- +[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] +[INFO] from docs/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec +[INFO] +[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- +[INFO] +[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- +[INFO] Copying 72 resources from source to target/source +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- +[INFO] Copying 72 resources from source to target/classes +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ docs --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- +[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. +[info] Processed 0 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- +[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] +[INFO] from metrics-bom/pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- +[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] +[INFO] from metrics-annotation/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. +[info] Processed 9 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- +[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] +[INFO] from metrics-core/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- +[INFO] Compiling 10 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[56,27] [this-escape] possible 'this' escape before subclass is fully initialized +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java:[68,17] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"%s is not in [0..1]", quantile);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[240,19] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean 'value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: %s", value);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java:[51,17] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"%s is not in [0..1]", quantile);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- +[INFO] Compiling 16 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[124,54] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean 'assertThat(futures.get(i).get()).withFailMessage("Future %s failed", i).isTrue();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[93,56] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) + Did you mean 'assertThat(b).isLessThan(b.resolve("key"));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[101,56] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) + Did you mean 'assertThat(MetricName.EMPTY).isLessThan(a);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[102,56] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) + Did you mean 'assertThat(MetricName.EMPTY).isLessThan(b);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[92,56] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsGreaterThan: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsGreaterThan) + Did you mean 'assertThat(b.resolve("key")).isGreaterThan(b);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[90,41] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) + Did you mean 'assertThat(a).isLessThan(b);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[103,41] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) + Did you mean 'assertThat(a).isLessThan(b);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[91,41] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsGreaterThan: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsGreaterThan) + Did you mean 'assertThat(b).isGreaterThan(a);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[104,41] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsGreaterThan: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsGreaterThan) + Did you mean 'assertThat(b).isGreaterThan(a);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[508,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[508,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[529,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[529,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[555,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[555,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[585,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[585,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[611,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[611,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[640,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability + (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) + Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[640,35] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean '.collect(toSet()));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[109,16] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail("NullPointerException must be thrown !!!");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[22,17] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '"Mismatched lengths: %s vs %s", values.length, weights.length);'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- +[info] Processed 87 files (6 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- +[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] +[INFO] from metrics-benchmarks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_arrTime_jmhTest' already exists on the sourcepath or classpath +[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_jmhType_B1' already exists on the sourcepath or classpath +[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_jmhType_B2' already exists on the sourcepath or classpath +[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_jmhType_B3' already exists on the sourcepath or classpath +[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_jmhType' already exists on the sourcepath or classpath +[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_slidingTime_jmhTest' already exists on the sourcepath or classpath +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22.jar +[INFO] +[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. +[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- +[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] +[INFO] from metrics-caffeine3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- +[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] +[INFO] from metrics-collectd/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[152,21] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '!username.isEmpty(), "username is required for securityLevel: %s", securityLevel);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[154,21] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '!password.isEmpty(), "password is required for securityLevel: %s", securityLevel);'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[125,20] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean 'if (Strings.isNullOrEmpty(val)) {'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- +[info] Processed 12 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- +[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] +[INFO] from metrics-ehcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- +[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] +[INFO] from metrics-graphite/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[68,35] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity + (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) + Did you mean 'checkArgument(!Strings.isNullOrEmpty(hostname), "hostname must not be null or empty");'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- +[info] Processed 13 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- +[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] +[INFO] from metrics-influxdb/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- +[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] +[INFO] from metrics-jvm/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[74,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[83,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[92,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[37,14] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(new FileDescriptorRatioGauge().getValue())'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- +[info] Processed 23 files (1 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- +[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] +[INFO] from metrics-healthchecks/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[97,19] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) + Did you mean '!healthChecks.containsKey(name), "A health check named %s already exists", name);'? +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- +[info] Processed 14 files (0 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] +[INFO] from metrics-httpclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[69,16] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- +[info] Processed 8 files (1 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] +[INFO] from metrics-httpclient5/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[104,26] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[109,26] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[147,28] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[157,28] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[163,16] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[214,28] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[219,28] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[69,16] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail();'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- +[info] Processed 13 files (2 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- +[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] +[INFO] from metrics-httpasyncclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[121,16] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail("This should fail as the client should not be able to connect");'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- +[info] Processed 5 files (1 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] +[INFO] from metrics-jakarta-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] +[INFO] from metrics-jakarta-servlet6/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- +[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] +[INFO] from metrics-json/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- +[info] Processed 4 files (1 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- +[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] +[INFO] from metrics-jetty11/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- +[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] +[INFO] from metrics-jakarta-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[223,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[224,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[244,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[245,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[247,46] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- +[info] Processed 17 files (1 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- +[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] +[INFO] from metrics-jcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- +[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] +[INFO] from metrics-jdbi3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- +[info] Processed 15 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- +[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] +[INFO] from metrics-jersey2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- +[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[110,16] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail("expected RuntimeException");'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- +[info] Processed 24 files (1 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- +[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] +[INFO] from metrics-jersey3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- +[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[111,16] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail("expected RuntimeException");'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- +[info] Processed 24 files (1 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- +[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] +[INFO] from metrics-jersey31/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- +[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[111,16] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'fail("expected RuntimeException");'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- +[info] Processed 24 files (1 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- +[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] +[INFO] from metrics-jetty10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- +[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] +[INFO] from metrics-log4j2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- +[info] Processed 3 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- +[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] +[INFO] from metrics-logback13/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- +[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] +[INFO] from metrics-logback14/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- +[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] +[INFO] from metrics-logback15/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- +[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] +[INFO] from metrics-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- +[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] +[INFO] from metrics-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[223,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[224,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[244,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletContext servletContext = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[245,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods + (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) + Did you mean 'final ServletConfig servletConfig = mock();'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[247,46] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` + (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) + Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- +[info] Processed 16 files (1 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- +[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] +[INFO] from metrics-jcstress/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- +[INFO] +[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. +[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. +[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: +[WARNING] - META-INF/AL2.0 +[WARNING] - META-INF/LGPL2.1 +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. +[info] Processed 3 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- +[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] +[INFO] from metrics-jmx/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ +[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] +[INFO] from metrics-legacy-adapter/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,49] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,9] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[108,27] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[112,27] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- +[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[25,60] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[26,60] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[21,59] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(1.58, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[22,56] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[23,66] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[24,64] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get95thPercentile()).isCloseTo(5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[25,64] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get98thPercentile()).isCloseTo(5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[26,64] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get99thPercentile()).isCloseTo(5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[27,65] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.get999thPercentile()).isCloseTo(5, offset(0.01));'? +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[25,60] Note: [StaticImport] Identifier should be statically imported + (see https://error-prone.picnic.tech/bugpatterns/StaticImport) + Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(36.47, offset(0.1));'? +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/metrics-legacy-adapter-5.0.0-rc22.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- +[info] Processed 60 files (4 reformatted). +[INFO] +[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- +[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] +[INFO] from metrics-legacy-adapter-healthchecks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] +[INFO] from metrics-jetty12/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] +[INFO] from metrics-jetty12-ee10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- +[info] Processed 2 files (0 reformatted). +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: +[INFO] +[INFO] Metrics5 Parent .................................... SUCCESS [ 0.391 s] +[INFO] Metrics5 Documentation ............................. SUCCESS [ 1.880 s] +[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.014 s] +[INFO] Annotations for Metrics5 ........................... SUCCESS [ 1.568 s] +[INFO] Metrics5 Core ...................................... SUCCESS [ 22.310 s] +[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 5.459 s] +[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 1.077 s] +[INFO] Metrics Integration for Collectd ................... SUCCESS [ 10.115 s] +[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 4.245 s] +[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 11.673 s] +[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 9.941 s] +[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 9.770 s] +[INFO] Metrics5 Health Checks ............................. SUCCESS [ 10.600 s] +[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 4.977 s] +[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 5.551 s] +[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 4.450 s] +[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 1.031 s] +[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 0.975 s] +[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 7.408 s] +[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 10.104 s] +[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 5.666 s] +[INFO] Metrics Integration for JCache ..................... SUCCESS [ 7.253 s] +[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 3.869 s] +[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 9.938 s] +[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 10.113 s] +[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 10.754 s] +[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 10.424 s] +[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 3.974 s] +[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 4.406 s] +[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 4.368 s] +[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 4.072 s] +[INFO] Metrics Integration for Servlets ................... SUCCESS [ 0.960 s] +[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 5.149 s] +[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 1.683 s] +[INFO] Metrics Integration with JMX ....................... SUCCESS [ 10.200 s] +[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 9.881 s] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 0.890 s] +[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 7.734 s] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 4.772 s] +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 04:00 min +[INFO] Finished at: 2024-11-18T12:55:25+01:00 +[INFO] ------------------------------------------------------------------------ +diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java +index 7b54d0b..b04d203 100644 +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java +@@ -150,9 +150,9 @@ public class CollectdReporter extends ScheduledReporter { + public CollectdReporter build(Sender sender) { + if (securityLevel != SecurityLevel.NONE) { + checkArgument( +- !username.isEmpty(), "username is required for securityLevel: " + securityLevel); ++ !username.isEmpty(), "username is required for securityLevel: %s", securityLevel); + checkArgument( +- !password.isEmpty(), "password is required for securityLevel: " + securityLevel); ++ !password.isEmpty(), "password is required for securityLevel: %s", securityLevel); + } + return new CollectdReporter( + registry, +diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java +index 764b5f8..8318562 100644 +--- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java ++++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java +@@ -4,6 +4,7 @@ import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.US_ASCII; + import static java.nio.charset.StandardCharsets.UTF_8; + ++import com.google.common.base.Strings; + import java.io.IOException; + import java.nio.BufferOverflowException; + import java.nio.ByteBuffer; +@@ -122,7 +123,7 @@ class PacketWriter { + } + + private void writeString(ByteBuffer buffer, int type, String val) { +- if (val == null || val.isEmpty()) { ++ if (Strings.isNullOrEmpty(val)) { + return; + } + int len = HEADER_LEN + val.length() + 1; +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java +index 6e22c83..257a72b 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java +@@ -1,6 +1,5 @@ + package io.dropwizard.metrics5; + +- + import com.google.common.collect.ImmutableSet; + import java.io.PrintStream; + import java.text.DateFormat; +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java +index 43690af..bf4470b 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java +@@ -238,7 +238,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { + */ + public Builder size(int value) { + checkArgument( +- value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: " + value); ++ value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: %s", value); + this.size = value; + return this; + } +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java +index 28c6a60..8a478d9 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java +@@ -50,7 +50,8 @@ public class UniformSnapshot extends Snapshot { + public double getValue(double quantile) { + checkArgument( + quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), +- quantile + " is not in [0..1]"); ++ "%s is not in [0..1]", ++ quantile); + + if (values.length == 0) { + return 0.0; +diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java +index 156bd3c..3e5c339 100644 +--- a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java ++++ b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java +@@ -67,7 +67,8 @@ public class WeightedSnapshot extends Snapshot { + public double getValue(double quantile) { + checkArgument( + quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), +- quantile + " is not in [0..1]"); ++ "%s is not in [0..1]", ++ quantile); + + if (values.length == 0) { + return 0.0; +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java +index 356b1a5..8c2720a 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java +@@ -121,7 +121,7 @@ final class CachedGaugeTest { + } + + for (int i = 0; i < futures.size(); i++) { +- assertThat(futures.get(i).get()).withFailMessage("Future " + i + " failed").isTrue(); ++ assertThat(futures.get(i).get()).withFailMessage("Future %s failed", i).isTrue(); + } + + executor.shutdown(); +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java +index 35860d7..286e40f 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java +@@ -87,10 +87,10 @@ final class MetricNameTest { + final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); + final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); + +- assertThat(a.compareTo(b)).isNegative(); +- assertThat(b.compareTo(a)).isPositive(); +- assertThat(b.resolve("key").compareTo(b)).isPositive(); +- assertThat(b.compareTo(b.resolve("key"))).isNegative(); ++ assertThat(a).isLessThan(b); ++ assertThat(b).isGreaterThan(a); ++ assertThat(b.resolve("key")).isGreaterThan(b); ++ assertThat(b).isLessThan(b.resolve("key")); + } + + @Test +@@ -98,9 +98,9 @@ final class MetricNameTest { + final MetricName a = MetricName.EMPTY.tagged("a", "x"); + final MetricName b = MetricName.EMPTY.tagged("b", "x"); + +- assertThat(MetricName.EMPTY.compareTo(a)).isNegative(); +- assertThat(MetricName.EMPTY.compareTo(b)).isNegative(); +- assertThat(a.compareTo(b)).isNegative(); +- assertThat(b.compareTo(a)).isPositive(); ++ assertThat(MetricName.EMPTY).isLessThan(a); ++ assertThat(MetricName.EMPTY).isLessThan(b); ++ assertThat(a).isLessThan(b); ++ assertThat(b).isGreaterThan(a); + } + } +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java +index d79a191..dddda8d 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java +@@ -12,7 +12,6 @@ import static org.mockito.Mockito.verify; + import java.util.HashMap; + import java.util.Map; + import java.util.Set; +-import java.util.stream.Collectors; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +@@ -505,7 +504,7 @@ final class MetricRegistryTest { + .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + } + + @Test +@@ -526,7 +525,7 @@ final class MetricRegistryTest { + .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + } + + @Test +@@ -552,7 +551,7 @@ final class MetricRegistryTest { + .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(childMetrics) + .containsAll( +@@ -582,7 +581,7 @@ final class MetricRegistryTest { + .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(childMetrics).doesNotContain(MetricName.build("test-1")); + } +@@ -608,7 +607,7 @@ final class MetricRegistryTest { + .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(childMetrics).doesNotContain(MetricName.build("test-1"), MetricName.build("test-3")); + } +@@ -637,7 +636,7 @@ final class MetricRegistryTest { + .hasSameElementsAs( + childMetrics.stream() + .map(m -> MetricName.build("child", m.getKey())) +- .collect(Collectors.toSet())); ++ .collect(toImmutableSet())); + + assertThat(childMetrics) + .containsAll( +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java +index a3e7329..59c187f 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5; + + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatThrownBy; ++import static org.assertj.core.api.Assertions.fail; + import static org.junit.jupiter.api.Assertions.assertEquals; + import static org.mockito.Mockito.any; + import static org.mockito.Mockito.eq; +@@ -19,7 +20,6 @@ import java.util.concurrent.ScheduledExecutorService; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.TimeoutException; + import java.util.concurrent.atomic.AtomicInteger; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; +@@ -106,7 +106,7 @@ final class ScheduledReporterTest { + r = + new DummyReporter( + null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); +- Assertions.fail("NullPointerException must be thrown !!!"); ++ fail("NullPointerException must be thrown !!!"); + } catch (NullPointerException e) { + assertEquals("registry == null", e.getMessage()); + } finally { +diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java +index 052948c..b059444 100644 +--- a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java ++++ b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java +@@ -21,7 +21,9 @@ final class WeightedSnapshotTest { + long[] values, double[] weights) { + checkArgument( + values.length == weights.length, +- "Mismatched lengths: " + values.length + " vs " + weights.length); ++ "Mismatched lengths: %s vs %s", ++ values.length, ++ weights.length); + + final List samples = new ArrayList<>(); + for (int i = 0; i < values.length; i++) { +diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java +index 8dfe5cf..36efd52 100644 +--- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java ++++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java +@@ -5,6 +5,7 @@ import static com.google.common.base.Preconditions.checkState; + import static java.nio.charset.StandardCharsets.UTF_8; + import static java.util.Objects.requireNonNull; + ++import com.google.common.base.Strings; + import java.io.BufferedWriter; + import java.io.IOException; + import java.io.OutputStreamWriter; +@@ -65,7 +66,7 @@ public class Graphite implements GraphiteSender { + * @param charset the character set used by the server + */ + public Graphite(String hostname, int port, SocketFactory socketFactory, Charset charset) { +- checkArgument(hostname != null && !hostname.isEmpty(), "hostname must not be null or empty"); ++ checkArgument(!Strings.isNullOrEmpty(hostname), "hostname must not be null or empty"); + + checkArgument(port >= 0 && port <= 65535, "port must be a valid IP port (0-65535)"); + +diff --git a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java +index 77b1e1e..467fc76 100644 +--- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java ++++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java +@@ -95,7 +95,7 @@ public class HealthCheckRegistry { + HealthCheck registered; + synchronized (lock) { + checkArgument( +- !healthChecks.containsKey(name), "A health check named " + name + " already exists"); ++ !healthChecks.containsKey(name), "A health check named %s already exists", name); + registered = healthCheck; + if (healthCheck.getClass().isAnnotationPresent(Async.class)) { + registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); +diff --git a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java +index 44f52fa..833855e 100644 +--- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java ++++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics5.httpasyncclient; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; +@@ -19,7 +20,6 @@ import org.apache.http.client.methods.HttpGet; + import org.apache.http.concurrent.FutureCallback; + import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; + import org.apache.http.nio.client.HttpAsyncClient; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; +@@ -118,7 +118,7 @@ final class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { + + try { + responseFuture.get(20, TimeUnit.SECONDS); +- Assertions.fail("This should fail as the client should not be able to connect"); ++ fail("This should fail as the client should not be able to connect"); + } catch (Exception e) { + // Ignore + } +diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java +index e5c7259..905b1a5 100644 +--- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics5.httpclient; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; +@@ -18,7 +19,6 @@ import org.apache.http.HttpRequest; + import org.apache.http.NoHttpResponseException; + import org.apache.http.client.HttpClient; + import org.apache.http.client.methods.HttpGet; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +@@ -66,7 +66,7 @@ final class InstrumentedHttpClientsTest { + + try { + client.execute(get); +- Assertions.fail(); ++ fail(); + } catch (NoHttpResponseException expected) { + assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); + } finally { +diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java +index b67225a..ee5ceb2 100644 +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.httpclient5; + + import static java.nio.charset.StandardCharsets.US_ASCII; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; + import static org.awaitility.Awaitility.await; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; +@@ -30,7 +31,6 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; + import org.apache.hc.core5.concurrent.FutureCallback; + import org.apache.hc.core5.http.ConnectionClosedException; + import org.apache.hc.core5.http.HttpRequest; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; +@@ -101,12 +101,12 @@ final class InstrumentedHttpAsyncClientsTest { + + @Override + public void failed(Exception ex) { +- Assertions.fail(); ++ fail(); + } + + @Override + public void cancelled() { +- Assertions.fail(); ++ fail(); + } + }); + responseFuture.get(1L, TimeUnit.SECONDS); +@@ -144,7 +144,7 @@ final class InstrumentedHttpAsyncClientsTest { + new FutureCallback() { + @Override + public void completed(SimpleHttpResponse result) { +- Assertions.fail(); ++ fail(); + } + + @Override +@@ -154,13 +154,13 @@ final class InstrumentedHttpAsyncClientsTest { + + @Override + public void cancelled() { +- Assertions.fail(); ++ fail(); + } + }); + countDownLatch.await(5, TimeUnit.SECONDS); + responseFuture.get(5, TimeUnit.SECONDS); + +- Assertions.fail(); ++ fail(); + } catch (ExecutionException e) { + assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class); + await() +@@ -211,12 +211,12 @@ final class InstrumentedHttpAsyncClientsTest { + + @Override + public void failed(Exception ex) { +- Assertions.fail(); ++ fail(); + } + + @Override + public void cancelled() { +- Assertions.fail(); ++ fail(); + } + }); + responseFuture.get(1L, TimeUnit.SECONDS); +diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java +index 46cdc5e..c935e61 100644 +--- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java ++++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics5.httpclient5; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; + import static org.mockito.ArgumentMatchers.any; + import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; +@@ -18,7 +19,6 @@ import org.apache.hc.client5.http.classic.HttpClient; + import org.apache.hc.client5.http.classic.methods.HttpGet; + import org.apache.hc.core5.http.HttpRequest; + import org.apache.hc.core5.http.NoHttpResponseException; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +@@ -66,7 +66,7 @@ final class InstrumentedHttpClientsTest { + + try { + client.execute(get); +- Assertions.fail(); ++ fail(); + } catch (NoHttpResponseException expected) { + assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); + } finally { +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +index e8208b0..df10b41 100644 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +@@ -220,8 +220,8 @@ final class HealthCheckServletTest extends AbstractServletTest { + throws Exception { + assertThatThrownBy( + () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); +diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +index d74900f..67d9741 100644 +--- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java ++++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.servlets; + + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatThrownBy; +-import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; + import static org.mockito.Mockito.verify; +@@ -241,10 +240,10 @@ final class MetricsServletTest extends AbstractServletTest { + throws Exception { + assertThatThrownBy( + () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); + + final MetricsServlet metricsServlet = new MetricsServlet(null); +diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java +index eeec0da..01abf40 100644 +--- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -1,6 +1,7 @@ + package io.dropwizard.metrics5.jersey2; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; + + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -10,7 +11,6 @@ import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceResponseM + import java.util.logging.Level; + import java.util.logging.Logger; + import javax.ws.rs.core.Application; +-import org.assertj.core.api.Assertions; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; +@@ -107,7 +107,7 @@ final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest + void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { + try { + target("responseMeteredRuntimeExceptionPerClass").request().get(); +- Assertions.fail("expected RuntimeException"); ++ fail("expected RuntimeException"); + } catch (Exception e) { + assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + } +diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java +index 00e401f..272caf0 100644 +--- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.jersey3; + + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; + + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -11,7 +12,6 @@ import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceResponseM + import jakarta.ws.rs.core.Application; + import java.util.logging.Level; + import java.util.logging.Logger; +-import org.assertj.core.api.Assertions; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; +@@ -108,7 +108,7 @@ final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest + void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { + try { + target("responseMeteredRuntimeExceptionPerClass").request().get(); +- Assertions.fail("expected RuntimeException"); ++ fail("expected RuntimeException"); + } catch (Exception e) { + assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + } +diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java +index fdd0440..e7d6d3c 100644 +--- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java ++++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java +@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.jersey31; + + import static io.dropwizard.metrics5.MetricRegistry.name; + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.fail; + + import io.dropwizard.metrics5.Meter; + import io.dropwizard.metrics5.MetricRegistry; +@@ -11,7 +12,6 @@ import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceResponse + import jakarta.ws.rs.core.Application; + import java.util.logging.Level; + import java.util.logging.Logger; +-import org.assertj.core.api.Assertions; + import org.glassfish.jersey.server.ResourceConfig; + import org.glassfish.jersey.test.JerseyTest; + import org.junit.jupiter.api.Test; +@@ -108,7 +108,7 @@ final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest + void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { + try { + target("responseMeteredRuntimeExceptionPerClass").request().get(); +- Assertions.fail("expected RuntimeException"); ++ fail("expected RuntimeException"); + } catch (Exception e) { + assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + } +diff --git a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java +index 0c6cfcf..7db5876 100644 +--- a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java ++++ b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java +@@ -1,6 +1,5 @@ + package io.dropwizard.metrics5.json; + +- + import com.fasterxml.jackson.core.JsonGenerator; + import com.fasterxml.jackson.core.Version; + import com.fasterxml.jackson.databind.Module; +diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java +index 019d29c..7f25d68 100644 +--- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java ++++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java +@@ -8,7 +8,6 @@ import static org.mockito.Mockito.when; + import com.sun.management.UnixOperatingSystemMXBean; + import java.lang.management.ManagementFactory; + import java.lang.management.OperatingSystemMXBean; +-import org.assertj.core.api.Assertions; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + +@@ -34,9 +33,7 @@ final class FileDescriptorRatioGaugeTest { + OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); + assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); + +- Assertions.assertThat(new FileDescriptorRatioGauge().getValue()) +- .isNotNegative() +- .isLessThanOrEqualTo(1.0); ++ assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative().isLessThanOrEqualTo(1.0); + } + + @Test +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java +index 39c5242..b57f137 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java +@@ -1,8 +1,8 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +@@ -22,7 +22,7 @@ final class ExponentiallyDecayingReservoirTest { + assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); + assertThat(snapshot.getMin()).isEqualTo(120); + assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1)); ++ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); + assertThat(snapshot.get75thPercentile()).isEqualTo(190); + assertThat(snapshot.get95thPercentile()).isEqualTo(200); + assertThat(snapshot.get98thPercentile()).isEqualTo(200); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java +index a141c70..db5f29b 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java +@@ -1,8 +1,8 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +@@ -23,7 +23,7 @@ final class HistogramTest { + assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); + assertThat(snapshot.getMin()).isEqualTo(120); + assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1)); ++ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); + assertThat(snapshot.get75thPercentile()).isEqualTo(190); + assertThat(snapshot.get95thPercentile()).isEqualTo(200); + assertThat(snapshot.get98thPercentile()).isEqualTo(200); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java +index 24a6ae0..77cbdf1 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java +@@ -1,10 +1,10 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + + import io.dropwizard.metrics5.UniformSnapshot; + import java.io.ByteArrayOutputStream; +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +@@ -18,13 +18,13 @@ final class SnapshotTest { + assertThat(snapshot.size()).isEqualTo(5); + assertThat(snapshot.getMin()).isEqualTo(1); + assertThat(snapshot.getMax()).isEqualTo(5); +- assertThat(snapshot.getStdDev()).isCloseTo(1.58, Offset.offset(0.01)); +- assertThat(snapshot.getMedian()).isCloseTo(3, Offset.offset(0.01)); +- assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, Offset.offset(0.01)); +- assertThat(snapshot.get95thPercentile()).isCloseTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get98thPercentile()).isCloseTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get99thPercentile()).isCloseTo(5, Offset.offset(0.01)); +- assertThat(snapshot.get999thPercentile()).isCloseTo(5, Offset.offset(0.01)); ++ assertThat(snapshot.getStdDev()).isCloseTo(1.58, offset(0.01)); ++ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.01)); ++ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.01)); ++ assertThat(snapshot.get95thPercentile()).isCloseTo(5, offset(0.01)); ++ assertThat(snapshot.get98thPercentile()).isCloseTo(5, offset(0.01)); ++ assertThat(snapshot.get99thPercentile()).isCloseTo(5, offset(0.01)); ++ assertThat(snapshot.get999thPercentile()).isCloseTo(5, offset(0.01)); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + snapshot.dump(baos); +diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java +index 0668c1e..01fb3d6 100644 +--- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java ++++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java +@@ -1,8 +1,8 @@ + package com.codahale.metrics; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.data.Offset.offset; + +-import org.assertj.core.data.Offset; + import org.junit.jupiter.api.Test; + + @SuppressWarnings("deprecation") +@@ -22,7 +22,7 @@ final class UniformReservoirTest { + assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); + assertThat(snapshot.getMin()).isEqualTo(120); + assertThat(snapshot.getMax()).isEqualTo(200); +- assertThat(snapshot.getStdDev()).isCloseTo(36.47, Offset.offset(0.1)); ++ assertThat(snapshot.getStdDev()).isCloseTo(36.47, offset(0.1)); + assertThat(snapshot.get75thPercentile()).isEqualTo(195); + assertThat(snapshot.get95thPercentile()).isEqualTo(200); + assertThat(snapshot.get98thPercentile()).isEqualTo(200); +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +index 80b40f1..5aa0027 100644 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +@@ -220,8 +220,8 @@ final class HealthCheckServletTest extends AbstractServletTest { + throws Exception { + assertThatThrownBy( + () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); +diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +index 78086f5..39bdcf2 100644 +--- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java ++++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.servlets; + + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatThrownBy; +-import static org.mockito.ArgumentMatchers.eq; + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.never; + import static org.mockito.Mockito.verify; +@@ -241,10 +240,10 @@ final class MetricsServletTest extends AbstractServletTest { + throws Exception { + assertThatThrownBy( + () -> { +- final ServletContext servletContext = mock(ServletContext.class); +- final ServletConfig servletConfig = mock(ServletConfig.class); ++ final ServletContext servletContext = mock(); ++ final ServletConfig servletConfig = mock(); + when(servletConfig.getServletContext()).thenReturn(servletContext); +- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) ++ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); + + final MetricsServlet metricsServlet = new MetricsServlet(null); +[detached HEAD 01cbee7] minor: Apply patches + 30 files changed, 77 insertions(+), 79 deletions(-) +[INFO] Scanning for projects... +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Build Order: +[INFO] +[INFO] Metrics5 Parent [pom] +[INFO] Metrics5 Documentation [jar] +[INFO] Metrics5 BOM [pom] +[INFO] Annotations for Metrics5 [bundle] +[INFO] Metrics5 Core [bundle] +[INFO] Benchmarks for Metrics5 [jar] +[INFO] Metrics Integration for Caffeine 3.x [bundle] +[INFO] Metrics Integration for Collectd [bundle] +[INFO] Metrics Integration for Ehcache [bundle] +[INFO] Graphite Integration for Metrics5 [bundle] +[INFO] InfluxDB integration for Metrics5 [bundle] +[INFO] JVM Integration for Metrics5 [bundle] +[INFO] Metrics5 Health Checks [bundle] +[INFO] Metrics Integration for Apache HttpClient [bundle] +[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] +[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] +[INFO] Metrics Integration for Jakarta Servlets [bundle] +[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] +[INFO] Jackson Integration for Metrics5 [bundle] +[INFO] Metrics Integration for Jetty 11.x and higher [bundle] +[INFO] Metrics5 Utility Jakarta Servlets [bundle] +[INFO] Metrics Integration for JCache [bundle] +[INFO] Metrics Integration for JDBI3 [bundle] +[INFO] Metrics Integration for Jersey 2.x [bundle] +[INFO] Metrics Integration for Jersey 3.0.x [bundle] +[INFO] Metrics Integration for Jersey 3.1.x [bundle] +[INFO] Metrics Integration for Jetty 10.x and higher [bundle] +[INFO] Metrics Integration for Log4j 2.x [bundle] +[INFO] Metrics Integration for Logback 1.3.x [bundle] +[INFO] Metrics Integration for Logback 1.4.x [bundle] +[INFO] Metrics Integration for Logback 1.5.x [bundle] +[INFO] Metrics Integration for Servlets [bundle] +[INFO] Metrics5 Utility Servlets [bundle] +[INFO] Metrics5 JCStress tests [jar] +[INFO] Metrics Integration with JMX [bundle] +[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] +[INFO] Metrics Integration for Jetty 12.x and higher [bundle] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- +[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] +[INFO] from pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- +[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] +[INFO] from docs/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec +[INFO] +[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- +[INFO] +[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- +[INFO] Copying 72 resources from source to target/source +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- +[INFO] Copying 72 resources from source to target/classes +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ docs --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- +[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. +[info] Processed 0 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- +[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] +[INFO] from metrics-bom/pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- +[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] +[INFO] from metrics-annotation/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. +[info] Processed 9 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- +[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] +[INFO] from metrics-core/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- +[info] Processed 87 files (0 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- +[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] +[INFO] from metrics-benchmarks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- +[INFO] +[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. +[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- +[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] +[INFO] from metrics-caffeine3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- +[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] +[INFO] from metrics-collectd/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- +[info] Processed 12 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- +[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] +[INFO] from metrics-ehcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- +[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] +[INFO] from metrics-graphite/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- +[info] Processed 13 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- +[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] +[INFO] from metrics-influxdb/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- +[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] +[INFO] from metrics-jvm/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- +[info] Processed 23 files (0 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- +[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] +[INFO] from metrics-healthchecks/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- +[info] Processed 14 files (0 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] +[INFO] from metrics-httpclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] +[INFO] from metrics-httpclient5/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- +[info] Processed 13 files (0 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- +[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] +[INFO] from metrics-httpasyncclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] +[INFO] from metrics-jakarta-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] +[INFO] from metrics-jakarta-servlet6/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- +[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] +[INFO] from metrics-json/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- +[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] +[INFO] from metrics-jetty11/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- +[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] +[INFO] from metrics-jakarta-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- +[info] Processed 17 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- +[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] +[INFO] from metrics-jcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- +[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] +[INFO] from metrics-jdbi3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- +[info] Processed 15 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- +[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] +[INFO] from metrics-jersey2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- +[info] Processed 24 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- +[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] +[INFO] from metrics-jersey3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- +[info] Processed 24 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- +[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] +[INFO] from metrics-jersey31/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- +[info] Processed 24 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- +[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] +[INFO] from metrics-jetty10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- +[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] +[INFO] from metrics-log4j2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- +[info] Processed 3 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- +[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] +[INFO] from metrics-logback13/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- +[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] +[INFO] from metrics-logback14/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- +[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] +[INFO] from metrics-logback15/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- +[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] +[INFO] from metrics-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- +[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] +[INFO] from metrics-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- +[info] Processed 16 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- +[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] +[INFO] from metrics-jcstress/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- +[INFO] +[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. +[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. +[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: +[WARNING] - META-INF/AL2.0 +[WARNING] - META-INF/LGPL2.1 +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. +[info] Processed 3 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- +[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] +[INFO] from metrics-jmx/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ +[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] +[INFO] from metrics-legacy-adapter/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- +[info] Processed 60 files (0 reformatted). +[INFO] +[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- +[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] +[INFO] from metrics-legacy-adapter-healthchecks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] +[INFO] from metrics-jetty12/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] +[INFO] from metrics-jetty12-ee10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- +[INFO] Nothing to compile - all classes are up to date. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- +[info] Processed 2 files (0 reformatted). +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: +[INFO] +[INFO] Metrics5 Parent .................................... SUCCESS [ 0.360 s] +[INFO] Metrics5 Documentation ............................. SUCCESS [ 1.633 s] +[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.010 s] +[INFO] Annotations for Metrics5 ........................... SUCCESS [ 1.490 s] +[INFO] Metrics5 Core ...................................... SUCCESS [ 11.952 s] +[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 1.680 s] +[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 1.138 s] +[INFO] Metrics Integration for Collectd ................... SUCCESS [ 1.143 s] +[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 1.143 s] +[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 4.578 s] +[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 1.134 s] +[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 4.038 s] +[INFO] Metrics5 Health Checks ............................. SUCCESS [ 1.171 s] +[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 3.962 s] +[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 5.074 s] +[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 4.234 s] +[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 1.043 s] +[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 0.974 s] +[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 4.146 s] +[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 1.212 s] +[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 4.821 s] +[INFO] Metrics Integration for JCache ..................... SUCCESS [ 1.155 s] +[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 1.069 s] +[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 4.570 s] +[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 4.438 s] +[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 4.365 s] +[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 1.063 s] +[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 1.018 s] +[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 1.002 s] +[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 1.031 s] +[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 0.990 s] +[INFO] Metrics Integration for Servlets ................... SUCCESS [ 0.951 s] +[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 4.621 s] +[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 1.508 s] +[INFO] Metrics Integration with JMX ....................... SUCCESS [ 1.102 s] +[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 4.456 s] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 0.861 s] +[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 1.028 s] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 1.186 s] +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 01:34 min +[INFO] Finished at: 2024-11-18T12:57:00+01:00 +[INFO] ------------------------------------------------------------------------ +[INFO] Scanning for projects... +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Build Order: +[INFO] +[INFO] Metrics5 Parent [pom] +[INFO] Metrics5 Documentation [jar] +[INFO] Metrics5 BOM [pom] +[INFO] Annotations for Metrics5 [bundle] +[INFO] Metrics5 Core [bundle] +[INFO] Benchmarks for Metrics5 [jar] +[INFO] Metrics Integration for Caffeine 3.x [bundle] +[INFO] Metrics Integration for Collectd [bundle] +[INFO] Metrics Integration for Ehcache [bundle] +[INFO] Graphite Integration for Metrics5 [bundle] +[INFO] InfluxDB integration for Metrics5 [bundle] +[INFO] JVM Integration for Metrics5 [bundle] +[INFO] Metrics5 Health Checks [bundle] +[INFO] Metrics Integration for Apache HttpClient [bundle] +[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] +[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] +[INFO] Metrics Integration for Jakarta Servlets [bundle] +[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] +[INFO] Jackson Integration for Metrics5 [bundle] +[INFO] Metrics Integration for Jetty 11.x and higher [bundle] +[INFO] Metrics5 Utility Jakarta Servlets [bundle] +[INFO] Metrics Integration for JCache [bundle] +[INFO] Metrics Integration for JDBI3 [bundle] +[INFO] Metrics Integration for Jersey 2.x [bundle] +[INFO] Metrics Integration for Jersey 3.0.x [bundle] +[INFO] Metrics Integration for Jersey 3.1.x [bundle] +[INFO] Metrics Integration for Jetty 10.x and higher [bundle] +[INFO] Metrics Integration for Log4j 2.x [bundle] +[INFO] Metrics Integration for Logback 1.3.x [bundle] +[INFO] Metrics Integration for Logback 1.4.x [bundle] +[INFO] Metrics Integration for Logback 1.5.x [bundle] +[INFO] Metrics Integration for Servlets [bundle] +[INFO] Metrics5 Utility Servlets [bundle] +[INFO] Metrics5 JCStress tests [jar] +[INFO] Metrics Integration with JMX [bundle] +[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] +[INFO] Metrics Integration for Jetty 12.x and higher [bundle] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- +[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] +[INFO] from pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-parent --- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- +[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] +[INFO] from docs/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ docs --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec +[INFO] +[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- +[INFO] +[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- +[INFO] Copying 72 resources from source to target/source +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- +[INFO] Copying 72 resources from source to target/classes +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ docs --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/docs-5.0.0-rc22.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- +[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. +[info] Processed 0 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- +[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] +[INFO] from metrics-bom/pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-bom --- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- +[INFO] Skipping format check: project uses 'pom' packaging +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- +[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] +[INFO] from metrics-annotation/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-annotation --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- +[INFO] Recompiling the module because of changed source code. +[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. +[info] Processed 9 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- +[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] +[INFO] from metrics-core/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-core --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- +[INFO] Recompiling the module because of changed source code. +[INFO] Compiling 49 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[56,27] [this-escape] possible 'this' escape before subclass is fully initialized +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 38 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- +[info] Processed 87 files (0 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- +[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] +[INFO] from metrics-benchmarks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-benchmarks --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22.jar +[INFO] +[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. +[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- +[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] +[INFO] from metrics-caffeine3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-caffeine3 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- +[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] +[INFO] from metrics-collectd/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-collectd --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- +[info] Processed 12 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- +[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] +[INFO] from metrics-ehcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-ehcache --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- +[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] +[INFO] from metrics-graphite/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-graphite --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- +[info] Processed 13 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- +[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] +[INFO] from metrics-influxdb/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-influxdb --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- +[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] +[INFO] from metrics-jvm/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jvm --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 12 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[74,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[83,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[92,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- +[info] Processed 23 files (0 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- +[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] +[INFO] from metrics-healthchecks/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-healthchecks --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- +[info] Processed 14 files (0 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] +[INFO] from metrics-httpclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpclient --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java:[114,8] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] +[INFO] from metrics-httpclient5/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpclient5 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[14,40] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[15,40] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[16,37] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[30,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[31,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[32,37] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[33,38] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[96,21] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[160,12] [deprecation] DefaultHttpClientConnectionOperator(Lookup,SchemePortResolver,DnsResolver) in DefaultHttpClientConnectionOperator has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java:[49,4] [deprecation] HttpRequestExecutor(Timeout,ConnectionReuseStrategy,Http1StreamListener) in HttpRequestExecutor has been deprecated +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- +[info] Processed 13 files (0 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- +[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] +[INFO] from metrics-httpasyncclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpasyncclient --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java:[40,8] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] +[INFO] from metrics-jakarta-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlet --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] +[INFO] from metrics-jakarta-servlet6/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlet6 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- +[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] +[INFO] from metrics-json/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-json --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java:[189,31] [serial] non-transient instance field of a serializable class declared with a non-serializable type +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- +[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] +[INFO] from metrics-jetty11/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty11 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- +[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] +[INFO] from metrics-jakarta-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlets --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- +[info] Processed 17 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- +[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] +[INFO] from metrics-jcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jcache --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- +[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] +[INFO] from metrics-jdbi3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jdbi3 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- +[info] Processed 15 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- +[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] +[INFO] from metrics-jersey2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey2 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- +[info] Processed 24 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- +[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] +[INFO] from metrics-jersey3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey3 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- +[info] Processed 24 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- +[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] +[INFO] from metrics-jersey31/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey31 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- +[info] Processed 24 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- +[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] +[INFO] from metrics-jetty10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty10 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- +[info] Processed 8 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- +[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] +[INFO] from metrics-log4j2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-log4j2 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- +[info] Processed 3 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- +[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] +[INFO] from metrics-logback13/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback13 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- +[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] +[INFO] from metrics-logback14/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback14 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- +[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] +[INFO] from metrics-logback15/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback15 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- +[info] Processed 2 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- +[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] +[INFO] from metrics-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-servlet --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- +[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] +[INFO] from metrics-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-servlets --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 10 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- +[info] Processed 16 files (0 reformatted). +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- +[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] +[INFO] from metrics-jcstress/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jcstress --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22.jar +[INFO] +[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. +[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. +[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: +[WARNING] - META-INF/AL2.0 +[WARNING] - META-INF/LGPL2.1 +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. +[info] Processed 3 files (0 reformatted). +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- +[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] +[INFO] from metrics-jmx/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jmx --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ +[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] +[INFO] from metrics-legacy-adapter/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-legacy-adapter --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 36 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,49] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,9] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[108,27] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[112,27] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 24 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[50,4] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[367,22] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/metrics-legacy-adapter-5.0.0-rc22.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- +[info] Processed 60 files (0 reformatted). +[INFO] +[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- +[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] +[INFO] from metrics-legacy-adapter-healthchecks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-legacy-adapter-healthchecks --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/metrics-legacy-adapter-healthchecks-5.0.0-rc22.jar +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- +[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. +[info] Processed 4 files (0 reformatted). +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] +[INFO] from metrics-jetty12/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty12 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- +[info] Processed 5 files (0 reformatted). +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] +[INFO] from metrics-jetty12-ee10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty12-ee10 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- +[INFO] Tests are skipped. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- +[info] Processed 2 files (0 reformatted). +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: +[INFO] +[INFO] Metrics5 Parent .................................... SUCCESS [ 0.418 s] +[INFO] Metrics5 Documentation ............................. SUCCESS [ 1.391 s] +[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.011 s] +[INFO] Annotations for Metrics5 ........................... SUCCESS [ 4.821 s] +[INFO] Metrics5 Core ...................................... SUCCESS [ 28.095 s] +[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 6.099 s] +[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 8.141 s] +[INFO] Metrics Integration for Collectd ................... SUCCESS [ 11.672 s] +[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 8.411 s] +[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 13.436 s] +[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 11.847 s] +[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 11.927 s] +[INFO] Metrics5 Health Checks ............................. SUCCESS [ 12.779 s] +[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 8.383 s] +[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 9.257 s] +[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 7.406 s] +[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 6.872 s] +[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 6.500 s] +[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 7.977 s] +[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 9.592 s] +[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 10.249 s] +[INFO] Metrics Integration for JCache ..................... SUCCESS [ 6.698 s] +[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 8.201 s] +[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 10.156 s] +[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 9.897 s] +[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 10.378 s] +[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 10.002 s] +[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 6.949 s] +[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 6.816 s] +[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 6.705 s] +[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 6.484 s] +[INFO] Metrics Integration for Servlets ................... SUCCESS [ 6.860 s] +[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 9.801 s] +[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 4.324 s] +[INFO] Metrics Integration with JMX ....................... SUCCESS [ 8.759 s] +[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 13.046 s] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 4.518 s] +[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 8.373 s] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 7.795 s] +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 05:31 min +[INFO] Finished at: 2024-11-18T13:02:34+01:00 +[INFO] ------------------------------------------------------------------------ +[INFO] Scanning for projects... +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Build Order: +[INFO] +[INFO] Metrics5 Parent [pom] +[INFO] Metrics5 Documentation [jar] +[INFO] Metrics5 BOM [pom] +[INFO] Annotations for Metrics5 [bundle] +[INFO] Metrics5 Core [bundle] +[INFO] Benchmarks for Metrics5 [jar] +[INFO] Metrics Integration for Caffeine 3.x [bundle] +[INFO] Metrics Integration for Collectd [bundle] +[INFO] Metrics Integration for Ehcache [bundle] +[INFO] Graphite Integration for Metrics5 [bundle] +[INFO] InfluxDB integration for Metrics5 [bundle] +[INFO] JVM Integration for Metrics5 [bundle] +[INFO] Metrics5 Health Checks [bundle] +[INFO] Metrics Integration for Apache HttpClient [bundle] +[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] +[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] +[INFO] Metrics Integration for Jakarta Servlets [bundle] +[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] +[INFO] Jackson Integration for Metrics5 [bundle] +[INFO] Metrics Integration for Jetty 11.x and higher [bundle] +[INFO] Metrics5 Utility Jakarta Servlets [bundle] +[INFO] Metrics Integration for JCache [bundle] +[INFO] Metrics Integration for JDBI3 [bundle] +[INFO] Metrics Integration for Jersey 2.x [bundle] +[INFO] Metrics Integration for Jersey 3.0.x [bundle] +[INFO] Metrics Integration for Jersey 3.1.x [bundle] +[INFO] Metrics Integration for Jetty 10.x and higher [bundle] +[INFO] Metrics Integration for Log4j 2.x [bundle] +[INFO] Metrics Integration for Logback 1.3.x [bundle] +[INFO] Metrics Integration for Logback 1.4.x [bundle] +[INFO] Metrics Integration for Logback 1.5.x [bundle] +[INFO] Metrics Integration for Servlets [bundle] +[INFO] Metrics5 Utility Servlets [bundle] +[INFO] Metrics5 JCStress tests [jar] +[INFO] Metrics Integration with JMX [bundle] +[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] +[INFO] Metrics Integration for Jetty 12.x and higher [bundle] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- +[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] +[INFO] from pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-parent --- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec +[INFO] +[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- +[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] +[INFO] from docs/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ docs --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec +[INFO] +[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- +[INFO] +[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- +[INFO] Copying 72 resources from source to target/source +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- +[INFO] Copying 72 resources from source to target/classes +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ docs --- +[INFO] No tests to run. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/docs-5.0.0-rc22.jar +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- +[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] +[INFO] from metrics-bom/pom.xml +[INFO] --------------------------------[ pom ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-bom --- +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- +[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] +[INFO] from metrics-annotation/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 +[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 +[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check +[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin +[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-annotation --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- +[INFO] Recompiling the module because of changed source code. +[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- +[INFO] No tests to run. +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- +[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] +[INFO] from metrics-core/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-core --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- +[INFO] Recompiling the module because of changed source code. +[INFO] Compiling 49 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[56,27] [this-escape] possible 'this' escape before subclass is fully initialized +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method + (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 38 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.ExponentialMovingAveragesTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.311 s -- in io.dropwizard.metrics5.ExponentialMovingAveragesTest +[INFO] Running io.dropwizard.metrics5.SlidingWindowReservoirTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.219 s -- in io.dropwizard.metrics5.SlidingWindowReservoirTest +[INFO] Running io.dropwizard.metrics5.InstrumentedScheduledExecutorServiceTest +[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.762 s -- in io.dropwizard.metrics5.InstrumentedScheduledExecutorServiceTest +[INFO] Running io.dropwizard.metrics5.ExponentiallyDecayingReservoirTest +[INFO] Tests run: 24, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.212 s -- in io.dropwizard.metrics5.ExponentiallyDecayingReservoirTest +[INFO] Running io.dropwizard.metrics5.HistogramTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.113 s -- in io.dropwizard.metrics5.HistogramTest +[INFO] Running io.dropwizard.metrics5.ScheduledReporterTest +[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.402 s -- in io.dropwizard.metrics5.ScheduledReporterTest +[INFO] Running io.dropwizard.metrics5.ConsoleReporterTest +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.200 s -- in io.dropwizard.metrics5.ConsoleReporterTest +[INFO] Running io.dropwizard.metrics5.RatioGaugeTest +[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in io.dropwizard.metrics5.RatioGaugeTest +[INFO] Running io.dropwizard.metrics5.SimpleSettableGaugeTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 s -- in io.dropwizard.metrics5.SimpleSettableGaugeTest +[INFO] Running io.dropwizard.metrics5.UniformSnapshotTest +[INFO] Tests run: 25, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 s -- in io.dropwizard.metrics5.UniformSnapshotTest +[INFO] Running io.dropwizard.metrics5.ChunkedAssociativeLongArrayTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in io.dropwizard.metrics5.ChunkedAssociativeLongArrayTest +[INFO] Running io.dropwizard.metrics5.MetricNameTest +[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 s -- in io.dropwizard.metrics5.MetricNameTest +[INFO] Running io.dropwizard.metrics5.MetricFilterTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 s -- in io.dropwizard.metrics5.MetricFilterTest +[INFO] Running io.dropwizard.metrics5.ClockTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 s -- in io.dropwizard.metrics5.ClockTest +[INFO] Running io.dropwizard.metrics5.SlidingTimeWindowReservoirTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.363 s -- in io.dropwizard.metrics5.SlidingTimeWindowReservoirTest +[INFO] Running io.dropwizard.metrics5.DefaultSettableGaugeTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in io.dropwizard.metrics5.DefaultSettableGaugeTest +[INFO] Running io.dropwizard.metrics5.TimerTest +[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.012 s -- in io.dropwizard.metrics5.TimerTest +[INFO] Running io.dropwizard.metrics5.Slf4jReporterTest +[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.189 s -- in io.dropwizard.metrics5.Slf4jReporterTest +[INFO] Running io.dropwizard.metrics5.SharedMetricRegistriesTest +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.022 s -- in io.dropwizard.metrics5.SharedMetricRegistriesTest +[INFO] Running io.dropwizard.metrics5.MetricRegistryListenerTest +[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.012 s -- in io.dropwizard.metrics5.MetricRegistryListenerTest +[INFO] Running io.dropwizard.metrics5.UniformReservoirTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in io.dropwizard.metrics5.UniformReservoirTest +[INFO] Running io.dropwizard.metrics5.InstrumentedThreadFactoryTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in io.dropwizard.metrics5.InstrumentedThreadFactoryTest +[INFO] Running io.dropwizard.metrics5.WeightedSnapshotTest +[INFO] Tests run: 27, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.230 s -- in io.dropwizard.metrics5.WeightedSnapshotTest +[INFO] Running io.dropwizard.metrics5.CounterTest +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s -- in io.dropwizard.metrics5.CounterTest +[INFO] Running io.dropwizard.metrics5.SlidingTimeWindowMovingAveragesTest +[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 s -- in io.dropwizard.metrics5.SlidingTimeWindowMovingAveragesTest +[INFO] Running io.dropwizard.metrics5.CsvReporterTest +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.083 s -- in io.dropwizard.metrics5.CsvReporterTest +[INFO] Running io.dropwizard.metrics5.MeterTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 s -- in io.dropwizard.metrics5.MeterTest +[INFO] Running io.dropwizard.metrics5.NoopMetricRegistryTest +[INFO] Tests run: 40, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.130 s -- in io.dropwizard.metrics5.NoopMetricRegistryTest +[INFO] Running io.dropwizard.metrics5.EWMATest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 s -- in io.dropwizard.metrics5.EWMATest +[INFO] Running io.dropwizard.metrics5.DerivativeGaugeTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 s -- in io.dropwizard.metrics5.DerivativeGaugeTest +[INFO] Running io.dropwizard.metrics5.MeterApproximationTest +[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.107 s -- in io.dropwizard.metrics5.MeterApproximationTest +[INFO] Running io.dropwizard.metrics5.InstrumentedExecutorServiceTest +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.018 s -- in io.dropwizard.metrics5.InstrumentedExecutorServiceTest +[INFO] Running io.dropwizard.metrics5.FixedNameCsvFileProviderTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.011 s -- in io.dropwizard.metrics5.FixedNameCsvFileProviderTest +[INFO] Running io.dropwizard.metrics5.SlidingTimeWindowArrayReservoirTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.209 s -- in io.dropwizard.metrics5.SlidingTimeWindowArrayReservoirTest +[INFO] Running io.dropwizard.metrics5.ClassMetadataTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.021 s -- in io.dropwizard.metrics5.ClassMetadataTest +[INFO] Running io.dropwizard.metrics5.CachedGaugeTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 10.16 s -- in io.dropwizard.metrics5.CachedGaugeTest +[INFO] Running io.dropwizard.metrics5.MetricRegistryTest +[INFO] Tests run: 53, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.079 s -- in io.dropwizard.metrics5.MetricRegistryTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 338, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- +[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] +[INFO] from metrics-benchmarks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-benchmarks --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- +[INFO] No tests to run. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22.jar +[INFO] +[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. +[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- +[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] +[INFO] from metrics-caffeine3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-caffeine3 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.caffeine3.MetricsStatsCounterTest +[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.281 s -- in io.dropwizard.metrics5.caffeine3.MetricsStatsCounterTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- +[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] +[INFO] from metrics-collectd/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-collectd --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.collectd.CollectdReporterSecurityTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.224 s -- in io.dropwizard.metrics5.collectd.CollectdReporterSecurityTest +[INFO] Running io.dropwizard.metrics5.collectd.PacketWriterTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.102 s -- in io.dropwizard.metrics5.collectd.PacketWriterTest +[INFO] Running io.dropwizard.metrics5.collectd.CollectdReporterTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 17, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.770 s -- in io.dropwizard.metrics5.collectd.CollectdReporterTest +[INFO] Running io.dropwizard.metrics5.collectd.SanitizeTest +[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.014 s -- in io.dropwizard.metrics5.collectd.SanitizeTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 26, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- +[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] +[INFO] from metrics-ehcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-ehcache --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.ehcache.InstrumentedCacheDecoratorFactoryTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.325 s -- in io.dropwizard.metrics5.ehcache.InstrumentedCacheDecoratorFactoryTest +[INFO] Running io.dropwizard.metrics5.ehcache.InstrumentedEhcacheTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 s -- in io.dropwizard.metrics5.ehcache.InstrumentedEhcacheTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- +[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] +[INFO] from metrics-graphite/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-graphite --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.graphite.GraphiteRabbitMQTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.020 s -- in io.dropwizard.metrics5.graphite.GraphiteRabbitMQTest +[INFO] Running io.dropwizard.metrics5.graphite.GraphiteTest +[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.297 s -- in io.dropwizard.metrics5.graphite.GraphiteTest +[INFO] Running io.dropwizard.metrics5.graphite.GraphiteUDPTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.108 s -- in io.dropwizard.metrics5.graphite.GraphiteUDPTest +[INFO] Running io.dropwizard.metrics5.graphite.PickledGraphiteTest +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 9.740 s -- in io.dropwizard.metrics5.graphite.PickledGraphiteTest +[INFO] Running io.dropwizard.metrics5.graphite.GraphiteSanitizeTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.351 s -- in io.dropwizard.metrics5.graphite.GraphiteSanitizeTest +[INFO] Running io.dropwizard.metrics5.graphite.GraphiteReporterTest +[INFO] Tests run: 19, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.429 s -- in io.dropwizard.metrics5.graphite.GraphiteReporterTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 45, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- +[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] +[INFO] from metrics-influxdb/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-influxdb --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) + (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.influxdb.InfluxDbReporterTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.312 s -- in io.dropwizard.metrics5.influxdb.InfluxDbReporterTest +[INFO] Running io.dropwizard.metrics5.influxdb.InfluxDbLineBuilderAssumptionsTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.009 s -- in io.dropwizard.metrics5.influxdb.InfluxDbLineBuilderAssumptionsTest +[INFO] Running io.dropwizard.metrics5.influxdb.InfluxDbUdpTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.144 s -- in io.dropwizard.metrics5.influxdb.InfluxDbUdpTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 20, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- +[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] +[INFO] from metrics-jvm/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jvm --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 12 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[74,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[83,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[92,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast + required: Gauge + found: Metric +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.jvm.ThreadStatesGaugeSetTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.806 s -- in io.dropwizard.metrics5.jvm.ThreadStatesGaugeSetTest +[INFO] Running io.dropwizard.metrics5.jvm.MemoryUsageGaugeSetTest +[INFO] Tests run: 25, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.315 s -- in io.dropwizard.metrics5.jvm.MemoryUsageGaugeSetTest +[INFO] Running io.dropwizard.metrics5.jvm.CpuTimeClockTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.010 s -- in io.dropwizard.metrics5.jvm.CpuTimeClockTest +[INFO] Running io.dropwizard.metrics5.jvm.JmxAttributeGaugeTest +[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.113 s -- in io.dropwizard.metrics5.jvm.JmxAttributeGaugeTest +[INFO] Running io.dropwizard.metrics5.jvm.FileDescriptorRatioGaugeTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.091 s -- in io.dropwizard.metrics5.jvm.FileDescriptorRatioGaugeTest +[INFO] Running io.dropwizard.metrics5.jvm.JvmAttributeGaugeSetTest +[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.072 s -- in io.dropwizard.metrics5.jvm.JvmAttributeGaugeSetTest +[INFO] Running io.dropwizard.metrics5.jvm.ThreadDeadlockDetectorTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.009 s -- in io.dropwizard.metrics5.jvm.ThreadDeadlockDetectorTest +[INFO] Running io.dropwizard.metrics5.jvm.BufferPoolMetricSetTest +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.162 s -- in io.dropwizard.metrics5.jvm.BufferPoolMetricSetTest +[INFO] Running io.dropwizard.metrics5.jvm.ThreadDumpTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.010 s -- in io.dropwizard.metrics5.jvm.ThreadDumpTest +[INFO] Running io.dropwizard.metrics5.jvm.GarbageCollectorMetricSetTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.061 s -- in io.dropwizard.metrics5.jvm.GarbageCollectorMetricSetTest +[INFO] Running io.dropwizard.metrics5.jvm.ClassLoadingGaugeSetTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.043 s -- in io.dropwizard.metrics5.jvm.ClassLoadingGaugeSetTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 66, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- +[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] +[INFO] from metrics-healthchecks/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-healthchecks --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.health.AsyncHealthCheckDecoratorTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 15, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.608 s -- in io.dropwizard.metrics5.health.AsyncHealthCheckDecoratorTest +[INFO] Running io.dropwizard.metrics5.health.HealthCheckFilterTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 s -- in io.dropwizard.metrics5.health.HealthCheckFilterTest +[INFO] Running io.dropwizard.metrics5.health.SharedHealthCheckRegistriesTest +[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.065 s -- in io.dropwizard.metrics5.health.SharedHealthCheckRegistriesTest +[INFO] Running io.dropwizard.metrics5.health.HealthCheckTest +[INFO] Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.271 s -- in io.dropwizard.metrics5.health.HealthCheckTest +[INFO] Running io.dropwizard.metrics5.health.HealthCheckRegistryTest +[INFO] Tests run: 17, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.108 s -- in io.dropwizard.metrics5.health.HealthCheckRegistryTest +[INFO] Running io.dropwizard.metrics5.health.jvm.ThreadDeadlockHealthCheckTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.048 s -- in io.dropwizard.metrics5.health.jvm.ThreadDeadlockHealthCheckTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 59, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] +[INFO] from metrics-httpclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpclient --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java:[114,8] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.httpclient.InstrumentedHttpClientsTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.183 s -- in io.dropwizard.metrics5.httpclient.InstrumentedHttpClientsTest +[INFO] Running io.dropwizard.metrics5.httpclient.InstrumentedHttpClientConnectionManagerTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.187 s -- in io.dropwizard.metrics5.httpclient.InstrumentedHttpClientConnectionManagerTest +[INFO] Running io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategiesTest +[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 s -- in io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategiesTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- +[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] +[INFO] from metrics-httpclient5/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpclient5 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[14,40] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[15,40] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[16,37] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[30,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[31,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[32,37] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[33,38] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[96,21] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[160,12] [deprecation] DefaultHttpClientConnectionOperator(Lookup,SchemePortResolver,DnsResolver) in DefaultHttpClientConnectionOperator has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java:[49,4] [deprecation] HttpRequestExecutor(Timeout,ConnectionReuseStrategy,Http1StreamListener) in HttpRequestExecutor has been deprecated +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.httpclient5.InstrumentedHttpClientsTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.411 s -- in io.dropwizard.metrics5.httpclient5.InstrumentedHttpClientsTest +[INFO] Running io.dropwizard.metrics5.httpclient5.InstrumentedHttpClientConnectionManagerTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.206 s -- in io.dropwizard.metrics5.httpclient5.InstrumentedHttpClientConnectionManagerTest +[INFO] Running io.dropwizard.metrics5.httpclient5.InstrumentedHttpAsyncClientsTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.550 s -- in io.dropwizard.metrics5.httpclient5.InstrumentedHttpAsyncClientsTest +[INFO] Running io.dropwizard.metrics5.httpclient5.InstrumentedAsyncClientConnectionManagerTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in io.dropwizard.metrics5.httpclient5.InstrumentedAsyncClientConnectionManagerTest +[INFO] Running io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategiesTest +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 s -- in io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategiesTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 17, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- +[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] +[INFO] from metrics-httpasyncclient/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpasyncclient --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java:[40,8] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.httpasyncclient.InstrumentedHttpClientsTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.927 s -- in io.dropwizard.metrics5.httpasyncclient.InstrumentedHttpClientsTest +[INFO] Running io.dropwizard.metrics5.httpasyncclient.InstrumentedHttpClientsTimerTest +[WARNING] Tests run: 3, Failures: 0, Errors: 0, Skipped: 3, Time elapsed: 0.001 s -- in io.dropwizard.metrics5.httpasyncclient.InstrumentedHttpClientsTimerTest +[INFO] +[INFO] Results: +[INFO] +[WARNING] Tests run: 4, Failures: 0, Errors: 0, Skipped: 3 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] +[INFO] from metrics-jakarta-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlet --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.servlet.InstrumentedFilterContextListenerTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.523 s -- in io.dropwizard.metrics5.servlet.InstrumentedFilterContextListenerTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- +[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] +[INFO] from metrics-jakarta-servlet6/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlet6 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.servlet6.InstrumentedFilterContextListenerTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.522 s -- in io.dropwizard.metrics5.servlet6.InstrumentedFilterContextListenerTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- +[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] +[INFO] from metrics-json/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-json --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java:[189,31] [serial] non-transient instance field of a serializable class declared with a non-serializable type +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.json.MetricsModuleTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.168 s -- in io.dropwizard.metrics5.json.MetricsModuleTest +[INFO] Running io.dropwizard.metrics5.json.HealthCheckModuleTest +[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.069 s -- in io.dropwizard.metrics5.json.HealthCheckModuleTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 13, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- +[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] +[INFO] from metrics-jetty11/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty11 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.jetty11.InstrumentedConnectionFactoryTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.029 s -- in io.dropwizard.metrics5.jetty11.InstrumentedConnectionFactoryTest +[INFO] Running io.dropwizard.metrics5.jetty11.InstrumentedHandlerTest +[WARNING] Tests run: 7, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.252 s -- in io.dropwizard.metrics5.jetty11.InstrumentedHandlerTest +[INFO] Running io.dropwizard.metrics5.jetty11.InstrumentedQueuedThreadPoolTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.014 s -- in io.dropwizard.metrics5.jetty11.InstrumentedQueuedThreadPoolTest +[INFO] Running io.dropwizard.metrics5.jetty11.InstrumentedHttpChannelListenerTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.454 s -- in io.dropwizard.metrics5.jetty11.InstrumentedHttpChannelListenerTest +[INFO] +[INFO] Results: +[INFO] +[WARNING] Tests run: 14, Failures: 0, Errors: 0, Skipped: 1 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- +[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] +[INFO] from metrics-jakarta-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlets --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.servlets.MetricsServletContextListenerTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.667 s -- in io.dropwizard.metrics5.servlets.MetricsServletContextListenerTest +[INFO] Running io.dropwizard.metrics5.servlets.HealthCheckServletTest +[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.359 s -- in io.dropwizard.metrics5.servlets.HealthCheckServletTest +[INFO] Running io.dropwizard.metrics5.servlets.ThreadDumpServletTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.072 s -- in io.dropwizard.metrics5.servlets.ThreadDumpServletTest +[INFO] Running io.dropwizard.metrics5.servlets.CpuProfileServletTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.032 s -- in io.dropwizard.metrics5.servlets.CpuProfileServletTest +[INFO] Running io.dropwizard.metrics5.servlets.AdminServletExclusionTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 s -- in io.dropwizard.metrics5.servlets.AdminServletExclusionTest +[INFO] Running io.dropwizard.metrics5.servlets.MetricsServletTest +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.150 s -- in io.dropwizard.metrics5.servlets.MetricsServletTest +[INFO] Running io.dropwizard.metrics5.servlets.PingServletTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 s -- in io.dropwizard.metrics5.servlets.PingServletTest +[INFO] Running io.dropwizard.metrics5.servlets.AdminServletTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in io.dropwizard.metrics5.servlets.AdminServletTest +[INFO] Running io.dropwizard.metrics5.servlets.AdminServletUriTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in io.dropwizard.metrics5.servlets.AdminServletUriTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 33, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- +[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] +[INFO] from metrics-jcache/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jcache --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running JCacheGaugeSetTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.112 s -- in JCacheGaugeSetTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- +[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] +[INFO] from metrics-jdbi3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jdbi3 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.525 s -- in io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest +[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.BasicSqlNameStrategyTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in io.dropwizard.metrics5.jdbi3.strategies.BasicSqlNameStrategyTest +[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.NaiveNameStrategyTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.012 s -- in io.dropwizard.metrics5.jdbi3.strategies.NaiveNameStrategyTest +[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.SmartNameStrategyTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.062 s -- in io.dropwizard.metrics5.jdbi3.strategies.SmartNameStrategyTest +[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.InstrumentedSqlLoggerTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.306 s -- in io.dropwizard.metrics5.jdbi3.strategies.InstrumentedSqlLoggerTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 15, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- +[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] +[INFO] from metrics-jersey2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey2 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsJerseyTest +[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.543 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsTimedPerClassJerseyTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.108 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsTimedPerClassJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey2.SingletonFilterMetricsJerseyTest +[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.417 s -- in io.dropwizard.metrics5.jersey2.SingletonFilterMetricsJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsMeteredPerClassJerseyTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.074 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsMeteredPerClassJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsExceptionMeteredPerClassJerseyTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.081 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsExceptionMeteredPerClassJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey2.CustomReservoirImplementationTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 s -- in io.dropwizard.metrics5.jersey2.CustomReservoirImplementationTest +[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsResponseMeteredPerClassJerseyTest +[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.242 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsResponseMeteredPerClassJerseyTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 28, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- +[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] +[INFO] from metrics-jersey3/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey3 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsJerseyTest +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.630 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsTimedPerClassJerseyTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.094 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsTimedPerClassJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey3.SingletonFilterMetricsJerseyTest +[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.367 s -- in io.dropwizard.metrics5.jersey3.SingletonFilterMetricsJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsMeteredPerClassJerseyTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.078 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsMeteredPerClassJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsExceptionMeteredPerClassJerseyTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.074 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsExceptionMeteredPerClassJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey3.CustomReservoirImplementationTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 s -- in io.dropwizard.metrics5.jersey3.CustomReservoirImplementationTest +[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsResponseMeteredPerClassJerseyTest +[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.216 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsResponseMeteredPerClassJerseyTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 30, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- +[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] +[INFO] from metrics-jersey31/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey31 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsJerseyTest +[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.924 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsTimedPerClassJerseyTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.103 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsTimedPerClassJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey31.SingletonFilterMetricsJerseyTest +[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.376 s -- in io.dropwizard.metrics5.jersey31.SingletonFilterMetricsJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsMeteredPerClassJerseyTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.069 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsMeteredPerClassJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsExceptionMeteredPerClassJerseyTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.077 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsExceptionMeteredPerClassJerseyTest +[INFO] Running io.dropwizard.metrics5.jersey31.CustomReservoirImplementationTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.044 s -- in io.dropwizard.metrics5.jersey31.CustomReservoirImplementationTest +[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsResponseMeteredPerClassJerseyTest +[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.215 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsResponseMeteredPerClassJerseyTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 31, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- +[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] +[INFO] from metrics-jetty10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty10 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.jetty10.InstrumentedConnectionFactoryTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.053 s -- in io.dropwizard.metrics5.jetty10.InstrumentedConnectionFactoryTest +[INFO] Running io.dropwizard.metrics5.jetty10.InstrumentedHandlerTest +[WARNING] Tests run: 7, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.255 s -- in io.dropwizard.metrics5.jetty10.InstrumentedHandlerTest +[INFO] Running io.dropwizard.metrics5.jetty10.InstrumentedQueuedThreadPoolTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.016 s -- in io.dropwizard.metrics5.jetty10.InstrumentedQueuedThreadPoolTest +[INFO] Running io.dropwizard.metrics5.jetty10.InstrumentedHttpChannelListenerTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.468 s -- in io.dropwizard.metrics5.jetty10.InstrumentedHttpChannelListenerTest +[INFO] +[INFO] Results: +[INFO] +[WARNING] Tests run: 14, Failures: 0, Errors: 0, Skipped: 1 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- +[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] +[INFO] from metrics-log4j2/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-log4j2 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- +[INFO] Copying 1 resource from src/test/resources to target/test-classes +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.log4j2.InstrumentedAppenderTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.721 s -- in io.dropwizard.metrics5.log4j2.InstrumentedAppenderTest +[INFO] Running io.dropwizard.metrics5.log4j2.InstrumentedAppenderConfigTest +2024-11-18T12:07:39.193984674Z main INFO Starting LoggerContext[name=18b4aac2] with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... +2024-11-18T12:07:39.200922446Z main WARN The use of package scanning to locate Log4j plugins is deprecated. +Please remove the `packages` attribute from your configuration file. +See https://logging.apache.org/log4j/2.x/faq.html#package-scanning for details. +2024-11-18T12:07:39.207876369Z main WARN Some custom `Core` Log4j plugins are not properly registered: + io.dropwizard.metrics5.log4j2.InstrumentedAppender +Please consider reporting this to the maintainers of these plugins. +See https://logging.apache.org/log4j/2.x/manual/plugins.html#plugin-registry for details. +2024-11-18T12:07:39.252201564Z main INFO Starting configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... +2024-11-18T12:07:39.252463966Z main INFO Start watching for changes to stream (376 bytes, unknown location) every 0 seconds +2024-11-18T12:07:39.253074854Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] started. +2024-11-18T12:07:39.254125924Z main INFO Stopping configuration org.apache.logging.log4j.core.config.DefaultConfiguration@ac4915e... +2024-11-18T12:07:39.254564734Z main INFO Configuration org.apache.logging.log4j.core.config.DefaultConfiguration@ac4915e stopped. +2024-11-18T12:07:39.258930312Z main INFO LoggerContext[name=18b4aac2] started with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]. +2024-11-18T12:07:39.273527830Z main INFO Stopping configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... +2024-11-18T12:07:39.273749982Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] stopped. +2024-11-18T12:07:39.281549911Z main INFO Starting LoggerContext[name=18b4aac2] with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... +2024-11-18T12:07:39.281853632Z main WARN The use of package scanning to locate Log4j plugins is deprecated. +Please remove the `packages` attribute from your configuration file. +See https://logging.apache.org/log4j/2.x/faq.html#package-scanning for details. +2024-11-18T12:07:39.282118934Z main WARN Some custom `Core` Log4j plugins are not properly registered: + io.dropwizard.metrics5.log4j2.InstrumentedAppender +Please consider reporting this to the maintainers of these plugins. +See https://logging.apache.org/log4j/2.x/manual/plugins.html#plugin-registry for details. +2024-11-18T12:07:39.283482926Z main INFO Starting configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... +2024-11-18T12:07:39.283620004Z main INFO Start watching for changes to stream (376 bytes, unknown location) every 0 seconds +2024-11-18T12:07:39.283897571Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] started. +2024-11-18T12:07:39.284115452Z main INFO Stopping configuration org.apache.logging.log4j.core.config.DefaultConfiguration@5086623f... +2024-11-18T12:07:39.284280232Z main INFO Configuration org.apache.logging.log4j.core.config.DefaultConfiguration@5086623f stopped. +2024-11-18T12:07:39.284468124Z main INFO LoggerContext[name=18b4aac2] started with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]. +2024-11-18T12:07:39.285252313Z main INFO Stopping configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... +2024-11-18T12:07:39.285427352Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] stopped. +2024-11-18T12:07:39.292498164Z main INFO Starting LoggerContext[name=18b4aac2] with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... +2024-11-18T12:07:39.292822040Z main WARN The use of package scanning to locate Log4j plugins is deprecated. +Please remove the `packages` attribute from your configuration file. +See https://logging.apache.org/log4j/2.x/faq.html#package-scanning for details. +2024-11-18T12:07:39.293143105Z main WARN Some custom `Core` Log4j plugins are not properly registered: + io.dropwizard.metrics5.log4j2.InstrumentedAppender +Please consider reporting this to the maintainers of these plugins. +See https://logging.apache.org/log4j/2.x/manual/plugins.html#plugin-registry for details. +2024-11-18T12:07:39.294793189Z main INFO Starting configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... +2024-11-18T12:07:39.294953661Z main INFO Start watching for changes to stream (376 bytes, unknown location) every 0 seconds +2024-11-18T12:07:39.295337107Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] started. +2024-11-18T12:07:39.295497681Z main INFO Stopping configuration org.apache.logging.log4j.core.config.DefaultConfiguration@7eae55... +2024-11-18T12:07:39.295668975Z main INFO Configuration org.apache.logging.log4j.core.config.DefaultConfiguration@7eae55 stopped. +2024-11-18T12:07:39.295909868Z main INFO LoggerContext[name=18b4aac2] started with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]. +2024-11-18T12:07:39.296699991Z main INFO Stopping configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... +2024-11-18T12:07:39.296886682Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] stopped. +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.633 s -- in io.dropwizard.metrics5.log4j2.InstrumentedAppenderConfigTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- +[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] +[INFO] from metrics-logback13/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback13 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics.logback13.InstrumentedAppenderTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.881 s -- in io.dropwizard.metrics.logback13.InstrumentedAppenderTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- +[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] +[INFO] from metrics-logback14/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback14 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics.logback14.InstrumentedAppenderTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.666 s -- in io.dropwizard.metrics.logback14.InstrumentedAppenderTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- +[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] +[INFO] from metrics-logback15/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback15 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.logback15.InstrumentedAppenderTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.605 s -- in io.dropwizard.metrics5.logback15.InstrumentedAppenderTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- +[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] +[INFO] from metrics-servlet/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-servlet --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.servlet.InstrumentedFilterContextListenerTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.546 s -- in io.dropwizard.metrics5.servlet.InstrumentedFilterContextListenerTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- +[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] +[INFO] from metrics-servlets/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-servlets --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 10 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone + (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.servlets.MetricsServletContextListenerTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.524 s -- in io.dropwizard.metrics5.servlets.MetricsServletContextListenerTest +[INFO] Running io.dropwizard.metrics5.servlets.HealthCheckServletTest +[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.360 s -- in io.dropwizard.metrics5.servlets.HealthCheckServletTest +[INFO] Running io.dropwizard.metrics5.servlets.ThreadDumpServletTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.064 s -- in io.dropwizard.metrics5.servlets.ThreadDumpServletTest +[INFO] Running io.dropwizard.metrics5.servlets.CpuProfileServletTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.050 s -- in io.dropwizard.metrics5.servlets.CpuProfileServletTest +[INFO] Running io.dropwizard.metrics5.servlets.MetricsServletTest +[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.159 s -- in io.dropwizard.metrics5.servlets.MetricsServletTest +[INFO] Running io.dropwizard.metrics5.servlets.PingServletTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.024 s -- in io.dropwizard.metrics5.servlets.PingServletTest +[INFO] Running io.dropwizard.metrics5.servlets.AdminServletTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.009 s -- in io.dropwizard.metrics5.servlets.AdminServletTest +[INFO] Running io.dropwizard.metrics5.servlets.AdminServletUriTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s -- in io.dropwizard.metrics5.servlets.AdminServletUriTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 32, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- +[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] +[INFO] from metrics-jcstress/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jcstress --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- +[INFO] No tests to run. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22.jar +[INFO] +[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- +[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. +[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. +[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. +[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. +[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. +[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. +[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. +[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. +[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. +[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. +[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. +[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. +[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. +[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml +[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. +[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE +[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: +[WARNING] - META-INF.versions.9.module-info +[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/LICENSE.txt +[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: +[WARNING] - META-INF/MANIFEST.MF +[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: +[WARNING] - META-INF/AL2.0 +[WARNING] - META-INF/LGPL2.1 +[WARNING] maven-shade-plugin has detected that some files are +[WARNING] present in two or more JARs. When this happens, only one +[WARNING] single version of the file is copied to the uber jar. +[WARNING] Usually this is not harmful and you can skip these warnings, +[WARNING] otherwise try to manually exclude artifacts based on +[WARNING] mvn dependency:tree -Ddetail=true and the above output. +[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ +[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar +[INFO] +[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- +[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] +[INFO] from metrics-jmx/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jmx --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics5.jmx.DefaultObjectNameFactoryTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.231 s -- in io.dropwizard.metrics5.jmx.DefaultObjectNameFactoryTest +[INFO] Running io.dropwizard.metrics5.jmx.JmxReporterTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.994 s -- in io.dropwizard.metrics5.jmx.JmxReporterTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ +[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] +[INFO] from metrics-legacy-adapter/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-legacy-adapter --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 36 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,49] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,9] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[108,27] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[112,27] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 24 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[50,4] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[367,22] [rawtypes] found raw type: Gauge + missing type arguments for generic class Gauge + where T is a type-variable: + T extends Object declared in interface Gauge +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running com.codahale.metrics.GaugeTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.162 s -- in com.codahale.metrics.GaugeTest +[INFO] Running com.codahale.metrics.SlidingWindowReservoirTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.010 s -- in com.codahale.metrics.SlidingWindowReservoirTest +[INFO] Running com.codahale.metrics.InstrumentedScheduledExecutorServiceTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.169 s -- in com.codahale.metrics.InstrumentedScheduledExecutorServiceTest +[INFO] Running com.codahale.metrics.ExponentiallyDecayingReservoirTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 s -- in com.codahale.metrics.ExponentiallyDecayingReservoirTest +[INFO] Running com.codahale.metrics.HistogramTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 s -- in com.codahale.metrics.HistogramTest +[INFO] Running com.codahale.metrics.ScheduledReporterTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.059 s -- in com.codahale.metrics.ScheduledReporterTest +[INFO] Running com.codahale.metrics.ConsoleReporterTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.059 s -- in com.codahale.metrics.ConsoleReporterTest +[INFO] Running com.codahale.metrics.RatioGaugeTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in com.codahale.metrics.RatioGaugeTest +[INFO] Running com.codahale.metrics.SnapshotTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 s -- in com.codahale.metrics.SnapshotTest +[INFO] Running com.codahale.metrics.ClockTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in com.codahale.metrics.ClockTest +[INFO] Running com.codahale.metrics.SlidingTimeWindowReservoirTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 s -- in com.codahale.metrics.SlidingTimeWindowReservoirTest +[INFO] Running com.codahale.metrics.TimerTest +[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.013 s -- in com.codahale.metrics.TimerTest +[INFO] Running com.codahale.metrics.Slf4jReporterTest +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.432 s -- in com.codahale.metrics.Slf4jReporterTest +[INFO] Running com.codahale.metrics.SharedMetricRegistriesTest +[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.033 s -- in com.codahale.metrics.SharedMetricRegistriesTest +[INFO] Running com.codahale.metrics.UniformReservoirTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in com.codahale.metrics.UniformReservoirTest +[INFO] Running com.codahale.metrics.InstrumentedThreadFactoryTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 s -- in com.codahale.metrics.InstrumentedThreadFactoryTest +[INFO] Running com.codahale.metrics.CounterTest +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in com.codahale.metrics.CounterTest +[INFO] Running com.codahale.metrics.MeterTest +[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in com.codahale.metrics.MeterTest +[INFO] Running com.codahale.metrics.DerivativeGaugeTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 s -- in com.codahale.metrics.DerivativeGaugeTest +[INFO] Running com.codahale.metrics.InstrumentedExecutorServiceTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s -- in com.codahale.metrics.InstrumentedExecutorServiceTest +[INFO] Running com.codahale.metrics.FixedNameCsvFileProviderTest +[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in com.codahale.metrics.FixedNameCsvFileProviderTest +[INFO] Running com.codahale.metrics.SlidingTimeWindowArrayReservoirTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in com.codahale.metrics.SlidingTimeWindowArrayReservoirTest +[INFO] Running com.codahale.metrics.CachedGaugeTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in com.codahale.metrics.CachedGaugeTest +[INFO] Running com.codahale.metrics.MetricRegistryTest +[INFO] Tests run: 32, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.160 s -- in com.codahale.metrics.MetricRegistryTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 83, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/metrics-legacy-adapter-5.0.0-rc22.jar +[INFO] +[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- +[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] +[INFO] from metrics-legacy-adapter-healthchecks/pom.xml +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-legacy-adapter-healthchecks --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- +[INFO] No sources to compile +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- +[INFO] No tests to run. +[INFO] +[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- +[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/metrics-legacy-adapter-healthchecks-5.0.0-rc22.jar +[INFO] +[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] +[INFO] from metrics-jetty12/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty12 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' +/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics.jetty12.InstrumentedConnectionFactoryTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.040 s -- in io.dropwizard.metrics.jetty12.InstrumentedConnectionFactoryTest +[INFO] Running io.dropwizard.metrics.jetty12.InstrumentedQueuedThreadPoolTest +[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.045 s -- in io.dropwizard.metrics.jetty12.InstrumentedQueuedThreadPoolTest +[INFO] +[INFO] Results: +[INFO] +[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF +[INFO] +[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- +[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] +[INFO] from metrics-jetty12-ee10/pom.xml +[INFO] -------------------------------[ bundle ]------------------------------- +[INFO] +[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty12-ee10 --- +[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target +[INFO] +[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- +[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed +[INFO] +[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- +[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec +[INFO] +[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources +[INFO] +[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- +[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources +[INFO] +[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- +[INFO] Recompiling the module because of changed dependency. +[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes +[WARNING] [options] source value 8 is obsolete and will be removed in a future release +[WARNING] [options] target value 8 is obsolete and will be removed in a future release +[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. +[INFO] +[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- +[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider +[INFO] +[INFO] ------------------------------------------------------- +[INFO] T E S T S +[INFO] ------------------------------------------------------- +[INFO] Running io.dropwizard.metrics.jetty12.ee10.InstrumentedEE10HandlerTest +[WARNING] Tests run: 7, Failures: 0, Errors: 0, Skipped: 2, Time elapsed: 1.101 s -- in io.dropwizard.metrics.jetty12.ee10.InstrumentedEE10HandlerTest +[INFO] +[INFO] Results: +[INFO] +[WARNING] Tests run: 7, Failures: 0, Errors: 0, Skipped: 2 +[INFO] +[INFO] +[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- +[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] +[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar +[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF +[INFO] ------------------------------------------------------------------------ +[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: +[INFO] +[INFO] Metrics5 Parent .................................... SUCCESS [ 0.301 s] +[INFO] Metrics5 Documentation ............................. SUCCESS [ 0.858 s] +[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.010 s] +[INFO] Annotations for Metrics5 ........................... SUCCESS [ 3.433 s] +[INFO] Metrics5 Core ...................................... SUCCESS [ 43.065 s] +[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 4.517 s] +[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 6.998 s] +[INFO] Metrics Integration for Collectd ................... SUCCESS [ 13.792 s] +[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 8.234 s] +[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 23.915 s] +[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 11.740 s] +[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 12.421 s] +[INFO] Metrics5 Health Checks ............................. SUCCESS [ 12.220 s] +[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 10.439 s] +[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 11.712 s] +[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 9.507 s] +[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 8.534 s] +[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 8.044 s] +[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 10.017 s] +[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 11.538 s] +[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 15.820 s] +[INFO] Metrics Integration for JCache ..................... SUCCESS [ 7.572 s] +[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 9.939 s] +[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 12.822 s] +[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 12.505 s] +[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 12.638 s] +[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 11.402 s] +[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 9.544 s] +[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 8.491 s] +[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 8.182 s] +[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 8.366 s] +[INFO] Metrics Integration for Servlets ................... SUCCESS [ 7.982 s] +[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 16.075 s] +[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 3.657 s] +[INFO] Metrics Integration with JMX ....................... SUCCESS [ 11.060 s] +[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 15.265 s] +[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 3.360 s] +[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 9.505 s] +[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 8.916 s] +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 06:45 min +[INFO] Finished at: 2024-11-18T13:09:20+01:00 +[INFO] ------------------------------------------------------------------------ +Inspecting changes... +Inspecting emitted warnings... From 3d557c0e661248f070ed57b5793fc7146ed3ca02 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Mon, 18 Nov 2024 16:11:22 +0100 Subject: [PATCH 36/59] Fix integration test setup --- .github/workflows/run-integration-tests.yml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index e586031507..61f15ed552 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -15,13 +15,13 @@ permissions: contents: read jobs: run-integration-tests: + name: On-demand integration test + if: | + github.event.issue.pull_request && contains(github.event.comment.body, '/integration-tests') runs-on: ubuntu-24.04 - # if: github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') - # XXX: Configure permissions. strategy: matrix: - integration-test: [ "metrics", "checkstyle" ] - name: On-demand integration test + integration-test: [ "checkstyle", "metrics" ] steps: - name: Install Harden-Runner uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1 @@ -40,7 +40,6 @@ jobs: - name: Check out code and set up JDK and Maven uses: s4u/setup-maven-action@382542f77617f34e56bf83868920a4d45b7451e7 # v1.16.0 with: - # checkout-ref: "refs/pull/894/head" checkout-ref: "refs/pull/${{ github.event.issue.number }}/head" java-version: 17.0.13 java-distribution: temurin From 9359441712dbf6bccc3e0c4910884c562c4805fd Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Mon, 18 Nov 2024 16:19:47 +0100 Subject: [PATCH 37/59] Cleanup --- .github/workflows/run-integration-tests.yml | 2 +- integration-tests/checkstyle.sh | 4 ++-- integration-tests/run-integration-test.sh | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 61f15ed552..fb60e80068 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -17,7 +17,7 @@ jobs: run-integration-tests: name: On-demand integration test if: | - github.event.issue.pull_request && contains(github.event.comment.body, '/integration-tests') + github.event.issue.pull_request && contains(github.event.comment.body, '/integration-tests') runs-on: ubuntu-24.04 strategy: matrix: diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index 3825904bc9..42ddc4bcd6 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -8,8 +8,8 @@ repository='https://github.com/checkstyle/checkstyle.git' revision='checkstyle-10.14.0' # XXX: Configure Renovate to manage the AssertJ version declared here. additional_build_flags='-Perror-prone-compile,error-prone-test-compile -Dassertj.version=3.24.2 -Dmaven.compiler.failOnError=true' -additional_source_directories="${project.basedir}${file.separator}src${file.separator}it${file.separator}java,${project.basedir}${file.separator}src${file.separator}xdocs-examples${file.separator}java" -shared_error_prone_flags="-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*" +additional_source_directories='${project.basedir}${file.separator}src${file.separator}it${file.separator}java,${project.basedir}${file.separator}src${file.separator}xdocs-examples${file.separator}java' +shared_error_prone_flags='-XepExcludedPaths:(\Q${project.basedir}${file.separator}src${file.separator}\E(it|test|xdocs-examples)\Q${file.separator}resources\E|\Q${project.build.directory}${file.separator}\E).*' patch_error_prone_flags='' validation_error_prone_flags='' # Validation skips some tests: diff --git a/integration-tests/run-integration-test.sh b/integration-tests/run-integration-test.sh index ccd49db43e..725dd46f3e 100755 --- a/integration-tests/run-integration-test.sh +++ b/integration-tests/run-integration-test.sh @@ -164,7 +164,6 @@ function apply_patch() { } apply_patch '' - # Run one more full build and log the output. # # By also running the tests, we validate that the (majority of) applied changes From 1d77a3ad106b45dfa108e39574c052e7c341f851 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Mon, 18 Nov 2024 19:14:56 +0100 Subject: [PATCH 38/59] Dont need this --- .github/workflows/run-integration-tests.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index fb60e80068..37e6a0aa55 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -7,8 +7,6 @@ # https://docs.github.com/en/actions/learn-github-actions/expressions#example-returning-a-json-object name: "Integration tests" on: - pull_request: - branches: [ master ] issue_comment: types: [ created ] permissions: From b5c51f5d4e79478908b1e65d6a010751cb76e954 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 19 Nov 2024 09:05:36 +0100 Subject: [PATCH 39/59] Forgot these --- integration-tests/run-integration-test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/run-integration-test.sh b/integration-tests/run-integration-test.sh index 725dd46f3e..5105c9451b 100755 --- a/integration-tests/run-integration-test.sh +++ b/integration-tests/run-integration-test.sh @@ -12,7 +12,7 @@ integration_test_root="$(cd "$(dirname -- "${0}")" && pwd)" error_prone_support_root="${integration_test_root}/.." repos_root="${integration_test_root}/.repos" -if [ "${#}" -lt 9 ] || [ "${#}" -gt 11 ] || ([ "${#}" = 11 ] && [ "${10:---sync}" != '--sync' ]); then +if [ "${#}" -lt 10 ] || [ "${#}" -gt 12 ] || ([ "${#}" = 12 ] && [ "${11:---sync}" != '--sync' ]); then >&2 echo "Usage: $(basename "${0}") [--sync] []" exit 1 fi From 13d84c363545a70ae854e500ce98c931ddfcd4fe Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 19 Nov 2024 09:09:59 +0100 Subject: [PATCH 40/59] Drop file --- simple-metrics.txt | 26775 ------------------------------------------- 1 file changed, 26775 deletions(-) delete mode 100644 simple-metrics.txt diff --git a/simple-metrics.txt b/simple-metrics.txt deleted file mode 100644 index 4c9b4099b5..0000000000 --- a/simple-metrics.txt +++ /dev/null @@ -1,26775 +0,0 @@ -Shared build flags: - -Derror-prone.version=2.35.1 - -Derror-prone-support.version=0.19.2-SNAPSHOT - -DadditionalSourceDirectories= - - -Error Prone patch flags: -XepExcludedPaths:.*/target/generated-sources/.* -XepPatchLocation:IN_PLACE -XepPatchChecks:AmbiguousJsonCreator,AssertJIsNull,AutowiredConstructor,CanonicalAnnotationSyntax,CanonicalClassNameUsage,ClassCastLambdaUsage,CollectorMutability,ConstantNaming,DirectReturn,EmptyMethod,EmptyMonoZip,ExplicitEnumOrdering,FluxFlatMapUsage,FluxImplicitBlock,FormatStringConcatenation,IdentityConversion,ImmutablesSortedSetComparator,IsInstanceLambdaUsage,JUnitClassModifiers,JUnitMethodDeclaration,JUnitNullaryParameterizedTestDeclaration,JUnitValueSource,LexicographicalAnnotationAttributeListing,LexicographicalAnnotationListing,MockitoMockClassReference,MockitoStubbing,MongoDBTextFilterUsage,NestedOptionals,NestedPublishers,NonEmptyMono,NonStaticImport,OptionalOrElseGet,PrimitiveComparison,RedundantStringConversion,RequestMappingAnnotation,RequestParamType,Slf4jLogStatement,Slf4jLoggerDeclaration,SpringMvcAnnotation,StaticImport,StringJoin,TimeZoneUsage,Refaster -Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).* -Error Prone validation flags: -XepExcludedPaths:.*/target/generated-sources/.* -XepDisableAllChecks -Xep:AmbiguousJsonCreator:WARN -Xep:AssertJIsNull:WARN -Xep:AutowiredConstructor:WARN -Xep:CanonicalAnnotationSyntax:WARN -Xep:CanonicalClassNameUsage:WARN -Xep:ClassCastLambdaUsage:WARN -Xep:CollectorMutability:WARN -Xep:ConstantNaming:WARN -Xep:DirectReturn:WARN -Xep:EmptyMethod:WARN -Xep:EmptyMonoZip:WARN -Xep:ExplicitEnumOrdering:WARN -Xep:FluxFlatMapUsage:WARN -Xep:FluxImplicitBlock:WARN -Xep:FormatStringConcatenation:WARN -Xep:IdentityConversion:WARN -Xep:ImmutablesSortedSetComparator:WARN -Xep:IsInstanceLambdaUsage:WARN -Xep:JUnitClassModifiers:WARN -Xep:JUnitMethodDeclaration:WARN -Xep:JUnitNullaryParameterizedTestDeclaration:WARN -Xep:JUnitValueSource:WARN -Xep:LexicographicalAnnotationAttributeListing:WARN -Xep:LexicographicalAnnotationListing:WARN -Xep:MockitoMockClassReference:WARN -Xep:MockitoStubbing:WARN -Xep:MongoDBTextFilterUsage:WARN -Xep:NestedOptionals:WARN -Xep:NestedPublishers:WARN -Xep:NonEmptyMono:WARN -Xep:NonStaticImport:WARN -Xep:OptionalOrElseGet:WARN -Xep:PrimitiveComparison:WARN -Xep:RedundantStringConversion:WARN -Xep:RequestMappingAnnotation:WARN -Xep:RequestParamType:WARN -Xep:Slf4jLogStatement:WARN -Xep:Slf4jLoggerDeclaration:WARN -Xep:SpringMvcAnnotation:WARN -Xep:StaticImport:WARN -Xep:StringJoin:WARN -Xep:TimeZoneUsage:WARN -Xep:Refaster:WARN -~/repos/error-prone-support/integration-tests/.repos/metrics ~/repos/error-prone-support -rick.ossendrijver@gmail.com -Rick Ossendrijver -[detached HEAD d508418] dependency: Introduce Error Prone Support - 5 files changed, 48 insertions(+), 4 deletions(-) -[INFO] Scanning for projects... -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Build Order: -[INFO] -[INFO] Metrics5 Parent [pom] -[INFO] Metrics5 Documentation [jar] -[INFO] Metrics5 BOM [pom] -[INFO] Annotations for Metrics5 [bundle] -[INFO] Metrics5 Core [bundle] -[INFO] Benchmarks for Metrics5 [jar] -[INFO] Metrics Integration for Caffeine 3.x [bundle] -[INFO] Metrics Integration for Collectd [bundle] -[INFO] Metrics Integration for Ehcache [bundle] -[INFO] Graphite Integration for Metrics5 [bundle] -[INFO] InfluxDB integration for Metrics5 [bundle] -[INFO] JVM Integration for Metrics5 [bundle] -[INFO] Metrics5 Health Checks [bundle] -[INFO] Metrics Integration for Apache HttpClient [bundle] -[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] -[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] -[INFO] Metrics Integration for Jakarta Servlets [bundle] -[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] -[INFO] Jackson Integration for Metrics5 [bundle] -[INFO] Metrics Integration for Jetty 11.x and higher [bundle] -[INFO] Metrics5 Utility Jakarta Servlets [bundle] -[INFO] Metrics Integration for JCache [bundle] -[INFO] Metrics Integration for JDBI3 [bundle] -[INFO] Metrics Integration for Jersey 2.x [bundle] -[INFO] Metrics Integration for Jersey 3.0.x [bundle] -[INFO] Metrics Integration for Jersey 3.1.x [bundle] -[INFO] Metrics Integration for Jetty 10.x and higher [bundle] -[INFO] Metrics Integration for Log4j 2.x [bundle] -[INFO] Metrics Integration for Logback 1.3.x [bundle] -[INFO] Metrics Integration for Logback 1.4.x [bundle] -[INFO] Metrics Integration for Logback 1.5.x [bundle] -[INFO] Metrics Integration for Servlets [bundle] -[INFO] Metrics5 Utility Servlets [bundle] -[INFO] Metrics5 JCStress tests [jar] -[INFO] Metrics Integration with JMX [bundle] -[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] -[INFO] Metrics Integration for Jetty 12.x and higher [bundle] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- -[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] -[INFO] from pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- -[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] -[INFO] from docs/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- -[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. -[info] Processed 0 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- -[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] -[INFO] from metrics-bom/pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- -[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] -[INFO] from metrics-annotation/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. -[info] Processed 9 files (9 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- -[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] -[INFO] from metrics-core/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- -[info] Processed 87 files (87 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- -[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] -[INFO] from metrics-benchmarks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. -[info] Processed 5 files (5 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- -[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] -[INFO] from metrics-caffeine3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- -[info] Processed 2 files (2 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- -[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] -[INFO] from metrics-collectd/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- -[info] Processed 12 files (12 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- -[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] -[INFO] from metrics-ehcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- -[info] Processed 4 files (4 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- -[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] -[INFO] from metrics-graphite/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- -[info] Processed 13 files (13 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- -[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] -[INFO] from metrics-influxdb/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- -[info] Processed 8 files (8 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- -[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] -[INFO] from metrics-jvm/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- -[info] Processed 23 files (23 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- -[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] -[INFO] from metrics-healthchecks/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- -[info] Processed 14 files (14 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] -[INFO] from metrics-httpclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- -[info] Processed 8 files (8 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] -[INFO] from metrics-httpclient5/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- -[info] Processed 13 files (13 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- -[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] -[INFO] from metrics-httpasyncclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- -[info] Processed 5 files (5 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] -[INFO] from metrics-jakarta-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- -[info] Processed 4 files (4 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] -[INFO] from metrics-jakarta-servlet6/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- -[info] Processed 4 files (4 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- -[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] -[INFO] from metrics-json/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- -[info] Processed 4 files (4 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- -[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] -[INFO] from metrics-jetty11/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- -[info] Processed 8 files (8 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- -[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] -[INFO] from metrics-jakarta-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- -[info] Processed 17 files (17 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- -[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] -[INFO] from metrics-jcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- -[info] Processed 2 files (2 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- -[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] -[INFO] from metrics-jdbi3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- -[info] Processed 15 files (15 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- -[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] -[INFO] from metrics-jersey2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- -[info] Processed 24 files (24 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- -[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] -[INFO] from metrics-jersey3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- -[info] Processed 24 files (24 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- -[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] -[INFO] from metrics-jersey31/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- -[info] Processed 24 files (24 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- -[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] -[INFO] from metrics-jetty10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- -[info] Processed 8 files (8 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- -[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] -[INFO] from metrics-log4j2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- -[info] Processed 3 files (3 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- -[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] -[INFO] from metrics-logback13/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- -[info] Processed 2 files (2 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- -[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] -[INFO] from metrics-logback14/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- -[info] Processed 2 files (2 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- -[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] -[INFO] from metrics-logback15/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- -[info] Processed 2 files (2 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- -[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] -[INFO] from metrics-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- -[info] Processed 4 files (4 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- -[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] -[INFO] from metrics-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- -[info] Processed 16 files (16 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- -[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] -[INFO] from metrics-jcstress/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. -[info] Processed 3 files (3 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- -[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] -[INFO] from metrics-jmx/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- -[info] Processed 5 files (5 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ -[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] -[INFO] from metrics-legacy-adapter/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- -[info] Processed 60 files (60 reformatted). -[INFO] -[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- -[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] -[INFO] from metrics-legacy-adapter-healthchecks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. -[info] Processed 4 files (4 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] -[INFO] from metrics-jetty12/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- -[info] Processed 5 files (5 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] -[INFO] from metrics-jetty12-ee10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- -[info] Processed 2 files (2 reformatted). -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: -[INFO] -[INFO] Metrics5 Parent .................................... SUCCESS [ 0.130 s] -[INFO] Metrics5 Documentation ............................. SUCCESS [ 0.588 s] -[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.003 s] -[INFO] Annotations for Metrics5 ........................... SUCCESS [ 0.951 s] -[INFO] Metrics5 Core ...................................... SUCCESS [ 1.412 s] -[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 0.835 s] -[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 0.987 s] -[INFO] Metrics Integration for Collectd ................... SUCCESS [ 1.186 s] -[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 1.283 s] -[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 1.226 s] -[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 1.048 s] -[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 1.128 s] -[INFO] Metrics5 Health Checks ............................. SUCCESS [ 1.026 s] -[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 0.934 s] -[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 0.969 s] -[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 0.977 s] -[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 0.883 s] -[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 0.916 s] -[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 1.071 s] -[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 1.007 s] -[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 1.003 s] -[INFO] Metrics Integration for JCache ..................... SUCCESS [ 1.001 s] -[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 0.956 s] -[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 1.021 s] -[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 1.053 s] -[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 1.143 s] -[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 1.029 s] -[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 1.003 s] -[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 0.969 s] -[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 0.954 s] -[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 0.914 s] -[INFO] Metrics Integration for Servlets ................... SUCCESS [ 0.863 s] -[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 0.970 s] -[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 0.877 s] -[INFO] Metrics Integration with JMX ....................... SUCCESS [ 1.028 s] -[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 1.100 s] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 0.845 s] -[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 0.997 s] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 1.008 s] -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 38.095 s -[INFO] Finished at: 2024-11-18T12:45:04+01:00 -[INFO] ------------------------------------------------------------------------ -[detached HEAD b1e8ab8] minor: Reformat using Google Java Format - 445 files changed, 38272 insertions(+), 38032 deletions(-) -[INFO] Scanning for projects... -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Build Order: -[INFO] -[INFO] Metrics5 Parent [pom] -[INFO] Metrics5 Documentation [jar] -[INFO] Metrics5 BOM [pom] -[INFO] Annotations for Metrics5 [bundle] -[INFO] Metrics5 Core [bundle] -[INFO] Benchmarks for Metrics5 [jar] -[INFO] Metrics Integration for Caffeine 3.x [bundle] -[INFO] Metrics Integration for Collectd [bundle] -[INFO] Metrics Integration for Ehcache [bundle] -[INFO] Graphite Integration for Metrics5 [bundle] -[INFO] InfluxDB integration for Metrics5 [bundle] -[INFO] JVM Integration for Metrics5 [bundle] -[INFO] Metrics5 Health Checks [bundle] -[INFO] Metrics Integration for Apache HttpClient [bundle] -[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] -[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] -[INFO] Metrics Integration for Jakarta Servlets [bundle] -[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] -[INFO] Jackson Integration for Metrics5 [bundle] -[INFO] Metrics Integration for Jetty 11.x and higher [bundle] -[INFO] Metrics5 Utility Jakarta Servlets [bundle] -[INFO] Metrics Integration for JCache [bundle] -[INFO] Metrics Integration for JDBI3 [bundle] -[INFO] Metrics Integration for Jersey 2.x [bundle] -[INFO] Metrics Integration for Jersey 3.0.x [bundle] -[INFO] Metrics Integration for Jersey 3.1.x [bundle] -[INFO] Metrics Integration for Jetty 10.x and higher [bundle] -[INFO] Metrics Integration for Log4j 2.x [bundle] -[INFO] Metrics Integration for Logback 1.3.x [bundle] -[INFO] Metrics Integration for Logback 1.4.x [bundle] -[INFO] Metrics Integration for Logback 1.5.x [bundle] -[INFO] Metrics Integration for Servlets [bundle] -[INFO] Metrics5 Utility Servlets [bundle] -[INFO] Metrics5 JCStress tests [jar] -[INFO] Metrics Integration with JMX [bundle] -[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] -[INFO] Metrics Integration for Jetty 12.x and higher [bundle] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- -[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] -[INFO] from pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- -[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] -[INFO] from docs/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec -[INFO] -[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- -[INFO] -[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- -[INFO] Copying 72 resources from source to target/source -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- -[INFO] Copying 72 resources from source to target/classes -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ docs --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/docs-5.0.0-rc22.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- -[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. -[info] Processed 0 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- -[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] -[INFO] from metrics-bom/pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- -[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] -[INFO] from metrics-annotation/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- -[INFO] Recompiling the module because of changed source code. -[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. -[info] Processed 9 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- -[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] -[INFO] from metrics-core/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- -[INFO] Recompiling the module because of changed source code. -[INFO] Compiling 49 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java:[56,53] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'disabledMetricAttributes = ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java:[56,44] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'disabledMetricAttributes = emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[175,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(this.scheduledFuture == null, "Reporter already started");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[144,4] Note: [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#RequireNonNullWithMessageStatement) - Did you mean 'requireNonNull(registry, "registry == null");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[131,28] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'ImmutableSet.of());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[157,90] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'disabledMetricAttributes != null ? disabledMetricAttributes : ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[131,19] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'emptySet());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[157,81] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'disabledMetricAttributes != null ? disabledMetricAttributes : emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[188,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@Deprecated'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[52,27] [this-escape] possible 'this' escape before subclass is fully initialized -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[94,4] Note: [Refaster Rule] PreconditionsRules.RequireNonNullWithMessageStatement: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#RequireNonNullWithMessageStatement) - Did you mean 'requireNonNull(metric, "metric == null");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[256,45] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Histogram;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[662,45] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Histogram;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[216,43] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Counter;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[649,43] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Counter;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[296,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Meter;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[331,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Timer;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[369,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Gauge;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[675,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Meter;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[688,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Timer;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[702,41] Note: [Refaster Rule] ClassRules.Instanceof: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#Instanceof) - Did you mean 'return metric instanceof Gauge;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[433,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableSortedSet(new TreeSet<>(metrics.keySet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[458,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableSortedMap(timers);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[565,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableSortedMap(timers);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[630,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(metrics);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[97,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(pairs.length % 2 == 0, "Argument count must be even");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[204,36] Note: [Refaster Rule] MapEntryRules.MapEntryComparingByKey: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MapEntryRules#MapEntryComparingByKey) - Did you mean '.sorted(comparingByKey())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[67,35] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean '.filter(s -> !Strings.isNullOrEmpty(s))'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[20,76] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean 'private static final Map EMPTY_TAGS = ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[66,47] Note: [Refaster Rule] StreamRules.StreamOfArray: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StreamRules#StreamOfArray) - Did you mean 'Stream.concat(Stream.of(key), Arrays.stream(parts))'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[20,67] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'private static final Map EMPTY_TAGS = emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[36,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.key = requireNonNull(key);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[68,31] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(joining(SEPARATOR));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[204,26] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.sorted(comparing(Map.Entry::getKey))'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java:[206,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(sorted);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[182,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(CsvReporter.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java:[20,30] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention - (see https://error-prone.picnic.tech/bugpatterns/ConstantNaming) - Did you mean 'private static final double MAX_TICK_ZERO_TARGET = 0.0001;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java:[22,27] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention - (see https://error-prone.picnic.tech/bugpatterns/ConstantNaming) - Did you mean 'private static final int MAX_TICKS;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java:[67,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), quantile + " is not in [0..1]");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java:[38,32] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'Arrays.sort(copy, comparingLong(w -> w.value));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[238,6] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: " + value);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[44,6] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention - (see https://error-prone.picnic.tech/bugpatterns/ConstantNaming) - Did you mean 'STATE_UPDATER ='? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[56,58] [ConstantNaming] Constant variables should adhere to the `UPPER_SNAKE_CASE` naming convention - (see https://error-prone.picnic.tech/bugpatterns/ConstantNaming) - Did you mean 'private static final AtomicIntegerFieldUpdater COUNT_UPDATER ='? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[129,15] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'requireNonNull(newValues.pollFirstEntry(), "Expected an entry");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[257,37] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[263,26] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.clock = requireNonNull(value, "clock is required");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[239,31] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean 'return ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[633,33] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'return ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[639,33] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'return ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[645,33] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'return ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[161,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedSet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[167,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[173,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[179,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[185,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[191,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[197,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[203,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[209,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[215,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[221,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[239,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[633,24] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[639,24] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java:[645,24] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java:[87,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) - Did you mean 'checkState(metricRegistry != null, "Default registry name has not been set.");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java:[7] Note: [NonStaticImport] Member should not be statically imported - (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java:[10] Note: [NonStaticImport] Member should not be statically imported - (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java:[84,58] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'this.disabledMetricAttributes = ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java:[84,49] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.disabledMetricAttributes = emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java:[189,9] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return adder.longValue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java:[50,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), quantile + " is not in [0..1]");'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 38 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[125,6] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatWithFailMessageStringIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatWithFailMessageStringIsTrue) - Did you mean 'assertThat(futures.get(i).get()).withFailMessage("Future " + i + " failed").isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[18] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CachedGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[19,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(CachedGaugeTest.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ChunkedAssociativeLongArrayTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java:[10,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void trim() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java:[7,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ClassMetadataTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java:[9,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void parameterMetadataIsAvailable() throws NoSuchMethodException {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java:[14,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java:[16,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ClockTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ConsoleReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[26,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistry registry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[27,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[77,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[96,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[100,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[141,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[170,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[178,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[242,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[286,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[294,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[352,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java:[356,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java:[12,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(counter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CounterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[20,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CsvReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[23,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistry registry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[24,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[56,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[66,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[70,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[108,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[116,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[140,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void csvFileProviderIsUsed() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[141,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'CsvFileProvider fileProvider = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[180,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java:[202,88] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'Files.readAllBytes(new File(dataDirectory, filename).toPath()), UTF_8);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class DefaultSettableGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class DerivativeGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[20,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[24,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[28,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[32,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[36,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[40,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[44,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[48,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[52,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[56,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[60,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[64,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[68,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[72,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[76,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[89,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[93,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[97,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[101,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[105,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[109,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[113,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[117,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[121,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[125,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[129,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[133,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[137,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[141,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[145,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[158,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[162,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[166,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[170,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[174,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[178,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[182,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[186,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[190,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[194,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[198,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[202,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[206,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[210,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[214,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[16,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[85,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[154,56] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class EWMATest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java:[10,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ExponentialMovingAveragesTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java:[12,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void maxTicks() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java:[13,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java:[14,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ExponentiallyDecayingReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java:[45,34] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableList());' or '.collect(toCollection(ArrayList::new));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java:[45,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toList());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java:[11,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class FixedNameCsvFileProviderTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java:[22,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getFile() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java:[30,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getFileSanitize() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[16,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(histogram.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[17,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(histogram.getSum()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HistogramTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[11,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Reservoir reservoir = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java:[28,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedExecutorServiceTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[24,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG ='? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[118,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("unchecked")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[183,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void reportsRejectedTasksForThreadPoolExecutor() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[210,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void removesMetricsAfterShutdownForThreadPoolExecutor() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[239,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("unchecked")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[294,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void removesMetricsAfterShutdownForForkJoinPool() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[46,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[60,65] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[75,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[89,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[103,65] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[120,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[134,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[150,65] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[167,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[181,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[197,65] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[216,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[230,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[282,55] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledRepetitively.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[47,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[61,60] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[76,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[90,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[104,60] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[121,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[135,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[151,60] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[168,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[182,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[198,60] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[217,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[231,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[283,50] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOverrun.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[48,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[62,59] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[77,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[91,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[105,59] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[122,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[136,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[152,59] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[169,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[183,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[199,59] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[218,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[232,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[284,49] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(percentOfPeriod.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[45,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[59,57] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[74,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[88,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[133,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[149,57] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[166,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[180,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[229,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[267,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[281,47] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(scheduledOnce.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[39,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[42,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[56,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[82,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[85,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[96,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[99,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[112,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[127,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[130,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[146,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[174,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[177,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[190,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[193,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[208,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[223,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[226,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[238,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[260,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[275,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[278,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(completed.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[290,53] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[313,43] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(submitted.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[43,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[57,52] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[86,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[100,52] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[131,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[147,52] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[178,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[194,52] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[227,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[279,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(duration.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[41,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[69,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[84,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[114,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[129,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[161,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[176,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[210,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[225,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[262,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[277,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[315,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(running.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[16] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedScheduledExecutorServiceTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[17,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG ='? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[38,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void submitRunnable() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[81,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void scheduleRunnable() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[126,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void submitCallable() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[173,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void scheduleCallable() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[222,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void scheduleFixedRateCallable() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[274,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void scheduleFixedDelayCallable() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedThreadFactoryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java:[61,18] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getFifteenMinuteRate() * 60.0).isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java:[48,18] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getFiveMinuteRate() * 60.0).isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java:[35,18] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getOneMinuteRate() * 60.0).isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java:[12,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MeterApproximationTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[51,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[33,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[49,51] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[47,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[31,51] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[29,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[27,45] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[45,45] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[23,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[25,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getSum()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MeterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java:[13,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricFilterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[77,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[68,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[63,87] Note: [Refaster Rule] AssertJMapRules.AbstractMapAssertContainsExactlyInAnyOrderEntriesOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AbstractMapAssertContainsExactlyInAnyOrderEntriesOf) - Did you mean 'assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()).containsExactlyInAnyOrderEntriesOf(refTags);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[91,59] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(b.resolve("key").compareTo(b)).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[92,56] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) - Did you mean 'assertThat(b.compareTo(b.resolve("key"))).isNegative();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[100,56] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) - Did you mean 'assertThat(MetricName.EMPTY.compareTo(a)).isNegative();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[101,56] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) - Did you mean 'assertThat(MetricName.EMPTY.compareTo(b)).isNegative();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[14,4] Note: [Refaster Rule] AssertJStringRules.AbstractStringAssertStringIsEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJStringRules#AbstractStringAssertStringIsEmpty) - Did you mean 'assertThat(MetricName.EMPTY.getKey()).isEmpty();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[55,41] Note: [Refaster Rule] AssertJMapRules.AbstractMapAssertContainsExactlyInAnyOrderEntriesOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AbstractMapAssertContainsExactlyInAnyOrderEntriesOf) - Did you mean 'assertThat(test2.getTags()).containsExactlyInAnyOrderEntriesOf(refTags);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[52,40] Note: [Refaster Rule] AssertJMapRules.AbstractMapAssertContainsExactlyInAnyOrderEntriesOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AbstractMapAssertContainsExactlyInAnyOrderEntriesOf) - Did you mean 'assertThat(test.getTags()).containsExactlyInAnyOrderEntriesOf(refTags);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[90,44] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(b.compareTo(a)).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[103,44] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(b.compareTo(a)).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[89,41] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) - Did you mean 'assertThat(a.compareTo(b)).isNegative();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[102,41] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNegative: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNegative) - Did you mean 'assertThat(a.compareTo(b)).isNegative();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricNameTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void empty() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[21,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void emptyResolve() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[27,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void resolveToEmpty() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[33,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void resolve() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[39,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void resolveBothEmpty() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[45,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void addTagsVarious() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[59,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void taggedMoreArguments() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[67,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void taggedNotPairs() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[76,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void taggedNotPairs2() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[85,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void compareTo() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[96,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void compareTo2() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricRegistryListenerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[11,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[12,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[13,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java:[14,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[504,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) - Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[525,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) - Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[551,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) - Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[581,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) - Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[607,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) - Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[636,18] Note: [Refaster Rule] AssertJRules.AssertThatSetsAreEqual: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetsAreEqual) - Did you mean 'assertThat(parentMetrics).hasSameElementsAs(childMetrics.stream()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[428,48] Note: [Refaster Rule] AssertJRules.AssertThatSetContainsExactlyOneElement: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetContainsExactlyOneElement) - Did you mean 'assertThat(registry.getNames()).containsExactly(MetricName.build("nested.gauge"));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[562,49] Note: [Refaster Rule] AssertJRules.AssertThatIterableHasSize: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatIterableHasSize) - Did you mean 'assertThat(deepChildMetrics).hasSize(3);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[649,49] Note: [Refaster Rule] AssertJRules.AssertThatIterableHasSize: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatIterableHasSize) - Did you mean 'assertThat(deepChildMetrics).hasSize(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[563,45] Note: [Refaster Rule] AssertJRules.AssertThatIterableHasSize: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatIterableHasSize) - Did you mean 'assertThat(childMetrics).hasSize(5);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[650,45] Note: [Refaster Rule] AssertJRules.AssertThatIterableHasSize: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatIterableHasSize) - Did you mean 'assertThat(childMetrics).hasSize(3);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[18] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricRegistryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[40,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistryListener listener = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[44,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[45,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[46,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[47,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[294,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistryListener other = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[507,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[507,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[528,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[528,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[554,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[554,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[560,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[560,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[584,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[584,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[610,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[610,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[639,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[639,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[645,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[645,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[496,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByNullPointerExceptionHasMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByNullPointerExceptionHasMessage) - Did you mean 'assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)).isInstanceOf(NullPointerException.class).hasMessage("metric == null");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class NoopMetricRegistryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[18,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistryListener listener = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[21,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[22,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[23,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[24,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[223,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("rawtypes")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java:[245,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistryListener other = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java:[12,42] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) - Did you mean 'assertThat(ratio).hasToString("100.0:200.0");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class RatioGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[205,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[195,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[185,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[110,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) - Did you mean 'Assertions.fail("NullPointerException must be thrown !!!");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[234,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) - Did you mean 'assertThat(customExecutor.isTerminated()).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[241,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsFalse: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsFalse) - Did you mean 'assertThat(mockExecutor.isTerminated()).isFalse();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[242,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsFalse: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsFalse) - Did you mean 'assertThat(mockExecutor.isShutdown()).isFalse();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[148,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockExecutor)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[309,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(reporter)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ScheduledReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[30,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[31,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[32,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[33,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[35,60] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ScheduledExecutorService mockExecutor = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java:[84,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) - Did you mean 'assertThat(exception.getMessage().contains("Default metric registry name is already set.")).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java:[63,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) - Did you mean 'assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java:[31,59] Note: [Refaster Rule] AssertJRules.AssertThatSetContainsExactlyOneElement: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetContainsExactlyOneElement) - Did you mean 'assertThat(SharedMetricRegistries.names()).containsExactly("one");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SharedMetricRegistriesTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SimpleSettableGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[6] Note: [NonStaticImport] Member should not be statically imported - (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class Slf4jReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[25,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Logger logger = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[26,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Marker marker = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[27,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistry registry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[82,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[90,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[107,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[110,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[127,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java:[137,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[102,55] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(clock.getTick() * 256).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SlidingTimeWindowArrayReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[19,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[33,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java:[85,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getTickOverflow() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java:[45,62] Note: [Refaster Rule] TimeRules.EpochInstant: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/TimeRules#EpochInstant) - Did you mean 'assertThat(stwm.calculateIndexOfTick(Instant.EPOCH)).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java:[63,79] Note: [Refaster Rule] TimeRules.EpochInstant: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/TimeRules#EpochInstant) - Did you mean 'assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.EPOCH);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SlidingTimeWindowMovingAveragesTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[75,55] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(clock.getTick() * 256).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SlidingTimeWindowReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[15,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[29,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java:[54,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getTickOverflow() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SlidingWindowReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[41,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[39,51] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[37,50] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[35,45] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[31,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[46,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[114,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[133,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[140,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(timer.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[33,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(timer.getSum()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[47,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(timer.getSum()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[115,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(timer.getSum()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[141,37] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(timer.getSum()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class TimerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[16,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Reservoir reservoir = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java:[104,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java:[23,59] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNotNegative: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNotNegative) - Did you mean 'assertThat(i).isLessThan(1000).isNotNegative();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class UniformReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java:[8,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("unchecked")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[30,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[39,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[48,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[141,43] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) - Did you mean 'assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n"));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[82,55] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[62,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[67,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[72,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[77,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[161,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[20,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[25,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[57,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[196,53] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) - Did you mean 'assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[189,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) - Did you mean 'assertThat(emptySnapshot.getStdDev()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[182,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) - Did you mean 'assertThat(emptySnapshot.getMean()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[168,45] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(emptySnapshot.getMin()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[175,45] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(emptySnapshot.getMax()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class UniformSnapshotTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[21,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(values.length == weights.length, "Mismatched lengths: " + values.length + " vs " + weights.length);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[49,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[58,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[67,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[150,43] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) - Did you mean 'assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n"));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[101,55] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[81,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[86,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[91,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[96,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[170,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[39,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[44,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[76,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[210,53] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) - Did you mean 'assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[202,48] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) - Did you mean 'assertThat(emptySnapshot.getStdDev()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[194,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsZero) - Did you mean 'assertThat(emptySnapshot.getMean()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[178,45] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(emptySnapshot.getMin()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[186,45] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(emptySnapshot.getMax()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class WeightedSnapshotTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[121,33] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.toArray(any(WeightedSample[].class));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[136,33] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.toArray(any(WeightedSample[].class));'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- -[info] Processed 87 files (22 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- -[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] -[INFO] from metrics-benchmarks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java:[45,13] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return slidingTime.getSnapshot();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java:[61,13] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return arrTime.getSnapshot();'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22.jar -[INFO] -[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. -[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. -[info] Processed 5 files (1 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- -[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] -[INFO] from metrics-caffeine3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- -[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] -[INFO] from metrics-collectd/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[311,57] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[7] Note: [NonStaticImport] Member should not be statically imported - (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[10] Note: [NonStaticImport] Member should not be statically imported - (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[153,8] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(!username.isEmpty(), "username is required for securityLevel: " + securityLevel);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[157,8] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(!password.isEmpty(), "password is required for securityLevel: " + securityLevel);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[84,80] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'private Set disabledMetricAttributes = ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[84,71] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'private Set disabledMetricAttributes = emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[305,14] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean 'LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java:[22,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) - Did you mean 'checkState(!isConnected(), "Already connected");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[239,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) - Did you mean 'checkState(iv.length == IV_LENGTH, "Bad initialization vector");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[264,6] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) - Did you mean 'checkState(output.length == SHA1_LENGTH, "Bad SHA1 hash");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[122,36] Note: [Refaster Rule] StringRules.StringIsEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsEmpty) - Did you mean 'if (val == null || val.isEmpty()) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[67,73] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.username = username != null ? username.getBytes(UTF_8) : null;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[68,73] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.password = password != null ? password.getBytes(UTF_8) : null;'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[127,44] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'buffer.put(val.getBytes(US_ASCII)).put(NULL);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[22,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalArgumentExceptionHasMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalArgumentExceptionHasMessage) - Did you mean 'assertThatThrownBy(() ->'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[35,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalArgumentExceptionHasMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalArgumentExceptionHasMessage) - Did you mean 'assertThatThrownBy(() ->'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CollectdReporterSecurityTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[13,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void unableSetSecurityLevelToSignWithoutUsername() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java:[26,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void unableSetSecurityLevelToSignWithoutPassword() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[248,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalArgumentExceptionHasMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalArgumentExceptionHasMessage) - Did you mean 'assertThatThrownBy(() ->'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[261,20] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalArgumentExceptionHasMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalArgumentExceptionHasMessage) - Did you mean 'assertThatThrownBy(() ->'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[269,59] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf1: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf1) - Did you mean 'final Map map = ImmutableMap.of(name, metric);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[292,52] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) - Did you mean 'return valueList == null ? ImmutableList.of() : valueList.getValues();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[28,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CollectdReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[99,26] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[114,22] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[133,30] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[134,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[157,22] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[158,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[198,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[205,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[239,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void unableSetSecurityLevelToSignWithoutUsername() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[252,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void unableSetSecurityLevelToSignWithoutPassword() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[265,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySortedMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[269,46] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'final Map map = singletonMap(name, metric);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java:[292,42] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return valueList == null ? emptyList() : valueList.getValues();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java:[193,75] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class PacketWriterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java:[31,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void signRequest() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java:[77,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void encryptRequest() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java:[7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SanitizeTest {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- -[info] Processed 12 files (4 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- -[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] -[INFO] from metrics-ehcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedCacheDecoratorFactoryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java:[16] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedEhcacheTest {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- -[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] -[INFO] from metrics-graphite/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[66,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(hostname != null && !hostname.isEmpty(), "hostname must not be null or empty");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[70,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(port >= 0 && port <= 65535, "port must be a valid IP port (0-65535)");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[119,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) - Did you mean 'checkState(!isConnected(), "Already connected");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[32,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(Graphite.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java:[112,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) - Did you mean 'checkState(!isConnected(), "Already connected");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java:[136,53] Note: [RedundantStringConversion] Avoid redundant string conversions when possible - (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) - Did you mean 'sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n';'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[7] Note: [NonStaticImport] Member should not be statically imported - (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[10] Note: [NonStaticImport] Member should not be statically imported - (see https://error-prone.picnic.tech/bugpatterns/NonStaticImport) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[88,58] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'this.disabledMetricAttributes = ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[88,49] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.disabledMetricAttributes = emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[252,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(GraphiteReporter.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[433,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[438,19] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[451,20] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java:[46,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) - Did you mean 'checkState(!isConnected(), "Already connected");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java:[66,64] Note: [RedundantStringConversion] Avoid redundant string conversions when possible - (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) - Did you mean 'String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n';'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java:[176,4] Note: [Refaster Rule] PreconditionsRules.CheckStateWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckStateWithMessage) - Did you mean 'checkState(!isConnected(), "Already connected");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java:[252,23] Note: [Refaster Rule] CollectionRules.CollectionIsEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/CollectionRules#CollectionIsEmpty) - Did you mean 'if (!metrics.isEmpty()) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java:[51,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(PickledGraphite.class);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[98,45] Note: [Refaster Rule] AssertJIntegerRules.AbstractIntegerAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJIntegerRules#AbstractIntegerAssertIsZero) - Did you mean 'assertThat(graphite.getFailures()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[111,45] Note: [Refaster Rule] AssertJIntegerRules.AbstractIntegerAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJIntegerRules#AbstractIntegerAssertIsZero) - Did you mean 'assertThat(graphite.getFailures()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[95,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(channel)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[108,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(channel)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class GraphiteRabbitMQTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[24,58] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ConnectionFactory connectionFactory = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[25,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Connection connection = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[26,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Channel channel = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[28,63] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ConnectionFactory bogusConnectionFactory = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[29,49] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Connection bogusConnection = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java:[30,43] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Channel bogusChannel = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[182,58] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[479,28] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'ImmutableSet.of(),'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[495,54] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[52,56] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[62,56] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[36] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class GraphiteReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[42,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[43,40] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Graphite graphite = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[44,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistry registry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[52,47] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.disabledMetricAttributes(emptySet())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[62,47] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.disabledMetricAttributes(emptySet())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[182,49] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.disabledMetricAttributes(emptySet())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[225,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[241,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[245,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[283,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[309,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[336,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[344,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[413,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[421,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[453,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[479,19] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'emptySet(),'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java:[495,45] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.disabledMetricAttributes(emptySet())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java:[6] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class GraphiteSanitizeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[87,47] Note: [Refaster Rule] AssertJIntegerRules.AbstractIntegerAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJIntegerRules#AbstractIntegerAssertIsZero) - Did you mean 'assertThat(graphite.getFailures()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[26] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class GraphiteTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[29,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final SocketFactory socketFactory = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[32,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Socket socket = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java:[33,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ByteArrayOutputStream output = spy();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class GraphiteUDPTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java:[33,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'DatagramChannel mockDatagramChannel = Mockito.mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java:[33,49] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'DatagramChannel mockDatagramChannel = mock(DatagramChannel.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java:[34] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class PickledGraphiteTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java:[35,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final SocketFactory socketFactory = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java:[39,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Socket socket = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java:[40,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ByteArrayOutputStream output = spy();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- -[info] Processed 13 files (5 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- -[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] -[INFO] from metrics-influxdb/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[81,58] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'this.disabledMetricAttributes = ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[81,49] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.disabledMetricAttributes = emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[199,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(InfluxDbReporter.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,19] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java:[45,26] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.address = requireNonNull(address);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InfluxDbLineBuilderAssumptionsTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[56,56] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[66,56] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean '.disabledMetricAttributes(ImmutableSet.of())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[39] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InfluxDbReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[45,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[46,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final InfluxDbSender sender = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[48,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistry registry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[56,47] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.disabledMetricAttributes(emptySet())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[66,47] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.disabledMetricAttributes(emptySet())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[200,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[217,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[221,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[252,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[277,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[303,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[311,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[363,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java:[371,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java:[19] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InfluxDbUdpTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java:[25,62] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final DatagramChannel datagramChannel = Mockito.mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java:[25,57] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'private final DatagramChannel datagramChannel = mock(DatagramChannel.class);'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- -[info] Processed 8 files (4 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- -[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] -[INFO] from metrics-jvm/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 12 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java:[22,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(BufferPoolMetricSet.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java:[50,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(gauges);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java:[62,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(gauges);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[56,31] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'return ImmutableSet.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[43,44] Note: [RedundantStringConversion] Avoid redundant string conversions when possible - (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) - Did you mean 'stackTrace.append("\t at ").append(element).append(String.format("%n"));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[47,25] Note: [RedundantStringConversion] Avoid redundant string conversions when possible - (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) - Did you mean 'stackTrace));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[54,24] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableSet(deadlocks);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java:[56,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return emptySet();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java:[46,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(gauges);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java:[50,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(gauges);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java:[142,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(gauges);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[74,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[83,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[92,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[16] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class BufferPoolMetricSetTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[27,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MBeanServer mBeanServer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ClassLoadingGaugeSetTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java:[16,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ClassLoadingMXBean cl = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java:[21,44] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat((double) clockTick).isCloseTo(systemTick, offset(1000000.0));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java:[17,44] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat((double) clockTime).isCloseTo(systemTime, offset(200.0));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CpuTimeClockTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[37,31] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNotNegative: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNotNegative) - Did you mean 'Assertions.assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class FileDescriptorRatioGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[16,51] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final UnixOperatingSystemMXBean os = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[28,14] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(gauge.getValue()).isEqualTo(0.1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[36,14] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(new FileDescriptorRatioGauge().getValue())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[43,14] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[49,80] Note: [Refaster Rule] AssertJMapRules.AssertThatMapIsNotEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AssertThatMapIsNotEmpty) - Did you mean 'assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[18,61] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf1: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf1) - Did you mean 'new GarbageCollectorMetricSet(ImmutableList.of(gc));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class GarbageCollectorMetricSetTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[16,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final GarbageCollectorMXBean gc = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java:[18,47] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'new GarbageCollectorMetricSet(singletonList(gc));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java:[56,56] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat((Integer) gauge.getValue()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java:[16] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class JmxAttributeGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class JvmAttributeGaugeSetTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java:[15,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final RuntimeMXBean runtime = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[299,74] Note: [Refaster Rule] AssertJMapRules.AssertThatMapIsNotEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJMapRules#AssertThatMapIsNotEmpty) - Did you mean 'assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MemoryUsageGaugeSetTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[18,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MemoryUsage heap = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[19,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MemoryUsage nonHeap = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[20,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MemoryUsage pool = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[21,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MemoryUsage weirdPool = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[22,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MemoryUsage weirdCollection = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[23,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MemoryMXBean mxBean = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[24,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MemoryPoolMXBean memoryPool = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[25,55] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MemoryPoolMXBean weirdMemoryPool = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[162,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java:[241,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ThreadDeadlockDetectorTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java:[15,43] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadMXBean threads = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java:[27,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ThreadInfo thread1 = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java:[38,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ThreadInfo thread2 = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java:[43,18] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) - Did you mean 'assertThat(output).hasToString(String.format('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ThreadDumpTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java:[18,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadMXBean threadMXBean = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java:[21,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadInfo runnable = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ThreadStatesGaugeSetTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[18,43] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadMXBean threads = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[19,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadDeadlockDetector detector = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[23,43] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadInfo newThread = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[24,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadInfo runnableThread = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[25,47] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadInfo blockedThread = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[26,47] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadInfo waitingThread = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[27,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadInfo timedWaitingThread = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[28,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ThreadInfo terminatedThread = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java:[90,14] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1);'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- -[info] Processed 23 files (10 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- -[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] -[INFO] from metrics-healthchecks/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java:[80,4] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(expression, message);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java:[35,44] Note: [Refaster Rule] EqualityRules.EnumReferenceEquality: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/EqualityRules#EnumReferenceEquality) - Did you mean 'if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java:[32,41] Note: [Refaster Rule] EqualityRules.EnumReferenceEquality: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/EqualityRules#EnumReferenceEquality) - Did you mean 'Async.InitialState.HEALTHY == async.initialState()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java:[165,59] Note: [Refaster Rule] TimeRules.InstantAtZone: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/TimeRules#InstantAtZone) - Did you mean 'ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java:[126,57] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.details = details == null ? null : unmodifiableMap(details);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java:[221,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return PRIME * result + (Long.hashCode(time));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java:[240,55] Note: [RedundantStringConversion] Avoid redundant string conversions when possible - (see https://error-prone.picnic.tech/bugpatterns/RedundantStringConversion) - Did you mean 'builder.append(e.getKey()).append("=").append(e.getValue());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[95,6] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(!healthChecks.containsKey(name), "A health check named " + name + " already exists");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[30,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(HealthCheckRegistry.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[131,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[183,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableSortedMap(results);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[225,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableSortedMap(results);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[85,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[67,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[76,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[58,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[40,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[49,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[100,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockExecutorService)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[112,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockExecutorService)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[139,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockExecutorService)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[158,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockExecutorService)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[181,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockExecutorService)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[198,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockExecutorService)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[217,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockExecutorService)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[235,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockExecutorService)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[141,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(mockFuture).cancel(eq(true));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[19] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class AsyncHealthCheckDecoratorTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[32,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final HealthCheck mockHealthCheck = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[33,67] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ScheduledExecutorService mockExecutorService = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[36,49] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ScheduledFuture mockFuture = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[127,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("unchecked")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[141,39] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'verify(mockFuture, times(1)).cancel(true);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[144,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("unchecked")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java:[168,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("unchecked")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HealthCheckFilterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[77,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[26] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HealthCheckRegistryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[27,63] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ScheduledExecutorService executorService = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[29,59] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final HealthCheckRegistryListener listener = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[31,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final HealthCheck hc1 = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[32,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final HealthCheck hc2 = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[34,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final HealthCheck.Result r1 = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[35,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final HealthCheck.Result r2 = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[37,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final HealthCheck.Result ar = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[41,41] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ScheduledFuture af = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[104,47] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'HealthCheckRegistryListener listener = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java:[118,47] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'HealthCheckRegistryListener listener = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[184,59] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsNotNegative: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsNotNegative) - Did you mean 'assertThat(actual.getDuration()).isNotNegative();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HealthCheckTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[32,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final HealthCheck underlying = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[92,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final RuntimeException e = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[147,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final RuntimeException e = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[164,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final HealthCheck.Result result = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[174,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final RuntimeException e = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[88,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) - Did you mean 'assertThat(exception.getMessage().contains("Default health check registry is already set.")).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[100,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) - Did you mean 'assertThat(exception.getMessage().contains("Default health check registry is already set.")).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[61,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) - Did you mean 'assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[31,64] Note: [Refaster Rule] AssertJRules.AssertThatSetContainsExactlyOneElement: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJRules#AssertThatSetContainsExactlyOneElement) - Did you mean 'assertThat(SharedHealthCheckRegistries.names()).containsExactly("db");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SharedHealthCheckRegistriesTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[21,73] Note: [Refaster Rule] ImmutableSetRules.ImmutableSetOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableSetRules#ImmutableSetOf) - Did you mean 'when(detector.getDeadlockedThreads()).thenReturn(ImmutableSet.of());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ThreadDeadlockHealthCheckTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[18,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ThreadDeadlockDetector detector = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[21,64] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'when(detector.getDeadlockedThreads()).thenReturn(emptySet());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[23,14] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(healthCheck.execute().isHealthy()).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[32,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ThreadDeadlockDetector detector = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java:[47,14] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(healthCheck.execute().isHealthy()).isTrue();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- -[info] Processed 14 files (6 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] -[INFO] from metrics-httpclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java:[114,8] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HttpClientMetricNameStrategiesTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[50,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) - Did you mean 'assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHttpClientConnectionManagerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[40,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistry registry = Mockito.mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[40,43] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'final MetricRegistry registry = mock(MetricRegistry.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[49,11] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java:[49,36] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'Mockito.verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[70,10] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) - Did you mean 'Assertions.fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHttpClientsTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[27,10] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[28,62] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistryListener registryListener = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- -[info] Processed 8 files (2 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] -[INFO] from metrics-httpclient5/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[14,40] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[15,40] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[16,37] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[30,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[31,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[32,37] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[33,38] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[96,21] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[160,12] [deprecation] DefaultHttpClientConnectionOperator(Lookup,SchemePortResolver,DnsResolver) in DefaultHttpClientConnectionOperator has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java:[49,4] [deprecation] HttpRequestExecutor(Timeout,ConnectionReuseStrategy,Http1StreamListener) in HttpRequestExecutor has been deprecated -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[47,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[69,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java:[19] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HttpClientMetricNameStrategiesTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[57,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) - Did you mean 'assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedAsyncClientConnectionManagerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[47,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistry registry = Mockito.mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[47,43] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'final MetricRegistry registry = mock(MetricRegistry.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[56,11] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java:[56,36] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'Mockito.verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[104,20] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) - Did you mean 'Assertions.fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[109,20] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) - Did you mean 'Assertions.fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[147,22] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) - Did you mean 'Assertions.fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[157,22] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) - Did you mean 'Assertions.fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[163,10] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) - Did you mean 'Assertions.fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[214,22] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) - Did you mean 'Assertions.fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[219,22] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) - Did you mean 'Assertions.fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[42] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHttpAsyncClientsTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[86,75] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'exchange.getResponseBody().write("TEST".getBytes(US_ASCII));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[196,77] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'exchange.getResponseBody().write("TEST".getBytes(US_ASCII));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[55,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatIsTrue: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatIsTrue) - Did you mean 'assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHttpClientConnectionManagerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[45,48] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistry registry = Mockito.mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[45,43] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'final MetricRegistry registry = mock(MetricRegistry.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[54,11] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java:[54,36] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'Mockito.verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[70,10] Note: [Refaster Rule] JUnitToAssertJRules.Fail: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#Fail) - Did you mean 'Assertions.fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHttpClientsTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[27,10] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[28,62] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistryListener registryListener = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- -[info] Processed 13 files (4 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- -[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] -[INFO] from metrics-httpasyncclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java:[40,8] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHttpClientsTest extends HttpClientTestBase {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[121,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) - Did you mean 'Assertions.fail("This should fail as the client should not be able to connect");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[32] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHttpClientsTimerTest extends HttpClientTestBase {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[49,22] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[75,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("unchecked")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[81,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'FutureCallback futureCallback = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[102,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("unchecked")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[109,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'FutureCallback futureCallback = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- -[info] Processed 5 files (1 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] -[INFO] from metrics-jakarta-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java:[67,27] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean 'if (Strings.isNullOrEmpty(metricName)) {'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedFilterContextListenerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[13,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistry registry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[24,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext context = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[26,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContextEvent event = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] -[INFO] from metrics-jakarta-servlet6/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java:[67,27] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean 'if (Strings.isNullOrEmpty(metricName)) {'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedFilterContextListenerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java:[13,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistry registry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java:[24,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext context = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java:[26,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContextEvent event = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- -[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] -[INFO] from metrics-json/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java:[189,31] [serial] non-transient instance field of a serializable class declared with a non-serializable type -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java:[83,55] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf1: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf1) - Did you mean 'new SimpleSerializers(ImmutableList.of(new HealthCheckResultSerializer())));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java:[83,41] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'new SimpleSerializers(singletonList(new HealthCheckResultSerializer())));'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[13] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HealthCheckModuleTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[20,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[28,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[43,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[62,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[90,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java:[131,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", result.getTimestamp());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[19] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricsModuleTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[45,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[53,36] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[56,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[110,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[130,28] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java:[137,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot snapshot = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- -[info] Processed 4 files (2 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- -[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] -[INFO] from metrics-jetty11/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[256,44] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) - Did you mean 'this.responses = ImmutableList.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[176,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean ': ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[176,25] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[191,21] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'unmodifiableList('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java:[256,34] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.responses = emptyList();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[146,35] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) - Did you mean ': ImmutableList.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[135,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean ': ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[135,25] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[138,25] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '? unmodifiableList('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java:[146,25] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyList();'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java:[24] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedConnectionFactoryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[161,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[165,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()).isPositive()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[153,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[31] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHandlerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[121,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[131,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[140,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@Disabled("flaky on virtual machines")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java:[228,91] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '"some content from the async\n".getBytes(UTF_8));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHttpChannelListenerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java:[191,89] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '"some content from the async".getBytes(UTF_8));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedQueuedThreadPoolTest {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- -[info] Processed 8 files (4 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- -[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] -[INFO] from metrics-jakarta-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java:[102,13] Note: [Refaster Rule] NullRules.IsNull: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/NullRules#IsNull) - Did you mean 'if (registry == null) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java:[134,13] Note: [Refaster Rule] NullRules.IsNull: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/NullRules#IsNull) - Did you mean 'if (registry == null) {'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class AdminServletExclusionTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class AdminServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class AdminServletUriTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CpuProfileServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[231,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[225,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[208,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletConfig).getServletContext();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[224,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletConfig).getServletContext();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[30] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HealthCheckServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[32,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[97,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", EXPECTED_TIMESTAMP);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[113,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", EXPECTED_TIMESTAMP);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[170,25] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", EXPECTED_TIMESTAMP));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[200,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final HealthCheckRegistry healthCheckRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[201,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[202,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[214,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final HealthCheckRegistry healthCheckRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[215,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[216,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[234,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[235,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[248,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[249,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricsServletContextListenerTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java:[21,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[258,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[252,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletContext).getAttribute(eq(MetricsServlet.METRICS_REGISTRY));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[235,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletConfig).getServletContext();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[251,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletConfig).getServletContext();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricsServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[29,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[132,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", callbackParamVal);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[227,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistry metricRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[228,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[229,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[236,48] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[241,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistry metricRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[242,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[243,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[245,36] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[252,49] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'verify(servletContext, times(1)).getAttribute(MetricsServlet.METRICS_REGISTRY);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[261,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[262,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[264,42] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class PingServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ThreadDumpServletTest extends AbstractServletTest {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- -[info] Processed 17 files (2 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- -[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] -[INFO] from metrics-jcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java:[36,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(JCacheGaugeSet.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java:[55,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(gauges);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[74,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat((Float) registry.getGauges().get(myCache.resolve("average-remove-time")).getValue()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[70,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat((Float) registry.getGauges().get(myCache.resolve("average-get-time")).getValue()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[72,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat((Float) registry.getGauges().get(myCache.resolve("average-put-time")).getValue()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/test/java/JCacheGaugeSetTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class JCacheGaugeSetTest {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- -[info] Processed 2 files (2 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- -[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] -[INFO] from metrics-jdbi3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java:[16,28] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean 'return Strings.isNullOrEmpty(rawSql) ? MetricName.build("sql.empty") : null;'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class BasicSqlNameStrategyTest extends AbstractStrategyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedSqlLoggerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[18,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistry mockRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[19,55] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final StatementNameStrategy mockNameStrategy = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[22,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final StatementContext mockContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[23,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Timer mockTimer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[40,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistry mockRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[41,55] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final StatementNameStrategy mockNameStrategy = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[44,45] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final StatementContext mockContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java:[45,32] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Timer mockTimer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class NaiveNameStrategyTest extends AbstractStrategyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[15] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SmartNameStrategyTest extends AbstractStrategyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class TimedAnnotationNameStrategyTest extends AbstractStrategyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[47,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void annotationOnMethod() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[57,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void annotationOnMethodWithCustomName() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[67,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void annotationOnMethodWithCustomAbsoluteName() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[75,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void annotationOnClass() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[85,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void annotationOnMethodAndClassWithCustomNames() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[94,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void noAnnotations() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java:[101,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void noMethod() {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- -[info] Processed 15 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- -[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] -[INFO] from metrics-jersey2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[310,50] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) - Did you mean '&& metric.cause.isInstance(event.getException().getCause()))) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[308,43] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) - Did you mean 'if (metric.cause.isInstance(event.getException())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[546,29] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean 'if (!Strings.isNullOrEmpty(explicitName)) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[170,37] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) - Did you mean ': ImmutableList.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[174,36] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean ': ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[162,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '? unmodifiableList('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[170,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyList();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[174,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[421,31] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return new ChainedRequestEventListener('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java:[607,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return 31 * result + method.hashCode();'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CustomReservoirImplementationTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonFilterMetricsJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java:[37,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(new InstrumentedFilteredResource(testClock));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[53,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[78,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[37,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResourceExceptionMeteredPerClass.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[95,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[98,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter4xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[101,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter5xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[70,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[27] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[40,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResource.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java:[110,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void resourceNotFound() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java:[34,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResourceMeteredPerClass.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[112,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) - Did you mean 'Assertions.fail("expected RuntimeException");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[37,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(new TestExceptionMapper());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java:[34,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResourceTimedPerClass.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java:[20,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java:[28,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java:[36,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java:[52,4] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[23,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[37,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@ExceptionMetered(cause = IOException.class)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[48,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[56,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[64,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[72,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[79,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java:[86,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java:[12,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- -[info] Processed 24 files (7 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- -[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] -[INFO] from metrics-jersey3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[311,50] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) - Did you mean '&& metric.cause.isInstance(event.getException().getCause()))) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[309,43] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) - Did you mean 'if (metric.cause.isInstance(event.getException())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[547,29] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean 'if (!Strings.isNullOrEmpty(explicitName)) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[171,37] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) - Did you mean ': ImmutableList.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[175,36] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean ': ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[163,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '? unmodifiableList('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[171,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyList();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[175,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[422,31] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return new ChainedRequestEventListener('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java:[605,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return 31 * result + method.hashCode();'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CustomReservoirImplementationTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonFilterMetricsJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(new InstrumentedFilteredResource(testClock));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[54,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[79,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[24] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResourceExceptionMeteredPerClass.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[92,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[95,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter4xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[98,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter5xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[118,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[119,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[120,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter201.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[130,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[142,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[143,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[131,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[132,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter201.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[146,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[147,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[70,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[41,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResource.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[136,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void responseMeteredMethodsAreMeteredWithAllLevel() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java:[151,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void resourceNotFound() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java:[35,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResourceMeteredPerClass.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[143,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[144,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[157,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[158,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[113,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) - Did you mean 'Assertions.fail("expected RuntimeException");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(new TestExceptionMapper());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java:[35,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResourceTimedPerClass.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java:[20,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java:[28,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java:[36,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java:[52,4] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[23,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[37,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@ExceptionMetered(cause = IOException.class)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[48,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[56,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[64,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[72,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[79,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java:[86,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java:[12,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- -[info] Processed 24 files (7 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- -[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] -[INFO] from metrics-jersey31/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[311,50] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) - Did you mean '&& metric.cause.isInstance(event.getException().getCause()))) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[309,43] Note: [Refaster Rule] ClassRules.ClassIsInstance: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ClassRules#ClassIsInstance) - Did you mean 'if (metric.cause.isInstance(event.getException())'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[547,29] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean 'if (!Strings.isNullOrEmpty(explicitName)) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[171,37] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) - Did you mean ': ImmutableList.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[175,36] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean ': ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[163,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '? unmodifiableList('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[171,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyList();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[175,27] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[422,31] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return new ChainedRequestEventListener('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java:[605,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return 31 * result + method.hashCode();'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CustomReservoirImplementationTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java:[22] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonFilterMetricsJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(new InstrumentedFilteredResource(testClock));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[54,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[79,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[24] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResourceExceptionMeteredPerClass.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[92,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[95,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter4xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[98,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter5xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[109,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[110,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[114,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[129,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[130,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[131,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter201.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[141,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[153,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[154,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[113,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[142,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[143,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter201.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[157,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[158,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[70,39] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[41,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResource.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[103,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void responseMeteredMethodsAreMeteredWithCoarseLevel() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[118,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void responseMeteredMethodsAreMeteredWithDetailedLevel() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[147,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void responseMeteredMethodsAreMeteredWithAllLevel() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java:[162,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void resourceNotFound() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java:[35,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResourceMeteredPerClass.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[143,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[144,42] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsZero: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsZero) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(0);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[149,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter2xx.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[150,41] Note: [Refaster Rule] AssertJLongRules.AbstractLongAssertIsOne: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJLongRules#AbstractLongAssertIsOne) - Did you mean 'assertThat(meter200.getCount()).isEqualTo(1);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[113,10] Note: [Refaster Rule] JUnitToAssertJRules.FailWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#FailWithMessage) - Did you mean 'Assertions.fail("expected RuntimeException");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[23] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[38,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(new TestExceptionMapper());'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java:[21] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java:[35,4] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return config.register(InstrumentedResourceTimedPerClass.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java:[20,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java:[28,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java:[36,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java:[52,4] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[23,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[37,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@ExceptionMetered(cause = IOException.class)'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[48,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[56,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[64,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[72,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[79,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java:[86,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java:[12,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@GET'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- -[info] Processed 24 files (7 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- -[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] -[INFO] from metrics-jetty10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[256,44] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) - Did you mean 'this.responses = ImmutableList.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[176,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean ': ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[176,25] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[191,21] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'unmodifiableList('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java:[256,34] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.responses = emptyList();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[146,35] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) - Did you mean ': ImmutableList.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[135,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean ': ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[135,25] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[138,25] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '? unmodifiableList('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java:[146,25] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyList();'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java:[24] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedConnectionFactoryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[161,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[165,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()).isPositive()'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[153,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[31] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHandlerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[121,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[131,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[140,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@Disabled("flaky on virtual machines")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java:[228,91] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '"some content from the async\n".getBytes(UTF_8));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java:[25] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedHttpChannelListenerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java:[191,89] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '"some content from the async".getBytes(UTF_8));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedQueuedThreadPoolTest {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- -[info] Processed 8 files (4 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- -[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] -[INFO] from metrics-log4j2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/apache/logging/log4j/log4j-core/2.24.1/log4j-core-2.24.1.jar(/org/apache/logging/log4j/core/LoggerContext.class): warning: Cannot find annotation method 'value()' in type 'SuppressFBWarnings': class file for edu.umd.cs.findbugs.annotations.SuppressFBWarnings not found -/home/rick/.m2/repository/org/apache/logging/log4j/log4j-core/2.24.1/log4j-core-2.24.1.jar(/org/apache/logging/log4j/core/LoggerContext.class): warning: Cannot find annotation method 'justification()' in type 'SuppressFBWarnings' -/home/rick/.m2/repository/org/apache/logging/log4j/log4j-core/2.24.1/log4j-core-2.24.1.jar(/org/apache/logging/log4j/core/config/ConfigurationSource.class): warning: Cannot find annotation method 'value()' in type 'SuppressFBWarnings' -/home/rick/.m2/repository/org/apache/logging/log4j/log4j-core/2.24.1/log4j-core-2.24.1.jar(/org/apache/logging/log4j/core/config/ConfigurationSource.class): warning: Cannot find annotation method 'justification()' in type 'SuppressFBWarnings' -/home/rick/.m2/repository/org/apache/logging/log4j/log4j-api/2.24.1/log4j-api-2.24.1.jar(/org/apache/logging/log4j/Level.class): warning: Cannot find annotation method 'value()' in type 'BaselineIgnore': class file for aQute.bnd.annotation.baseline.BaselineIgnore not found -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedAppenderConfigTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedAppenderTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java:[21,37] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final LogEvent event = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- -[info] Processed 3 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- -[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] -[INFO] from metrics-logback13/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedAppenderTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java:[21,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ILoggingEvent event = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- -[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] -[INFO] from metrics-logback14/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedAppenderTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java:[21,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ILoggingEvent event = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- -[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] -[INFO] from metrics-logback15/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java:[15,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedAppenderTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java:[21,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ILoggingEvent event = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- -[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] -[INFO] from metrics-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java:[67,27] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean 'if (Strings.isNullOrEmpty(metricName)) {'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedFilterContextListenerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[13,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final MetricRegistry registry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[24,39] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext context = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java:[26,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContextEvent event = mock();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- -[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] -[INFO] from metrics-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java:[102,13] Note: [Refaster Rule] NullRules.IsNull: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/NullRules#IsNull) - Did you mean 'if (registry == null) {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java:[134,13] Note: [Refaster Rule] NullRules.IsNull: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/NullRules#IsNull) - Did you mean 'if (registry == null) {'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 10 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class AdminServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class AdminServletUriTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CpuProfileServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[231,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[225,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[208,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletConfig).getServletContext();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[224,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletConfig).getServletContext();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[30] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HealthCheckServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[32,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[97,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", EXPECTED_TIMESTAMP);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[113,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", EXPECTED_TIMESTAMP);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[170,25] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", EXPECTED_TIMESTAMP));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[200,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final HealthCheckRegistry healthCheckRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[201,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[202,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[214,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final HealthCheckRegistry healthCheckRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[215,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[216,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[234,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[235,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[248,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[249,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricsServletContextListenerTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java:[21,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[258,4] Note: [Refaster Rule] JUnitToAssertJRules.AssertThatThrownByIsInstanceOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/JUnitToAssertJRules#AssertThatThrownByIsInstanceOf) - Did you mean 'assertThatThrownBy(() -> {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[252,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletContext).getAttribute(eq(MetricsServlet.METRICS_REGISTRY));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[235,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletConfig).getServletContext();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[251,10] Note: [Refaster Rule] MockitoRules.VerifyOnce: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/MockitoRules#VerifyOnce) - Did you mean 'verify(servletConfig).getServletContext();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[28] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricsServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[29,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Clock clock = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[132,18] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", callbackParamVal);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[227,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistry metricRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[228,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[229,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[236,48] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[241,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final MetricRegistry metricRegistry = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[242,46] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[243,44] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[245,36] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[252,49] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'verify(servletContext, times(1)).getAttribute(MetricsServlet.METRICS_REGISTRY);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[261,52] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[262,50] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[264,42] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class PingServletTest extends AbstractServletTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ThreadDumpServletTest extends AbstractServletTest {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- -[info] Processed 16 files (2 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- -[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] -[INFO] from metrics-jcstress/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22.jar -[INFO] -[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. -[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. -[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: -[WARNING] - META-INF/AL2.0 -[WARNING] - META-INF/LGPL2.1 -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. -[info] Processed 3 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- -[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] -[INFO] from metrics-jmx/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java:[13,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectNameFactory.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java:[41,6] Note: [DirectReturn] Variable assignment is redundant; value can be returned directly - (see https://error-prone.picnic.tech/bugpatterns/DirectReturn) - Did you mean 'return new ObjectName(domain, properties);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[91,6] Note: [Refaster Rule] PreconditionsRules.CheckArgumentWithMessage: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/PreconditionsRules#CheckArgumentWithMessage) - Did you mean 'checkArgument(onFactory != null, "null objectNameFactory");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[64,55] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean 'this.specificDurationUnits = ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[65,51] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean 'this.specificRateUnits = ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[64,46] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.specificDurationUnits = emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[65,42] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.specificRateUnits = emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[132,46] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.specificDurationUnits = unmodifiableMap(specificDurationUnits);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[143,42] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.specificRateUnits = unmodifiableMap(specificRateUnits);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[162,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLoggerDeclaration) - Did you mean 'private static final Logger LOG = LoggerFactory.getLogger(JmxReporter.class);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class DefaultObjectNameFactoryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[38] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class JmxReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[40,34] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'private final String name = randomUUID().toString().replaceAll("[{\\-}]", "");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[52,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Gauge gauge = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[53,38] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Counter counter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[54,42] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Histogram histogram = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[55,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Meter meter = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[56,34] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final Timer timer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[57,62] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private final ObjectNameFactory mockObjectNameFactory = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[69,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot hSnapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[98,35] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final Snapshot tSnapshot = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[288,40] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'MBeanServer mockedMBeanServer = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java:[313,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void jmxMetricNameWithAsterisk() {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- -[info] Processed 5 files (3 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ -[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] -[INFO] from metrics-legacy-adapter/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 36 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,49] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,9] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[110,27] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[114,27] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java:[118,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableSortedMap(items);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[107,31] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toCollection(TreeSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[163,22] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableSortedMap(items);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java:[27,26] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(items);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java:[51,24] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'return unmodifiableMap(items);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 24 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[50,4] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[367,22] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CachedGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void create() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java:[24,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createWothClock() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[13,45] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(clock.getTick()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[19,45] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(clock.getTick()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ClockTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[11,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void defaultClockCanBeUsed() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[17,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void userTimeClockCanBeUsed() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java:[23,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void customTimeClockCanBeUsed() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java:[20] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ConsoleReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java:[38,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createConsoleReporter() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java:[75,79] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(new String(byteArrayOutputStream.toByteArray(), UTF_8))'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class CounterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[14,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void incrementCounter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[21,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void incrementCounterOnManyPoints() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[28,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void decrementCounter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java:[35,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void decrementCounterOnManyPoints() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class DerivativeGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java:[11,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void calculate() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[25,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ExponentiallyDecayingReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createReservoir() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[25,60] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getStdDev()).isEqualTo(32.62, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[34,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createReservoirWithCustomSizeAndAlpha() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[41,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createReservoirWithCustomSizeAlphaAndClock() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java:[13] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class FixedNameCsvFileProviderTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java:[8] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class GaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java:[13,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getValue() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[26,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class HistogramTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void create() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[26,60] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getStdDev()).isEqualTo(32.62, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java:[12] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedExecutorServiceTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java:[15,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void create() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java:[13] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedScheduledExecutorServiceTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java:[22,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void create() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedThreadFactoryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java:[14,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void factory() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java:[12,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@SuppressWarnings("DoNotCall")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MeterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createMeteer() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java:[18,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createMeterWithCustomClock() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java:[31,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void mark() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[14] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class MetricRegistryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[19,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void registerMetric() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[26,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void registerAll() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[43,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void registerGauge() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[49,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createCustomGauge() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[55,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createCounter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[62,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createCustomCounter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[76,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createHistogram() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[86,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createCustomHistogram() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[98,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createMeter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[107,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createCustomMeter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[122,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createTimer() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[132,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createCustomTimer() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[148,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void removeMetric() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[159,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void removeMatching() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[171,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void addListenerForGauge() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[200,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void addListenerForCounter() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[228,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void addListenerForHistogram() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[257,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void addListenerForMeter() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[286,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void addListenerForTimer() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[315,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void removeListener() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[334,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getNames() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[345,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getGauges() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[372,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getGaugesWithFilter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[401,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getHistograms() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[414,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getHistogramsWithFilter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[427,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getCounters() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[440,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getCountersWithFilter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[453,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getMeters() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[467,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getMetersWithFilter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[481,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getTimers() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[494,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getTimersWithFilter() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[507,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getMetrics() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[21,58] Note: [Refaster Rule] AssertJObjectRules.AssertThatHasToString: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJObjectRules#AssertThatHasToString) - Did you mean 'assertThat(ratioGauge.getRatio()).hasToString("1.0:3.0");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class RatioGaugeTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[20,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void viewRatin() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[25,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void calculateRatio() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java:[26,60] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(ratioGauge.getValue()).isCloseTo(0.33, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[13] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class ScheduledReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[54,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void report() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[64,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void start() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java:[74,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void startWithoutDelay() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[52,48] Note: [Refaster Rule] AssertJThrowingCallableRules.AssertThatThrownByIllegalStateException: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJThrowingCallableRules#AssertThatThrownByIllegalStateException) - Did you mean 'assertThatThrownBy(SharedMetricRegistries::getDefault).isInstanceOf(IllegalStateException.class);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SharedMetricRegistriesTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[18,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getOrCreateMetricRegistry() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[26,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void addMetricRegistry() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[36,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void names() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[46,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void tryGetDefaultRegistry() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java:[51,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void getDefaultRegistry() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java:[17] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class Slf4jReporterTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java:[20,30] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private Logger logger = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java:[21,30] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'private Marker marker = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java:[34,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void report() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SlidingTimeWindowArrayReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[13,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createWithWindow() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[21,71] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[25,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createWithWindowAndClock() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java:[32,71] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[10] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SlidingTimeWindowReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[13,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createWithWindow() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[20,71] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[24,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createWithWindowAndClock() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java:[31,71] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SlidingWindowReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createWithBigWindow() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[19,71] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[23,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createWithLowWindow() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java:[31,71] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[23,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, Offset.offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[27,55] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get999thPercentile()).isCloseTo(5, Offset.offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[24,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get95thPercentile()).isCloseTo(5, Offset.offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[25,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get98thPercentile()).isCloseTo(5, Offset.offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[26,54] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.get99thPercentile()).isCloseTo(5, Offset.offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[21,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(1.58, Offset.offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[22,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getMedian()).isCloseTo(3, Offset.offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class SnapshotTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[14,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createSnapshot() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[21,59] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getStdDev()).isEqualTo(1.58, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[22,56] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[23,66] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[24,64] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get95thPercentile()).isEqualTo(5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[25,64] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get98thPercentile()).isEqualTo(5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[26,64] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get99thPercentile()).isEqualTo(5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[27,65] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get999thPercentile()).isEqualTo(5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[11] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class TimerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[29,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void create() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[38,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createWithCustomReservoir() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[47,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createWithCustomReservoirAndClock() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[56,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void timerContext() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[64,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void timerRunnable() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[75,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void timerCallable() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[85,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void timerSupplier() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java:[95,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void updateDuration() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[25,46] Note: [Refaster Rule] AssertJDoubleRules.AbstractDoubleAssertIsCloseToWithOffset: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJDoubleRules#AbstractDoubleAssertIsCloseToWithOffset) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(36.47, Offset.offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[9] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class UniformReservoirTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[12,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createReservoir() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[25,60] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getStdDev()).isEqualTo(36.47, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[34,7] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createReservoirWithCustomSize() {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/metrics-legacy-adapter-5.0.0-rc22.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- -[info] Processed 60 files (13 reformatted). -[INFO] -[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- -[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] -[INFO] from metrics-legacy-adapter-healthchecks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/metrics-legacy-adapter-healthchecks-5.0.0-rc22.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] -[INFO] from metrics-jetty12/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[247,44] Note: [Refaster Rule] ImmutableListRules.ImmutableListOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableListRules#ImmutableListOf) - Did you mean 'this.responses = ImmutableList.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[167,34] Note: [Refaster Rule] ImmutableMapRules.ImmutableMapOf: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/ImmutableMapRules#ImmutableMapOf) - Did you mean ': ImmutableMap.of();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[167,25] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean ': emptyMap();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[182,21] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'unmodifiableList('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java:[247,34] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'this.responses = emptyList();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/12.0.14/jetty-server-12.0.14.jar(/org/eclipse/jetty/server/HttpConnectionFactory.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/12.0.14/jetty-server-12.0.14.jar(/org/eclipse/jetty/server/HttpConnectionFactory.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/12.0.14/jetty-server-12.0.14.jar(/org/eclipse/jetty/server/HttpConnectionFactory.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/12.0.14/jetty-server-12.0.14.jar(/org/eclipse/jetty/server/HttpConnectionFactory.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/ssl/SslContextFactory.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/ssl/SslContextFactory.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/ssl/SslContextFactory.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/ssl/SslContextFactory.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[22,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedConnectionFactoryTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[35,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void setUp() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[53,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void tearDown() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[59,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void instrumentsConnectionTimes() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java:[73,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void instrumentsActiveConnections() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java:[10,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedQueuedThreadPoolTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java:[17,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void setUp() {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java:[23,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void customMetricsPrefix() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java:[38,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void metricsPrefixBackwardCompatible() throws Exception {'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- -[info] Processed 5 files (1 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] -[INFO] from metrics-jetty12-ee10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/ee10/jetty-ee10-servlet/12.0.14/jetty-ee10-servlet-12.0.14.jar(/org/eclipse/jetty/ee10/servlet/DefaultServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/ee10/jetty-ee10-servlet/12.0.14/jetty-ee10-servlet-12.0.14.jar(/org/eclipse/jetty/ee10/servlet/ServletContextHandler.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/ee10/jetty-ee10-servlet/12.0.14/jetty-ee10-servlet-12.0.14.jar(/org/eclipse/jetty/ee10/servlet/ServletContextHandler.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[180,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[185,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat('? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[172,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(registry.getMeters().get(metricName().resolve(".200-responses")).getCount()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[170,22] Note: [Refaster Rule] AssertJNumberRules.NumberAssertIsPositive: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJNumberRules#NumberAssertIsPositive) - Did you mean 'assertThat(registry.getMeters().get(metricName().resolve("2xx-responses")).getCount()).isPositive();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[35,7] Note: [JUnitClassModifiers] Non-abstract JUnit test classes should be declared package-private and final - (see https://error-prone.picnic.tech/bugpatterns/JUnitClassModifiers) - Did you mean 'final class InstrumentedEE10HandlerTest {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[43,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void setUp() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[65,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void tearDown() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[71,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void hasAName() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[76,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void createsAndRemovesMetricsForTheHandler() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[120,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void responseTimesAreRecordedForBlockingResponses() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[118,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@Disabled("flaky on virtual machines")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[130,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void doStopDoesNotThrowNPE() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[138,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[148,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[159,14] Note: [JUnitMethodDeclaration] JUnit method declaration can likely be improved - (see https://error-prone.picnic.tech/bugpatterns/JUnitMethodDeclaration) - Did you mean 'void responseTimesAreRecordedForAsyncResponses() throws Exception {'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[157,2] Note: [LexicographicalAnnotationListing] Sort annotations lexicographically where possible - (see https://error-prone.picnic.tech/bugpatterns/LexicographicalAnnotationListing) - Did you mean '@Disabled("flaky on virtual machines")'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java:[253,91] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '"some content from the async\n".getBytes(UTF_8));'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- -[info] Processed 2 files (1 reformatted). -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: -[INFO] -[INFO] Metrics5 Parent .................................... SUCCESS [ 0.348 s] -[INFO] Metrics5 Documentation ............................. SUCCESS [ 1.412 s] -[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.009 s] -[INFO] Annotations for Metrics5 ........................... SUCCESS [ 4.564 s] -[INFO] Metrics5 Core ...................................... SUCCESS [ 27.676 s] -[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 5.998 s] -[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 8.001 s] -[INFO] Metrics Integration for Collectd ................... SUCCESS [ 14.076 s] -[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 8.093 s] -[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 14.205 s] -[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 11.589 s] -[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 11.988 s] -[INFO] Metrics5 Health Checks ............................. SUCCESS [ 11.640 s] -[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 9.543 s] -[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 10.951 s] -[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 8.025 s] -[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 7.862 s] -[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 7.217 s] -[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 8.924 s] -[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 11.442 s] -[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 11.180 s] -[INFO] Metrics Integration for JCache ..................... SUCCESS [ 7.736 s] -[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 9.524 s] -[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 12.614 s] -[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 14.470 s] -[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 16.701 s] -[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 13.086 s] -[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 7.669 s] -[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 7.401 s] -[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 7.500 s] -[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 9.950 s] -[INFO] Metrics Integration for Servlets ................... SUCCESS [ 7.850 s] -[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 11.958 s] -[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 5.342 s] -[INFO] Metrics Integration with JMX ....................... SUCCESS [ 10.732 s] -[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 15.020 s] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 4.963 s] -[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 9.111 s] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 8.927 s] -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 06:16 min -[INFO] Finished at: 2024-11-18T12:51:22+01:00 -[INFO] ------------------------------------------------------------------------ -diff --git a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java -index 72f85e8..13f3b2c 100644 ---- a/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java -+++ b/metrics-benchmarks/src/main/java/io/dropwizard/metrics5/benchmarks/SlidingTimeWindowReservoirsBenchmark.java -@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.benchmarks; - - import io.dropwizard.metrics5.SlidingTimeWindowArrayReservoir; - import io.dropwizard.metrics5.SlidingTimeWindowReservoir; --import io.dropwizard.metrics5.Snapshot; - import java.util.concurrent.TimeUnit; - import org.openjdk.jmh.annotations.Benchmark; - import org.openjdk.jmh.annotations.Group; -@@ -42,8 +41,7 @@ public class SlidingTimeWindowReservoirsBenchmark { - @Group("slidingTime") - @GroupThreads(1) - public Object slidingTimeRead() { -- Snapshot snapshot = slidingTime.getSnapshot(); -- return snapshot; -+ return slidingTime.getSnapshot(); - } - - @Benchmark -@@ -58,8 +56,7 @@ public class SlidingTimeWindowReservoirsBenchmark { - @Group("arrTime") - @GroupThreads(1) - public Object arrTimeRead() { -- Snapshot snapshot = arrTime.getSnapshot(); -- return snapshot; -+ return arrTime.getSnapshot(); - } - - public static void main(String[] args) throws RunnerException { -diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java -index 9ea691f..7b54d0b 100644 ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java -@@ -1,13 +1,12 @@ - package io.dropwizard.metrics5.collectd; - -+import static com.google.common.base.Preconditions.checkArgument; - import static io.dropwizard.metrics5.MetricAttribute.COUNT; - import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; - import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; - import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MAX; - import static io.dropwizard.metrics5.MetricAttribute.MEAN; - import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MIN; - import static io.dropwizard.metrics5.MetricAttribute.P50; - import static io.dropwizard.metrics5.MetricAttribute.P75; - import static io.dropwizard.metrics5.MetricAttribute.P95; -@@ -16,6 +15,7 @@ import static io.dropwizard.metrics5.MetricAttribute.P99; - import static io.dropwizard.metrics5.MetricAttribute.P999; - import static io.dropwizard.metrics5.MetricAttribute.STDDEV; - -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -30,7 +30,6 @@ import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; - import java.io.IOException; - import java.net.InetAddress; --import java.util.Collections; - import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -81,7 +80,7 @@ public class CollectdReporter extends ScheduledReporter { - private SecurityLevel securityLevel = SecurityLevel.NONE; - private String username = ""; - private String password = ""; -- private Set disabledMetricAttributes = Collections.emptySet(); -+ private Set disabledMetricAttributes = ImmutableSet.of(); - private int maxLength = Sanitize.DEFAULT_MAX_LENGTH; - - private Builder(MetricRegistry registry) { -@@ -150,14 +149,10 @@ public class CollectdReporter extends ScheduledReporter { - - public CollectdReporter build(Sender sender) { - if (securityLevel != SecurityLevel.NONE) { -- if (username.isEmpty()) { -- throw new IllegalArgumentException( -- "username is required for securityLevel: " + securityLevel); -- } -- if (password.isEmpty()) { -- throw new IllegalArgumentException( -- "password is required for securityLevel: " + securityLevel); -- } -+ checkArgument( -+ !username.isEmpty(), "username is required for securityLevel: " + securityLevel); -+ checkArgument( -+ !password.isEmpty(), "password is required for securityLevel: " + securityLevel); - } - return new CollectdReporter( - registry, -@@ -302,7 +297,7 @@ public class CollectdReporter extends ScheduledReporter { - try { - writer.write(metaData, value); - } catch (RuntimeException e) { -- LOG.warn("Failed to process metric '" + metaData.getPlugin() + "': " + e.getMessage()); -+ LOG.warn("Failed to process metric '{}': {}", metaData.getPlugin(), e.getMessage()); - } catch (IOException e) { - LOG.error("Failed to send metric to collectd", e); - } -@@ -336,9 +331,9 @@ public class CollectdReporter extends ScheduledReporter { - private void serializeHistogram(MetaData.Builder metaData, Histogram metric) { - final Snapshot snapshot = metric.getSnapshot(); - writeValue(metaData, COUNT, (double) metric.getCount()); -- writeValue(metaData, MAX, (double) snapshot.getMax()); -+ writeValue(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); - writeValue(metaData, MEAN, snapshot.getMean()); -- writeValue(metaData, MIN, (double) snapshot.getMin()); -+ writeValue(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); - writeValue(metaData, STDDEV, snapshot.getStdDev()); - writeValue(metaData, P50, snapshot.getMedian()); - writeValue(metaData, P75, snapshot.get75thPercentile()); -@@ -351,9 +346,9 @@ public class CollectdReporter extends ScheduledReporter { - private void serializeTimer(MetaData.Builder metaData, Timer metric) { - final Snapshot snapshot = metric.getSnapshot(); - writeValue(metaData, COUNT, (double) metric.getCount()); -- writeDuration(metaData, MAX, (double) snapshot.getMax()); -+ writeDuration(metaData, MetricAttribute.MAX, (double) snapshot.getMax()); - writeDuration(metaData, MEAN, snapshot.getMean()); -- writeDuration(metaData, MIN, (double) snapshot.getMin()); -+ writeDuration(metaData, MetricAttribute.MIN, (double) snapshot.getMin()); - writeDuration(metaData, STDDEV, snapshot.getStdDev()); - writeDuration(metaData, P50, snapshot.getMedian()); - writeDuration(metaData, P75, snapshot.get75thPercentile()); -diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java -index 4c5716e..764b5f8 100644 ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java -@@ -1,10 +1,13 @@ - package io.dropwizard.metrics5.collectd; - -+import static com.google.common.base.Preconditions.checkState; -+import static java.nio.charset.StandardCharsets.US_ASCII; -+import static java.nio.charset.StandardCharsets.UTF_8; -+ - import java.io.IOException; - import java.nio.BufferOverflowException; - import java.nio.ByteBuffer; - import java.nio.ByteOrder; --import java.nio.charset.StandardCharsets; - import java.security.InvalidKeyException; - import java.security.MessageDigest; - import java.security.NoSuchAlgorithmException; -@@ -64,8 +67,8 @@ class PacketWriter { - PacketWriter(Sender sender, String username, String password, SecurityLevel securityLevel) { - this.sender = sender; - this.securityLevel = securityLevel; -- this.username = username != null ? username.getBytes(StandardCharsets.UTF_8) : null; -- this.password = password != null ? password.getBytes(StandardCharsets.UTF_8) : null; -+ this.username = username != null ? username.getBytes(UTF_8) : null; -+ this.password = password != null ? password.getBytes(UTF_8) : null; - } - - void write(MetaData metaData, Number... values) throws BufferOverflowException, IOException { -@@ -119,12 +122,12 @@ class PacketWriter { - } - - private void writeString(ByteBuffer buffer, int type, String val) { -- if (val == null || val.length() == 0) { -+ if (val == null || val.isEmpty()) { - return; - } - int len = HEADER_LEN + val.length() + 1; - writeHeader(buffer, type, len); -- buffer.put(val.getBytes(StandardCharsets.US_ASCII)).put(NULL); -+ buffer.put(val.getBytes(US_ASCII)).put(NULL); - } - - private void writeNumber(ByteBuffer buffer, int type, long val) { -@@ -236,9 +239,7 @@ class PacketWriter { - } catch (InvalidParameterSpecException e) { - throw new RuntimeException(e); - } -- if (iv.length != IV_LENGTH) { -- throw new IllegalStateException("Bad initialization vector"); -- } -+ checkState(iv.length == IV_LENGTH, "Bad initialization vector"); - final ByteBuffer output = ByteBuffer.allocate(input.remaining() * 2); - try { - cipher.doFinal(input, output); -@@ -261,9 +262,7 @@ class PacketWriter { - final MessageDigest digest = MessageDigest.getInstance(SHA_1_ALGORITHM); - digest.update(input); - final byte[] output = digest.digest(); -- if (output.length != SHA1_LENGTH) { -- throw new IllegalStateException("Bad SHA1 hash"); -- } -+ checkState(output.length == SHA1_LENGTH, "Bad SHA1 hash"); - return output; - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); -diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java -index 271e31b..4a99ab6 100644 ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/Sender.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.collectd; - -+import static com.google.common.base.Preconditions.checkState; -+ - import java.io.IOException; - import java.net.InetSocketAddress; - import java.nio.ByteBuffer; -@@ -19,9 +21,7 @@ public class Sender { - } - - public void connect() throws IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -+ checkState(!isConnected(), "Already connected"); - if (host != null) { - address = new InetSocketAddress(host, port); - } -diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java -index 4d62df2..c666135 100644 ---- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java -+++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java -@@ -1,37 +1,37 @@ - package io.dropwizard.metrics5.collectd; - --import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - - import io.dropwizard.metrics5.MetricRegistry; - import org.junit.jupiter.api.Test; - --class CollectdReporterSecurityTest { -+final class CollectdReporterSecurityTest { - - private final MetricRegistry registry = new MetricRegistry(); - - @Test -- void testUnableSetSecurityLevelToSignWithoutUsername() { -- assertThatIllegalArgumentException() -- .isThrownBy( -+ void unableSetSecurityLevelToSignWithoutUsername() { -+ assertThatThrownBy( - () -> - CollectdReporter.forRegistry(registry) - .withHostName("eddie") - .withSecurityLevel(SecurityLevel.SIGN) - .withPassword("t1_g3r") - .build(new Sender("localhost", 25826))) -- .withMessage("username is required for securityLevel: SIGN"); -+ .isInstanceOf(IllegalArgumentException.class) -+ .hasMessage("username is required for securityLevel: SIGN"); - } - - @Test -- void testUnableSetSecurityLevelToSignWithoutPassword() { -- assertThatIllegalArgumentException() -- .isThrownBy( -+ void unableSetSecurityLevelToSignWithoutPassword() { -+ assertThatThrownBy( - () -> - CollectdReporter.forRegistry(registry) - .withHostName("eddie") - .withSecurityLevel(SecurityLevel.SIGN) - .withUsername("scott") - .build(new Sender("localhost", 25826))) -- .withMessage("password is required for securityLevel: SIGN"); -+ .isInstanceOf(IllegalArgumentException.class) -+ .hasMessage("password is required for securityLevel: SIGN"); - } - } -diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java -index 6213497..2dd98c8 100644 ---- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java -+++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java -@@ -1,11 +1,14 @@ - package io.dropwizard.metrics5.collectd; - -+import static java.util.Collections.emptySortedMap; - import static java.util.concurrent.TimeUnit.MILLISECONDS; - import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; - -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Histogram; - import io.dropwizard.metrics5.Meter; -@@ -14,7 +17,6 @@ import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -25,7 +27,7 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - import org.junit.jupiter.api.extension.RegisterExtension; - --public class CollectdReporterTest { -+final class CollectdReporterTest { - @RegisterExtension public static Receiver receiver = new Receiver(25826); - - private final MetricRegistry registry = new MetricRegistry(); -@@ -96,7 +98,7 @@ public class CollectdReporterTest { - - @Test - void reportsCounters() throws Exception { -- Counter counter = mock(Counter.class); -+ Counter counter = mock(); - when(counter.getCount()).thenReturn(42L); - - reporter.report( -@@ -111,7 +113,7 @@ public class CollectdReporterTest { - - @Test - void reportsMeters() throws Exception { -- Meter meter = mock(Meter.class); -+ Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); -@@ -130,8 +132,8 @@ public class CollectdReporterTest { - - @Test - void reportsHistograms() throws Exception { -- Histogram histogram = mock(Histogram.class); -- Snapshot snapshot = mock(Snapshot.class); -+ Histogram histogram = mock(); -+ Snapshot snapshot = mock(); - when(histogram.getCount()).thenReturn(1L); - when(histogram.getSnapshot()).thenReturn(snapshot); - when(snapshot.getMax()).thenReturn(2L); -@@ -154,8 +156,8 @@ public class CollectdReporterTest { - - @Test - void reportsTimers() throws Exception { -- Timer timer = mock(Timer.class); -- Snapshot snapshot = mock(Snapshot.class); -+ Timer timer = mock(); -+ Snapshot snapshot = mock(); - when(timer.getSnapshot()).thenReturn(snapshot); - when(timer.getCount()).thenReturn(1L); - when(timer.getSnapshot()).thenReturn(snapshot); -@@ -195,14 +197,14 @@ public class CollectdReporterTest { - - @Test - void doesNotReportDisabledMetricAttributes() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getOneMinuteRate()).thenReturn(2.0); - when(meter.getFiveMinuteRate()).thenReturn(3.0); - when(meter.getFifteenMinuteRate()).thenReturn(4.0); - when(meter.getMeanRate()).thenReturn(5.0); - -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(11L); - - CollectdReporter reporter = -@@ -236,37 +238,37 @@ public class CollectdReporterTest { - } - - @Test -- void testUnableSetSecurityLevelToSignWithoutUsername() { -- assertThatIllegalArgumentException() -- .isThrownBy( -+ void unableSetSecurityLevelToSignWithoutUsername() { -+ assertThatThrownBy( - () -> - CollectdReporter.forRegistry(registry) - .withHostName("eddie") - .withSecurityLevel(SecurityLevel.SIGN) - .withPassword("t1_g3r") - .build(new Sender("localhost", 25826))) -- .withMessage("username is required for securityLevel: SIGN"); -+ .isInstanceOf(IllegalArgumentException.class) -+ .hasMessage("username is required for securityLevel: SIGN"); - } - - @Test -- void testUnableSetSecurityLevelToSignWithoutPassword() { -- assertThatIllegalArgumentException() -- .isThrownBy( -+ void unableSetSecurityLevelToSignWithoutPassword() { -+ assertThatThrownBy( - () -> - CollectdReporter.forRegistry(registry) - .withHostName("eddie") - .withSecurityLevel(SecurityLevel.SIGN) - .withUsername("scott") - .build(new Sender("localhost", 25826))) -- .withMessage("password is required for securityLevel: SIGN"); -+ .isInstanceOf(IllegalArgumentException.class) -+ .hasMessage("password is required for securityLevel: SIGN"); - } - - private SortedMap map() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - private SortedMap map(MetricName name, T metric) { -- final Map map = Collections.singletonMap(name, metric); -+ final Map map = ImmutableMap.of(name, metric); - return new TreeMap<>(map); - } - -@@ -289,6 +291,6 @@ public class CollectdReporterTest { - - private List nextValues(Receiver receiver) throws Exception { - final ValueList valueList = receiver.next(); -- return valueList == null ? Collections.emptyList() : valueList.getValues(); -+ return valueList == null ? ImmutableList.of() : valueList.getValues(); - } - } -diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java -index 27d6b2f..53749ca 100644 ---- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java -+++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java -@@ -17,7 +17,7 @@ import javax.crypto.spec.IvParameterSpec; - import javax.crypto.spec.SecretKeySpec; - import org.junit.jupiter.api.Test; - --class PacketWriterTest { -+final class PacketWriterTest { - - private MetaData metaData = - new MetaData.Builder("nw-1.alpine.example.com", 1520961345L, 100) -@@ -28,7 +28,7 @@ class PacketWriterTest { - private String password = "t1_g$r"; - - @Test -- void testSignRequest() throws Exception { -+ void signRequest() throws Exception { - AtomicBoolean packetVerified = new AtomicBoolean(); - Sender sender = - new Sender("localhost", 4009) { -@@ -74,7 +74,7 @@ class PacketWriterTest { - } - - @Test -- void testEncryptRequest() throws Exception { -+ void encryptRequest() throws Exception { - AtomicBoolean packetVerified = new AtomicBoolean(); - Sender sender = - new Sender("localhost", 4009) { -@@ -190,6 +190,6 @@ class PacketWriterTest { - assertThat(amountOfValues).isEqualTo((short) 1); - byte dataType = packet.get(); - assertThat(dataType).isEqualTo((byte) 1); -- assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isEqualTo(42.0, offset(0.01)); -+ assertThat(packet.order(ByteOrder.LITTLE_ENDIAN).getDouble()).isCloseTo(42.0, offset(0.01)); - } - } -diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java -index 365d6bd..52ee6cc 100644 ---- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java -+++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java -@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; - - import org.junit.jupiter.api.Test; - --class SanitizeTest { -+final class SanitizeTest { - - private Sanitize sanitize = new Sanitize(Sanitize.DEFAULT_MAX_LENGTH); - -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java -index 22c8d4c..6e22c83 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java -@@ -1,8 +1,9 @@ - package io.dropwizard.metrics5; - -+ -+import com.google.common.collect.ImmutableSet; - import java.io.PrintStream; - import java.text.DateFormat; --import java.util.Collections; - import java.util.Date; - import java.util.Locale; - import java.util.Map; -@@ -53,7 +54,7 @@ public class ConsoleReporter extends ScheduledReporter { - this.filter = MetricFilter.ALL; - this.executor = null; - this.shutdownExecutorOnStop = true; -- disabledMetricAttributes = Collections.emptySet(); -+ disabledMetricAttributes = ImmutableSet.of(); - } - - /** -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java -index cff228f..6f77ff9 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java -@@ -179,7 +179,7 @@ public class CsvReporter extends ScheduledReporter { - } - } - -- private static final Logger LOGGER = LoggerFactory.getLogger(CsvReporter.class); -+ private static final Logger LOG = LoggerFactory.getLogger(CsvReporter.class); - - private final File directory; - private final Locale locale; -@@ -391,7 +391,7 @@ public class CsvReporter extends ScheduledReporter { - } - } - } catch (IOException e) { -- LOGGER.warn("Error writing to {}", name, e); -+ LOG.warn("Error writing to {}", name, e); - } - } - -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java b/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java -index 4770275..6e9741a 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ExponentialMovingAverages.java -@@ -17,9 +17,9 @@ public class ExponentialMovingAverages implements MovingAverages { - * If ticking would reduce even Long.MAX_VALUE in the 15 minute EWMA below this target then don't - * bother ticking in a loop and instead reset all the EWMAs. - */ -- private static final double maxTickZeroTarget = 0.0001; -+ private static final double MAX_TICK_ZERO_TARGET = 0.0001; - -- private static final int maxTicks; -+ private static final int MAX_TICKS; - private static final long TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5); - - static { -@@ -29,8 +29,8 @@ public class ExponentialMovingAverages implements MovingAverages { - do { - m3.tick(); - m3Ticks++; -- } while (m3.getRate(TimeUnit.SECONDS) > maxTickZeroTarget); -- maxTicks = m3Ticks; -+ } while (m3.getRate(TimeUnit.SECONDS) > MAX_TICK_ZERO_TARGET); -+ MAX_TICKS = m3Ticks; - } - - private final EWMA m1Rate = EWMA.oneMinuteEWMA(); -@@ -69,7 +69,7 @@ public class ExponentialMovingAverages implements MovingAverages { - if (lastTick.compareAndSet(oldTick, newIntervalStartTick)) { - sum.add(age); - final long requiredTicks = age / TICK_INTERVAL; -- if (requiredTicks >= maxTicks) { -+ if (requiredTicks >= MAX_TICKS) { - m1Rate.reset(); - m5Rate.reset(); - m15Rate.reset(); -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java -index 6c0a2ff..43690af 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java -@@ -1,8 +1,10 @@ - package io.dropwizard.metrics5; - -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.util.Objects.requireNonNull; -+ - import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; - import java.time.Duration; --import java.util.Objects; - import java.util.concurrent.ConcurrentSkipListMap; - import java.util.concurrent.ThreadLocalRandom; - import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -@@ -41,7 +43,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - - private static final double SECONDS_PER_NANO = .000_000_001D; - private static final AtomicReferenceFieldUpdater -- stateUpdater = -+ STATE_UPDATER = - AtomicReferenceFieldUpdater.newUpdater( - LockFreeExponentiallyDecayingReservoir.class, State.class, "state"); - -@@ -53,7 +55,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - - private static final class State { - -- private static final AtomicIntegerFieldUpdater countUpdater = -+ private static final AtomicIntegerFieldUpdater COUNT_UPDATER = - AtomicIntegerFieldUpdater.newUpdater(State.class, "count"); - - private final double alphaNanos; -@@ -89,7 +91,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - private void addSample( - double priority, long value, double itemWeight, boolean bypassIncrement) { - if (values.putIfAbsent(priority, new WeightedSample(value, itemWeight)) == null -- && (bypassIncrement || countUpdater.incrementAndGet(this) > size)) { -+ && (bypassIncrement || COUNT_UPDATER.incrementAndGet(this) > size)) { - values.pollFirstEntry(); - } - } -@@ -126,7 +128,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - // It's possible that more values were added while the map was scanned, those with the - // minimum priorities are removed. - while (newCount > size) { -- Objects.requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); -+ requireNonNull(newValues.pollFirstEntry(), "Expected an entry"); - newCount--; - } - return new State(alphaNanos, size, newTick, newCount, newValues); -@@ -193,7 +195,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - - private State doRescale(long currentTick, State stateSnapshot) { - State newState = stateSnapshot.rescale(currentTick); -- if (stateUpdater.compareAndSet(this, stateSnapshot, newState)) { -+ if (STATE_UPDATER.compareAndSet(this, stateSnapshot, newState)) { - // newState successfully installed - return newState; - } -@@ -235,10 +237,8 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - * are replaced (based on weight, with some amount of random jitter). - */ - public Builder size(int value) { -- if (value <= 0) { -- throw new IllegalArgumentException( -- "LockFreeExponentiallyDecayingReservoir size must be positive: " + value); -- } -+ checkArgument( -+ value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: " + value); - this.size = value; - return this; - } -@@ -254,13 +254,13 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - - /** Interval at which this reservoir is rescaled. */ - public Builder rescaleThreshold(Duration value) { -- this.rescaleThreshold = Objects.requireNonNull(value, "rescaleThreshold is required"); -+ this.rescaleThreshold = requireNonNull(value, "rescaleThreshold is required"); - return this; - } - - /** Clock instance used for decay. */ - public Builder clock(Clock value) { -- this.clock = Objects.requireNonNull(value, "clock is required"); -+ this.clock = requireNonNull(value, "clock is required"); - return this; - } - -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java -index 5779398..e3ac43a 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricName.java -@@ -1,13 +1,19 @@ - package io.dropwizard.metrics5; - --import java.util.Collections; --import java.util.Comparator; -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.util.Collections.unmodifiableMap; -+import static java.util.Map.Entry.comparingByKey; -+import static java.util.Objects.requireNonNull; -+import static java.util.stream.Collectors.joining; -+ -+import com.google.common.base.Strings; -+import com.google.common.collect.ImmutableMap; -+import java.util.Arrays; - import java.util.HashMap; - import java.util.Iterator; - import java.util.LinkedHashMap; - import java.util.Map; - import java.util.Objects; --import java.util.stream.Collectors; - import java.util.stream.Stream; - - /** -@@ -17,7 +23,7 @@ import java.util.stream.Stream; - public class MetricName implements Comparable { - - private static final String SEPARATOR = "."; -- private static final Map EMPTY_TAGS = Collections.emptyMap(); -+ private static final Map EMPTY_TAGS = ImmutableMap.of(); - static final MetricName EMPTY = new MetricName("", EMPTY_TAGS); - - /** -@@ -33,7 +39,7 @@ public class MetricName implements Comparable { - private final Map tags; - - public MetricName(String key, Map tags) { -- this.key = Objects.requireNonNull(key); -+ this.key = requireNonNull(key); - this.tags = tags.isEmpty() ? EMPTY_TAGS : unmodifiableSortedCopy(tags); - } - -@@ -63,9 +69,9 @@ public class MetricName implements Comparable { - } - - String newKey = -- Stream.concat(Stream.of(key), Stream.of(parts)) -- .filter(s -> s != null && !s.isEmpty()) -- .collect(Collectors.joining(SEPARATOR)); -+ Stream.concat(Stream.of(key), Arrays.stream(parts)) -+ .filter(s -> !Strings.isNullOrEmpty(s)) -+ .collect(joining(SEPARATOR)); - return new MetricName(newKey, tags); - } - -@@ -94,9 +100,7 @@ public class MetricName implements Comparable { - return this; - } - -- if (pairs.length % 2 != 0) { -- throw new IllegalArgumentException("Argument count must be even"); -- } -+ checkArgument(pairs.length % 2 == 0, "Argument count must be even"); - - final Map add = new HashMap<>(); - for (int i = 0; i < pairs.length; i += 2) { -@@ -201,8 +205,8 @@ public class MetricName implements Comparable { - private static , V> Map unmodifiableSortedCopy(Map map) { - LinkedHashMap sorted = new LinkedHashMap<>(); - map.entrySet().stream() -- .sorted(Comparator.comparing(Map.Entry::getKey)) -+ .sorted(comparingByKey()) - .forEach(e -> sorted.put(e.getKey(), e.getValue())); -- return Collections.unmodifiableMap(sorted); -+ return unmodifiableMap(sorted); - } - } -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java -index 806cef0..d30ac87 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java -@@ -1,6 +1,10 @@ - package io.dropwizard.metrics5; - --import java.util.Collections; -+import static java.util.Collections.unmodifiableMap; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Collections.unmodifiableSortedSet; -+import static java.util.Objects.requireNonNull; -+ - import java.util.List; - import java.util.Map; - import java.util.SortedMap; -@@ -91,9 +95,7 @@ public class MetricRegistry implements MetricSet { - * @throws IllegalArgumentException if the name is already registered or metric variable is null - */ - public T register(MetricName name, T metric) throws IllegalArgumentException { -- if (metric == null) { -- throw new NullPointerException("metric == null"); -- } -+ requireNonNull(metric, "metric == null"); - - if (metric instanceof MetricRegistry) { - final MetricRegistry childRegistry = (MetricRegistry) metric; -@@ -213,7 +215,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Counter.class.isInstance(metric); -+ return metric instanceof Counter; - } - }); - } -@@ -253,7 +255,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Histogram.class.isInstance(metric); -+ return metric instanceof Histogram; - } - }); - } -@@ -293,7 +295,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Meter.class.isInstance(metric); -+ return metric instanceof Meter; - } - }); - } -@@ -328,7 +330,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Timer.class.isInstance(metric); -+ return metric instanceof Timer; - } - }); - } -@@ -366,7 +368,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Gauge.class.isInstance(metric); -+ return metric instanceof Gauge; - } - }); - } -@@ -430,7 +432,7 @@ public class MetricRegistry implements MetricSet { - * @return the names of all the metrics - */ - public SortedSet getNames() { -- return Collections.unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); -+ return unmodifiableSortedSet(new TreeSet<>(metrics.keySet())); - } - - /** -@@ -455,7 +457,7 @@ public class MetricRegistry implements MetricSet { - timers.put(entry.getKey(), (Gauge) entry.getValue()); - } - } -- return Collections.unmodifiableSortedMap(timers); -+ return unmodifiableSortedMap(timers); - } - - /** -@@ -562,7 +564,7 @@ public class MetricRegistry implements MetricSet { - timers.put(entry.getKey(), (T) entry.getValue()); - } - } -- return Collections.unmodifiableSortedMap(timers); -+ return unmodifiableSortedMap(timers); - } - - private void onMetricAdded(MetricName name, Metric metric) { -@@ -627,7 +629,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public Map getMetrics() { -- return Collections.unmodifiableMap(metrics); -+ return unmodifiableMap(metrics); - } - - @FunctionalInterface -@@ -646,7 +648,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Counter.class.isInstance(metric); -+ return metric instanceof Counter; - } - }; - -@@ -659,7 +661,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Histogram.class.isInstance(metric); -+ return metric instanceof Histogram; - } - }; - -@@ -672,7 +674,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Meter.class.isInstance(metric); -+ return metric instanceof Meter; - } - }; - -@@ -685,7 +687,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Timer.class.isInstance(metric); -+ return metric instanceof Timer; - } - }; - -@@ -699,7 +701,7 @@ public class MetricRegistry implements MetricSet { - - @Override - public boolean isInstance(Metric metric) { -- return Gauge.class.isInstance(metric); -+ return metric instanceof Gauge; - } - }; - -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java b/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java -index 79d3683..7630290 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/NoopMetricRegistry.java -@@ -1,11 +1,14 @@ - package io.dropwizard.metrics5; - -+import static java.util.Collections.emptySortedMap; -+import static java.util.Collections.emptySortedSet; - import static java.util.Objects.requireNonNull; - -+import com.google.common.collect.ImmutableMap; -+import com.google.common.collect.ImmutableSet; - import java.io.OutputStream; - import java.time.Duration; - import java.util.Collection; --import java.util.Collections; - import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -158,67 +161,67 @@ public final class NoopMetricRegistry extends MetricRegistry { - /** {@inheritDoc} */ - @Override - public SortedSet getNames() { -- return Collections.emptySortedSet(); -+ return emptySortedSet(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap> getGauges() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap> getGauges(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getCounters() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getCounters(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getHistograms() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getHistograms(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getMeters() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getMeters(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getTimers() { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ - @Override - public SortedMap getTimers(MetricFilter filter) { -- return Collections.emptySortedMap(); -+ return emptySortedMap(); - } - - /** {@inheritDoc} */ -@@ -236,7 +239,7 @@ public final class NoopMetricRegistry extends MetricRegistry { - /** {@inheritDoc} */ - @Override - public Map getMetrics() { -- return Collections.emptyMap(); -+ return ImmutableMap.of(); - } - - static final class NoopMetric implements Metric { -@@ -630,19 +633,19 @@ public final class NoopMetricRegistry extends MetricRegistry { - /** {@inheritDoc} */ - @Override - public Set keySet() { -- return Collections.emptySet(); -+ return ImmutableSet.of(); - } - - /** {@inheritDoc} */ - @Override - public Collection values() { -- return Collections.emptySet(); -+ return ImmutableSet.of(); - } - - /** {@inheritDoc} */ - @Override - public Set> entrySet() { -- return Collections.emptySet(); -+ return ImmutableSet.of(); - } - } - } -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java -index 9269921..0b6827d 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java -@@ -1,7 +1,10 @@ - package io.dropwizard.metrics5; - -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.util.Objects.requireNonNull; -+ -+import com.google.common.collect.ImmutableSet; - import java.io.Closeable; --import java.util.Collections; - import java.util.Locale; - import java.util.Set; - import java.util.SortedMap; -@@ -128,7 +131,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - durationUnit, - executor, - shutdownExecutorOnStop, -- Collections.emptySet()); -+ ImmutableSet.of()); - } - - protected ScheduledReporter( -@@ -141,9 +144,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - boolean shutdownExecutorOnStop, - Set disabledMetricAttributes) { - -- if (registry == null) { -- throw new NullPointerException("registry == null"); -- } -+ requireNonNull(registry, "registry == null"); - - this.registry = registry; - this.filter = filter; -@@ -154,7 +155,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - this.durationFactor = durationUnit.toNanos(1); - this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); - this.disabledMetricAttributes = -- disabledMetricAttributes != null ? disabledMetricAttributes : Collections.emptySet(); -+ disabledMetricAttributes != null ? disabledMetricAttributes : ImmutableSet.of(); - } - - /** -@@ -172,9 +173,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - * for testing. - */ - synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) { -- if (this.scheduledFuture != null) { -- throw new IllegalArgumentException("Reporter already started"); -- } -+ checkArgument(this.scheduledFuture == null, "Reporter already started"); - - this.scheduledFuture = getScheduledFuture(initialDelay, period, unit, runnable); - } -@@ -185,8 +184,8 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - * @deprecated Use {@link #getScheduledFuture(long, long, TimeUnit, Runnable, - * ScheduledExecutorService)} instead. - */ -- @SuppressWarnings("DeprecatedIsStillUsed") - @Deprecated -+ @SuppressWarnings("DeprecatedIsStillUsed") - protected ScheduledFuture getScheduledFuture( - long initialDelay, long period, TimeUnit unit, Runnable runnable) { - return getScheduledFuture(initialDelay, period, unit, runnable, this.executor); -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java b/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java -index a36606a..9787356 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SharedMetricRegistries.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5; - -+import static com.google.common.base.Preconditions.checkState; -+ - import java.util.Set; - import java.util.concurrent.ConcurrentHashMap; - import java.util.concurrent.ConcurrentMap; -@@ -84,9 +86,7 @@ public class SharedMetricRegistries { - */ - public static MetricRegistry getDefault() { - MetricRegistry metricRegistry = tryGetDefault(); -- if (metricRegistry == null) { -- throw new IllegalStateException("Default registry name has not been set."); -- } -+ checkState(metricRegistry != null, "Default registry name has not been set."); - return metricRegistry; - } - -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java -index 9ab54ba..06dfa94 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/Slf4jReporter.java -@@ -4,10 +4,8 @@ import static io.dropwizard.metrics5.MetricAttribute.COUNT; - import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; - import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; - import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MAX; - import static io.dropwizard.metrics5.MetricAttribute.MEAN; - import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MIN; - import static io.dropwizard.metrics5.MetricAttribute.P50; - import static io.dropwizard.metrics5.MetricAttribute.P75; - import static io.dropwizard.metrics5.MetricAttribute.P95; -@@ -16,7 +14,7 @@ import static io.dropwizard.metrics5.MetricAttribute.P99; - import static io.dropwizard.metrics5.MetricAttribute.P999; - import static io.dropwizard.metrics5.MetricAttribute.STDDEV; - --import java.util.Collections; -+import com.google.common.collect.ImmutableSet; - import java.util.Map.Entry; - import java.util.Set; - import java.util.SortedMap; -@@ -81,7 +79,7 @@ public class Slf4jReporter extends ScheduledReporter { - this.loggingLevel = LoggingLevel.INFO; - this.executor = null; - this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -+ this.disabledMetricAttributes = ImmutableSet.of(); - } - - /** -@@ -306,8 +304,8 @@ public class Slf4jReporter extends ScheduledReporter { - b.append("type=TIMER"); - append(b, "name", prefix(name)); - appendCountIfEnabled(b, timer); -- appendLongDurationIfEnabled(b, MIN, snapshot::getMin); -- appendLongDurationIfEnabled(b, MAX, snapshot::getMax); -+ appendLongDurationIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); -+ appendLongDurationIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); - appendDoubleDurationIfEnabled(b, MEAN, snapshot::getMean); - appendDoubleDurationIfEnabled(b, STDDEV, snapshot::getStdDev); - appendDoubleDurationIfEnabled(b, P50, snapshot::getMedian); -@@ -338,8 +336,8 @@ public class Slf4jReporter extends ScheduledReporter { - b.append("type=HISTOGRAM"); - append(b, "name", prefix(name)); - appendCountIfEnabled(b, histogram); -- appendLongIfEnabled(b, MIN, snapshot::getMin); -- appendLongIfEnabled(b, MAX, snapshot::getMax); -+ appendLongIfEnabled(b, MetricAttribute.MIN, snapshot::getMin); -+ appendLongIfEnabled(b, MetricAttribute.MAX, snapshot::getMax); - appendDoubleIfEnabled(b, MEAN, snapshot::getMean); - appendDoubleIfEnabled(b, STDDEV, snapshot::getStdDev); - appendDoubleIfEnabled(b, P50, snapshot::getMedian); -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java -index e70b020..cccf48a 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAverages.java -@@ -186,8 +186,7 @@ public class SlidingTimeWindowMovingAverages implements MovingAverages { - buckets.stream().limit(toIndex).mapToLong(LongAdder::longValue).forEach(adder::add); - buckets.stream().skip(fromIndex).mapToLong(LongAdder::longValue).forEach(adder::add); - } -- long retval = adder.longValue(); -- return retval; -+ return adder.longValue(); - } - - @Override -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java -index 3416ecf..28c6a60 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5; - -+import static com.google.common.base.Preconditions.checkArgument; - import static java.lang.Math.floor; - import static java.nio.charset.StandardCharsets.UTF_8; - -@@ -47,9 +48,9 @@ public class UniformSnapshot extends Snapshot { - */ - @Override - public double getValue(double quantile) { -- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { -- throw new IllegalArgumentException(quantile + " is not in [0..1]"); -- } -+ checkArgument( -+ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), -+ quantile + " is not in [0..1]"); - - if (values.length == 0) { - return 0.0; -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java -index 9ef6212..156bd3c 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java -@@ -1,13 +1,14 @@ - package io.dropwizard.metrics5; - -+import static com.google.common.base.Preconditions.checkArgument; - import static java.nio.charset.StandardCharsets.UTF_8; -+import static java.util.Comparator.comparingLong; - - import java.io.OutputStream; - import java.io.OutputStreamWriter; - import java.io.PrintWriter; - import java.util.Arrays; - import java.util.Collection; --import java.util.Comparator; - - /** A statistical snapshot of a {@link WeightedSnapshot}. */ - public class WeightedSnapshot extends Snapshot { -@@ -35,7 +36,7 @@ public class WeightedSnapshot extends Snapshot { - public WeightedSnapshot(Collection values) { - final WeightedSample[] copy = values.toArray(new WeightedSample[] {}); - -- Arrays.sort(copy, Comparator.comparingLong(w -> w.value)); -+ Arrays.sort(copy, comparingLong(w -> w.value)); - - this.values = new long[copy.length]; - this.normWeights = new double[copy.length]; -@@ -64,9 +65,9 @@ public class WeightedSnapshot extends Snapshot { - */ - @Override - public double getValue(double quantile) { -- if (quantile < 0.0 || quantile > 1.0 || Double.isNaN(quantile)) { -- throw new IllegalArgumentException(quantile + " is not in [0..1]"); -- } -+ checkArgument( -+ quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), -+ quantile + " is not in [0..1]"); - - if (values.length == 0) { - return 0.0; -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java -index ba6975e..356b1a5 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertTrue; - - import java.util.ArrayList; - import java.util.List; -@@ -15,8 +14,8 @@ import org.junit.jupiter.api.Test; - import org.slf4j.Logger; - import org.slf4j.LoggerFactory; - --class CachedGaugeTest { -- private static final Logger LOGGER = LoggerFactory.getLogger(CachedGaugeTest.class); -+final class CachedGaugeTest { -+ private static final Logger LOG = LoggerFactory.getLogger(CachedGaugeTest.class); - private static final int THREAD_COUNT = 10; - private static final long RUNNING_TIME_MILLIS = TimeUnit.SECONDS.toMillis(10); - -@@ -100,12 +99,12 @@ class CachedGaugeTest { - Integer newValue = shortTimeoutGauge.getValue(); - - if (newValue == null) { -- LOGGER.warn("Cached gauge returned null value"); -+ LOG.warn("Cached gauge returned null value"); - return false; - } - - if (newValue < lastValue) { -- LOGGER.error( -+ LOG.error( - "Cached gauge returned stale value, last: {}, new: {}", - lastValue, - newValue); -@@ -122,7 +121,7 @@ class CachedGaugeTest { - } - - for (int i = 0; i < futures.size(); i++) { -- assertTrue(futures.get(i).get(), "Future " + i + " failed"); -+ assertThat(futures.get(i).get()).withFailMessage("Future " + i + " failed").isTrue(); - } - - executor.shutdown(); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java -index 7b1f2a0..c95bb23 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java -@@ -4,10 +4,10 @@ import static org.assertj.core.api.BDDAssertions.then; - - import org.junit.jupiter.api.Test; - --class ChunkedAssociativeLongArrayTest { -+final class ChunkedAssociativeLongArrayTest { - - @Test -- void testTrim() { -+ void trim() { - ChunkedAssociativeLongArray array = new ChunkedAssociativeLongArray(3); - array.put(-3, 3); - array.put(-2, 1); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java -index 0cf31e2..3f0840f 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClassMetadataTest.java -@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat; - - import org.junit.jupiter.api.Test; - --public class ClassMetadataTest { -+final class ClassMetadataTest { - @Test -- public void testParameterMetadataIsAvailable() throws NoSuchMethodException { -+ void parameterMetadataIsAvailable() throws NoSuchMethodException { - assertThat(DefaultSettableGauge.class.getConstructor(Object.class).getParameters()) - .allSatisfy(parameter -> assertThat(parameter.isNamePresent()).isTrue()); - } -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java -index 3d35a89..bb669f9 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java -@@ -5,15 +5,15 @@ import static org.assertj.core.api.Assertions.offset; - - import org.junit.jupiter.api.Test; - --class ClockTest { -+final class ClockTest { - - @Test - void userTimeClock() { - final Clock.UserTimeClock clock = new Clock.UserTimeClock(); - -- assertThat((double) clock.getTime()).isEqualTo(System.currentTimeMillis(), offset(100.0)); -+ assertThat((double) clock.getTime()).isCloseTo(System.currentTimeMillis(), offset(100.0)); - -- assertThat((double) clock.getTick()).isEqualTo(System.nanoTime(), offset(1000000.0)); -+ assertThat((double) clock.getTick()).isCloseTo(System.nanoTime(), offset(1000000.0)); - } - - @Test -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java -index 2544152..f6d1b2e 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java -@@ -19,12 +19,12 @@ import org.apache.commons.lang3.SystemUtils; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class ConsoleReporterTest { -+final class ConsoleReporterTest { - private final Locale locale = Locale.US; - private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); - -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final Clock clock = mock(Clock.class); -+ private final MetricRegistry registry = mock(); -+ private final Clock clock = mock(); - private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - private final PrintStream output = new PrintStream(bytes); - private final ConsoleReporter reporter = -@@ -74,7 +74,7 @@ class ConsoleReporterTest { - - @Test - void reportsCounterValues() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); -@@ -93,11 +93,11 @@ class ConsoleReporterTest { - - @Test - void reportsHistogramValues() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - when(histogram.getSum()).thenReturn(4L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -138,7 +138,7 @@ class ConsoleReporterTest { - - @Test - void reportsMeterValues() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getSum()).thenReturn(3L); - when(meter.getMeanRate()).thenReturn(2.0); -@@ -167,7 +167,7 @@ class ConsoleReporterTest { - - @Test - void reportsTimerValues() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(5)); - when(timer.getMeanRate()).thenReturn(2.0); -@@ -175,7 +175,7 @@ class ConsoleReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -239,7 +239,7 @@ class ConsoleReporterTest { - .disabledMetricAttributes(disabledMetricAttributes) - .build(); - -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getSum()).thenReturn(5L); - when(meter.getMeanRate()).thenReturn(2.0); -@@ -283,7 +283,7 @@ class ConsoleReporterTest { - .disabledMetricAttributes(disabledMetricAttributes) - .build(); - -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); - when(timer.getMeanRate()).thenReturn(2.0); -@@ -291,7 +291,7 @@ class ConsoleReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -349,11 +349,11 @@ class ConsoleReporterTest { - .disabledMetricAttributes(disabledMetricAttributes) - .build(); - -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - when(histogram.getSum()).thenReturn(5L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java -index cbff53e..6f4778a 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java -@@ -4,12 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat; - - import org.junit.jupiter.api.Test; - --class CounterTest { -+final class CounterTest { - private final Counter counter = new Counter(); - - @Test - void startsAtZero() { -- assertThat(counter.getCount()).isZero(); -+ assertThat(counter.getCount()).isEqualTo(0); - } - - @Test -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java -index bebc00e..63b9baf 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5; - -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; -@@ -7,7 +8,6 @@ import static org.mockito.Mockito.when; - - import java.io.File; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.nio.file.Files; - import java.util.Locale; - import java.util.SortedMap; -@@ -17,11 +17,11 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - import org.junit.jupiter.api.io.TempDir; - --public class CsvReporterTest { -+final class CsvReporterTest { - @TempDir public File folder; - -- private final MetricRegistry registry = mock(MetricRegistry.class); -- private final Clock clock = mock(Clock.class); -+ private final MetricRegistry registry = mock(); -+ private final Clock clock = mock(); - - private File dataDirectory; - private CsvReporter reporter; -@@ -53,7 +53,7 @@ public class CsvReporterTest { - - @Test - void reportsCounterValues() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); -@@ -63,11 +63,11 @@ public class CsvReporterTest { - - @Test - void reportsHistogramValues() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - when(histogram.getSum()).thenReturn(12L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -105,7 +105,7 @@ public class CsvReporterTest { - - @Test - void reportsTimerValues() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); - when(timer.getMeanRate()).thenReturn(2.0); -@@ -113,7 +113,7 @@ public class CsvReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -137,8 +137,8 @@ public class CsvReporterTest { - } - - @Test -- void testCsvFileProviderIsUsed() { -- CsvFileProvider fileProvider = mock(CsvFileProvider.class); -+ void csvFileProviderIsUsed() { -+ CsvFileProvider fileProvider = mock(); - when(fileProvider.getFile(dataDirectory, "gauge")) - .thenReturn(new File(dataDirectory, "guage.csv")); - -@@ -177,7 +177,7 @@ public class CsvReporterTest { - } - - private Meter mockMeter() { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getSum()).thenReturn(6L); - when(meter.getMeanRate()).thenReturn(2.0); -@@ -198,8 +198,7 @@ public class CsvReporterTest { - - @SuppressWarnings("FilesReadStringWithCharset") - private String fileContents(String filename) throws IOException { -- return new String( -- Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); -+ return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), UTF_8); - } - - private SortedMap map() { -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java -index d5fdf29..70b5c03 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java -@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; - - import org.junit.jupiter.api.Test; - --class DefaultSettableGaugeTest { -+final class DefaultSettableGaugeTest { - @Test - void newSettableGaugeWithoutDefaultReturnsNull() { - DefaultSettableGauge gauge = new DefaultSettableGauge<>(); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java -index 9b09b3c..557ac5c 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java -@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; - - import org.junit.jupiter.api.Test; - --class DerivativeGaugeTest { -+final class DerivativeGaugeTest { - private final Gauge gauge1 = () -> "woo"; - private final Gauge gauge2 = - new DerivativeGauge(gauge1) { -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java -index a373839..e4318b9 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java -@@ -6,74 +6,74 @@ import static org.assertj.core.api.Assertions.offset; - import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; - --class EWMATest { -+final class EWMATest { - @Test - void aOneMinuteEWMAWithAValueOfThree() { - final EWMA ewma = EWMA.oneMinuteEWMA(); - ewma.update(3); - ewma.tick(); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.01098938, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.01098938, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00404277, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00404277, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00148725, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00148725, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00054713, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00054713, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00020128, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00020128, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00007405, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00007405, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00002724, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00002724, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00001002, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00001002, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000369, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000369, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000136, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000136, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000050, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000050, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.00000018, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.00000018, offset(0.000001)); - } - - @Test -@@ -82,67 +82,67 @@ class EWMATest { - ewma.update(3); - ewma.tick(); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.18071653, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.18071653, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.14795818, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.14795818, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.12113791, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.12113791, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.09917933, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.09917933, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.08120117, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.08120117, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.06648190, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.06648190, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.05443077, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.05443077, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.04456415, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.04456415, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.03648604, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.03648604, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.02987224, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.02987224, offset(0.000001)); - } - - @Test -@@ -151,67 +151,67 @@ class EWMATest { - ewma.update(3); - ewma.tick(); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.6, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.6, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.56130419, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.56130419, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.52510399, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.52510399, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.49123845, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.49123845, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.45955700, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.45955700, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.42991879, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.42991879, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.40219203, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.40219203, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.37625345, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.37625345, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.35198773, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.35198773, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.32928698, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.32928698, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.30805027, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.30805027, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.28818318, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.28818318, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.26959738, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.26959738, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.25221023, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.25221023, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.23594443, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.23594443, offset(0.000001)); - - elapseMinute(ewma); - -- assertThat(ewma.getRate(TimeUnit.SECONDS)).isEqualTo(0.22072766, offset(0.000001)); -+ assertThat(ewma.getRate(TimeUnit.SECONDS)).isCloseTo(0.22072766, offset(0.000001)); - } - - private void elapseMinute(EWMA ewma) { -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java -index 2a21820..c1f8a8c 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentialMovingAveragesTest.java -@@ -7,10 +7,10 @@ import static org.mockito.Mockito.when; - import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; - --public class ExponentialMovingAveragesTest { -+final class ExponentialMovingAveragesTest { - @Test -- public void testMaxTicks() { -- final Clock clock = mock(Clock.class); -+ void maxTicks() { -+ final Clock clock = mock(); - when(clock.getTick()).thenReturn(0L, Long.MAX_VALUE); - final ExponentialMovingAverages ema = new ExponentialMovingAverages(clock); - ema.update(Long.MAX_VALUE); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java -index 5985e81..151ccbc 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5; - -+import static com.google.common.collect.ImmutableList.toImmutableList; - import static org.assertj.core.api.Assertions.assertThat; - - import java.util.Arrays; -@@ -7,11 +8,10 @@ import java.util.Collection; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicBoolean; - import java.util.concurrent.atomic.AtomicInteger; --import java.util.stream.Collectors; - import org.junit.jupiter.params.ParameterizedTest; - import org.junit.jupiter.params.provider.MethodSource; - --public class ExponentiallyDecayingReservoirTest { -+final class ExponentiallyDecayingReservoirTest { - - public enum ReservoirFactory { - EXPONENTIALLY_DECAYING() { -@@ -42,7 +42,7 @@ public class ExponentiallyDecayingReservoirTest { - public static Collection reservoirs() { - return Arrays.stream(ReservoirFactory.values()) - .map(value -> new Object[] {value}) -- .collect(Collectors.toList()); -+ .collect(toImmutableList()); - } - - private ReservoirFactory reservoirFactory; -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java -index c0a9f6b..5b003df 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java -@@ -8,7 +8,7 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - import org.junit.jupiter.api.io.TempDir; - --public class FixedNameCsvFileProviderTest { -+final class FixedNameCsvFileProviderTest { - @TempDir public File folder; - - private File dataDirectory; -@@ -19,7 +19,7 @@ public class FixedNameCsvFileProviderTest { - } - - @Test -- void testGetFile() { -+ void getFile() { - FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); - File file = provider.getFile(dataDirectory, "test"); - assertThat(file.getParentFile()).isEqualTo(dataDirectory); -@@ -27,7 +27,7 @@ public class FixedNameCsvFileProviderTest { - } - - @Test -- void testGetFileSanitize() { -+ void getFileSanitize() { - FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); - File file = provider.getFile(dataDirectory, "/myfake/uri"); - assertThat(file.getParentFile()).isEqualTo(dataDirectory); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java -index 770c53a..ec2901f 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java -@@ -7,14 +7,14 @@ import static org.mockito.Mockito.when; - - import org.junit.jupiter.api.Test; - --class HistogramTest { -- private final Reservoir reservoir = mock(Reservoir.class); -+final class HistogramTest { -+ private final Reservoir reservoir = mock(); - private final Histogram histogram = new Histogram(reservoir); - - @Test - void updatesTheCountAndSumOnUpdates() { -- assertThat(histogram.getCount()).isZero(); -- assertThat(histogram.getSum()).isZero(); -+ assertThat(histogram.getCount()).isEqualTo(0); -+ assertThat(histogram.getSum()).isEqualTo(0); - - histogram.update(1); - histogram.update(5); -@@ -25,7 +25,7 @@ class HistogramTest { - - @Test - void returnsTheSnapshotFromTheReservoir() { -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(reservoir.getSnapshot()).thenReturn(snapshot); - - assertThat(histogram.getSnapshot()).isEqualTo(snapshot); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java -index 46d7690..cfb2386 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java -@@ -19,10 +19,9 @@ import org.junit.jupiter.api.Test; - import org.slf4j.Logger; - import org.slf4j.LoggerFactory; - --class InstrumentedExecutorServiceTest { -+final class InstrumentedExecutorServiceTest { - -- private static final Logger LOGGER = -- LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); -+ private static final Logger LOG = LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); - private ExecutorService executor; - private MetricRegistry registry; - private InstrumentedExecutorService instrumentedExecutorService; -@@ -48,7 +47,7 @@ class InstrumentedExecutorServiceTest { - void tearDown() throws Exception { - instrumentedExecutorService.shutdown(); - if (!instrumentedExecutorService.awaitTermination(2, TimeUnit.SECONDS)) { -- LOGGER.error("InstrumentedExecutorService did not terminate."); -+ LOG.error("InstrumentedExecutorService did not terminate."); - } - } - -@@ -115,8 +114,8 @@ class InstrumentedExecutorServiceTest { - assertThat(idle.getSnapshot().size()).isEqualTo(1); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - void reportsTasksInformationForThreadPoolExecutor() throws Exception { - executor = - new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); -@@ -180,7 +179,7 @@ class InstrumentedExecutorServiceTest { - } - - @Test -- public void reportsRejectedTasksForThreadPoolExecutor() throws Exception { -+ void reportsRejectedTasksForThreadPoolExecutor() throws Exception { - executor = - new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1)); - instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); -@@ -207,7 +206,7 @@ class InstrumentedExecutorServiceTest { - } - - @Test -- public void removesMetricsAfterShutdownForThreadPoolExecutor() { -+ void removesMetricsAfterShutdownForThreadPoolExecutor() { - executor = - new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); - instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "stp"); -@@ -236,8 +235,8 @@ class InstrumentedExecutorServiceTest { - MetricRegistry.name("stp", "tasks.capacity")); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - void reportsTasksInformationForForkJoinPool() throws Exception { - executor = Executors.newWorkStealingPool(4); - instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); -@@ -291,7 +290,7 @@ class InstrumentedExecutorServiceTest { - } - - @Test -- public void removesMetricsAfterShutdownForForkJoinPool() { -+ void removesMetricsAfterShutdownForForkJoinPool() { - executor = Executors.newWorkStealingPool(4); - instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "sfjp"); - -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java -index fb9cbe9..b85071b 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java -@@ -13,8 +13,8 @@ import org.junit.jupiter.api.Test; - import org.slf4j.Logger; - import org.slf4j.LoggerFactory; - --class InstrumentedScheduledExecutorServiceTest { -- private static final Logger LOGGER = -+final class InstrumentedScheduledExecutorServiceTest { -+ private static final Logger LOG = - LoggerFactory.getLogger(InstrumentedScheduledExecutorServiceTest.class); - - private final ScheduledExecutorService scheduledExecutor = -@@ -35,17 +35,17 @@ class InstrumentedScheduledExecutorServiceTest { - private final Histogram percentOfPeriod = registry.histogram("xs.scheduled.percent-of-period"); - - @Test -- void testSubmitRunnable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ void submitRunnable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - Future theFuture = - instrumentedScheduledExecutor.submit( -@@ -53,87 +53,87 @@ class InstrumentedScheduledExecutorServiceTest { - assertThat(submitted.getCount()).isEqualTo(1); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - }); - - theFuture.get(); - - assertThat(submitted.getCount()).isEqualTo(1); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test -- void testScheduleRunnable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ void scheduleRunnable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - ScheduledFuture theFuture = - instrumentedScheduledExecutor.schedule( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - }, - 10L, - TimeUnit.MILLISECONDS); - - theFuture.get(); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test -- void testSubmitCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ void submitCallable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - final Object obj = new Object(); - -@@ -143,13 +143,13 @@ class InstrumentedScheduledExecutorServiceTest { - assertThat(submitted.getCount()).isEqualTo(1); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - return obj; - }); -@@ -158,45 +158,45 @@ class InstrumentedScheduledExecutorServiceTest { - - assertThat(submitted.getCount()).isEqualTo(1); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test -- void testScheduleCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ void scheduleCallable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - final Object obj = new Object(); - - ScheduledFuture theFuture = - instrumentedScheduledExecutor.schedule( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - return obj; - }, -@@ -205,37 +205,37 @@ class InstrumentedScheduledExecutorServiceTest { - - assertThat(theFuture.get()).isEqualTo(obj); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isEqualTo(1); - assertThat(duration.getCount()).isEqualTo(1); - assertThat(duration.getSnapshot().size()).isEqualTo(1); - - assertThat(scheduledOnce.getCount()).isEqualTo(1); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - } - - @Test -- void testScheduleFixedRateCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ void scheduleFixedRateCallable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - CountDownLatch countDownLatch = new CountDownLatch(1); - ScheduledFuture theFuture = - instrumentedScheduledExecutor.scheduleAtFixedRate( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); - -@@ -257,37 +257,37 @@ class InstrumentedScheduledExecutorServiceTest { - theFuture.cancel(true); - TimeUnit.MILLISECONDS.sleep(200); // Wait while the task is cancelled - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isNotEqualTo(0); - assertThat(duration.getCount()).isNotEqualTo(0); - assertThat(duration.getSnapshot().size()).isNotEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); - assertThat(scheduledRepetitively.getCount()).isEqualTo(1); - assertThat(scheduledOverrun.getCount()).isNotEqualTo(0); - assertThat(percentOfPeriod.getCount()).isNotEqualTo(0); - } - - @Test -- void testScheduleFixedDelayCallable() throws Exception { -- assertThat(submitted.getCount()).isZero(); -+ void scheduleFixedDelayCallable() throws Exception { -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -- assertThat(completed.getCount()).isZero(); -- assertThat(duration.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); -+ assertThat(completed.getCount()).isEqualTo(0); -+ assertThat(duration.getCount()).isEqualTo(0); - -- assertThat(scheduledOnce.getCount()).isZero(); -- assertThat(scheduledRepetitively.getCount()).isZero(); -- assertThat(scheduledOverrun.getCount()).isZero(); -- assertThat(percentOfPeriod.getCount()).isZero(); -+ assertThat(scheduledOnce.getCount()).isEqualTo(0); -+ assertThat(scheduledRepetitively.getCount()).isEqualTo(0); -+ assertThat(scheduledOverrun.getCount()).isEqualTo(0); -+ assertThat(percentOfPeriod.getCount()).isEqualTo(0); - - CountDownLatch countDownLatch = new CountDownLatch(1); - ScheduledFuture theFuture = - instrumentedScheduledExecutor.scheduleWithFixedDelay( - () -> { -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - - assertThat(running.getCount()).isEqualTo(1); - -@@ -310,9 +310,9 @@ class InstrumentedScheduledExecutorServiceTest { - theFuture.cancel(true); - TimeUnit.MILLISECONDS.sleep(200); - -- assertThat(submitted.getCount()).isZero(); -+ assertThat(submitted.getCount()).isEqualTo(0); - -- assertThat(running.getCount()).isZero(); -+ assertThat(running.getCount()).isEqualTo(0); - assertThat(completed.getCount()).isNotEqualTo(0); - assertThat(duration.getCount()).isNotEqualTo(0); - assertThat(duration.getSnapshot().size()).isNotEqualTo(0); -@@ -322,7 +322,7 @@ class InstrumentedScheduledExecutorServiceTest { - void tearDown() throws Exception { - instrumentedScheduledExecutor.shutdown(); - if (!instrumentedScheduledExecutor.awaitTermination(2, TimeUnit.SECONDS)) { -- LOGGER.error("InstrumentedScheduledExecutorService did not terminate."); -+ LOG.error("InstrumentedScheduledExecutorService did not terminate."); - } - } - } -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java -index fcd3736..1228864 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java -@@ -11,7 +11,7 @@ import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicInteger; - import org.junit.jupiter.api.Test; - --class InstrumentedThreadFactoryTest { -+final class InstrumentedThreadFactoryTest { - private static final int THREAD_COUNT = 10; - - private final ThreadFactory factory = Executors.defaultThreadFactory(); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java -index 32c2380..e2fe1d8 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java -@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit; - import org.junit.jupiter.params.ParameterizedTest; - import org.junit.jupiter.params.provider.MethodSource; - --public class MeterApproximationTest { -+final class MeterApproximationTest { - - public static Collection ratesPerMinute() { - Object[][] data = new Object[][] {{15}, {60}, {600}, {6000}}; -@@ -32,7 +32,7 @@ public class MeterApproximationTest { - 3, TimeUnit.MINUTES); - - assertThat(meter.getOneMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); - } - - @MethodSource("ratesPerMinute") -@@ -45,7 +45,7 @@ public class MeterApproximationTest { - 13, TimeUnit.MINUTES); - - assertThat(meter.getFiveMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); - } - - @MethodSource("ratesPerMinute") -@@ -58,7 +58,7 @@ public class MeterApproximationTest { - 38, TimeUnit.MINUTES); - - assertThat(meter.getFifteenMinuteRate() * 60.0) -- .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); -+ .isCloseTo(ratePerMinute, offset(0.1 * ratePerMinute)); - } - - private Meter simulateMetronome( -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java -index afddef9..f589811 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java -@@ -9,8 +9,8 @@ import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class MeterTest { -- private final Clock clock = mock(Clock.class); -+final class MeterTest { -+ private final Clock clock = mock(); - private final Meter meter = new Meter(clock); - - @BeforeEach -@@ -20,17 +20,17 @@ class MeterTest { - - @Test - void startsOutWithNoRatesOrCount() { -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - -- assertThat(meter.getSum()).isZero(); -+ assertThat(meter.getSum()).isEqualTo(0); - -- assertThat(meter.getMeanRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getMeanRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); - } - - @Test -@@ -42,12 +42,12 @@ class MeterTest { - - assertThat(meter.getSum()).isEqualTo(10000000000L); - -- assertThat(meter.getMeanRate()).isEqualTo(0.3, offset(0.001)); -+ assertThat(meter.getMeanRate()).isCloseTo(0.3, offset(0.001)); - -- assertThat(meter.getOneMinuteRate()).isEqualTo(0.1840, offset(0.001)); -+ assertThat(meter.getOneMinuteRate()).isCloseTo(0.1840, offset(0.001)); - -- assertThat(meter.getFiveMinuteRate()).isEqualTo(0.1966, offset(0.001)); -+ assertThat(meter.getFiveMinuteRate()).isCloseTo(0.1966, offset(0.001)); - -- assertThat(meter.getFifteenMinuteRate()).isEqualTo(0.1988, offset(0.001)); -+ assertThat(meter.getFifteenMinuteRate()).isCloseTo(0.1988, offset(0.001)); - } - } -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java -index 6152bde..53dfece 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java -@@ -5,7 +5,7 @@ import static org.mockito.Mockito.mock; - - import org.junit.jupiter.api.Test; - --class MetricFilterTest { -+final class MetricFilterTest { - @Test - void theAllFilterMatchesAllMetrics() { - assertThat(MetricFilter.ALL.matches(MetricName.build(""), mock(Metric.class))).isTrue(); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java -index 490c830..35860d7 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java -@@ -1,105 +1,106 @@ - package io.dropwizard.metrics5; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - - import java.util.HashMap; - import java.util.Map; - import org.junit.jupiter.api.Test; - --class MetricNameTest { -+final class MetricNameTest { - @Test -- void testEmpty() { -+ void empty() { - assertThat(MetricName.EMPTY.getTags()).isEmpty(); -- assertThat(MetricName.EMPTY.getKey()).isEqualTo(""); -+ assertThat(MetricName.EMPTY.getKey()).isEmpty(); - - assertThat(MetricName.build()).isEqualTo(MetricName.EMPTY); - assertThat(MetricName.EMPTY.resolve((String) null)).isEqualTo(MetricName.EMPTY); - } - - @Test -- void testEmptyResolve() { -+ void emptyResolve() { - final MetricName name = MetricName.build(); - assertThat(name.resolve("foo")).isEqualTo(MetricName.build("foo")); - } - - @Test -- void testResolveToEmpty() { -+ void resolveToEmpty() { - final MetricName name = MetricName.build("foo"); - assertThat(name.resolve((String) null)).isEqualTo(MetricName.build("foo")); - } - - @Test -- void testResolve() { -+ void resolve() { - final MetricName name = MetricName.build("foo"); - assertThat(name.resolve("bar")).isEqualTo(MetricName.build("foo.bar")); - } - - @Test -- void testResolveBothEmpty() { -+ void resolveBothEmpty() { - final MetricName name = MetricName.build(); - assertThat(name.resolve((String) null)).isEqualTo(MetricName.EMPTY); - } - - @Test -- void testAddTagsVarious() { -+ void addTagsVarious() { - final Map refTags = new HashMap(); - refTags.put("foo", "bar"); - final MetricName test = MetricName.EMPTY.tagged("foo", "bar"); - final MetricName test2 = MetricName.EMPTY.tagged(refTags); - - assertThat(test).isEqualTo(new MetricName("", refTags)); -- assertThat(test.getTags()).isEqualTo(refTags); -+ assertThat(test.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); - - assertThat(test2).isEqualTo(new MetricName("", refTags)); -- assertThat(test2.getTags()).isEqualTo(refTags); -+ assertThat(test2.getTags()).containsExactlyInAnyOrderEntriesOf(refTags); - } - - @Test -- void testTaggedMoreArguments() { -+ void taggedMoreArguments() { - final Map refTags = new HashMap(); - refTags.put("foo", "bar"); - refTags.put("baz", "biz"); -- assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()).isEqualTo(refTags); -+ assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()) -+ .containsExactlyInAnyOrderEntriesOf(refTags); - } - - @Test -- void testTaggedNotPairs() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- MetricName.EMPTY.tagged("foo"); -- }); -+ void taggedNotPairs() { -+ assertThatThrownBy( -+ () -> { -+ MetricName.EMPTY.tagged("foo"); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test -- void testTaggedNotPairs2() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- MetricName.EMPTY.tagged("foo", "bar", "baz"); -- }); -+ void taggedNotPairs2() { -+ assertThatThrownBy( -+ () -> { -+ MetricName.EMPTY.tagged("foo", "bar", "baz"); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test -- void testCompareTo() { -+ void compareTo() { - final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); - final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); - -- assertThat(a.compareTo(b)).isLessThan(0); -- assertThat(b.compareTo(a)).isGreaterThan(0); -- assertThat(b.resolve("key").compareTo(b)).isGreaterThan(0); -- assertThat(b.compareTo(b.resolve("key"))).isLessThan(0); -+ assertThat(a.compareTo(b)).isNegative(); -+ assertThat(b.compareTo(a)).isPositive(); -+ assertThat(b.resolve("key").compareTo(b)).isPositive(); -+ assertThat(b.compareTo(b.resolve("key"))).isNegative(); - } - - @Test -- void testCompareTo2() { -+ void compareTo2() { - final MetricName a = MetricName.EMPTY.tagged("a", "x"); - final MetricName b = MetricName.EMPTY.tagged("b", "x"); - -- assertThat(MetricName.EMPTY.compareTo(a)).isLessThan(0); -- assertThat(MetricName.EMPTY.compareTo(b)).isLessThan(0); -- assertThat(a.compareTo(b)).isLessThan(0); -- assertThat(b.compareTo(a)).isGreaterThan(0); -+ assertThat(MetricName.EMPTY.compareTo(a)).isNegative(); -+ assertThat(MetricName.EMPTY.compareTo(b)).isNegative(); -+ assertThat(a.compareTo(b)).isNegative(); -+ assertThat(b.compareTo(a)).isPositive(); - } - } -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java -index 3f9b427..a32294b 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java -@@ -5,13 +5,13 @@ import static org.mockito.Mockito.verifyNoInteractions; - - import org.junit.jupiter.api.Test; - --class MetricRegistryListenerTest { -+final class MetricRegistryListenerTest { - private static final MetricName BLAH = MetricName.build("blah"); - -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - private final MetricRegistryListener listener = new MetricRegistryListener.Base() {}; - - @Test -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java -index 865dfca..d79a191 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5; - -+import static com.google.common.collect.ImmutableSet.toImmutableSet; - import static io.dropwizard.metrics5.MetricRegistry.name; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatThrownBy; -@@ -15,7 +16,7 @@ import java.util.stream.Collectors; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class MetricRegistryTest { -+final class MetricRegistryTest { - - private static class CustomCounter extends Counter { - -@@ -37,14 +38,14 @@ class MetricRegistryTest { - private static final MetricName GAUGE2 = MetricName.build("gauge2"); - private static final MetricName SETTABLE_GAUGE = MetricName.build("settable-gauge"); - private static final MetricName THING = MetricName.build("thing"); -- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); -+ private final MetricRegistryListener listener = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private final Gauge gauge = () -> ""; - private final SettableGauge settableGauge = new DefaultSettableGauge<>(""); -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - - @BeforeEach - void setUp() { -@@ -291,7 +292,7 @@ class MetricRegistryTest { - registry.register(METER2, meter); - registry.register(TIMER2, timer); - -- final MetricRegistryListener other = mock(MetricRegistryListener.class); -+ final MetricRegistryListener other = mock(); - registry.addListener(other); - - verify(other).onGaugeAdded(GAUGE2, gauge); -@@ -425,7 +426,7 @@ class MetricRegistryTest { - MetricRegistry other = new MetricRegistry(); - other.register(GAUGE, gauge); - registry.register(MetricName.build("nested"), other); -- assertThat(registry.getNames()).containsOnly(MetricName.build("nested.gauge")); -+ assertThat(registry.getNames()).containsExactly(MetricName.build("nested.gauge")); - } - - @Test -@@ -501,7 +502,7 @@ class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo( -+ .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) - .collect(Collectors.toSet())); -@@ -522,7 +523,7 @@ class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo( -+ .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) - .collect(Collectors.toSet())); -@@ -548,7 +549,7 @@ class MetricRegistryTest { - Set deepChildMetrics = deepChild.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo( -+ .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) - .collect(Collectors.toSet())); -@@ -557,10 +558,10 @@ class MetricRegistryTest { - .containsAll( - deepChildMetrics.stream() - .map(m -> MetricName.build("deep-child", m.getKey())) -- .collect(Collectors.toSet())); -+ .collect(toImmutableSet())); - -- assertThat(deepChildMetrics.size()).isEqualTo(3); -- assertThat(childMetrics.size()).isEqualTo(5); -+ assertThat(deepChildMetrics).hasSize(3); -+ assertThat(childMetrics).hasSize(5); - } - - @Test -@@ -578,7 +579,7 @@ class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo( -+ .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) - .collect(Collectors.toSet())); -@@ -604,7 +605,7 @@ class MetricRegistryTest { - Set childMetrics = child.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo( -+ .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) - .collect(Collectors.toSet())); -@@ -633,7 +634,7 @@ class MetricRegistryTest { - Set deepChildMetrics = deepChild.getMetrics().keySet(); - - assertThat(parentMetrics) -- .isEqualTo( -+ .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) - .collect(Collectors.toSet())); -@@ -642,12 +643,12 @@ class MetricRegistryTest { - .containsAll( - deepChildMetrics.stream() - .map(m -> MetricName.build("deep-child", m.getKey())) -- .collect(Collectors.toSet())); -+ .collect(toImmutableSet())); - - assertThat(deepChildMetrics).doesNotContain(MetricName.build("test-2")); - -- assertThat(deepChildMetrics.size()).isEqualTo(1); -- assertThat(childMetrics.size()).isEqualTo(3); -+ assertThat(deepChildMetrics).hasSize(1); -+ assertThat(childMetrics).hasSize(3); - } - - @Test -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java -index 657462d..0dc6e29 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java -@@ -1,7 +1,7 @@ - package io.dropwizard.metrics5; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatNullPointerException; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; - import static org.mockito.Mockito.verify; -@@ -12,16 +12,16 @@ import java.util.Set; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class NoopMetricRegistryTest { -+final class NoopMetricRegistryTest { - private static final MetricName METRIC_THING = MetricName.build("thing"); - -- private final MetricRegistryListener listener = mock(MetricRegistryListener.class); -+ private final MetricRegistryListener listener = mock(); - private final NoopMetricRegistry registry = new NoopMetricRegistry(); - private final Gauge gauge = () -> ""; -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - - @BeforeEach - void setUp() { -@@ -220,8 +220,8 @@ class NoopMetricRegistryTest { - verify(listener, never()).onGaugeAdded(METRIC_THING, gauge1); - } - -- @Test - @SuppressWarnings("rawtypes") -+ @Test - void accessingACustomGaugeRegistersAndReusesIt() { - final MetricRegistry.MetricSupplier> supplier = () -> gauge; - final Gauge gauge1 = registry.gauge(METRIC_THING, supplier); -@@ -242,7 +242,7 @@ class NoopMetricRegistryTest { - registry.register(MetricName.build("meter"), meter); - registry.register(MetricName.build("timer"), timer); - -- final MetricRegistryListener other = mock(MetricRegistryListener.class); -+ final MetricRegistryListener other = mock(); - registry.addListener(other); - - verify(other, never()).onGaugeAdded(MetricName.build("gauge"), gauge); -@@ -491,8 +491,8 @@ class NoopMetricRegistryTest { - @Test - void registerNullMetric() { - MetricRegistry registry = new NoopMetricRegistry(); -- assertThatNullPointerException() -- .isThrownBy(() -> registry.register(MetricName.build("any_name"), null)) -- .withMessage("metric == null"); -+ assertThatThrownBy(() -> registry.register(MetricName.build("any_name"), null)) -+ .isInstanceOf(NullPointerException.class) -+ .hasMessage("metric == null"); - } - } -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java -index 15ea461..e181635 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java -@@ -4,12 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat; - - import org.junit.jupiter.api.Test; - --class RatioGaugeTest { -+final class RatioGaugeTest { - @Test - void ratiosAreHumanReadable() { - final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); - -- assertThat(ratio.toString()).isEqualTo("100.0:200.0"); -+ assertThat(ratio).hasToString("100.0:200.0"); - } - - @Test -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java -index 5f2f8ad..a3e7329 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java -@@ -1,10 +1,8 @@ - package io.dropwizard.metrics5; - -+import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.junit.jupiter.api.Assertions.assertEquals; --import static org.junit.jupiter.api.Assertions.assertFalse; --import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.junit.jupiter.api.Assertions.assertTrue; --import static org.junit.jupiter.api.Assertions.fail; - import static org.mockito.Mockito.any; - import static org.mockito.Mockito.eq; - import static org.mockito.Mockito.mock; -@@ -21,18 +19,19 @@ import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.TimeoutException; - import java.util.concurrent.atomic.AtomicInteger; -+import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class ScheduledReporterTest { -+final class ScheduledReporterTest { - private final Gauge gauge = () -> ""; -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); - -- private final ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); -+ private final ScheduledExecutorService mockExecutor = mock(); - private final ScheduledExecutorService customExecutor = - Executors.newSingleThreadScheduledExecutor(); - private final ScheduledExecutorService externalExecutor = -@@ -107,7 +106,7 @@ class ScheduledReporterTest { - r = - new DummyReporter( - null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); -- fail("NullPointerException must be thrown !!!"); -+ Assertions.fail("NullPointerException must be thrown !!!"); - } catch (NullPointerException e) { - assertEquals("registry == null", e.getMessage()); - } finally { -@@ -145,7 +144,7 @@ class ScheduledReporterTest { - void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { - reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); - -- verify(mockExecutor, times(1)) -+ verify(mockExecutor) - .scheduleWithFixedDelay(any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS)); - } - -@@ -182,32 +181,32 @@ class ScheduledReporterTest { - - @Test - void shouldDisallowToStartReportingMultiple() throws Exception { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- reporter.start(200, TimeUnit.MILLISECONDS); -- reporter.start(200, TimeUnit.MILLISECONDS); -- }); -+ assertThatThrownBy( -+ () -> { -+ reporter.start(200, TimeUnit.MILLISECONDS); -+ reporter.start(200, TimeUnit.MILLISECONDS); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -- reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -- }); -+ assertThatThrownBy( -+ () -> { -+ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -+ reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void shouldDisallowToStartReportingMultipleTimesOnExternallyManagedExecutor() throws Exception { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -- reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -- }); -+ assertThatThrownBy( -+ () -> { -+ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -+ reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test -@@ -231,15 +230,15 @@ class ScheduledReporterTest { - void shouldShutdownExecutorOnStopByDefault() { - reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); - reporterWithCustomExecutor.stop(); -- assertTrue(customExecutor.isTerminated()); -+ assertThat(customExecutor.isTerminated()).isTrue(); - } - - @Test - void shouldNotShutdownExternallyManagedExecutorOnStop() { - reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); - reporterWithExternallyManagedExecutor.stop(); -- assertFalse(mockExecutor.isTerminated()); -- assertFalse(mockExecutor.isShutdown()); -+ assertThat(mockExecutor.isTerminated()).isFalse(); -+ assertThat(mockExecutor.isShutdown()).isFalse(); - } - - @Test -@@ -306,7 +305,7 @@ class ScheduledReporterTest { - - Thread.sleep(1_000); - -- verify(reporter, times(1)) -+ verify(reporter) - .report( - map(MetricName.build("gauge"), gauge), - map(MetricName.build("counter"), counter), -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java -index 9bdc888..9d0a08b 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java -@@ -2,13 +2,12 @@ package io.dropwizard.metrics5; - - import static org.assertj.core.api.Assertions.assertThat; - import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.junit.jupiter.api.Assertions.assertTrue; - - import java.util.concurrent.atomic.AtomicReference; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class SharedMetricRegistriesTest { -+final class SharedMetricRegistriesTest { - - @BeforeEach - void setUp() { -@@ -28,7 +27,7 @@ class SharedMetricRegistriesTest { - void hasASetOfNames() { - SharedMetricRegistries.getOrCreate("one"); - -- assertThat(SharedMetricRegistries.names()).containsOnly("one"); -+ assertThat(SharedMetricRegistries.names()).containsExactly("one"); - } - - @Test -@@ -60,7 +59,7 @@ class SharedMetricRegistriesTest { - () -> { - SharedMetricRegistries.getDefault(); - }); -- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); -+ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); - } - - @Test -@@ -81,7 +80,8 @@ class SharedMetricRegistriesTest { - SharedMetricRegistries.setDefault("foobah"); - SharedMetricRegistries.setDefault("borg"); - }); -- assertTrue(exception.getMessage().contains("Default metric registry name is already set.")); -+ assertThat(exception.getMessage().contains("Default metric registry name is already set.")) -+ .isTrue(); - } - - @Test -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java -index 78e54ea..d95e9c8 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java -@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; - - import org.junit.jupiter.api.Test; - --class SimpleSettableGaugeTest { -+final class SimpleSettableGaugeTest { - - @Test - void defaultValue() { -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java -index cd5f781..1aa7767 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java -@@ -3,7 +3,6 @@ package io.dropwizard.metrics5; - import static io.dropwizard.metrics5.MetricAttribute.COUNT; - import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; - import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MIN; - import static io.dropwizard.metrics5.MetricAttribute.P50; - import static io.dropwizard.metrics5.MetricAttribute.P999; - import static io.dropwizard.metrics5.MetricAttribute.STDDEV; -@@ -20,11 +19,11 @@ import org.junit.jupiter.api.Test; - import org.slf4j.Logger; - import org.slf4j.Marker; - --class Slf4jReporterTest { -+final class Slf4jReporterTest { - -- private final Logger logger = mock(Logger.class); -- private final Marker marker = mock(Marker.class); -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final Logger logger = mock(); -+ private final Marker marker = mock(); -+ private final MetricRegistry registry = mock(); - - /** - * The set of disabled metric attributes to pass to the Slf4jReporter builder in the default -@@ -79,7 +78,7 @@ class Slf4jReporterTest { - } - - private Timer timer() { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - - when(timer.getMeanRate()).thenReturn(2.0); -@@ -87,7 +86,7 @@ class Slf4jReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -104,10 +103,10 @@ class Slf4jReporterTest { - } - - private Histogram histogram() { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -124,7 +123,7 @@ class Slf4jReporterTest { - } - - private Meter meter() { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(3.0); -@@ -134,7 +133,7 @@ class Slf4jReporterTest { - } - - private Counter counter() { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - return counter; - } -@@ -168,7 +167,7 @@ class Slf4jReporterTest { - - @Test - void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); -+ disabledMetricAttributes = EnumSet.of(COUNT, MetricAttribute.MIN, P50); - reportsHistogramValuesAtError( - "type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " - + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); -@@ -192,7 +191,7 @@ class Slf4jReporterTest { - - @Test - void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); -+ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, P50, M1_RATE); - reportsMeterValuesAtError( - "type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " - + "mean_rate=2.0, rate_unit=events/second"); -@@ -218,7 +217,7 @@ class Slf4jReporterTest { - - @Test - void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { -- disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); -+ disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, STDDEV, P999, MEAN_RATE); - reportsTimerValuesAtError( - "type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " - + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java -index 3063fe2..c6a8b49 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java -@@ -12,11 +12,11 @@ import java.util.concurrent.atomic.AtomicLong; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("Duplicates") --class SlidingTimeWindowArrayReservoirTest { -+final class SlidingTimeWindowArrayReservoirTest { - - @Test - void storesMeasurementsWithDuplicateTicks() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - final SlidingTimeWindowArrayReservoir reservoir = - new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); - -@@ -30,7 +30,7 @@ class SlidingTimeWindowArrayReservoirTest { - - @Test - void boundsMeasurementsToATimeWindow() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - final SlidingTimeWindowArrayReservoir reservoir = - new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); - -@@ -82,7 +82,7 @@ class SlidingTimeWindowArrayReservoirTest { - } - - @Test -- void testGetTickOverflow() { -+ void getTickOverflow() { - final Random random = new Random(0); - final int window = 128; - AtomicLong counter = new AtomicLong(0L); -@@ -99,7 +99,7 @@ class SlidingTimeWindowArrayReservoirTest { - // Set the clock to overflow in (2*window+1)ns - final ManualClock clock = new ManualClock(); - clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -- assertThat(clock.getTick() * 256).isGreaterThan(0); -+ assertThat(clock.getTick() * 256).isPositive(); - - // Create the reservoir - final SlidingTimeWindowArrayReservoir reservoir = -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java -index 1dc69b9..748536b 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java -@@ -7,7 +7,7 @@ import java.time.Instant; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class SlidingTimeWindowMovingAveragesTest { -+final class SlidingTimeWindowMovingAveragesTest { - - private ManualClock clock; - private SlidingTimeWindowMovingAverages movingAverages; -@@ -42,7 +42,7 @@ class SlidingTimeWindowMovingAveragesTest { - - SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); - -- assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(0L))).isEqualTo(0); -+ assertThat(stwm.calculateIndexOfTick(Instant.EPOCH)).isEqualTo(0); - assertThat(stwm.calculateIndexOfTick(Instant.ofEpochSecond(1L))).isEqualTo(1); - } - -@@ -60,7 +60,7 @@ class SlidingTimeWindowMovingAveragesTest { - } - - // verify that no cleanup happened yet -- assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.ofEpochSecond(0L)); -+ assertThat(movingAverages.oldestBucketTime).isEqualTo(Instant.EPOCH); - - assertThat(meter.getOneMinuteRate()).isEqualTo(60.0); - assertThat(meter.getFiveMinuteRate()).isEqualTo(300.0); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java -index 3677975..0817849 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java -@@ -9,10 +9,10 @@ import java.util.Arrays; - import java.util.Random; - import org.junit.jupiter.api.Test; - --class SlidingTimeWindowReservoirTest { -+final class SlidingTimeWindowReservoirTest { - @Test - void storesMeasurementsWithDuplicateTicks() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - final SlidingTimeWindowReservoir reservoir = - new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); - -@@ -26,7 +26,7 @@ class SlidingTimeWindowReservoirTest { - - @Test - void boundsMeasurementsToATimeWindow() { -- final Clock clock = mock(Clock.class); -+ final Clock clock = mock(); - when(clock.getTick()).thenReturn(0L); - - final SlidingTimeWindowReservoir reservoir = -@@ -51,7 +51,7 @@ class SlidingTimeWindowReservoirTest { - } - - @Test -- void testGetTickOverflow() { -+ void getTickOverflow() { - final Random random = new Random(0); - final int window = 128; - -@@ -72,7 +72,7 @@ class SlidingTimeWindowReservoirTest { - - // Set the clock to overflow in (2*window+1)ns - clock.addNanos(Long.MAX_VALUE / 256 - 2 * window - clock.getTick()); -- assertThat(clock.getTick() * 256).isGreaterThan(0); -+ assertThat(clock.getTick() * 256).isPositive(); - - int updatesAfterThreshold = 0; - while (true) { -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java -index 2f6bbd0..122e7d5 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java -@@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; - - import org.junit.jupiter.api.Test; - --class SlidingWindowReservoirTest { -+final class SlidingWindowReservoirTest { - private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); - - @Test -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java -index 55eb3e3..7281be4 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java -@@ -12,8 +12,8 @@ import java.util.concurrent.TimeUnit; - import java.util.concurrent.atomic.AtomicBoolean; - import org.junit.jupiter.api.Test; - --class TimerTest { -- private final Reservoir reservoir = mock(Reservoir.class); -+final class TimerTest { -+ private final Reservoir reservoir = mock(); - private final Clock clock = - new Clock() { - // a mock clock that increments its ticker by 50msec per call -@@ -28,23 +28,23 @@ class TimerTest { - - @Test - void hasRates() { -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - -- assertThat(timer.getSum()).isZero(); -+ assertThat(timer.getSum()).isEqualTo(0); - -- assertThat(timer.getMeanRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getMeanRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getOneMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getOneMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getFiveMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getFiveMinuteRate()).isCloseTo(0.0, offset(0.001)); - -- assertThat(timer.getFifteenMinuteRate()).isEqualTo(0.0, offset(0.001)); -+ assertThat(timer.getFifteenMinuteRate()).isCloseTo(0.0, offset(0.001)); - } - - @Test - void updatesTheCountAndSumOnUpdates() { -- assertThat(timer.getCount()).isZero(); -- assertThat(timer.getSum()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); -+ assertThat(timer.getSum()).isEqualTo(0); - - timer.update(1, TimeUnit.SECONDS); - timer.update(5, TimeUnit.SECONDS); -@@ -101,7 +101,7 @@ class TimerTest { - - @Test - void returnsTheSnapshotFromTheReservoir() { -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(reservoir.getSnapshot()).thenReturn(snapshot); - - assertThat(timer.getSnapshot()).isEqualTo(snapshot); -@@ -111,8 +111,8 @@ class TimerTest { - void ignoresNegativeValues() { - timer.update(-1, TimeUnit.SECONDS); - -- assertThat(timer.getCount()).isZero(); -- assertThat(timer.getSum()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); -+ assertThat(timer.getSum()).isEqualTo(0); - - verifyNoInteractions(reservoir); - } -@@ -130,15 +130,15 @@ class TimerTest { - void java8NegativeDuration() { - timer.update(Duration.ofMillis(-5678)); - -- assertThat(timer.getCount()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); - - verifyNoInteractions(reservoir); - } - - @Test - void tryWithResourcesWork() { -- assertThat(timer.getCount()).isZero(); -- assertThat(timer.getSum()).isZero(); -+ assertThat(timer.getCount()).isEqualTo(0); -+ assertThat(timer.getSum()).isEqualTo(0); - - int dummy = 0; - try (Timer.Context context = timer.time()) { -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java -index fbab25c..50c682e 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java -@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat; - - import org.junit.jupiter.api.Test; - --class UniformReservoirTest { -- @Test -+final class UniformReservoirTest { - @SuppressWarnings("unchecked") -+ @Test - void aReservoirOf100OutOf1000Elements() { - final UniformReservoir reservoir = new UniformReservoir(100); - for (int i = 0; i < 1000; i++) { -@@ -20,7 +20,7 @@ class UniformReservoirTest { - assertThat(snapshot.size()).isEqualTo(100); - - for (double i : snapshot.getValues()) { -- assertThat(i).isLessThan(1000).isGreaterThanOrEqualTo(0); -+ assertThat(i).isLessThan(1000).isNotNegative(); - } - } - } -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java -index 34ffc56..5db094c 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java -@@ -2,8 +2,8 @@ package io.dropwizard.metrics5; - - import static java.util.Arrays.asList; - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.assertj.core.api.Assertions.offset; --import static org.junit.jupiter.api.Assertions.assertThrows; - - import java.io.ByteArrayOutputStream; - import java.util.Random; -@@ -12,74 +12,74 @@ import java.util.concurrent.CountDownLatch; - import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; - --class UniformSnapshotTest { -+final class UniformSnapshotTest { - private final Snapshot snapshot = new UniformSnapshot(new long[] {5, 1, 2, 3, 4}); - - @Test - void smallQuantilesAreTheFirstValue() { -- assertThat(snapshot.getValue(0.0)).isEqualTo(1, offset(0.1)); -+ assertThat(snapshot.getValue(0.0)).isCloseTo(1, offset(0.1)); - } - - @Test - void bigQuantilesAreTheLastValue() { -- assertThat(snapshot.getValue(1.0)).isEqualTo(5, offset(0.1)); -+ assertThat(snapshot.getValue(1.0)).isCloseTo(5, offset(0.1)); - } - - @Test - void disallowsNotANumberQuantile() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- snapshot.getValue(Double.NaN); -- }); -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(Double.NaN); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void disallowsNegativeQuantile() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- snapshot.getValue(-0.5); -- }); -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(-0.5); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void disallowsQuantileOverOne() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- snapshot.getValue(1.5); -- }); -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(1.5); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void hasAMedian() { -- assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); -+ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.1)); - } - - @Test - void hasAp75() { -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.1)); - } - - @Test - void hasAp95() { -- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - void hasAp98() { -- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - void hasAp99() { -- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - void hasAp999() { -- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test -@@ -138,7 +138,7 @@ class UniformSnapshotTest { - - snapshot.dump(output); - -- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); -+ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); - } - - @Test -@@ -158,41 +158,41 @@ class UniformSnapshotTest { - - @Test - void calculatesTheStdDev() { -- assertThat(snapshot.getStdDev()).isEqualTo(1.5811, offset(0.0001)); -+ assertThat(snapshot.getStdDev()).isCloseTo(1.5811, offset(0.0001)); - } - - @Test - void calculatesAMinOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMin()).isZero(); -+ assertThat(emptySnapshot.getMin()).isEqualTo(0); - } - - @Test - void calculatesAMaxOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMax()).isZero(); -+ assertThat(emptySnapshot.getMax()).isEqualTo(0); - } - - @Test - void calculatesAMeanOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getMean()).isZero(); -+ assertThat(emptySnapshot.getMean()).isEqualTo(0); - } - - @Test - void calculatesAStdDevOfZeroForAnEmptySnapshot() { - final Snapshot emptySnapshot = new UniformSnapshot(new long[] {}); - -- assertThat(emptySnapshot.getStdDev()).isZero(); -+ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); - } - - @Test - void calculatesAStdDevOfZeroForASingletonSnapshot() { - final Snapshot singleItemSnapshot = new UniformSnapshot(new long[] {1}); - -- assertThat(singleItemSnapshot.getStdDev()).isZero(); -+ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); - } - } -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java -index f53854f..052948c 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java -@@ -1,8 +1,10 @@ - package io.dropwizard.metrics5; - -+import static com.google.common.base.Preconditions.checkArgument; - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.assertj.core.api.Assertions.offset; --import static org.junit.jupiter.api.Assertions.assertThrows; -+import static org.mockito.ArgumentMatchers.any; - import static org.mockito.Mockito.doReturn; - import static org.mockito.Mockito.spy; - import static org.mockito.Mockito.when; -@@ -12,16 +14,14 @@ import java.io.ByteArrayOutputStream; - import java.util.ArrayList; - import java.util.List; - import org.junit.jupiter.api.Test; --import org.mockito.ArgumentMatchers; - --class WeightedSnapshotTest { -+final class WeightedSnapshotTest { - - private static List weightedArray( - long[] values, double[] weights) { -- if (values.length != weights.length) { -- throw new IllegalArgumentException( -- "Mismatched lengths: " + values.length + " vs " + weights.length); -- } -+ checkArgument( -+ values.length == weights.length, -+ "Mismatched lengths: " + values.length + " vs " + weights.length); - - final List samples = new ArrayList<>(); - for (int i = 0; i < values.length; i++) { -@@ -36,69 +36,69 @@ class WeightedSnapshotTest { - - @Test - void smallQuantilesAreTheFirstValue() { -- assertThat(snapshot.getValue(0.0)).isEqualTo(1.0, offset(0.1)); -+ assertThat(snapshot.getValue(0.0)).isCloseTo(1.0, offset(0.1)); - } - - @Test - void bigQuantilesAreTheLastValue() { -- assertThat(snapshot.getValue(1.0)).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.getValue(1.0)).isCloseTo(5.0, offset(0.1)); - } - - @Test - void disallowsNotANumberQuantile() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- snapshot.getValue(Double.NaN); -- }); -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(Double.NaN); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void disallowsNegativeQuantile() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- snapshot.getValue(-0.5); -- }); -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(-0.5); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void disallowsQuantileOverOne() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- snapshot.getValue(1.5); -- }); -+ assertThatThrownBy( -+ () -> { -+ snapshot.getValue(1.5); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void hasAMedian() { -- assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); -+ assertThat(snapshot.getMedian()).isCloseTo(3.0, offset(0.1)); - } - - @Test - void hasAp75() { -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.0, offset(0.1)); - } - - @Test - void hasAp95() { -- assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - void hasAp98() { -- assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - void hasAp99() { -- assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test - void hasAp999() { -- assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5.0, offset(0.1)); - } - - @Test -@@ -118,7 +118,7 @@ class WeightedSnapshotTest { - final List spyItems = spy(originalItems); - doReturn(originalItems.toArray(new WeightedSample[] {})) - .when(spyItems) -- .toArray(ArgumentMatchers.any(WeightedSample[].class)); -+ .toArray(any(WeightedSample[].class)); - when(spyItems.size()).thenReturn(4, 5); - - final Snapshot other = new WeightedSnapshot(spyItems); -@@ -133,7 +133,7 @@ class WeightedSnapshotTest { - final List spyItems = spy(originalItems); - doReturn(originalItems.toArray(new WeightedSample[] {})) - .when(spyItems) -- .toArray(ArgumentMatchers.any(WeightedSample[].class)); -+ .toArray(any(WeightedSample[].class)); - when(spyItems.size()).thenReturn(6, 5); - - final Snapshot other = new WeightedSnapshot(spyItems); -@@ -147,7 +147,7 @@ class WeightedSnapshotTest { - - snapshot.dump(output); - -- assertThat(output.toString()).isEqualTo(String.format("1%n2%n3%n4%n5%n")); -+ assertThat(output).hasToString(String.format("1%n2%n3%n4%n5%n")); - } - - @Test -@@ -167,7 +167,7 @@ class WeightedSnapshotTest { - - @Test - void calculatesTheStdDev() { -- assertThat(snapshot.getStdDev()).isEqualTo(1.2688, offset(0.0001)); -+ assertThat(snapshot.getStdDev()).isCloseTo(1.2688, offset(0.0001)); - } - - @Test -@@ -175,7 +175,7 @@ class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getMin()).isZero(); -+ assertThat(emptySnapshot.getMin()).isEqualTo(0); - } - - @Test -@@ -183,7 +183,7 @@ class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getMax()).isZero(); -+ assertThat(emptySnapshot.getMax()).isEqualTo(0); - } - - @Test -@@ -191,7 +191,7 @@ class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getMean()).isZero(); -+ assertThat(emptySnapshot.getMean()).isEqualTo(0); - } - - @Test -@@ -199,7 +199,7 @@ class WeightedSnapshotTest { - final Snapshot emptySnapshot = - new WeightedSnapshot(weightedArray(new long[] {}, new double[] {})); - -- assertThat(emptySnapshot.getStdDev()).isZero(); -+ assertThat(emptySnapshot.getStdDev()).isEqualTo(0); - } - - @Test -@@ -207,7 +207,7 @@ class WeightedSnapshotTest { - final Snapshot singleItemSnapshot = - new WeightedSnapshot(weightedArray(new long[] {1}, new double[] {1.0})); - -- assertThat(singleItemSnapshot.getStdDev()).isZero(); -+ assertThat(singleItemSnapshot.getStdDev()).isEqualTo(0); - } - - @Test -diff --git a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java -index f53b4c2..531ff9e 100644 ---- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java -+++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java -@@ -12,7 +12,7 @@ import net.sf.ehcache.Element; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedCacheDecoratorFactoryTest { -+final class InstrumentedCacheDecoratorFactoryTest { - private static final CacheManager MANAGER = CacheManager.create(); - - private MetricRegistry registry; -diff --git a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java -index 58bca0c..340cd66 100644 ---- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java -+++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java -@@ -13,7 +13,7 @@ import net.sf.ehcache.config.CacheConfiguration; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedEhcacheTest { -+final class InstrumentedEhcacheTest { - private static final CacheManager MANAGER = CacheManager.create(); - - private final MetricRegistry registry = new MetricRegistry(); -diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java -index bab371a..8dfe5cf 100644 ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.graphite; - -+import static com.google.common.base.Preconditions.checkArgument; -+import static com.google.common.base.Preconditions.checkState; - import static java.nio.charset.StandardCharsets.UTF_8; - import static java.util.Objects.requireNonNull; - -@@ -29,7 +31,7 @@ public class Graphite implements GraphiteSender { - private Writer writer; - private int failures; - -- private static final Logger LOGGER = LoggerFactory.getLogger(Graphite.class); -+ private static final Logger LOG = LoggerFactory.getLogger(Graphite.class); - - /** - * Creates a new client which connects to the given address using the default {@link -@@ -63,13 +65,9 @@ public class Graphite implements GraphiteSender { - * @param charset the character set used by the server - */ - public Graphite(String hostname, int port, SocketFactory socketFactory, Charset charset) { -- if (hostname == null || hostname.isEmpty()) { -- throw new IllegalArgumentException("hostname must not be null or empty"); -- } -+ checkArgument(hostname != null && !hostname.isEmpty(), "hostname must not be null or empty"); - -- if (port < 0 || port > 65535) { -- throw new IllegalArgumentException("port must be a valid IP port (0-65535)"); -- } -+ checkArgument(port >= 0 && port <= 65535, "port must be a valid IP port (0-65535)"); - - this.hostname = hostname; - this.port = port; -@@ -116,9 +114,7 @@ public class Graphite implements GraphiteSender { - - @Override - public void connect() throws IllegalStateException, IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -+ checkState(!isConnected(), "Already connected"); - InetSocketAddress address = this.address; - // the previous dns retry logic did not work, as address.getAddress would always return the - // cached value -@@ -178,7 +174,7 @@ public class Graphite implements GraphiteSender { - writer.close(); - } - } catch (IOException ex) { -- LOGGER.debug("Error closing writer", ex); -+ LOG.debug("Error closing writer", ex); - } finally { - this.writer = null; - } -@@ -188,7 +184,7 @@ public class Graphite implements GraphiteSender { - socket.close(); - } - } catch (IOException ex) { -- LOGGER.debug("Error closing socket", ex); -+ LOG.debug("Error closing socket", ex); - } finally { - this.socket = null; - } -diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java -index fd9ee5f..7532a9f 100644 ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQ.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5.graphite; - -+import static com.google.common.base.Preconditions.checkState; - import static java.nio.charset.StandardCharsets.UTF_8; - - import com.rabbitmq.client.Channel; -@@ -109,9 +110,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { - - @Override - public void connect() throws IllegalStateException, IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -+ checkState(!isConnected(), "Already connected"); - - try { - connection = connectionFactory.newConnection(); -@@ -132,8 +131,7 @@ public class GraphiteRabbitMQ implements GraphiteSender { - final String sanitizedName = sanitize(name); - final String sanitizedValue = sanitize(value); - -- final String message = -- sanitizedName + ' ' + sanitizedValue + ' ' + Long.toString(timestamp) + '\n'; -+ final String message = sanitizedName + ' ' + sanitizedValue + ' ' + timestamp + '\n'; - channel.basicPublish(exchange, sanitizedName, null, message.getBytes(UTF_8)); - } catch (IOException e) { - failures++; -diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java -index 1e14d15..f189ad7 100644 ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java -@@ -4,10 +4,8 @@ import static io.dropwizard.metrics5.MetricAttribute.COUNT; - import static io.dropwizard.metrics5.MetricAttribute.M15_RATE; - import static io.dropwizard.metrics5.MetricAttribute.M1_RATE; - import static io.dropwizard.metrics5.MetricAttribute.M5_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MAX; - import static io.dropwizard.metrics5.MetricAttribute.MEAN; - import static io.dropwizard.metrics5.MetricAttribute.MEAN_RATE; --import static io.dropwizard.metrics5.MetricAttribute.MIN; - import static io.dropwizard.metrics5.MetricAttribute.P50; - import static io.dropwizard.metrics5.MetricAttribute.P75; - import static io.dropwizard.metrics5.MetricAttribute.P95; -@@ -17,6 +15,7 @@ import static io.dropwizard.metrics5.MetricAttribute.P999; - import static io.dropwizard.metrics5.MetricAttribute.STDDEV; - import static io.dropwizard.metrics5.MetricAttribute.SUM; - -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -31,7 +30,6 @@ import io.dropwizard.metrics5.ScheduledReporter; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; - import java.io.IOException; --import java.util.Collections; - import java.util.Locale; - import java.util.Map; - import java.util.Set; -@@ -85,7 +83,7 @@ public class GraphiteReporter extends ScheduledReporter { - this.filter = MetricFilter.ALL; - this.executor = null; - this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -+ this.disabledMetricAttributes = ImmutableSet.of(); - this.addMetricAttributesAsTags = false; - this.floatingPointFormatter = DEFAULT_FP_FORMATTER; - } -@@ -249,7 +247,7 @@ public class GraphiteReporter extends ScheduledReporter { - } - } - -- private static final Logger LOGGER = LoggerFactory.getLogger(GraphiteReporter.class); -+ private static final Logger LOG = LoggerFactory.getLogger(GraphiteReporter.class); - // the Carbon plaintext format is pretty underspecified, but it seems like it just wants - // US-formatted digits - private static final DoubleFunction DEFAULT_FP_FORMATTER = -@@ -430,12 +428,12 @@ public class GraphiteReporter extends ScheduledReporter { - } - graphite.flush(); - } catch (IOException e) { -- LOGGER.warn("Unable to report to Graphite", graphite, e); -+ LOG.warn("Unable to report to Graphite", graphite, e); - } finally { - try { - graphite.close(); - } catch (IOException e1) { -- LOGGER.warn("Error closing Graphite", graphite, e1); -+ LOG.warn("Error closing Graphite", graphite, e1); - } - } - } -@@ -448,16 +446,16 @@ public class GraphiteReporter extends ScheduledReporter { - try { - graphite.close(); - } catch (IOException e) { -- LOGGER.debug("Error disconnecting from Graphite", graphite, e); -+ LOG.debug("Error disconnecting from Graphite", graphite, e); - } - } - } - - private void reportTimer(MetricName name, Timer timer, long timestamp) throws IOException { - final Snapshot snapshot = timer.getSnapshot(); -- sendIfEnabled(MAX, name, convertDuration(snapshot.getMax()), timestamp); -+ sendIfEnabled(MetricAttribute.MAX, name, convertDuration(snapshot.getMax()), timestamp); - sendIfEnabled(MEAN, name, convertDuration(snapshot.getMean()), timestamp); -- sendIfEnabled(MIN, name, convertDuration(snapshot.getMin()), timestamp); -+ sendIfEnabled(MetricAttribute.MIN, name, convertDuration(snapshot.getMin()), timestamp); - sendIfEnabled(STDDEV, name, convertDuration(snapshot.getStdDev()), timestamp); - sendIfEnabled(P50, name, convertDuration(snapshot.getMedian()), timestamp); - sendIfEnabled(P75, name, convertDuration(snapshot.get75thPercentile()), timestamp); -@@ -484,9 +482,9 @@ public class GraphiteReporter extends ScheduledReporter { - final Snapshot snapshot = histogram.getSnapshot(); - sendIfEnabled(COUNT, name, histogram.getCount(), timestamp); - sendIfEnabled(SUM, name, histogram.getSum(), timestamp); -- sendIfEnabled(MAX, name, snapshot.getMax(), timestamp); -+ sendIfEnabled(MetricAttribute.MAX, name, snapshot.getMax(), timestamp); - sendIfEnabled(MEAN, name, snapshot.getMean(), timestamp); -- sendIfEnabled(MIN, name, snapshot.getMin(), timestamp); -+ sendIfEnabled(MetricAttribute.MIN, name, snapshot.getMin(), timestamp); - sendIfEnabled(STDDEV, name, snapshot.getStdDev(), timestamp); - sendIfEnabled(P50, name, snapshot.getMedian(), timestamp); - sendIfEnabled(P75, name, snapshot.get75thPercentile(), timestamp); -diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java -index fc3560d..0466527 100644 ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteUDP.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5.graphite; - -+import static com.google.common.base.Preconditions.checkState; - import static java.nio.charset.StandardCharsets.UTF_8; - - import java.io.IOException; -@@ -43,9 +44,7 @@ public class GraphiteUDP implements GraphiteSender { - - @Override - public void connect() throws IllegalStateException, IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -+ checkState(!isConnected(), "Already connected"); - - // Resolve hostname - if (hostname != null) { -@@ -63,7 +62,7 @@ public class GraphiteUDP implements GraphiteSender { - @Override - public void send(String name, String value, long timestamp) throws IOException { - try { -- String str = sanitize(name) + ' ' + sanitize(value) + ' ' + Long.toString(timestamp) + '\n'; -+ String str = sanitize(name) + ' ' + sanitize(value) + ' ' + timestamp + '\n'; - ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes(UTF_8)); - datagramChannel.send(byteBuffer, address); - this.failures = 0; -diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java -index 42e72e5..6312111 100644 ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5.graphite; - -+import static com.google.common.base.Preconditions.checkState; - import static java.nio.charset.StandardCharsets.UTF_8; - - import java.io.BufferedWriter; -@@ -48,7 +49,7 @@ public class PickledGraphite implements GraphiteSender { - QUOTE = '\'', - LF = '\n'; - -- private static final Logger LOGGER = LoggerFactory.getLogger(PickledGraphite.class); -+ private static final Logger LOG = LoggerFactory.getLogger(PickledGraphite.class); - private static final int DEFAULT_BATCH_SIZE = 100; - - private int batchSize; -@@ -173,9 +174,7 @@ public class PickledGraphite implements GraphiteSender { - - @Override - public void connect() throws IllegalStateException, IOException { -- if (isConnected()) { -- throw new IllegalStateException("Already connected"); -- } -+ checkState(!isConnected(), "Already connected"); - InetSocketAddress address = this.address; - if (address == null) { - address = new InetSocketAddress(hostname, port); -@@ -249,7 +248,7 @@ public class PickledGraphite implements GraphiteSender { - * message to graphite 3. Clear out the list of metrics - */ - private void writeMetrics() throws IOException { -- if (metrics.size() > 0) { -+ if (!metrics.isEmpty()) { - try { - byte[] payload = pickleMetrics(metrics); - byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array(); -@@ -260,8 +259,8 @@ public class PickledGraphite implements GraphiteSender { - outputStream.write(payload); - outputStream.flush(); - -- if (LOGGER.isDebugEnabled()) { -- LOGGER.debug("Wrote {} metrics", metrics.size()); -+ if (LOG.isDebugEnabled()) { -+ LOG.debug("Wrote {} metrics", metrics.size()); - } - } catch (IOException e) { - this.failures++; -diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java -index f7f01d6..29eb9ed 100755 ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java -@@ -8,7 +8,6 @@ import static org.mockito.Mockito.anyString; - import static org.mockito.Mockito.atMost; - import static org.mockito.Mockito.doThrow; - import static org.mockito.Mockito.mock; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -20,14 +19,14 @@ import java.net.UnknownHostException; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class GraphiteRabbitMQTest { -- private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); -- private final Connection connection = mock(Connection.class); -- private final Channel channel = mock(Channel.class); -+final class GraphiteRabbitMQTest { -+ private final ConnectionFactory connectionFactory = mock(); -+ private final Connection connection = mock(); -+ private final Channel channel = mock(); - -- private final ConnectionFactory bogusConnectionFactory = mock(ConnectionFactory.class); -- private final Connection bogusConnection = mock(Connection.class); -- private final Channel bogusChannel = mock(Channel.class); -+ private final ConnectionFactory bogusConnectionFactory = mock(); -+ private final Connection bogusConnection = mock(); -+ private final Channel bogusChannel = mock(); - - private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); - -@@ -92,10 +91,9 @@ class GraphiteRabbitMQTest { - - String expectedMessage = "name value 100\n"; - -- verify(channel, times(1)) -- .basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); -+ verify(channel).basicPublish("graphite", "name", null, expectedMessage.getBytes(UTF_8)); - -- assertThat(graphite.getFailures()).isZero(); -+ assertThat(graphite.getFailures()).isEqualTo(0); - } - - @Test -@@ -105,10 +103,10 @@ class GraphiteRabbitMQTest { - - String expectedMessage = "name-to-sanitize value-to-sanitize 100\n"; - -- verify(channel, times(1)) -+ verify(channel) - .basicPublish("graphite", "name-to-sanitize", null, expectedMessage.getBytes(UTF_8)); - -- assertThat(graphite.getFailures()).isZero(); -+ assertThat(graphite.getFailures()).isEqualTo(0); - } - - @Test -diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java -index 934c6a9..0302ddc 100644 ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java -@@ -8,6 +8,7 @@ import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verifyNoMoreInteractions; - import static org.mockito.Mockito.when; - -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -22,7 +23,6 @@ import io.dropwizard.metrics5.Timer; - import java.net.UnknownHostException; - import java.text.DecimalFormat; - import java.text.DecimalFormatSymbols; --import java.util.Collections; - import java.util.EnumSet; - import java.util.Locale; - import java.util.Set; -@@ -33,15 +33,15 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - import org.mockito.InOrder; - --class GraphiteReporterTest { -+final class GraphiteReporterTest { - private static final MetricName GAUGE = MetricName.build("gauge"); - private static final MetricName METER = MetricName.build("meter"); - private static final MetricName COUNTER = MetricName.build("counter"); - - private final long timestamp = 1000198; -- private final Clock clock = mock(Clock.class); -- private final Graphite graphite = mock(Graphite.class); -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final Clock clock = mock(); -+ private final Graphite graphite = mock(); -+ private final MetricRegistry registry = mock(); - private final GraphiteReporter reporter = - GraphiteReporter.forRegistry(registry) - .withClock(clock) -@@ -49,7 +49,7 @@ class GraphiteReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(ImmutableSet.of()) - .build(graphite); - - private final GraphiteReporter minuteRateReporter = -@@ -59,7 +59,7 @@ class GraphiteReporterTest { - .convertRatesTo(TimeUnit.MINUTES) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(ImmutableSet.of()) - .build(graphite); - - @BeforeEach -@@ -179,7 +179,7 @@ class GraphiteReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(ImmutableSet.of()) - .withFloatingPointFormatter(formatter::format) - .build(graphite)) { - reportGaugeValue(graphiteReporter, 0.000045322); -@@ -222,7 +222,7 @@ class GraphiteReporterTest { - - @Test - void reportsCounters() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map(COUNTER, counter), map(), map(), map()); -@@ -238,11 +238,11 @@ class GraphiteReporterTest { - - @Test - void reportsHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - when(histogram.getSum()).thenReturn(12L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -280,7 +280,7 @@ class GraphiteReporterTest { - - @Test - void reportsMeters() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getSum()).thenReturn(6L); - when(meter.getOneMinuteRate()).thenReturn(2.0); -@@ -306,7 +306,7 @@ class GraphiteReporterTest { - - @Test - void reportsMetersInMinutes() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getSum()).thenReturn(6L); - when(meter.getOneMinuteRate()).thenReturn(2.0); -@@ -333,7 +333,7 @@ class GraphiteReporterTest { - - @Test - void reportsTimers() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); - when(timer.getMeanRate()).thenReturn(2.0); -@@ -341,7 +341,7 @@ class GraphiteReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -410,7 +410,7 @@ class GraphiteReporterTest { - - @Test - void disabledMetricsAttribute() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getSum()).thenReturn(6L); - when(meter.getOneMinuteRate()).thenReturn(2.0); -@@ -418,7 +418,7 @@ class GraphiteReporterTest { - when(meter.getFifteenMinuteRate()).thenReturn(4.0); - when(meter.getMeanRate()).thenReturn(5.0); - -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(11L); - - Set disabledMetricAttributes = -@@ -450,7 +450,7 @@ class GraphiteReporterTest { - - @Test - void sendsMetricAttributesAsTagsIfEnabled() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - getReporterThatSendsMetricAttributesAsTags() -@@ -476,7 +476,7 @@ class GraphiteReporterTest { - MetricFilter.ALL, - null, - false, -- Collections.emptySet(), -+ ImmutableSet.of(), - false) { - @Override - protected String format(double v) { -@@ -492,7 +492,7 @@ class GraphiteReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(ImmutableSet.of()) - .addMetricAttributesAsTags(true) - .build(graphite); - } -diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java -index 9cbadb6..edca420 100644 ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java -@@ -3,7 +3,7 @@ package io.dropwizard.metrics5.graphite; - import org.assertj.core.api.SoftAssertions; - import org.junit.jupiter.api.Test; - --class GraphiteSanitizeTest { -+final class GraphiteSanitizeTest { - @Test - void sanitizeGraphiteValues() { - SoftAssertions softly = new SoftAssertions(); -diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java -index 575ff2e..80e19d6 100644 ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java -@@ -23,14 +23,14 @@ import javax.net.SocketFactory; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class GraphiteTest { -+final class GraphiteTest { - private final String host = "example.com"; - private final int port = 1234; -- private final SocketFactory socketFactory = mock(SocketFactory.class); -+ private final SocketFactory socketFactory = mock(); - private final InetSocketAddress address = new InetSocketAddress(host, port); - -- private final Socket socket = mock(Socket.class); -- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); -+ private final Socket socket = mock(); -+ private final ByteArrayOutputStream output = spy(); - - @BeforeEach - void setUp() throws Exception { -@@ -84,7 +84,7 @@ class GraphiteTest { - @Test - void measuresFailures() throws IOException { - try (Graphite graphite = new Graphite(address, socketFactory)) { -- assertThat(graphite.getFailures()).isZero(); -+ assertThat(graphite.getFailures()).isEqualTo(0); - } - } - -diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java -index a293305..5a8828e 100644 ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java -@@ -1,15 +1,15 @@ - package io.dropwizard.metrics5.graphite; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; - - import java.net.InetSocketAddress; - import java.nio.ByteBuffer; - import java.nio.channels.DatagramChannel; - import org.junit.jupiter.api.Test; --import org.mockito.Mockito; - --class GraphiteUDPTest { -+final class GraphiteUDPTest { - - private final String host = "example.com"; - private final int port = 1234; -@@ -30,7 +30,7 @@ class GraphiteUDPTest { - @Test - void writesValue() throws Exception { - graphiteUDP = new GraphiteUDP(host, port); -- DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); -+ DatagramChannel mockDatagramChannel = mock(); - graphiteUDP.setDatagramChannel(mockDatagramChannel); - graphiteUDP.setAddress(new InetSocketAddress(host, port)); - -diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java -index 6bb1d9c..50567d0 100644 ---- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java -+++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java -@@ -31,13 +31,13 @@ import org.junit.jupiter.api.Test; - import org.python.core.PyList; - import org.python.core.PyTuple; - --class PickledGraphiteTest { -- private final SocketFactory socketFactory = mock(SocketFactory.class); -+final class PickledGraphiteTest { -+ private final SocketFactory socketFactory = mock(); - private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); - private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); - -- private final Socket socket = mock(Socket.class); -- private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); -+ private final Socket socket = mock(); -+ private final ByteArrayOutputStream output = spy(); - - private CompiledScript unpickleScript; - -diff --git a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java -index f34fc4a..81e0265 100644 ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecorator.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.health; - -+import static com.google.common.base.Preconditions.checkArgument; -+ - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.health.annotation.Async; - import java.util.concurrent.ScheduledExecutorService; -@@ -29,10 +31,10 @@ public class AsyncHealthCheckDecorator implements HealthCheck, Runnable { - this.healthyTtl = - async.unit().toMillis(async.healthyTtl() <= 0 ? 2 * async.period() : async.healthyTtl()); - result = -- Async.InitialState.HEALTHY.equals(async.initialState()) -+ Async.InitialState.HEALTHY == async.initialState() - ? Result.healthy(NO_RESULT_YET_MESSAGE) - : Result.unhealthy(NO_RESULT_YET_MESSAGE); -- if (Async.ScheduleType.FIXED_RATE.equals(async.scheduleType())) { -+ if (Async.ScheduleType.FIXED_RATE == async.scheduleType()) { - future = - executorService.scheduleAtFixedRate( - this, async.initialDelay(), async.period(), async.unit()); -@@ -77,8 +79,6 @@ public class AsyncHealthCheckDecorator implements HealthCheck, Runnable { - } - - private static void check(boolean expression, String message) { -- if (!expression) { -- throw new IllegalArgumentException(message); -- } -+ checkArgument(expression, message); - } - } -diff --git a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java -index 017ab9c..e7c8eae 100644 ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheck.java -@@ -1,11 +1,12 @@ - package io.dropwizard.metrics5.health; - -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Clock; - import java.time.Instant; - import java.time.ZoneId; - import java.time.ZonedDateTime; - import java.time.format.DateTimeFormatter; --import java.util.Collections; - import java.util.LinkedHashMap; - import java.util.Map; - import java.util.concurrent.TimeUnit; -@@ -123,7 +124,7 @@ public interface HealthCheck { - this.healthy = isHealthy; - this.message = message; - this.error = error; -- this.details = details == null ? null : Collections.unmodifiableMap(details); -+ this.details = details == null ? null : unmodifiableMap(details); - this.time = clock.getTime(); - } - -@@ -162,7 +163,7 @@ public interface HealthCheck { - */ - public String getTimestamp() { - Instant currentInstant = Instant.ofEpochMilli(time); -- ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(currentInstant, ZoneId.systemDefault()); -+ ZonedDateTime zonedDateTime = currentInstant.atZone(ZoneId.systemDefault()); - return DATE_FORMAT_PATTERN.format(zonedDateTime); - } - -@@ -218,8 +219,7 @@ public interface HealthCheck { - int result = healthy ? 1 : 0; - result = PRIME * result + (message != null ? message.hashCode() : 0); - result = PRIME * result + (error != null ? error.hashCode() : 0); -- result = PRIME * result + (Long.hashCode(time)); -- return result; -+ return PRIME * result + (Long.hashCode(time)); - } - - @Override -@@ -237,7 +237,7 @@ public interface HealthCheck { - if (details != null) { - for (Map.Entry e : details.entrySet()) { - builder.append(", "); -- builder.append(e.getKey()).append("=").append(String.valueOf(e.getValue())); -+ builder.append(e.getKey()).append("=").append(e.getValue()); - } - } - builder.append('}'); -diff --git a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java -index b920a9d..77b1e1e 100644 ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java -@@ -1,9 +1,11 @@ - package io.dropwizard.metrics5.health; - -+import static com.google.common.base.Preconditions.checkArgument; - import static io.dropwizard.metrics5.health.HealthCheck.Result; -+import static java.util.Collections.unmodifiableSortedMap; -+import static java.util.Collections.unmodifiableSortedSet; - - import io.dropwizard.metrics5.health.annotation.Async; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -27,7 +29,7 @@ import org.slf4j.LoggerFactory; - - /** A registry for health checks. */ - public class HealthCheckRegistry { -- private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckRegistry.class); -+ private static final Logger LOG = LoggerFactory.getLogger(HealthCheckRegistry.class); - private static final int ASYNC_EXECUTOR_POOL_SIZE = 2; - - private final ConcurrentMap healthChecks; -@@ -92,9 +94,8 @@ public class HealthCheckRegistry { - public void register(String name, HealthCheck healthCheck) { - HealthCheck registered; - synchronized (lock) { -- if (healthChecks.containsKey(name)) { -- throw new IllegalArgumentException("A health check named " + name + " already exists"); -- } -+ checkArgument( -+ !healthChecks.containsKey(name), "A health check named " + name + " already exists"); - registered = healthCheck; - if (healthCheck.getClass().isAnnotationPresent(Async.class)) { - registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); -@@ -128,7 +129,7 @@ public class HealthCheckRegistry { - * @return the names of all registered health checks - */ - public SortedSet getNames() { -- return Collections.unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); -+ return unmodifiableSortedSet(new TreeSet<>(healthChecks.keySet())); - } - - /** -@@ -180,7 +181,7 @@ public class HealthCheckRegistry { - results.put(entry.getKey(), result); - } - } -- return Collections.unmodifiableSortedMap(results); -+ return unmodifiableSortedMap(results); - } - - /** -@@ -217,12 +218,12 @@ public class HealthCheckRegistry { - try { - results.put(entry.getKey(), entry.getValue().get()); - } catch (Exception e) { -- LOGGER.warn("Error executing health check {}", entry.getKey(), e); -+ LOG.warn("Error executing health check {}", entry.getKey(), e); - results.put(entry.getKey(), HealthCheck.Result.unhealthy(e)); - } - } - -- return Collections.unmodifiableSortedMap(results); -+ return unmodifiableSortedMap(results); - } - - private void onHealthCheckAdded(String name, HealthCheck healthCheck) { -diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java -index 209aede..83f8daa 100644 ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java -@@ -1,11 +1,12 @@ - package io.dropwizard.metrics5.health; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.ArgumentCaptor.forClass; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.*; -+import static org.mockito.Mockito.verify; - - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.health.annotation.Async; -@@ -16,7 +17,7 @@ import org.junit.jupiter.api.Test; - import org.mockito.ArgumentCaptor; - - /** Unit tests for {@link AsyncHealthCheckDecorator}. */ --class AsyncHealthCheckDecoratorTest { -+final class AsyncHealthCheckDecoratorTest { - - private static final long CURRENT_TIME = 1551002401000L; - -@@ -29,65 +30,66 @@ class AsyncHealthCheckDecoratorTest { - .withMessage("Result was healthy but it expired 1 milliseconds ago") - .build(); - -- private final HealthCheck mockHealthCheck = mock(HealthCheck.class); -- private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); -+ private final HealthCheck mockHealthCheck = mock(); -+ private final ScheduledExecutorService mockExecutorService = mock(); - - @SuppressWarnings("rawtypes") -- private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); -+ private final ScheduledFuture mockFuture = mock(); - - @Test - void nullHealthCheckTriggersInstantiationFailure() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- new AsyncHealthCheckDecorator(null, mockExecutorService); -- }); -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator(null, mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void nullExecutorServiceTriggersInstantiationFailure() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- new AsyncHealthCheckDecorator(mockHealthCheck, null); -- }); -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator(mockHealthCheck, null); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void nonAsyncHealthCheckTriggersInstantiationFailure() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); -- }); -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void negativePeriodTriggersInstantiationFailure() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- new AsyncHealthCheckDecorator(new NegativePeriodAsyncHealthCheck(), mockExecutorService); -- }); -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator( -+ new NegativePeriodAsyncHealthCheck(), mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void zeroPeriodTriggersInstantiationFailure() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); -- }); -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void negativeInitialValueTriggersInstantiationFailure() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- new AsyncHealthCheckDecorator( -- new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); -- }); -+ assertThatThrownBy( -+ () -> { -+ new AsyncHealthCheckDecorator( -+ new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test -@@ -97,7 +99,7 @@ class AsyncHealthCheckDecoratorTest { - AsyncHealthCheckDecorator asyncDecorator = - new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); - -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); - assertThat(asyncDecorator.check().isHealthy()).isTrue(); -@@ -109,7 +111,7 @@ class AsyncHealthCheckDecoratorTest { - AsyncHealthCheckDecorator asyncDecorator = - new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); - -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - assertThat(asyncDecorator.getHealthCheck()).isEqualTo(asyncHealthCheck); - } -@@ -124,8 +126,8 @@ class AsyncHealthCheckDecoratorTest { - assertThat(asyncDecorator.check().isHealthy()).isFalse(); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - void tearDownTriggersCancellation() throws Exception { - when(mockExecutorService.scheduleAtFixedRate( - any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) -@@ -136,13 +138,13 @@ class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(new DefaultAsyncHealthCheck(), mockExecutorService); - asyncDecorator.tearDown(); - -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); -- verify(mockFuture, times(1)).cancel(eq(true)); -+ verify(mockFuture).cancel(true); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { - HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); - when(mockExecutorService.scheduleAtFixedRate( -@@ -155,7 +157,7 @@ class AsyncHealthCheckDecoratorTest { - HealthCheck.Result initialResult = asyncDecorator.check(); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); - capturedRunnable.run(); -@@ -165,8 +167,8 @@ class AsyncHealthCheckDecoratorTest { - assertThat(actualResult).isNotEqualTo(initialResult); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { - Exception exception = new Exception("TestException"); - when(mockExecutorService.scheduleAtFixedRate( -@@ -178,7 +180,7 @@ class AsyncHealthCheckDecoratorTest { - new ConfigurableAsyncHealthCheck(exception), mockExecutorService); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); - capturedRunnable.run(); -@@ -195,7 +197,7 @@ class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate( - runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); -@@ -214,7 +216,7 @@ class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate( - runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); -@@ -232,7 +234,7 @@ class AsyncHealthCheckDecoratorTest { - new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - - ArgumentCaptor runnableCaptor = forClass(Runnable.class); -- verify(mockExecutorService, times(1)) -+ verify(mockExecutorService) - .scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1L), eq(TimeUnit.SECONDS)); - Runnable capturedRunnable = runnableCaptor.getValue(); - capturedRunnable.run(); -diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java -index 1177c7b..31a20bc 100644 ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java -@@ -5,7 +5,7 @@ import static org.mockito.Mockito.mock; - - import org.junit.jupiter.api.Test; - --class HealthCheckFilterTest { -+final class HealthCheckFilterTest { - - @Test - void theAllFilterMatchesAllHealthChecks() { -diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java -index 236b355..c099cc7 100644 ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java -@@ -1,9 +1,9 @@ - package io.dropwizard.metrics5.health; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.assertj.core.api.Assertions.entry; - import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; --import static org.junit.jupiter.api.Assertions.assertThrows; - import static org.mockito.ArgumentCaptor.forClass; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; -@@ -23,22 +23,22 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - import org.mockito.ArgumentCaptor; - --class HealthCheckRegistryTest { -- private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); -+final class HealthCheckRegistryTest { -+ private final ScheduledExecutorService executorService = mock(); - private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); -- private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -+ private final HealthCheckRegistryListener listener = mock(); - -- private final HealthCheck hc1 = mock(HealthCheck.class); -- private final HealthCheck hc2 = mock(HealthCheck.class); -+ private final HealthCheck hc1 = mock(); -+ private final HealthCheck hc2 = mock(); - -- private final HealthCheck.Result r1 = mock(HealthCheck.Result.class); -- private final HealthCheck.Result r2 = mock(HealthCheck.Result.class); -+ private final HealthCheck.Result r1 = mock(); -+ private final HealthCheck.Result r2 = mock(); - -- private final HealthCheck.Result ar = mock(HealthCheck.Result.class); -+ private final HealthCheck.Result ar = mock(); - private final HealthCheck ahc = new TestAsyncHealthCheck(ar); - - @SuppressWarnings("rawtypes") -- private final ScheduledFuture af = mock(ScheduledFuture.class); -+ private final ScheduledFuture af = mock(); - - @BeforeEach - @SuppressWarnings("unchecked") -@@ -74,11 +74,11 @@ class HealthCheckRegistryTest { - - @Test - void registeringHealthCheckTwiceThrowsException() { -- assertThrows( -- IllegalArgumentException.class, -- () -> { -- registry.register("hc1", hc1); -- }); -+ assertThatThrownBy( -+ () -> { -+ registry.register("hc1", hc1); -+ }) -+ .isInstanceOf(IllegalArgumentException.class); - } - - @Test -@@ -101,7 +101,7 @@ class HealthCheckRegistryTest { - - @Test - void addingListenerCatchesExistingHealthChecks() { -- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -+ HealthCheckRegistryListener listener = mock(); - HealthCheckRegistry registry = new HealthCheckRegistry(); - registry.register("hc1", hc1); - registry.register("hc2", hc2); -@@ -115,7 +115,7 @@ class HealthCheckRegistryTest { - - @Test - void removedListenerDoesNotReceiveUpdates() { -- HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); -+ HealthCheckRegistryListener listener = mock(); - HealthCheckRegistry registry = new HealthCheckRegistry(); - registry.addListener(listener); - registry.register("hc1", hc1); -diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java -index b64faa4..62df29b 100644 ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java -@@ -11,7 +11,7 @@ import java.time.ZonedDateTime; - import java.time.format.DateTimeFormatter; - import org.junit.jupiter.api.Test; - --class HealthCheckTest { -+final class HealthCheckTest { - - private static final DateTimeFormatter DATE_TIME_FORMATTER = - DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); -@@ -29,7 +29,7 @@ class HealthCheckTest { - } - } - -- private final HealthCheck underlying = mock(HealthCheck.class); -+ private final HealthCheck underlying = mock(); - private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); - - @Test -@@ -89,7 +89,7 @@ class HealthCheckTest { - - @Test - void canHaveUnhealthyResultsWithExceptions() { -- final RuntimeException e = mock(RuntimeException.class); -+ final RuntimeException e = mock(); - when(e.getMessage()).thenReturn("oh noes"); - - final HealthCheck.Result result = HealthCheck.Result.unhealthy(e); -@@ -144,7 +144,7 @@ class HealthCheckTest { - - @Test - void canHaveUnHealthyBuilderWithDetailAndError() { -- final RuntimeException e = mock(RuntimeException.class); -+ final RuntimeException e = mock(); - when(e.getMessage()).thenReturn("oh noes"); - - final HealthCheck.Result result = -@@ -161,7 +161,7 @@ class HealthCheckTest { - - @Test - void returnsResultsWhenExecuted() { -- final HealthCheck.Result result = mock(HealthCheck.Result.class); -+ final HealthCheck.Result result = mock(); - when(underlying.execute()).thenReturn(result); - - assertThat(healthCheck.execute()).isEqualTo(result); -@@ -171,7 +171,7 @@ class HealthCheckTest { - - @Test - void wrapsExceptionsWhenExecuted() { -- final RuntimeException e = mock(RuntimeException.class); -+ final RuntimeException e = mock(); - when(e.getMessage()).thenReturn("oh noes"); - - when(underlying.execute()).thenThrow(e); -@@ -181,7 +181,7 @@ class HealthCheckTest { - assertThat(actual.getMessage()).isEqualTo("oh noes"); - assertThat(actual.getError()).isEqualTo(e); - assertThat(actual.getDetails()).isNull(); -- assertThat(actual.getDuration()).isGreaterThanOrEqualTo(0); -+ assertThat(actual.getDuration()).isNotNegative(); - } - - @Test -diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java -index 1578e44..08071b6 100644 ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java -@@ -2,13 +2,12 @@ package io.dropwizard.metrics5.health; - - import static org.assertj.core.api.Assertions.assertThat; - import static org.junit.jupiter.api.Assertions.assertThrows; --import static org.junit.jupiter.api.Assertions.assertTrue; - - import java.util.concurrent.atomic.AtomicReference; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class SharedHealthCheckRegistriesTest { -+final class SharedHealthCheckRegistriesTest { - - @BeforeEach - void setUp() { -@@ -28,7 +27,7 @@ class SharedHealthCheckRegistriesTest { - void returnsSetOfCreatedRegistries() { - SharedHealthCheckRegistries.getOrCreate("db"); - -- assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); -+ assertThat(SharedHealthCheckRegistries.names()).containsExactly("db"); - } - - @Test -@@ -58,7 +57,7 @@ class SharedHealthCheckRegistriesTest { - () -> { - SharedHealthCheckRegistries.getDefault(); - }); -- assertTrue(exception.getMessage().contains("Default registry name has not been set.")); -+ assertThat(exception.getMessage().contains("Default registry name has not been set.")).isTrue(); - } - - @Test -@@ -85,7 +84,8 @@ class SharedHealthCheckRegistriesTest { - SharedHealthCheckRegistries.setDefault("default"); - SharedHealthCheckRegistries.setDefault("default"); - }); -- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); -+ assertThat(exception.getMessage().contains("Default health check registry is already set.")) -+ .isTrue(); - } - - @Test -@@ -97,6 +97,7 @@ class SharedHealthCheckRegistriesTest { - SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); - SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); - }); -- assertTrue(exception.getMessage().contains("Default health check registry is already set.")); -+ assertThat(exception.getMessage().contains("Default health check registry is already set.")) -+ .isTrue(); - } - } -diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java -index 948152a..7829d74 100644 ---- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java -+++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java -@@ -4,23 +4,22 @@ import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; - -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.health.HealthCheck; - import io.dropwizard.metrics5.jvm.ThreadDeadlockDetector; --import java.util.Collections; - import java.util.Set; - import java.util.TreeSet; --import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.Test; - --class ThreadDeadlockHealthCheckTest { -+final class ThreadDeadlockHealthCheckTest { - @Test - void isHealthyIfNoThreadsAreDeadlocked() { -- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -+ final ThreadDeadlockDetector detector = mock(); - final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); - -- when(detector.getDeadlockedThreads()).thenReturn(Collections.emptySet()); -+ when(detector.getDeadlockedThreads()).thenReturn(ImmutableSet.of()); - -- Assertions.assertThat(healthCheck.execute().isHealthy()).isTrue(); -+ assertThat(healthCheck.execute().isHealthy()).isTrue(); - } - - @Test -@@ -29,7 +28,7 @@ class ThreadDeadlockHealthCheckTest { - threads.add("one"); - threads.add("two"); - -- final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -+ final ThreadDeadlockDetector detector = mock(); - final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); - - when(detector.getDeadlockedThreads()).thenReturn(threads); -@@ -44,6 +43,6 @@ class ThreadDeadlockHealthCheckTest { - @Test - void automaticallyUsesThePlatformThreadBeans() { - final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(); -- Assertions.assertThat(healthCheck.execute().isHealthy()).isTrue(); -+ assertThat(healthCheck.execute().isHealthy()).isTrue(); - } - } -diff --git a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java -index ece43e4..3c22974 100644 ---- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java -+++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java -@@ -22,7 +22,7 @@ import org.mockito.Mock; - import org.mockito.junit.jupiter.MockitoExtension; - - @ExtendWith(MockitoExtension.class) --class InstrumentedHttpClientsTest extends HttpClientTestBase { -+final class InstrumentedHttpClientsTest extends HttpClientTestBase { - - private final MetricRegistry metricRegistry = new MetricRegistry(); - -diff --git a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java -index 55e5785..44f52fa 100644 ---- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java -+++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.httpasyncclient; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; -@@ -20,6 +19,7 @@ import org.apache.http.client.methods.HttpGet; - import org.apache.http.concurrent.FutureCallback; - import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; - import org.apache.http.nio.client.HttpAsyncClient; -+import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Disabled; - import org.junit.jupiter.api.Test; -@@ -29,7 +29,7 @@ import org.mockito.junit.jupiter.MockitoExtension; - - @ExtendWith(MockitoExtension.class) - @Disabled("The tests are flaky") --class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { -+final class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - - private HttpAsyncClient asyncHttpClient; - -@@ -46,7 +46,7 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - chac.start(); - asyncHttpClient = chac; - -- Timer timer = mock(Timer.class); -+ Timer timer = mock(); - when(timer.time()).thenReturn(context); - when(metricRegistry.timer(MetricName.build("test"))).thenReturn(timer); - } -@@ -72,13 +72,13 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - verify(context, timeout(200).times(1)).stop(); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { - HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); - HttpGet get = new HttpGet("/?q=something"); - -- FutureCallback futureCallback = mock(FutureCallback.class); -+ FutureCallback futureCallback = mock(); - - // Timer hasn't been stopped prior to executing the request - verify(context, never()).stop(); -@@ -99,14 +99,14 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - verify(context, timeout(200).times(1)).stop(); - } - -- @Test - @SuppressWarnings("unchecked") -+ @Test - void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { - // There should be nothing listening on this port - HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); - HttpGet get = new HttpGet("/?q=something"); - -- FutureCallback futureCallback = mock(FutureCallback.class); -+ FutureCallback futureCallback = mock(); - - // Timer hasn't been stopped prior to executing the request - verify(context, never()).stop(); -@@ -118,7 +118,7 @@ class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - - try { - responseFuture.get(20, TimeUnit.SECONDS); -- fail("This should fail as the client should not be able to connect"); -+ Assertions.fail("This should fail as the client should not be able to connect"); - } catch (Exception e) { - // Ignore - } -diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java -index 2e09143..ed7927a 100644 ---- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java -+++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java -@@ -17,7 +17,7 @@ import org.apache.http.client.methods.HttpRequestWrapper; - import org.apache.http.client.utils.URIUtils; - import org.junit.jupiter.api.Test; - --class HttpClientMetricNameStrategiesTest { -+final class HttpClientMetricNameStrategiesTest { - - @Test - void methodOnlyWithName() { -diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java -index 5e33b2f..b4570e8 100644 ---- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java -+++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java -@@ -3,16 +3,17 @@ package io.dropwizard.metrics5.httpclient; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.junit.jupiter.api.Assertions.assertEquals; --import static org.junit.jupiter.api.Assertions.assertTrue; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import org.junit.jupiter.api.Test; - import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; - --class InstrumentedHttpClientConnectionManagerTest { -+final class InstrumentedHttpClientConnectionManagerTest { - private final MetricRegistry metricRegistry = new MetricRegistry(); - - @Test -@@ -37,7 +38,7 @@ class InstrumentedHttpClientConnectionManagerTest { - - @Test - void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -+ final MetricRegistry registry = mock(); - - InstrumentedHttpClientConnectionManager.builder(registry) - .name("some-name") -@@ -46,7 +47,7 @@ class InstrumentedHttpClientConnectionManagerTest { - .close(); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); - } - } -diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java -index abaa84b..e5c7259 100644 ---- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.httpclient; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; -@@ -19,13 +18,13 @@ import org.apache.http.HttpRequest; - import org.apache.http.NoHttpResponseException; - import org.apache.http.client.HttpClient; - import org.apache.http.client.methods.HttpGet; -+import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedHttpClientsTest { -- private final HttpClientMetricNameStrategy metricNameStrategy = -- mock(HttpClientMetricNameStrategy.class); -- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); -+final class InstrumentedHttpClientsTest { -+ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); -+ private final MetricRegistryListener registryListener = mock(); - private final MetricRegistry metricRegistry = new MetricRegistry(); - private final HttpClient client = - InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) -@@ -67,7 +66,7 @@ class InstrumentedHttpClientsTest { - - try { - client.execute(get); -- fail(); -+ Assertions.fail(); - } catch (NoHttpResponseException expected) { - assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); - } finally { -diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java -index 848b025..67741ec 100644 ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java -@@ -16,7 +16,7 @@ import org.apache.hc.core5.http.message.HttpRequestWrapper; - import org.apache.hc.core5.net.URIBuilder; - import org.junit.jupiter.api.Test; - --class HttpClientMetricNameStrategiesTest { -+final class HttpClientMetricNameStrategiesTest { - - @Test - void methodOnlyWithName() { -diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java -index 78095dc..24fa03b 100644 ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java -@@ -3,16 +3,17 @@ package io.dropwizard.metrics5.httpclient5; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.junit.jupiter.api.Assertions.assertEquals; --import static org.junit.jupiter.api.Assertions.assertTrue; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import org.junit.jupiter.api.Test; - import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; - --class InstrumentedAsyncClientConnectionManagerTest { -+final class InstrumentedAsyncClientConnectionManagerTest { - private final MetricRegistry metricRegistry = new MetricRegistry(); - - @Test -@@ -44,7 +45,7 @@ class InstrumentedAsyncClientConnectionManagerTest { - - @Test - void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -+ final MetricRegistry registry = mock(); - - InstrumentedAsyncClientConnectionManager.builder(registry) - .name("some-name") -@@ -53,7 +54,7 @@ class InstrumentedAsyncClientConnectionManagerTest { - .close(); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); - } - } -diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java -index ebabd69..b67225a 100644 ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java -@@ -1,8 +1,8 @@ - package io.dropwizard.metrics5.httpclient5; - -+import static java.nio.charset.StandardCharsets.US_ASCII; - import static org.assertj.core.api.Assertions.assertThat; - import static org.awaitility.Awaitility.await; --import static org.junit.jupiter.api.Assertions.fail; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.atLeastOnce; -@@ -18,7 +18,6 @@ import io.dropwizard.metrics5.MetricRegistryListener; - import io.dropwizard.metrics5.Timer; - import java.io.IOException; - import java.net.InetSocketAddress; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.CountDownLatch; - import java.util.concurrent.ExecutionException; - import java.util.concurrent.Future; -@@ -31,6 +30,7 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; - import org.apache.hc.core5.concurrent.FutureCallback; - import org.apache.hc.core5.http.ConnectionClosedException; - import org.apache.hc.core5.http.HttpRequest; -+import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; -@@ -39,7 +39,7 @@ import org.mockito.Mock; - import org.mockito.junit.jupiter.MockitoExtension; - - @ExtendWith(MockitoExtension.class) --class InstrumentedHttpAsyncClientsTest { -+final class InstrumentedHttpAsyncClientsTest { - - @Mock private HttpClientMetricNameStrategy metricNameStrategy; - @Mock private MetricRegistryListener registryListener; -@@ -83,7 +83,7 @@ class InstrumentedHttpAsyncClientsTest { - exchange -> { - exchange.sendResponseHeaders(200, 0L); - exchange.setStreams(null, null); -- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); -+ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); - exchange.close(); - }); - httpServer.start(); -@@ -101,12 +101,12 @@ class InstrumentedHttpAsyncClientsTest { - - @Override - public void failed(Exception ex) { -- fail(); -+ Assertions.fail(); - } - - @Override - public void cancelled() { -- fail(); -+ Assertions.fail(); - } - }); - responseFuture.get(1L, TimeUnit.SECONDS); -@@ -144,7 +144,7 @@ class InstrumentedHttpAsyncClientsTest { - new FutureCallback() { - @Override - public void completed(SimpleHttpResponse result) { -- fail(); -+ Assertions.fail(); - } - - @Override -@@ -154,13 +154,13 @@ class InstrumentedHttpAsyncClientsTest { - - @Override - public void cancelled() { -- fail(); -+ Assertions.fail(); - } - }); - countDownLatch.await(5, TimeUnit.SECONDS); - responseFuture.get(5, TimeUnit.SECONDS); - -- fail(); -+ Assertions.fail(); - } catch (ExecutionException e) { - assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class); - await() -@@ -193,7 +193,7 @@ class InstrumentedHttpAsyncClientsTest { - exchange -> { - exchange.sendResponseHeaders(200, 0L); - exchange.setStreams(null, null); -- exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); -+ exchange.getResponseBody().write("TEST".getBytes(US_ASCII)); - exchange.close(); - }); - httpServer.start(); -@@ -211,12 +211,12 @@ class InstrumentedHttpAsyncClientsTest { - - @Override - public void failed(Exception ex) { -- fail(); -+ Assertions.fail(); - } - - @Override - public void cancelled() { -- fail(); -+ Assertions.fail(); - } - }); - responseFuture.get(1L, TimeUnit.SECONDS); -diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java -index bddad25..4f63d65 100644 ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java -@@ -3,16 +3,17 @@ package io.dropwizard.metrics5.httpclient5; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.junit.jupiter.api.Assertions.assertEquals; --import static org.junit.jupiter.api.Assertions.assertTrue; - import static org.mockito.ArgumentMatchers.any; -+import static org.mockito.Mockito.atLeast; -+import static org.mockito.Mockito.mock; -+import static org.mockito.Mockito.verify; - - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import org.junit.jupiter.api.Test; - import org.mockito.ArgumentCaptor; --import org.mockito.Mockito; - --class InstrumentedHttpClientConnectionManagerTest { -+final class InstrumentedHttpClientConnectionManagerTest { - private final MetricRegistry metricRegistry = new MetricRegistry(); - - @Test -@@ -42,7 +43,7 @@ class InstrumentedHttpClientConnectionManagerTest { - - @Test - void configurableViaBuilder() { -- final MetricRegistry registry = Mockito.mock(MetricRegistry.class); -+ final MetricRegistry registry = mock(); - - InstrumentedHttpClientConnectionManager.builder(registry) - .name("some-name") -@@ -51,7 +52,7 @@ class InstrumentedHttpClientConnectionManagerTest { - .close(); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(MetricName.class); -- Mockito.verify(registry, Mockito.atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -- assertTrue(argumentCaptor.getValue().getKey().contains("some-other-name")); -+ verify(registry, atLeast(1)).registerGauge(argumentCaptor.capture(), any()); -+ assertThat(argumentCaptor.getValue().getKey().contains("some-other-name")).isTrue(); - } - } -diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java -index 86a450e..46cdc5e 100644 ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.httpclient5; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; -@@ -19,13 +18,13 @@ import org.apache.hc.client5.http.classic.HttpClient; - import org.apache.hc.client5.http.classic.methods.HttpGet; - import org.apache.hc.core5.http.HttpRequest; - import org.apache.hc.core5.http.NoHttpResponseException; -+import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedHttpClientsTest { -- private final HttpClientMetricNameStrategy metricNameStrategy = -- mock(HttpClientMetricNameStrategy.class); -- private final MetricRegistryListener registryListener = mock(MetricRegistryListener.class); -+final class InstrumentedHttpClientsTest { -+ private final HttpClientMetricNameStrategy metricNameStrategy = mock(); -+ private final MetricRegistryListener registryListener = mock(); - private final MetricRegistry metricRegistry = new MetricRegistry(); - private final HttpClient client = - InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy) -@@ -67,7 +66,7 @@ class InstrumentedHttpClientsTest { - - try { - client.execute(get); -- fail(); -+ Assertions.fail(); - } catch (NoHttpResponseException expected) { - assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); - } finally { -diff --git a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java -index 3d674ce..1e2cf3a 100644 ---- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java -+++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java -@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.influxdb; - - import static io.dropwizard.metrics5.MetricAttribute.*; - -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -15,7 +16,6 @@ import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.Snapshot; - import io.dropwizard.metrics5.Timer; - import java.io.IOException; --import java.util.Collections; - import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -78,7 +78,7 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { - this.filter = MetricFilter.ALL; - this.executor = null; - this.shutdownExecutorOnStop = true; -- this.disabledMetricAttributes = Collections.emptySet(); -+ this.disabledMetricAttributes = ImmutableSet.of(); - } - - /** -@@ -196,7 +196,7 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { - } - } - -- private static final Logger LOGGER = LoggerFactory.getLogger(InfluxDbReporter.class); -+ private static final Logger LOG = LoggerFactory.getLogger(InfluxDbReporter.class); - private static final String VALUE = "value"; - - private final Clock clock; -@@ -279,12 +279,12 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { - } - sender.flush(); - } catch (IOException e) { -- LOGGER.warn("Unable to report to InfluxDb", sender, e); -+ LOG.warn("Unable to report to InfluxDb", sender, e); - } finally { - try { - sender.disconnect(); - } catch (IOException e) { -- LOGGER.warn("Error disconnecting InfluxDb", sender, e); -+ LOG.warn("Error disconnecting InfluxDb", sender, e); - } - } - } -@@ -297,7 +297,7 @@ public class InfluxDbReporter extends GarbageFreeScheduledReporter { - try { - sender.close(); - } catch (IOException e) { -- LOGGER.debug("Error disconnecting from InfluxDb", e); -+ LOG.debug("Error disconnecting from InfluxDb", e); - } - } - } -diff --git a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java -index 77be29b..0a75252 100644 ---- a/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java -+++ b/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpSender.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.influxdb; - -+import static java.util.Objects.requireNonNull; -+ - import java.io.IOException; - import java.net.InetSocketAddress; - import java.nio.ByteBuffer; -@@ -9,7 +11,6 @@ import java.nio.charset.Charset; - import java.nio.charset.CharsetEncoder; - import java.nio.charset.CoderResult; - import java.nio.charset.CodingErrorAction; --import java.util.Objects; - - public class InfluxDbUdpSender implements InfluxDbSender { - -@@ -42,7 +43,7 @@ public class InfluxDbUdpSender implements InfluxDbSender { - * @param address the address of the InfluxDb server - */ - public InfluxDbUdpSender(InetSocketAddress address) { -- this.address = Objects.requireNonNull(address); -+ this.address = requireNonNull(address); - charBuf = CharBuffer.allocate(mtu * 2); - byteBuf = ByteBuffer.allocate(mtu * 2); - } -diff --git a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java -index 75af4ca..3cb0035 100644 ---- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java -+++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java -@@ -5,7 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; - import io.dropwizard.metrics5.MetricAttribute; - import org.junit.jupiter.api.Test; - --class InfluxDbLineBuilderAssumptionsTest { -+final class InfluxDbLineBuilderAssumptionsTest { - - @Test - void ensureMetricAttributeCodesAreSafeFieldKeys() { -diff --git a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java -index d50c1fa..98f5c99 100644 ---- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java -+++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java -@@ -11,6 +11,7 @@ import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.verifyNoMoreInteractions; - import static org.mockito.Mockito.when; - -+import com.google.common.collect.ImmutableSet; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; -@@ -25,7 +26,6 @@ import io.dropwizard.metrics5.Timer; - import java.io.IOException; - import java.net.UnknownHostException; - import java.util.ArrayList; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Set; -@@ -36,16 +36,16 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - import org.mockito.InOrder; - --class InfluxDbReporterTest { -+final class InfluxDbReporterTest { - private static final MetricName GAUGE = MetricName.build("gauge"); - private static final MetricName METER = MetricName.build("meter"); - private static final MetricName COUNTER = MetricName.build("counter"); - - private final long timestamp = 1000198; -- private final Clock clock = mock(Clock.class); -- private final InfluxDbSender sender = mock(InfluxDbSender.class); -+ private final Clock clock = mock(); -+ private final InfluxDbSender sender = mock(); - private final List send = new ArrayList<>(); -- private final MetricRegistry registry = mock(MetricRegistry.class); -+ private final MetricRegistry registry = mock(); - private final InfluxDbReporter reporter = - InfluxDbReporter.forRegistry(registry) - .withClock(clock) -@@ -53,7 +53,7 @@ class InfluxDbReporterTest { - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(ImmutableSet.of()) - .build(sender); - - private final InfluxDbReporter minuteRateReporter = -@@ -63,7 +63,7 @@ class InfluxDbReporterTest { - .convertRatesTo(TimeUnit.MINUTES) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) -- .disabledMetricAttributes(Collections.emptySet()) -+ .disabledMetricAttributes(ImmutableSet.of()) - .build(sender); - - @BeforeEach -@@ -197,7 +197,7 @@ class InfluxDbReporterTest { - - @Test - void reportsCounters() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - reporter.report(map(), map(COUNTER, counter), map(), map(), map()); -@@ -214,11 +214,11 @@ class InfluxDbReporterTest { - - @Test - void reportsHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - when(histogram.getSum()).thenReturn(12L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -249,7 +249,7 @@ class InfluxDbReporterTest { - - @Test - void reportsMeters() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getSum()).thenReturn(6L); - when(meter.getOneMinuteRate()).thenReturn(2.0); -@@ -274,7 +274,7 @@ class InfluxDbReporterTest { - - @Test - void reportsMetersInMinutes() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getSum()).thenReturn(6L); - when(meter.getOneMinuteRate()).thenReturn(2.0); -@@ -300,7 +300,7 @@ class InfluxDbReporterTest { - - @Test - void reportsTimers() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getSum()).thenReturn(6L); - when(timer.getMeanRate()).thenReturn(2.0); -@@ -308,7 +308,7 @@ class InfluxDbReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -360,7 +360,7 @@ class InfluxDbReporterTest { - - @Test - void disabledMetricsAttribute() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getSum()).thenReturn(6L); - when(meter.getOneMinuteRate()).thenReturn(2.0); -@@ -368,7 +368,7 @@ class InfluxDbReporterTest { - when(meter.getFifteenMinuteRate()).thenReturn(4.0); - when(meter.getMeanRate()).thenReturn(5.0); - -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(11L); - - Set disabledMetricAttributes = -diff --git a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java -index 29d4ddf..1f5a23a 100644 ---- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java -+++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java -@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.influxdb; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.any; - import static org.mockito.Mockito.doAnswer; -+import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - -@@ -14,15 +15,14 @@ import java.util.ArrayList; - import java.util.List; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; --import org.mockito.Mockito; - --class InfluxDbUdpTest { -+final class InfluxDbUdpTest { - - private final String host = "example.com"; - private final int port = 1234; - - private InfluxDbUdpSender influxdbUdp; -- private final DatagramChannel datagramChannel = Mockito.mock(DatagramChannel.class); -+ private final DatagramChannel datagramChannel = mock(); - private final List sent = new ArrayList<>(); - - @BeforeEach -diff --git a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -index 3a776cc..459acf7 100644 ---- a/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -+++ b/metrics-jakarta-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.servlet; - - import static io.dropwizard.metrics5.MetricRegistry.name; - -+import com.google.common.base.Strings; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -64,7 +65,7 @@ public abstract class AbstractInstrumentedFilter implements Filter { - final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); - - String metricName = filterConfig.getInitParameter(METRIC_PREFIX); -- if (metricName == null || metricName.isEmpty()) { -+ if (Strings.isNullOrEmpty(metricName)) { - metricName = getClass().getName(); - } - -diff --git a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -index d6768d4..163e420 100644 ---- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -+++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -@@ -9,8 +9,8 @@ import jakarta.servlet.ServletContext; - import jakarta.servlet.ServletContextEvent; - import org.junit.jupiter.api.Test; - --class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -+final class InstrumentedFilterContextListenerTest { -+ private final MetricRegistry registry = mock(); - private final InstrumentedFilterContextListener listener = - new InstrumentedFilterContextListener() { - @Override -@@ -21,9 +21,9 @@ class InstrumentedFilterContextListenerTest { - - @Test - void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ final ServletContext context = mock(); - -- final ServletContextEvent event = mock(ServletContextEvent.class); -+ final ServletContextEvent event = mock(); - when(event.getServletContext()).thenReturn(context); - - listener.contextInitialized(event); -diff --git a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java -index 7473d89..8057b76 100644 ---- a/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java -+++ b/metrics-jakarta-servlet6/src/main/java/io/dropwizard/metrics5/servlet6/AbstractInstrumentedFilter.java -@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.servlet6; - - import static io.dropwizard.metrics5.MetricRegistry.name; - -+import com.google.common.base.Strings; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -64,7 +65,7 @@ public abstract class AbstractInstrumentedFilter implements Filter { - final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); - - String metricName = filterConfig.getInitParameter(METRIC_PREFIX); -- if (metricName == null || metricName.isEmpty()) { -+ if (Strings.isNullOrEmpty(metricName)) { - metricName = getClass().getName(); - } - -diff --git a/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java b/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java -index af9fc44..0f00187 100644 ---- a/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java -+++ b/metrics-jakarta-servlet6/src/test/java/io/dropwizard/metrics5/servlet6/InstrumentedFilterContextListenerTest.java -@@ -9,8 +9,8 @@ import jakarta.servlet.ServletContext; - import jakarta.servlet.ServletContextEvent; - import org.junit.jupiter.api.Test; - --class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -+final class InstrumentedFilterContextListenerTest { -+ private final MetricRegistry registry = mock(); - private final InstrumentedFilterContextListener listener = - new InstrumentedFilterContextListener() { - @Override -@@ -21,9 +21,9 @@ class InstrumentedFilterContextListenerTest { - - @Test - void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ final ServletContext context = mock(); - -- final ServletContextEvent event = mock(ServletContextEvent.class); -+ final ServletContextEvent event = mock(); - when(event.getServletContext()).thenReturn(context); - - listener.contextInitialized(event); -diff --git a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -index a6081a8..440debd 100644 ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); - if (registryAttr instanceof HealthCheckRegistry) { - this.registry = (HealthCheckRegistry) registryAttr; -diff --git a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -index b8a0e3c..a365885 100644 ---- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -+++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(METRICS_REGISTRY); - if (registryAttr instanceof MetricRegistry) { - this.registry = (MetricRegistry) registryAttr; -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java -index b71f2fa..92530f2 100755 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java -@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class AdminServletExclusionTest extends AbstractServletTest { -+final class AdminServletExclusionTest extends AbstractServletTest { - private final MetricRegistry registry = new MetricRegistry(); - private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); - -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java -index 8fcdf8a..77b50ba 100755 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java -@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class AdminServletTest extends AbstractServletTest { -+final class AdminServletTest extends AbstractServletTest { - private final MetricRegistry registry = new MetricRegistry(); - private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); - -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java -index ebe2c81..424a05e 100755 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java -@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class AdminServletUriTest extends AbstractServletTest { -+final class AdminServletUriTest extends AbstractServletTest { - private final MetricRegistry registry = new MetricRegistry(); - private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); - -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java -index 1c63a41..2df4050 100644 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java -@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class CpuProfileServletTest extends AbstractServletTest { -+final class CpuProfileServletTest extends AbstractServletTest { - - @Override - protected void setUp(ServletTester tester) { -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -index f8f0a87..e8208b0 100644 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -@@ -1,10 +1,9 @@ - package io.dropwizard.metrics5.servlets; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -27,7 +26,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class HealthCheckServletTest extends AbstractServletTest { -+final class HealthCheckServletTest extends AbstractServletTest { - - private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); - -@@ -95,9 +94,8 @@ class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - } - - @Test -@@ -111,9 +109,8 @@ class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - } - - @Test -@@ -168,15 +165,8 @@ class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getContent()) - .isEqualTo( - String.format( -- "{%n" -- + " \"fun\" : {%n" -- + " \"healthy\" : true,%n" -- + " \"message\" : \"foo bar 123\",%n" -- + " \"duration\" : 0,%n" -- + " \"timestamp\" : \"" -- + EXPECTED_TIMESTAMP -- + "\"" -- + "%n }%n}")); -+ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", -+ EXPECTED_TIMESTAMP)); - } - - private static HealthCheck.Result healthyResultWithMessage(String message) { -@@ -197,23 +187,23 @@ class HealthCheckServletTest extends AbstractServletTest { - - @Test - void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -+ verify(servletConfig).getServletContext(); - verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); - } - - @Test - void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn(healthCheckRegistry); -@@ -221,32 +211,32 @@ class HealthCheckServletTest extends AbstractServletTest { - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); - } - - @Test - void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- assertThrows( -- ServletException.class, -- () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -- .thenReturn("IRELLEVANT_STRING"); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -- healthCheckServlet.init(servletConfig); -- }); -+ assertThatThrownBy( -+ () -> { -+ final ServletContext servletContext = mock(ServletContext.class); -+ final ServletConfig servletConfig = mock(ServletConfig.class); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -+ .thenReturn("IRELLEVANT_STRING"); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -+ healthCheckServlet.init(servletConfig); -+ }) -+ .isInstanceOf(ServletException.class); - } - - @Test - void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn(registry); -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java -index 2e1d334..f30c0b9 100644 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java -@@ -17,8 +17,8 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class MetricsServletContextListenerTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+final class MetricsServletContextListenerTest extends AbstractServletTest { -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private final String allowedOrigin = "some.other.origin"; - -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -index 08d39bc..d74900f 100644 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -@@ -1,11 +1,10 @@ - package io.dropwizard.metrics5.servlets; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -25,8 +24,8 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class MetricsServletTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+final class MetricsServletTest extends AbstractServletTest { -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private ServletTester tester; - -@@ -130,22 +129,8 @@ class MetricsServletTest extends AbstractServletTest { - assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); - assertThat(response.getContent()) - .isEqualTo( -- callbackParamVal -- + "({" -- + "\"version\":\"5.0.0\"," -- + "\"gauges\":{" -- + "\"g1\":{\"value\":100}" -- + "}," -- + "\"counters\":{" -- + "\"c\":{\"count\":1}" -- + "}," -- + "\"histograms\":{" -- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -- + "}," -- + "\"meters\":{" -- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -- + "}" -- + "})"); -+ "%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", -+ callbackParamVal); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -224,48 +209,47 @@ class MetricsServletTest extends AbstractServletTest { - - @Test - void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); - } - - @Test - void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn(metricRegistry); -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); - - final MetricsServlet metricsServlet = new MetricsServlet(null); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); - } - - @Test - void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- assertThrows( -- ServletException.class, -- () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn("IRELLEVANT_STRING"); -- -- final MetricsServlet metricsServlet = new MetricsServlet(null); -- metricsServlet.init(servletConfig); -- }); -+ assertThatThrownBy( -+ () -> { -+ final ServletContext servletContext = mock(ServletContext.class); -+ final ServletConfig servletConfig = mock(ServletConfig.class); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -+ .thenReturn("IRELLEVANT_STRING"); -+ -+ final MetricsServlet metricsServlet = new MetricsServlet(null); -+ metricsServlet.init(servletConfig); -+ }) -+ .isInstanceOf(ServletException.class); - } - } -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java -index 72e4d9f..56bb1ee 100644 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java -@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class PingServletTest extends AbstractServletTest { -+final class PingServletTest extends AbstractServletTest { - @Override - protected void setUp(ServletTester tester) { - tester.addServlet(PingServlet.class, "/ping"); -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java -index 3b92675..5bbb7b1 100644 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java -@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class ThreadDumpServletTest extends AbstractServletTest { -+final class ThreadDumpServletTest extends AbstractServletTest { - @Override - protected void setUp(ServletTester tester) { - tester.addServlet(ThreadDumpServlet.class, "/threads"); -diff --git a/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java b/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java -index 946c66f..9810386 100644 ---- a/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java -+++ b/metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics5.jcache; - - import static io.dropwizard.metrics5.MetricRegistry.name; -+import static java.util.Collections.unmodifiableMap; - - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; -@@ -9,7 +10,6 @@ import io.dropwizard.metrics5.jvm.JmxAttributeGauge; - import java.lang.management.ManagementFactory; - import java.lang.reflect.Method; - import java.util.ArrayList; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Locale; -@@ -33,7 +33,7 @@ public class JCacheGaugeSet implements MetricSet { - private static final String M_BEAN_COORDINATES = - "javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"; - -- private static final Logger LOGGER = LoggerFactory.getLogger(JCacheGaugeSet.class); -+ private static final Logger LOG = LoggerFactory.getLogger(JCacheGaugeSet.class); - - @Override - public Map getMetrics() { -@@ -52,7 +52,7 @@ public class JCacheGaugeSet implements MetricSet { - } - } - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - - private Set getCacheBeans() { -@@ -60,7 +60,7 @@ public class JCacheGaugeSet implements MetricSet { - return ManagementFactory.getPlatformMBeanServer() - .queryMBeans(ObjectName.getInstance(M_BEAN_COORDINATES), null); - } catch (MalformedObjectNameException e) { -- LOGGER.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); -+ LOG.error("Unable to retrieve {}. Are JCache statistics enabled?", M_BEAN_COORDINATES); - throw new RuntimeException(e); - } - } -diff --git a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java -index cf3e28d..cf0f223 100644 ---- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java -+++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java -@@ -11,7 +11,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class JCacheGaugeSetTest { -+final class JCacheGaugeSetTest { - - private MetricRegistry registry; - private Cache myCache; -@@ -67,11 +67,11 @@ class JCacheGaugeSetTest { - - this.myCache.remove("woo2"); - assertThat((Float) registry.getGauges().get(myCache.resolve("average-get-time")).getValue()) -- .isGreaterThan(0.0f); -+ .isPositive(); - assertThat((Float) registry.getGauges().get(myCache.resolve("average-put-time")).getValue()) -- .isGreaterThan(0.0f); -+ .isPositive(); - assertThat((Float) registry.getGauges().get(myCache.resolve("average-remove-time")).getValue()) -- .isGreaterThan(0.0f); -+ .isPositive(); - } - - @AfterEach -diff --git a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java -index 5f67c62..ceea60d 100644 ---- a/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java -+++ b/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/strategies/DefaultNameStrategy.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5.jdbi3.strategies; - -+import com.google.common.base.Strings; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import org.jdbi.v3.core.extension.ExtensionMethod; -@@ -13,7 +14,7 @@ public enum DefaultNameStrategy implements StatementNameStrategy { - @Override - public MetricName getStatementName(StatementContext statementContext) { - final String rawSql = statementContext.getRawSql(); -- return rawSql == null || rawSql.isEmpty() ? MetricName.build("sql.empty") : null; -+ return Strings.isNullOrEmpty(rawSql) ? MetricName.build("sql.empty") : null; - } - }, - -diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java -index 4588a32..5378df0 100644 ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java -@@ -8,7 +8,7 @@ import io.dropwizard.metrics5.MetricName; - import org.jdbi.v3.core.extension.ExtensionMethod; - import org.junit.jupiter.api.Test; - --class BasicSqlNameStrategyTest extends AbstractStrategyTest { -+final class BasicSqlNameStrategyTest extends AbstractStrategyTest { - - private final BasicSqlNameStrategy basicSqlNameStrategy = new BasicSqlNameStrategy(); - -diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java -index b8cf361..c8f74aa 100755 ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java -@@ -12,15 +12,15 @@ import java.util.concurrent.TimeUnit; - import org.jdbi.v3.core.statement.StatementContext; - import org.junit.jupiter.api.Test; - --class InstrumentedSqlLoggerTest { -+final class InstrumentedSqlLoggerTest { - @Test - void logsExecutionTime() { -- final MetricRegistry mockRegistry = mock(MetricRegistry.class); -- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); -+ final MetricRegistry mockRegistry = mock(); -+ final StatementNameStrategy mockNameStrategy = mock(); - final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); - -- final StatementContext mockContext = mock(StatementContext.class); -- final Timer mockTimer = mock(Timer.class); -+ final StatementContext mockContext = mock(); -+ final Timer mockTimer = mock(); - - final MetricName statementName = MetricName.build("my-fake-name"); - final long fakeElapsed = 1234L; -@@ -37,12 +37,12 @@ class InstrumentedSqlLoggerTest { - - @Test - void logsExceptionTime() { -- final MetricRegistry mockRegistry = mock(MetricRegistry.class); -- final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); -+ final MetricRegistry mockRegistry = mock(); -+ final StatementNameStrategy mockNameStrategy = mock(); - final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); - -- final StatementContext mockContext = mock(StatementContext.class); -- final Timer mockTimer = mock(Timer.class); -+ final StatementContext mockContext = mock(); -+ final Timer mockTimer = mock(); - - final MetricName statementName = MetricName.build("my-fake-name"); - final long fakeElapsed = 1234L; -diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java -index 7d8d115..8175106 100644 ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java -@@ -5,7 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; - import io.dropwizard.metrics5.MetricName; - import org.junit.jupiter.api.Test; - --class NaiveNameStrategyTest extends AbstractStrategyTest { -+final class NaiveNameStrategyTest extends AbstractStrategyTest { - - private final NaiveNameStrategy naiveNameStrategy = new NaiveNameStrategy(); - -diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java -index efca9da..b9f4c6a 100644 ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java -@@ -12,7 +12,7 @@ import org.jdbi.v3.core.extension.ExtensionMethod; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class SmartNameStrategyTest extends AbstractStrategyTest { -+final class SmartNameStrategyTest extends AbstractStrategyTest { - - private final StatementNameStrategy smartNameStrategy = new SmartNameStrategy(); - private InstrumentedTimingCollector collector; -diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java -index 20cd360..b380772 100644 ---- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java -+++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java -@@ -8,7 +8,7 @@ import io.dropwizard.metrics5.annotation.Timed; - import org.jdbi.v3.core.extension.ExtensionMethod; - import org.junit.jupiter.api.Test; - --class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { -+final class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { - - private final TimedAnnotationNameStrategy timedAnnotationNameStrategy = - new TimedAnnotationNameStrategy(); -@@ -44,7 +44,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { - } - - @Test -- void testAnnotationOnMethod() throws Exception { -+ void annotationOnMethod() throws Exception { - when(ctx.getExtensionMethod()) - .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("update"))); - assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -@@ -54,7 +54,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { - } - - @Test -- void testAnnotationOnMethodWithCustomName() throws Exception { -+ void annotationOnMethodWithCustomName() throws Exception { - when(ctx.getExtensionMethod()) - .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("customUpdate"))); - assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -@@ -64,7 +64,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { - } - - @Test -- void testAnnotationOnMethodWithCustomAbsoluteName() throws Exception { -+ void annotationOnMethodWithCustomAbsoluteName() throws Exception { - when(ctx.getExtensionMethod()) - .thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("absoluteUpdate"))); - assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -@@ -72,7 +72,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { - } - - @Test -- void testAnnotationOnClass() throws Exception { -+ void annotationOnClass() throws Exception { - when(ctx.getExtensionMethod()) - .thenReturn(new ExtensionMethod(Bar.class, Bar.class.getMethod("update"))); - assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) -@@ -82,7 +82,7 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { - } - - @Test -- void testAnnotationOnMethodAndClassWithCustomNames() throws Exception { -+ void annotationOnMethodAndClassWithCustomNames() throws Exception { - when(ctx.getExtensionMethod()) - .thenReturn( - new ExtensionMethod(CustomBar.class, CustomBar.class.getMethod("find", String.class))); -@@ -91,14 +91,14 @@ class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { - } - - @Test -- void testNoAnnotations() throws Exception { -+ void noAnnotations() throws Exception { - when(ctx.getExtensionMethod()) - .thenReturn(new ExtensionMethod(Dummy.class, Dummy.class.getMethod("show"))); - assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); - } - - @Test -- void testNoMethod() { -+ void noMethod() { - assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); - } - } -diff --git a/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java b/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java -index 7116636..0d33048 100644 ---- a/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey2/src/main/java/io/dropwizard/metrics5/jersey2/InstrumentedResourceMethodApplicationListener.java -@@ -3,7 +3,11 @@ package io.dropwizard.metrics5.jersey2; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; - -+import com.google.common.base.Strings; -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Meter; -@@ -19,7 +23,6 @@ import io.dropwizard.metrics5.annotation.Timed; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -159,7 +162,7 @@ public class InstrumentedResourceMethodApplicationListener - this.level = responseMetered.level(); - this.meters = - COARSE_METER_LEVELS.contains(level) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(metricName.resolve("1xx-responses")), // 1xx - registry.meter(metricName.resolve("2xx-responses")), // 2xx -@@ -167,11 +170,9 @@ public class InstrumentedResourceMethodApplicationListener - registry.meter(metricName.resolve("4xx-responses")), // 4xx - registry.meter(metricName.resolve("5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : ImmutableList.of(); - this.responseCodeMeters = -- DETAILED_METER_LEVELS.contains(level) -- ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); - this.metricRegistry = registry; - } - -@@ -305,9 +306,9 @@ public class InstrumentedResourceMethodApplicationListener - : null; - - if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) -+ if (metric.cause.isInstance(event.getException()) - || (event.getException().getCause() != null -- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -+ && metric.cause.isInstance(event.getException().getCause()))) { - metric.meter.mark(); - } - } -@@ -418,14 +419,11 @@ public class InstrumentedResourceMethodApplicationListener - - @Override - public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = -- new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); - } - - private T getClassLevelAnnotation( -@@ -543,7 +541,7 @@ public class InstrumentedResourceMethodApplicationListener - final String... suffixes) { - final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - MetricName metricName; -- if (explicitName != null && !explicitName.isEmpty()) { -+ if (!Strings.isNullOrEmpty(explicitName)) { - metricName = - absolute - ? MetricRegistry.name(explicitName) -@@ -604,8 +602,7 @@ public class InstrumentedResourceMethodApplicationListener - @Override - public int hashCode() { - int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -+ return 31 * result + method.hashCode(); - } - } - } -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java -index d077730..9252eec 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java -@@ -14,7 +14,7 @@ import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --class CustomReservoirImplementationTest extends JerseyTest { -+final class CustomReservoirImplementationTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java -index b96f71a..47ae1ce 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java -@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} with filter tracking - */ --class SingletonFilterMetricsJerseyTest extends JerseyTest { -+final class SingletonFilterMetricsJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -34,8 +34,7 @@ class SingletonFilterMetricsJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry, testClock, true)); - config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -+ return config.register(new InstrumentedFilteredResource(testClock)); - } - - @BeforeEach -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -index 4258938..db81836 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -34,9 +34,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); - } - - @Test -@@ -50,7 +48,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -75,7 +73,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - assertThat(target("subresource/exception-metered").request().get(String.class)) - .isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("subresource/exception-metered") -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java -index 2aeb6ef..e79e200 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java -@@ -24,7 +24,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link org.glassfish.jersey.server.ResourceConfig} - */ --class SingletonMetricsJerseyTest extends JerseyTest { -+final class SingletonMetricsJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -37,9 +37,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { - - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -+ return config.register(InstrumentedResource.class); - } - - @Test -@@ -67,7 +65,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -92,13 +90,13 @@ class SingletonMetricsJerseyTest extends JerseyTest { - registry.meter( - MetricRegistry.name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); - assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter4xx.getCount()).isZero(); -+ assertThat(meter4xx.getCount()).isEqualTo(0); - assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); - -- assertThat(meter5xx.getCount()).isZero(); -+ assertThat(meter5xx.getCount()).isEqualTo(0); - assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); - - assertThat(meter2xx.getCount()).isEqualTo(1); -@@ -107,7 +105,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { - } - - @Test -- void testResourceNotFound() { -+ void resourceNotFound() { - final Response response = target().path("not-found").request().get(); - assertThat(response.getStatus()).isEqualTo(404); - -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java -index 561a942..ce3e94f 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -31,9 +31,7 @@ class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceMeteredPerClass.class); - } - - @Test -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -index bc36e7a..eeec0da 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -1,7 +1,6 @@ - package io.dropwizard.metrics5.jersey2; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; - - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -11,6 +10,7 @@ import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceResponseM - import java.util.logging.Level; - import java.util.logging.Logger; - import javax.ws.rs.core.Application; -+import org.assertj.core.api.Assertions; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; -@@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -34,9 +34,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - - config = config.register(new MetricsFeature(this.registry)); - config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -+ return config.register(new TestExceptionMapper()); - } - - @Test -@@ -109,7 +107,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { - try { - target("responseMeteredRuntimeExceptionPerClass").request().get(); -- fail("expected RuntimeException"); -+ Assertions.fail("expected RuntimeException"); - } catch (Exception e) { - assertThat(e.getCause()).isInstanceOf(RuntimeException.class); - } -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java -index c8a6468..cd7c883 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java -@@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -31,9 +31,7 @@ class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceTimedPerClass.class); - } - - @Test -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java -index b1a48cc..6173844 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedFilteredResource.java -@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { - } - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick++; - return "yay"; - } - - @GET -- @Timed(name = "fancyName") - @Path("/named") -+ @Timed(name = "fancyName") - public String named() { - testClock.tick++; - return "fancy"; - } - - @GET -- @Timed(name = "absolutelyFancy", absolute = true) - @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) - public String absolute() { - testClock.tick++; - return "absolute"; -@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { - public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick += 2; - return "yay"; -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java -index a74a5c8..566fef8 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedResource.java -@@ -21,8 +21,8 @@ import javax.ws.rs.core.Response; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -@@ -34,8 +34,8 @@ public class InstrumentedResource { - return "woo"; - } - -- @GET - @ExceptionMetered(cause = IOException.class) -+ @GET - @Path("/exception-metered") - public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) - throws IOException { -@@ -46,46 +46,46 @@ public class InstrumentedResource { - } - - @GET -- @ResponseMetered(level = DETAILED) - @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) - public Response responseMeteredDetailed( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = COARSE) - @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) - public Response responseMeteredCoarse( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = ALL) - @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) - public Response responseMeteredAll( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered - @Path("/response-2xx-metered") -+ @ResponseMetered - public Response response2xxMetered() { - return Response.ok().build(); - } - - @GET -- @ResponseMetered - @Path("/response-4xx-metered") -+ @ResponseMetered - public Response response4xxMetered() { - return Response.status(Response.Status.BAD_REQUEST).build(); - } - - @GET -- @ResponseMetered - @Path("/response-5xx-metered") -+ @ResponseMetered - public Response response5xxMetered() { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java -index 32fffd6..b99a6cf 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/resources/InstrumentedSubResource.java -@@ -10,8 +10,8 @@ import javax.ws.rs.core.MediaType; - public class InstrumentedSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -diff --git a/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java b/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java -index dc0e1bb..4298701 100644 ---- a/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey3/src/main/java/io/dropwizard/metrics5/jersey3/InstrumentedResourceMethodApplicationListener.java -@@ -4,7 +4,11 @@ import static io.dropwizard.metrics5.MetricRegistry.name; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; - -+import com.google.common.base.Strings; -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Meter; -@@ -22,7 +26,6 @@ import jakarta.ws.rs.ext.Provider; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -160,7 +163,7 @@ public class InstrumentedResourceMethodApplicationListener - this.level = responseMetered.level(); - this.meters = - COARSE_METER_LEVELS.contains(level) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(metricName.resolve("1xx-responses")), // 1xx - registry.meter(metricName.resolve("2xx-responses")), // 2xx -@@ -168,11 +171,9 @@ public class InstrumentedResourceMethodApplicationListener - registry.meter(metricName.resolve("4xx-responses")), // 4xx - registry.meter(metricName.resolve("5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : ImmutableList.of(); - this.responseCodeMeters = -- DETAILED_METER_LEVELS.contains(level) -- ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); - this.metricRegistry = registry; - } - -@@ -306,9 +307,9 @@ public class InstrumentedResourceMethodApplicationListener - : null; - - if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) -+ if (metric.cause.isInstance(event.getException()) - || (event.getException().getCause() != null -- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -+ && metric.cause.isInstance(event.getException().getCause()))) { - metric.meter.mark(); - } - } -@@ -419,14 +420,11 @@ public class InstrumentedResourceMethodApplicationListener - - @Override - public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = -- new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); - } - - private T getClassLevelAnnotation( -@@ -544,7 +542,7 @@ public class InstrumentedResourceMethodApplicationListener - final String... suffixes) { - final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - MetricName metricName; -- if (explicitName != null && !explicitName.isEmpty()) { -+ if (!Strings.isNullOrEmpty(explicitName)) { - metricName = - absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); - } else { -@@ -602,8 +600,7 @@ public class InstrumentedResourceMethodApplicationListener - @Override - public int hashCode() { - int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -+ return 31 * result + method.hashCode(); - } - } - } -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java -index a3ac358..c512f1e 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java -@@ -14,7 +14,7 @@ import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --class CustomReservoirImplementationTest extends JerseyTest { -+final class CustomReservoirImplementationTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java -index a95000f..59b42a3 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java -@@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} with filter tracking - */ --class SingletonFilterMetricsJerseyTest extends JerseyTest { -+final class SingletonFilterMetricsJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -35,8 +35,7 @@ class SingletonFilterMetricsJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry, testClock, true)); - config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -+ return config.register(new InstrumentedFilteredResource(testClock)); - } - - @BeforeEach -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -index 80d90a6..023155e 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -35,9 +35,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); - } - - @Test -@@ -51,7 +49,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -76,7 +74,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - assertThat(target("subresource/exception-metered").request().get(String.class)) - .isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("subresource/exception-metered") -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java -index f507662..9dca17f 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java -@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link org.glassfish.jersey.server.ResourceConfig} - */ --class SingletonMetricsJerseyTest extends JerseyTest { -+final class SingletonMetricsJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -38,9 +38,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { - - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -+ return config.register(InstrumentedResource.class); - } - - @Test -@@ -67,7 +65,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -89,13 +87,13 @@ class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter5xx = - registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); - assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter4xx.getCount()).isZero(); -+ assertThat(meter4xx.getCount()).isEqualTo(0); - assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); - -- assertThat(meter5xx.getCount()).isZero(); -+ assertThat(meter5xx.getCount()).isEqualTo(0); - assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); - - assertThat(meter2xx.getCount()).isEqualTo(1); -@@ -115,9 +113,9 @@ class SingletonMetricsJerseyTest extends JerseyTest { - registry.meter( - name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); - assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); - assertThat( - target("response-metered-detailed") -@@ -127,28 +125,28 @@ class SingletonMetricsJerseyTest extends JerseyTest { - .getStatus()) - .isEqualTo(201); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); - } - - @Test -- public void responseMeteredMethodsAreMeteredWithAllLevel() { -+ void responseMeteredMethodsAreMeteredWithAllLevel() { - final Meter meter2xx = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - - @Test -- void testResourceNotFound() { -+ void resourceNotFound() { - final Response response = target().path("not-found").request().get(); - assertThat(response.getStatus()).isEqualTo(404); - -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java -index f9a9aaf..18c0712 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -32,9 +32,7 @@ class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceMeteredPerClass.class); - } - - @Test -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -index 9e3e887..00e401f 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.jersey3; - - import static io.dropwizard.metrics5.MetricRegistry.name; - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; - - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -12,6 +11,7 @@ import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceResponseM - import jakarta.ws.rs.core.Application; - import java.util.logging.Level; - import java.util.logging.Logger; -+import org.assertj.core.api.Assertions; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; -@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -35,9 +35,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - - config = config.register(new MetricsFeature(this.registry)); - config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -+ return config.register(new TestExceptionMapper()); - } - - @Test -@@ -110,7 +108,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { - try { - target("responseMeteredRuntimeExceptionPerClass").request().get(); -- fail("expected RuntimeException"); -+ Assertions.fail("expected RuntimeException"); - } catch (Exception e) { - assertThat(e.getCause()).isInstanceOf(RuntimeException.class); - } -@@ -140,8 +138,8 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - - assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); -@@ -154,7 +152,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - "2xx-responses")); - assertThat(meter.getCount()).isEqualTo(1); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - } -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java -index 96977e6..edcb12d 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java -@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -32,9 +32,7 @@ class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceTimedPerClass.class); - } - - @Test -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java -index 76fdaa4..7514cf6 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedFilteredResource.java -@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { - } - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick++; - return "yay"; - } - - @GET -- @Timed(name = "fancyName") - @Path("/named") -+ @Timed(name = "fancyName") - public String named() { - testClock.tick++; - return "fancy"; - } - - @GET -- @Timed(name = "absolutelyFancy", absolute = true) - @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) - public String absolute() { - testClock.tick++; - return "absolute"; -@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { - public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick += 2; - return "yay"; -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java -index f865db2..9e4d521 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedResource.java -@@ -21,8 +21,8 @@ import java.io.IOException; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -@@ -34,8 +34,8 @@ public class InstrumentedResource { - return "woo"; - } - -- @GET - @ExceptionMetered(cause = IOException.class) -+ @GET - @Path("/exception-metered") - public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) - throws IOException { -@@ -46,46 +46,46 @@ public class InstrumentedResource { - } - - @GET -- @ResponseMetered(level = DETAILED) - @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) - public Response responseMeteredDetailed( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = COARSE) - @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) - public Response responseMeteredCoarse( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = ALL) - @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) - public Response responseMeteredAll( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered - @Path("/response-2xx-metered") -+ @ResponseMetered - public Response response2xxMetered() { - return Response.ok().build(); - } - - @GET -- @ResponseMetered - @Path("/response-4xx-metered") -+ @ResponseMetered - public Response response4xxMetered() { - return Response.status(Response.Status.BAD_REQUEST).build(); - } - - @GET -- @ResponseMetered - @Path("/response-5xx-metered") -+ @ResponseMetered - public Response response5xxMetered() { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java -index 5df3fc5..98e889d 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/resources/InstrumentedSubResource.java -@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; - public class InstrumentedSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -diff --git a/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java b/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java -index 830d052..ff2dea3 100644 ---- a/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java -+++ b/metrics-jersey31/src/main/java/io/dropwizard/metrics5/jersey31/InstrumentedResourceMethodApplicationListener.java -@@ -4,7 +4,11 @@ import static io.dropwizard.metrics5.MetricRegistry.name; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; - -+import com.google.common.base.Strings; -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Clock; - import io.dropwizard.metrics5.ExponentiallyDecayingReservoir; - import io.dropwizard.metrics5.Meter; -@@ -22,7 +26,6 @@ import jakarta.ws.rs.ext.Provider; - import java.lang.annotation.Annotation; - import java.lang.reflect.Method; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -160,7 +163,7 @@ public class InstrumentedResourceMethodApplicationListener - this.level = responseMetered.level(); - this.meters = - COARSE_METER_LEVELS.contains(level) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(metricName.resolve("1xx-responses")), // 1xx - registry.meter(metricName.resolve("2xx-responses")), // 2xx -@@ -168,11 +171,9 @@ public class InstrumentedResourceMethodApplicationListener - registry.meter(metricName.resolve("4xx-responses")), // 4xx - registry.meter(metricName.resolve("5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : ImmutableList.of(); - this.responseCodeMeters = -- DETAILED_METER_LEVELS.contains(level) -- ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ DETAILED_METER_LEVELS.contains(level) ? new ConcurrentHashMap<>() : ImmutableMap.of(); - this.metricRegistry = registry; - } - -@@ -306,9 +307,9 @@ public class InstrumentedResourceMethodApplicationListener - : null; - - if (metric != null) { -- if (metric.cause.isAssignableFrom(event.getException().getClass()) -+ if (metric.cause.isInstance(event.getException()) - || (event.getException().getCause() != null -- && metric.cause.isAssignableFrom(event.getException().getCause().getClass()))) { -+ && metric.cause.isInstance(event.getException().getCause()))) { - metric.meter.mark(); - } - } -@@ -419,14 +420,11 @@ public class InstrumentedResourceMethodApplicationListener - - @Override - public RequestEventListener onRequest(final RequestEvent event) { -- final RequestEventListener listener = -- new ChainedRequestEventListener( -- new TimerRequestEventListener(timers, clock), -- new MeterRequestEventListener(meters), -- new ExceptionMeterRequestEventListener(exceptionMeters), -- new ResponseMeterRequestEventListener(responseMeters)); -- -- return listener; -+ return new ChainedRequestEventListener( -+ new TimerRequestEventListener(timers, clock), -+ new MeterRequestEventListener(meters), -+ new ExceptionMeterRequestEventListener(exceptionMeters), -+ new ResponseMeterRequestEventListener(responseMeters)); - } - - private T getClassLevelAnnotation( -@@ -544,7 +542,7 @@ public class InstrumentedResourceMethodApplicationListener - final String... suffixes) { - final Method definitionMethod = method.getInvocable().getDefinitionMethod(); - MetricName metricName; -- if (explicitName != null && !explicitName.isEmpty()) { -+ if (!Strings.isNullOrEmpty(explicitName)) { - metricName = - absolute ? name(explicitName) : name(definitionMethod.getDeclaringClass(), explicitName); - } else { -@@ -602,8 +600,7 @@ public class InstrumentedResourceMethodApplicationListener - @Override - public int hashCode() { - int result = type.hashCode(); -- result = 31 * result + method.hashCode(); -- return result; -+ return 31 * result + method.hashCode(); - } - } - } -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java -index 46996eb..6aaa268 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java -@@ -14,7 +14,7 @@ import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; - --class CustomReservoirImplementationTest extends JerseyTest { -+final class CustomReservoirImplementationTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java -index b93ab95..546f28b 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java -@@ -19,7 +19,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} with filter tracking - */ --class SingletonFilterMetricsJerseyTest extends JerseyTest { -+final class SingletonFilterMetricsJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -35,8 +35,7 @@ class SingletonFilterMetricsJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry, testClock, true)); - config = config.register(new TestRequestFilter(testClock)); -- config = config.register(new InstrumentedFilteredResource(testClock)); -- return config; -+ return config.register(new InstrumentedFilteredResource(testClock)); - } - - @BeforeEach -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -index f67f1d0..32d2dde 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java -@@ -21,7 +21,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -35,9 +35,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceExceptionMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceExceptionMeteredPerClass.class); - } - - @Test -@@ -51,7 +49,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -76,7 +74,7 @@ class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { - assertThat(target("subresource/exception-metered").request().get(String.class)) - .isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("subresource/exception-metered") -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java -index aa0251c..3b35f93 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java -@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsJerseyTest extends JerseyTest { -+final class SingletonMetricsJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -38,9 +38,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { - - ResourceConfig config = new ResourceConfig(); - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResource.class); -- -- return config; -+ return config.register(InstrumentedResource.class); - } - - @Test -@@ -67,7 +65,7 @@ class SingletonMetricsJerseyTest extends JerseyTest { - - assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh"); - -- assertThat(meter.getCount()).isZero(); -+ assertThat(meter.getCount()).isEqualTo(0); - - try { - target("exception-metered").queryParam("splode", true).request().get(String.class); -@@ -89,33 +87,33 @@ class SingletonMetricsJerseyTest extends JerseyTest { - final Meter meter5xx = - registry.meter(name(InstrumentedResource.class, "response5xxMetered", "5xx-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); - assertThat(target("response-2xx-metered").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter4xx.getCount()).isZero(); -+ assertThat(meter4xx.getCount()).isEqualTo(0); - assertThat(target("response-4xx-metered").request().get().getStatus()).isEqualTo(400); - -- assertThat(meter5xx.getCount()).isZero(); -+ assertThat(meter5xx.getCount()).isEqualTo(0); - assertThat(target("response-5xx-metered").request().get().getStatus()).isEqualTo(500); - } - - @Test -- public void responseMeteredMethodsAreMeteredWithCoarseLevel() { -+ void responseMeteredMethodsAreMeteredWithCoarseLevel() { - final Meter meter2xx = - registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "2xx-responses")); - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredCoarse", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-coarse").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(0); - } - - @Test -- public void responseMeteredMethodsAreMeteredWithDetailedLevel() { -+ void responseMeteredMethodsAreMeteredWithDetailedLevel() { - final Meter meter2xx = - registry.meter( - name(InstrumentedResource.class, "responseMeteredDetailed", "2xx-responses")); -@@ -126,9 +124,9 @@ class SingletonMetricsJerseyTest extends JerseyTest { - registry.meter( - name(InstrumentedResource.class, "responseMeteredDetailed", "201-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -- assertThat(meter201.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); -+ assertThat(meter201.getCount()).isEqualTo(0); - assertThat(target("response-metered-detailed").request().get().getStatus()).isEqualTo(200); - assertThat( - target("response-metered-detailed") -@@ -138,28 +136,28 @@ class SingletonMetricsJerseyTest extends JerseyTest { - .getStatus()) - .isEqualTo(201); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isOne(); -- assertThat(meter201.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(1); -+ assertThat(meter201.getCount()).isEqualTo(1); - } - - @Test -- public void responseMeteredMethodsAreMeteredWithAllLevel() { -+ void responseMeteredMethodsAreMeteredWithAllLevel() { - final Meter meter2xx = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "2xx-responses")); - final Meter meter200 = - registry.meter(name(InstrumentedResource.class, "responseMeteredAll", "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - assertThat(target("response-metered-all").request().get().getStatus()).isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - - @Test -- void testResourceNotFound() { -+ void resourceNotFound() { - final Response response = target().path("not-found").request().get(); - assertThat(response.getStatus()).isEqualTo(404); - -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java -index a661f5d..9a90095 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java -@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -32,9 +32,7 @@ class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceMeteredPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceMeteredPerClass.class); - } - - @Test -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -index 1d68658..fdd0440 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.jersey31; - - import static io.dropwizard.metrics5.MetricRegistry.name; - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.fail; - - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -12,6 +11,7 @@ import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceResponse - import jakarta.ws.rs.core.Application; - import java.util.logging.Level; - import java.util.logging.Logger; -+import org.assertj.core.api.Assertions; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; -@@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -35,9 +35,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - - config = config.register(new MetricsFeature(this.registry)); - config = config.register(InstrumentedResourceResponseMeteredPerClass.class); -- config = config.register(new TestExceptionMapper()); -- -- return config; -+ return config.register(new TestExceptionMapper()); - } - - @Test -@@ -110,7 +108,7 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { - try { - target("responseMeteredRuntimeExceptionPerClass").request().get(); -- fail("expected RuntimeException"); -+ Assertions.fail("expected RuntimeException"); - } catch (Exception e) { - assertThat(e.getCause()).isInstanceOf(RuntimeException.class); - } -@@ -140,13 +138,13 @@ class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { - "responseMeteredPerClass", - "200-responses")); - -- assertThat(meter2xx.getCount()).isZero(); -- assertThat(meter200.getCount()).isZero(); -+ assertThat(meter2xx.getCount()).isEqualTo(0); -+ assertThat(meter200.getCount()).isEqualTo(0); - - assertThat(target("subresource/responseMeteredPerClass").request().get().getStatus()) - .isEqualTo(200); - -- assertThat(meter2xx.getCount()).isOne(); -- assertThat(meter200.getCount()).isOne(); -+ assertThat(meter2xx.getCount()).isEqualTo(1); -+ assertThat(meter200.getCount()).isEqualTo(1); - } - } -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java -index 2258ea8..ca5dd87 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java -@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; - * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton in a - * Jersey {@link ResourceConfig} - */ --class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { -+final class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - static { - Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); - } -@@ -32,9 +32,7 @@ class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { - ResourceConfig config = new ResourceConfig(); - - config = config.register(new MetricsFeature(this.registry)); -- config = config.register(InstrumentedResourceTimedPerClass.class); -- -- return config; -+ return config.register(InstrumentedResourceTimedPerClass.class); - } - - @Test -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java -index 08d974e..17d8a5b 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedFilteredResource.java -@@ -18,24 +18,24 @@ public class InstrumentedFilteredResource { - } - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick++; - return "yay"; - } - - @GET -- @Timed(name = "fancyName") - @Path("/named") -+ @Timed(name = "fancyName") - public String named() { - testClock.tick++; - return "fancy"; - } - - @GET -- @Timed(name = "absolutelyFancy", absolute = true) - @Path("/absolute") -+ @Timed(name = "absolutelyFancy", absolute = true) - public String absolute() { - testClock.tick++; - return "absolute"; -@@ -50,8 +50,8 @@ public class InstrumentedFilteredResource { - public class InstrumentedFilteredSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - testClock.tick += 2; - return "yay"; -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java -index 20cc56a..6befce2 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedResource.java -@@ -21,8 +21,8 @@ import java.io.IOException; - @Produces(MediaType.TEXT_PLAIN) - public class InstrumentedResource { - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -@@ -34,8 +34,8 @@ public class InstrumentedResource { - return "woo"; - } - -- @GET - @ExceptionMetered(cause = IOException.class) -+ @GET - @Path("/exception-metered") - public String exceptionMetered(@QueryParam("splode") @DefaultValue("false") boolean splode) - throws IOException { -@@ -46,46 +46,46 @@ public class InstrumentedResource { - } - - @GET -- @ResponseMetered(level = DETAILED) - @Path("/response-metered-detailed") -+ @ResponseMetered(level = DETAILED) - public Response responseMeteredDetailed( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = COARSE) - @Path("/response-metered-coarse") -+ @ResponseMetered(level = COARSE) - public Response responseMeteredCoarse( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered(level = ALL) - @Path("/response-metered-all") -+ @ResponseMetered(level = ALL) - public Response responseMeteredAll( - @QueryParam("status_code") @DefaultValue("200") int statusCode) { - return Response.status(Response.Status.fromStatusCode(statusCode)).build(); - } - - @GET -- @ResponseMetered - @Path("/response-2xx-metered") -+ @ResponseMetered - public Response response2xxMetered() { - return Response.ok().build(); - } - - @GET -- @ResponseMetered - @Path("/response-4xx-metered") -+ @ResponseMetered - public Response response4xxMetered() { - return Response.status(Response.Status.BAD_REQUEST).build(); - } - - @GET -- @ResponseMetered - @Path("/response-5xx-metered") -+ @ResponseMetered - public Response response5xxMetered() { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java -index 3db3c9f..2efa31f 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/resources/InstrumentedSubResource.java -@@ -10,8 +10,8 @@ import jakarta.ws.rs.core.MediaType; - public class InstrumentedSubResource { - - @GET -- @Timed - @Path("/timed") -+ @Timed - public String timed() { - return "yay"; - } -diff --git a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java -index 847cc4c..a75a1d4 100644 ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHandler.java -@@ -4,7 +4,10 @@ import static io.dropwizard.metrics5.MetricRegistry.name; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; - -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -14,7 +17,6 @@ import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -173,7 +175,7 @@ public class InstrumentedHandler extends HandlerWrapper { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : ImmutableMap.of(); - - this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); - this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); -@@ -188,7 +190,7 @@ public class InstrumentedHandler extends HandlerWrapper { - - if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { - this.responses = -- Collections.unmodifiableList( -+ unmodifiableList( - Arrays.asList( - metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx - metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx -@@ -253,7 +255,7 @@ public class InstrumentedHandler extends HandlerWrapper { - } - }); - } else { -- this.responses = Collections.emptyList(); -+ this.responses = ImmutableList.of(); - } - - this.listener = new AsyncAttachingListener(); -diff --git a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java -index bddd2b9..29e9004 100644 ---- a/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListener.java -@@ -3,7 +3,10 @@ package io.dropwizard.metrics5.jetty10; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; - -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -14,7 +17,6 @@ import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : ImmutableMap.of(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(prefix.resolve("1xx-responses")), // 1xx - registry.meter(prefix.resolve("2xx-responses")), // 2xx -@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { - registry.meter(prefix.resolve("4xx-responses")), // 4xx - registry.meter(prefix.resolve("5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : ImmutableList.of(); - - this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); - this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); -diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java -index 9a3d31c..fa1f566 100644 ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java -@@ -21,7 +21,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedConnectionFactoryTest { -+final class InstrumentedConnectionFactoryTest { - private final MetricRegistry registry = new MetricRegistry(); - private final Server server = new Server(); - private final ServerConnector connector = -diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java -index 771f5a4..337c76a 100644 ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java -@@ -3,13 +3,13 @@ package io.dropwizard.metrics5.jetty10; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; - - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.TimeUnit; - import javax.servlet.AsyncContext; - import javax.servlet.ServletException; -@@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Disabled; - import org.junit.jupiter.api.Test; - --class InstrumentedHandlerTest { -+final class InstrumentedHandlerTest { - private final HttpClient client = new HttpClient(); - private final MetricRegistry registry = new MetricRegistry(); - private final Server server = new Server(); -@@ -118,7 +118,7 @@ class InstrumentedHandlerTest { - } - - @Test -- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { -+ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { - InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); - handler.setHandler(new TestHandler()); - handler.setName("handler"); -@@ -128,7 +128,7 @@ class InstrumentedHandlerTest { - } - - @Test -- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { -+ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { - InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); - handler.setHandler(new TestHandler()); - handler.setName("handler"); -@@ -137,8 +137,8 @@ class InstrumentedHandlerTest { - .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); - } - -- @Test - @Disabled("flaky on virtual machines") -+ @Test - void responseTimesAreRecordedForAsyncResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/async")); -@@ -150,7 +150,7 @@ class InstrumentedHandlerTest { - - private void assertResponseTimesValid() { - assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) -- .isGreaterThan(0L); -+ .isPositive(); - - assertThat( - registry -@@ -158,11 +158,11 @@ class InstrumentedHandlerTest { - .get(metricName().resolve("get-requests")) - .getSnapshot() - .getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - - assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - } - -@@ -225,7 +225,7 @@ class InstrumentedHandlerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async\n".getBytes(UTF_8)); - context.complete(); - } - -diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java -index 295894d..aee388a 100644 ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java -@@ -1,12 +1,12 @@ - package io.dropwizard.metrics5.jetty10; - - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import javax.servlet.AsyncContext; - import javax.servlet.ServletOutputStream; - import javax.servlet.WriteListener; -@@ -22,7 +22,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedHttpChannelListenerTest { -+final class InstrumentedHttpChannelListenerTest { - private final HttpClient client = new HttpClient(); - private final Server server = new Server(); - private final ServerConnector connector = new ServerConnector(server); -@@ -188,7 +188,7 @@ class InstrumentedHttpChannelListenerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async".getBytes(UTF_8)); - context.complete(); - } - -diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java -index 2d97f27..73ba784 100644 ---- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java -+++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java -@@ -8,7 +8,7 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedQueuedThreadPoolTest { -+final class InstrumentedQueuedThreadPoolTest { - private static final String PREFIX = "prefix"; - - private MetricRegistry metricRegistry; -diff --git a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java -index 19987c1..b5a43cb 100644 ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHandler.java -@@ -4,7 +4,10 @@ import static io.dropwizard.metrics5.MetricRegistry.name; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; - -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -19,7 +22,6 @@ import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -173,7 +175,7 @@ public class InstrumentedHandler extends HandlerWrapper { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : ImmutableMap.of(); - - this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); - this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); -@@ -188,7 +190,7 @@ public class InstrumentedHandler extends HandlerWrapper { - - if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { - this.responses = -- Collections.unmodifiableList( -+ unmodifiableList( - Arrays.asList( - metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx - metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx -@@ -253,7 +255,7 @@ public class InstrumentedHandler extends HandlerWrapper { - } - }); - } else { -- this.responses = Collections.emptyList(); -+ this.responses = ImmutableList.of(); - } - - this.listener = new AsyncAttachingListener(); -diff --git a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java -index a423590..e0d710f 100644 ---- a/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java -+++ b/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListener.java -@@ -3,7 +3,10 @@ package io.dropwizard.metrics5.jetty11; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; - -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -18,7 +21,6 @@ import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; - import java.nio.ByteBuffer; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -132,10 +134,10 @@ public class InstrumentedHttpChannelListener implements Listener { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : ImmutableMap.of(); - this.responses = - COARSE_METER_LEVELS.contains(responseMeteredLevel) -- ? Collections.unmodifiableList( -+ ? unmodifiableList( - Arrays.asList( - registry.meter(prefix.resolve("1xx-responses")), // 1xx - registry.meter(prefix.resolve("2xx-responses")), // 2xx -@@ -143,7 +145,7 @@ public class InstrumentedHttpChannelListener implements Listener { - registry.meter(prefix.resolve("4xx-responses")), // 4xx - registry.meter(prefix.resolve("5xx-responses")) // 5xx - )) -- : Collections.emptyList(); -+ : ImmutableList.of(); - - this.getRequests = metricRegistry.timer(prefix.resolve("get-requests")); - this.postRequests = metricRegistry.timer(prefix.resolve("post-requests")); -diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java -index e1ae763..b810aef 100644 ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java -@@ -21,7 +21,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedConnectionFactoryTest { -+final class InstrumentedConnectionFactoryTest { - private final MetricRegistry registry = new MetricRegistry(); - private final Server server = new Server(); - private final ServerConnector connector = -diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java -index 74d5d78..743c45c 100644 ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java -@@ -3,6 +3,7 @@ package io.dropwizard.metrics5.jetty11; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; - -@@ -15,7 +16,6 @@ import jakarta.servlet.WriteListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; -@@ -28,7 +28,7 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Disabled; - import org.junit.jupiter.api.Test; - --class InstrumentedHandlerTest { -+final class InstrumentedHandlerTest { - private final HttpClient client = new HttpClient(); - private final MetricRegistry registry = new MetricRegistry(); - private final Server server = new Server(); -@@ -118,7 +118,7 @@ class InstrumentedHandlerTest { - } - - @Test -- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { -+ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { - InstrumentedHandler handler = new InstrumentedHandler(registry, "coarse", COARSE); - handler.setHandler(new TestHandler()); - handler.setName("handler"); -@@ -128,7 +128,7 @@ class InstrumentedHandlerTest { - } - - @Test -- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { -+ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { - InstrumentedHandler handler = new InstrumentedHandler(registry, "detailed", DETAILED); - handler.setHandler(new TestHandler()); - handler.setName("handler"); -@@ -137,8 +137,8 @@ class InstrumentedHandlerTest { - .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); - } - -- @Test - @Disabled("flaky on virtual machines") -+ @Test - void responseTimesAreRecordedForAsyncResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/async")); -@@ -150,7 +150,7 @@ class InstrumentedHandlerTest { - - private void assertResponseTimesValid() { - assertThat(registry.getMeters().get(metricName().resolve("200-responses")).getCount()) -- .isGreaterThan(0L); -+ .isPositive(); - - assertThat( - registry -@@ -158,11 +158,11 @@ class InstrumentedHandlerTest { - .get(metricName().resolve("get-requests")) - .getSnapshot() - .getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - - assertThat(registry.getTimers().get(metricName().resolve("requests")).getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - } - -@@ -225,7 +225,7 @@ class InstrumentedHandlerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async\n".getBytes(UTF_8)); - context.complete(); - } - -diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java -index aab3f77..4120921 100644 ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics5.jetty11; - - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - - import io.dropwizard.metrics5.MetricName; -@@ -11,7 +12,6 @@ import jakarta.servlet.WriteListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import org.eclipse.jetty.client.HttpClient; - import org.eclipse.jetty.client.api.ContentResponse; - import org.eclipse.jetty.server.Request; -@@ -22,7 +22,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedHttpChannelListenerTest { -+final class InstrumentedHttpChannelListenerTest { - private final HttpClient client = new HttpClient(); - private final Server server = new Server(); - private final ServerConnector connector = new ServerConnector(server); -@@ -188,7 +188,7 @@ class InstrumentedHttpChannelListenerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async".getBytes(UTF_8)); - context.complete(); - } - -diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java -index 464abd2..27d0872 100644 ---- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java -+++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java -@@ -8,7 +8,7 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class InstrumentedQueuedThreadPoolTest { -+final class InstrumentedQueuedThreadPoolTest { - private static final String PREFIX = "prefix"; - - private MetricRegistry metricRegistry; -diff --git a/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java b/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java -index 0e556df..20760f9 100644 ---- a/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java -+++ b/metrics-jetty12-ee10/src/test/java/io/dropwizard/metrics/jetty12/ee10/InstrumentedEE10HandlerTest.java -@@ -3,6 +3,7 @@ package io.dropwizard.metrics.jetty12.ee10; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatCode; - -@@ -14,7 +15,6 @@ import jakarta.servlet.WriteListener; - import jakarta.servlet.http.HttpServletRequest; - import jakarta.servlet.http.HttpServletResponse; - import java.io.IOException; --import java.nio.charset.StandardCharsets; - import java.util.concurrent.TimeUnit; - import org.eclipse.jetty.client.ContentResponse; - import org.eclipse.jetty.client.HttpClient; -@@ -32,7 +32,7 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Disabled; - import org.junit.jupiter.api.Test; - --public class InstrumentedEE10HandlerTest { -+final class InstrumentedEE10HandlerTest { - private final HttpClient client = new HttpClient(); - private final MetricRegistry registry = new MetricRegistry(); - private final Server server = new Server(); -@@ -40,7 +40,7 @@ public class InstrumentedEE10HandlerTest { - private final InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); - - @BeforeEach -- public void setUp() throws Exception { -+ void setUp() throws Exception { - handler.setName("handler"); - - TestHandler testHandler = new TestHandler(); -@@ -62,18 +62,18 @@ public class InstrumentedEE10HandlerTest { - } - - @AfterEach -- public void tearDown() throws Exception { -+ void tearDown() throws Exception { - server.stop(); - client.stop(); - } - - @Test -- public void hasAName() throws Exception { -+ void hasAName() throws Exception { - assertThat(handler.getName()).isEqualTo("handler"); - } - - @Test -- public void createsAndRemovesMetricsForTheHandler() throws Exception { -+ void createsAndRemovesMetricsForTheHandler() throws Exception { - final ContentResponse response = client.GET(uri("/hello")); - - assertThat(response.getStatus()).isEqualTo(404); -@@ -115,9 +115,9 @@ public class InstrumentedEE10HandlerTest { - assertThat(registry.getNames()).isEmpty(); - } - -- @Test - @Disabled("flaky on virtual machines") -- public void responseTimesAreRecordedForBlockingResponses() throws Exception { -+ @Test -+ void responseTimesAreRecordedForBlockingResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/blocking")); - -@@ -127,7 +127,7 @@ public class InstrumentedEE10HandlerTest { - } - - @Test -- public void doStopDoesNotThrowNPE() throws Exception { -+ void doStopDoesNotThrowNPE() throws Exception { - InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, null, ALL); - handler.setHandler(new TestHandler()); - -@@ -135,7 +135,7 @@ public class InstrumentedEE10HandlerTest { - } - - @Test -- public void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { -+ void gaugesAreRegisteredWithResponseMeteredLevelCoarse() throws Exception { - InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "coarse", COARSE); - handler.setHandler(new TestHandler()); - handler.setName("handler"); -@@ -145,7 +145,7 @@ public class InstrumentedEE10HandlerTest { - } - - @Test -- public void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { -+ void gaugesAreNotRegisteredWithResponseMeteredLevelDetailed() throws Exception { - InstrumentedEE10Handler handler = new InstrumentedEE10Handler(registry, "detailed", DETAILED); - handler.setHandler(new TestHandler()); - handler.setName("handler"); -@@ -154,9 +154,9 @@ public class InstrumentedEE10HandlerTest { - .doesNotContainKey(MetricName.build("detailed", "handler", "percent-4xx-1m")); - } - -- @Test - @Disabled("flaky on virtual machines") -- public void responseTimesAreRecordedForAsyncResponses() throws Exception { -+ @Test -+ void responseTimesAreRecordedForAsyncResponses() throws Exception { - - final ContentResponse response = client.GET(uri("/async")); - -@@ -167,9 +167,9 @@ public class InstrumentedEE10HandlerTest { - - private void assertResponseTimesValid() { - assertThat(registry.getMeters().get(metricName().resolve("2xx-responses")).getCount()) -- .isGreaterThan(0L); -+ .isPositive(); - assertThat(registry.getMeters().get(metricName().resolve(".200-responses")).getCount()) -- .isGreaterThan(0L); -+ .isPositive(); - - assertThat( - registry -@@ -177,12 +177,12 @@ public class InstrumentedEE10HandlerTest { - .get(metricName().resolve(".get-requests")) - .getSnapshot() - .getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - - assertThat( - registry.getTimers().get(metricName().resolve(".requests")).getSnapshot().getMedian()) -- .isGreaterThan(0.0) -+ .isPositive() - .isLessThan(TimeUnit.SECONDS.toNanos(1)); - } - -@@ -250,7 +250,7 @@ public class InstrumentedEE10HandlerTest { - @Override - public void onWritePossible() throws IOException { - servletOutputStream.write( -- "some content from the async\n".getBytes(StandardCharsets.UTF_8)); -+ "some content from the async\n".getBytes(UTF_8)); - context.complete(); - servletContextRequest.getServletChannel().handle(); - } -diff --git a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java -index e8e513f..8a7229d 100644 ---- a/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java -+++ b/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/AbstractInstrumentedHandler.java -@@ -4,7 +4,10 @@ import static io.dropwizard.metrics5.MetricRegistry.name; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.ALL; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.COARSE; - import static io.dropwizard.metrics5.annotation.ResponseMeteredLevel.DETAILED; -+import static java.util.Collections.unmodifiableList; - -+import com.google.common.collect.ImmutableList; -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricName; -@@ -13,7 +16,6 @@ import io.dropwizard.metrics5.RatioGauge; - import io.dropwizard.metrics5.Timer; - import io.dropwizard.metrics5.annotation.ResponseMeteredLevel; - import java.util.Arrays; --import java.util.Collections; - import java.util.EnumSet; - import java.util.List; - import java.util.Map; -@@ -164,7 +166,7 @@ public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { - this.responseCodeMeters = - DETAILED_METER_LEVELS.contains(responseMeteredLevel) - ? new ConcurrentHashMap<>() -- : Collections.emptyMap(); -+ : ImmutableMap.of(); - - this.getRequests = metricRegistry.timer(prefix.resolve(NAME_GET_REQUESTS)); - this.postRequests = metricRegistry.timer(prefix.resolve(NAME_POST_REQUESTS)); -@@ -179,7 +181,7 @@ public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { - - if (COARSE_METER_LEVELS.contains(responseMeteredLevel)) { - this.responses = -- Collections.unmodifiableList( -+ unmodifiableList( - Arrays.asList( - metricRegistry.meter(prefix.resolve(NAME_1XX_RESPONSES)), // 1xx - metricRegistry.meter(prefix.resolve(NAME_2XX_RESPONSES)), // 2xx -@@ -244,7 +246,7 @@ public abstract class AbstractInstrumentedHandler extends Handler.Wrapper { - } - }); - } else { -- this.responses = Collections.emptyList(); -+ this.responses = ImmutableList.of(); - } - } - -diff --git a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java -index 1ec7ffc..cf26f20 100644 ---- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java -+++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactoryTest.java -@@ -19,7 +19,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --public class InstrumentedConnectionFactoryTest { -+final class InstrumentedConnectionFactoryTest { - private final MetricRegistry registry = new MetricRegistry(); - private final Server server = new Server(); - private final ServerConnector connector = -@@ -32,7 +32,7 @@ public class InstrumentedConnectionFactoryTest { - private final HttpClient client = new HttpClient(); - - @BeforeEach -- public void setUp() throws Exception { -+ void setUp() throws Exception { - server.setHandler( - new Handler.Abstract() { - @Override -@@ -50,13 +50,13 @@ public class InstrumentedConnectionFactoryTest { - } - - @AfterEach -- public void tearDown() throws Exception { -+ void tearDown() throws Exception { - server.stop(); - client.stop(); - } - - @Test -- public void instrumentsConnectionTimes() throws Exception { -+ void instrumentsConnectionTimes() throws Exception { - final ContentResponse response = - client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); - assertThat(response.getStatus()).isEqualTo(200); -@@ -70,7 +70,7 @@ public class InstrumentedConnectionFactoryTest { - } - - @Test -- public void instrumentsActiveConnections() throws Exception { -+ void instrumentsActiveConnections() throws Exception { - final Counter counter = registry.counter("http.active-connections"); - - final ContentResponse response = -diff --git a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java -index a69021b..9fa9616 100644 ---- a/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java -+++ b/metrics-jetty12/src/test/java/io/dropwizard/metrics/jetty12/InstrumentedQueuedThreadPoolTest.java -@@ -7,20 +7,20 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --public class InstrumentedQueuedThreadPoolTest { -+final class InstrumentedQueuedThreadPoolTest { - private static final String PREFIX = "prefix"; - - private MetricRegistry metricRegistry; - private InstrumentedQueuedThreadPool iqtp; - - @BeforeEach -- public void setUp() { -+ void setUp() { - metricRegistry = new MetricRegistry(); - iqtp = new InstrumentedQueuedThreadPool(metricRegistry); - } - - @Test -- public void customMetricsPrefix() throws Exception { -+ void customMetricsPrefix() throws Exception { - iqtp.setPrefix(PREFIX); - iqtp.start(); - -@@ -35,7 +35,7 @@ public class InstrumentedQueuedThreadPoolTest { - } - - @Test -- public void metricsPrefixBackwardCompatible() throws Exception { -+ void metricsPrefixBackwardCompatible() throws Exception { - iqtp.start(); - assertThat(metricRegistry.getNames()) - .overridingErrorMessage("The default metrics prefix was changed") -diff --git a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java -index 4b72b5d..642fd3a 100644 ---- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java -+++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java -@@ -10,7 +10,7 @@ import org.slf4j.LoggerFactory; - public class DefaultObjectNameFactory implements ObjectNameFactory { - - private static final char[] QUOTABLE_CHARS = new char[] {',', '=', ':', '"'}; -- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); -+ private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectNameFactory.class); - - @Override - public ObjectName createName(String type, String domain, MetricName name) { -@@ -38,14 +38,13 @@ public class DefaultObjectNameFactory implements ObjectNameFactory { - || shouldQuote(objectName.getKeyProperty("type"))) { - properties.put("type", ObjectName.quote(type)); - } -- objectName = new ObjectName(domain, properties); -+ return new ObjectName(domain, properties); - -- return objectName; - } catch (MalformedObjectNameException e) { - try { - return new ObjectName(domain, "name", ObjectName.quote(name.getKey())); - } catch (MalformedObjectNameException e1) { -- LOGGER.warn("Unable to register {} {}", type, name, e1); -+ LOG.warn("Unable to register {} {}", type, name, e1); - throw new RuntimeException(e1); - } - } -diff --git a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java -index 085b4ef..d7c7b50 100644 ---- a/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java -+++ b/metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java -@@ -1,5 +1,9 @@ - package io.dropwizard.metrics5.jmx; - -+import static com.google.common.base.Preconditions.checkArgument; -+import static java.util.Collections.unmodifiableMap; -+ -+import com.google.common.collect.ImmutableMap; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Histogram; -@@ -13,7 +17,6 @@ import io.dropwizard.metrics5.Reporter; - import io.dropwizard.metrics5.Timer; - import java.io.Closeable; - import java.lang.management.ManagementFactory; --import java.util.Collections; - import java.util.Locale; - import java.util.Map; - import java.util.concurrent.ConcurrentHashMap; -@@ -61,8 +64,8 @@ public class JmxReporter implements Reporter, Closeable { - this.durationUnit = TimeUnit.MILLISECONDS; - this.domain = "metrics"; - this.objectNameFactory = new DefaultObjectNameFactory(); -- this.specificDurationUnits = Collections.emptyMap(); -- this.specificRateUnits = Collections.emptyMap(); -+ this.specificDurationUnits = ImmutableMap.of(); -+ this.specificRateUnits = ImmutableMap.of(); - } - - /** -@@ -88,9 +91,7 @@ public class JmxReporter implements Reporter, Closeable { - } - - public Builder createsObjectNamesWith(ObjectNameFactory onFactory) { -- if (onFactory == null) { -- throw new IllegalArgumentException("null objectNameFactory"); -- } -+ checkArgument(onFactory != null, "null objectNameFactory"); - this.objectNameFactory = onFactory; - return this; - } -@@ -129,7 +130,7 @@ public class JmxReporter implements Reporter, Closeable { - * @return {@code this} - */ - public Builder specificDurationUnits(Map specificDurationUnits) { -- this.specificDurationUnits = Collections.unmodifiableMap(specificDurationUnits); -+ this.specificDurationUnits = unmodifiableMap(specificDurationUnits); - return this; - } - -@@ -140,7 +141,7 @@ public class JmxReporter implements Reporter, Closeable { - * @return {@code this} - */ - public Builder specificRateUnits(Map specificRateUnits) { -- this.specificRateUnits = Collections.unmodifiableMap(specificRateUnits); -+ this.specificRateUnits = unmodifiableMap(specificRateUnits); - return this; - } - -@@ -159,7 +160,7 @@ public class JmxReporter implements Reporter, Closeable { - } - } - -- private static final Logger LOGGER = LoggerFactory.getLogger(JmxReporter.class); -+ private static final Logger LOG = LoggerFactory.getLogger(JmxReporter.class); - - @SuppressWarnings("UnusedDeclaration") - public interface MetricMBean { -@@ -570,9 +571,9 @@ public class JmxReporter implements Reporter, Closeable { - registerMBean(new JmxGauge(gauge, objectName), objectName); - } - } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register gauge", e); -+ LOG.debug("Unable to register gauge", e); - } catch (JMException e) { -- LOGGER.warn("Unable to register gauge", e); -+ LOG.warn("Unable to register gauge", e); - } - } - -@@ -582,9 +583,9 @@ public class JmxReporter implements Reporter, Closeable { - final ObjectName objectName = createName("gauges", name); - unregisterMBean(objectName); - } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister gauge", e); -+ LOG.debug("Unable to unregister gauge", e); - } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister gauge", e); -+ LOG.warn("Unable to unregister gauge", e); - } - } - -@@ -596,9 +597,9 @@ public class JmxReporter implements Reporter, Closeable { - registerMBean(new JmxCounter(counter, objectName), objectName); - } - } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register counter", e); -+ LOG.debug("Unable to register counter", e); - } catch (JMException e) { -- LOGGER.warn("Unable to register counter", e); -+ LOG.warn("Unable to register counter", e); - } - } - -@@ -608,9 +609,9 @@ public class JmxReporter implements Reporter, Closeable { - final ObjectName objectName = createName("counters", name); - unregisterMBean(objectName); - } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister counter", e); -+ LOG.debug("Unable to unregister counter", e); - } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister counter", e); -+ LOG.warn("Unable to unregister counter", e); - } - } - -@@ -622,9 +623,9 @@ public class JmxReporter implements Reporter, Closeable { - registerMBean(new JmxHistogram(histogram, objectName), objectName); - } - } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register histogram", e); -+ LOG.debug("Unable to register histogram", e); - } catch (JMException e) { -- LOGGER.warn("Unable to register histogram", e); -+ LOG.warn("Unable to register histogram", e); - } - } - -@@ -634,9 +635,9 @@ public class JmxReporter implements Reporter, Closeable { - final ObjectName objectName = createName("histograms", name); - unregisterMBean(objectName); - } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister histogram", e); -+ LOG.debug("Unable to unregister histogram", e); - } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister histogram", e); -+ LOG.warn("Unable to unregister histogram", e); - } - } - -@@ -649,9 +650,9 @@ public class JmxReporter implements Reporter, Closeable { - new JmxMeter(meter, objectName, timeUnits.rateFor(name.getKey())), objectName); - } - } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register meter", e); -+ LOG.debug("Unable to register meter", e); - } catch (JMException e) { -- LOGGER.warn("Unable to register meter", e); -+ LOG.warn("Unable to register meter", e); - } - } - -@@ -661,9 +662,9 @@ public class JmxReporter implements Reporter, Closeable { - final ObjectName objectName = createName("meters", name); - unregisterMBean(objectName); - } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister meter", e); -+ LOG.debug("Unable to unregister meter", e); - } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister meter", e); -+ LOG.warn("Unable to unregister meter", e); - } - } - -@@ -681,9 +682,9 @@ public class JmxReporter implements Reporter, Closeable { - objectName); - } - } catch (InstanceAlreadyExistsException e) { -- LOGGER.debug("Unable to register timer", e); -+ LOG.debug("Unable to register timer", e); - } catch (JMException e) { -- LOGGER.warn("Unable to register timer", e); -+ LOG.warn("Unable to register timer", e); - } - } - -@@ -693,9 +694,9 @@ public class JmxReporter implements Reporter, Closeable { - final ObjectName objectName = createName("timers", name); - unregisterMBean(objectName); - } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister timer", e); -+ LOG.debug("Unable to unregister timer", e); - } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister timer", e); -+ LOG.warn("Unable to unregister timer", e); - } - } - -@@ -708,9 +709,9 @@ public class JmxReporter implements Reporter, Closeable { - try { - unregisterMBean(name); - } catch (InstanceNotFoundException e) { -- LOGGER.debug("Unable to unregister metric", e); -+ LOG.debug("Unable to unregister metric", e); - } catch (MBeanRegistrationException e) { -- LOGGER.warn("Unable to unregister metric", e); -+ LOG.warn("Unable to unregister metric", e); - } - } - registered.clear(); -diff --git a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java -index 5fa8ffd..407c905 100644 ---- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java -+++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java -@@ -7,7 +7,7 @@ import io.dropwizard.metrics5.MetricName; - import javax.management.ObjectName; - import org.junit.jupiter.api.Test; - --class DefaultObjectNameFactoryTest { -+final class DefaultObjectNameFactoryTest { - - @Test - void createsObjectNameWithDomainInInput() { -diff --git a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java -index cd5cc55..b32b472 100644 ---- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java -+++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5.jmx; - -+import static java.util.UUID.randomUUID; - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.entry; - import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -@@ -21,7 +22,6 @@ import io.dropwizard.metrics5.Timer; - import java.lang.management.ManagementFactory; - import java.util.SortedMap; - import java.util.TreeMap; --import java.util.UUID; - import java.util.concurrent.TimeUnit; - import javax.management.Attribute; - import javax.management.AttributeList; -@@ -35,9 +35,9 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("rawtypes") --class JmxReporterTest { -+final class JmxReporterTest { - private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); -- private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); -+ private final String name = randomUUID().toString().replaceAll("[{\\-}]", ""); - private final MetricRegistry registry = new MetricRegistry(); - - private final JmxReporter reporter = -@@ -49,12 +49,12 @@ class JmxReporterTest { - .filter(MetricFilter.ALL) - .build(); - -- private final Gauge gauge = mock(Gauge.class); -- private final Counter counter = mock(Counter.class); -- private final Histogram histogram = mock(Histogram.class); -- private final Meter meter = mock(Meter.class); -- private final Timer timer = mock(Timer.class); -- private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); -+ private final Gauge gauge = mock(); -+ private final Counter counter = mock(); -+ private final Histogram histogram = mock(); -+ private final Meter meter = mock(); -+ private final Timer timer = mock(); -+ private final ObjectNameFactory mockObjectNameFactory = mock(); - private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); - - @BeforeEach -@@ -66,7 +66,7 @@ class JmxReporterTest { - when(histogram.getCount()).thenReturn(1L); - when(histogram.getSum()).thenReturn(12L); - -- final Snapshot hSnapshot = mock(Snapshot.class); -+ final Snapshot hSnapshot = mock(); - when(hSnapshot.getMax()).thenReturn(2L); - when(hSnapshot.getMean()).thenReturn(3.0); - when(hSnapshot.getMin()).thenReturn(4L); -@@ -95,7 +95,7 @@ class JmxReporterTest { - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot tSnapshot = mock(Snapshot.class); -+ final Snapshot tSnapshot = mock(); - when(tSnapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(tSnapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(tSnapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -285,7 +285,7 @@ class JmxReporterTest { - - @Test - void objectNameModifyingMBeanServer() throws Exception { -- MBeanServer mockedMBeanServer = mock(MBeanServer.class); -+ MBeanServer mockedMBeanServer = mock(); - - // overwrite the objectName - when(mockedMBeanServer.registerMBean(any(Object.class), any(ObjectName.class))) -@@ -310,7 +310,7 @@ class JmxReporterTest { - } - - @Test -- void testJmxMetricNameWithAsterisk() { -+ void jmxMetricNameWithAsterisk() { - MetricRegistry metricRegistry = new MetricRegistry(); - JmxReporter.forRegistry(metricRegistry).build().start(); - metricRegistry.counter("test*"); -diff --git a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java -index 69ee5d1..0c6cfcf 100644 ---- a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java -+++ b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java -@@ -1,14 +1,15 @@ - package io.dropwizard.metrics5.json; - -+ - import com.fasterxml.jackson.core.JsonGenerator; - import com.fasterxml.jackson.core.Version; - import com.fasterxml.jackson.databind.Module; - import com.fasterxml.jackson.databind.SerializerProvider; - import com.fasterxml.jackson.databind.module.SimpleSerializers; - import com.fasterxml.jackson.databind.ser.std.StdSerializer; -+import com.google.common.collect.ImmutableList; - import io.dropwizard.metrics5.health.HealthCheck; - import java.io.IOException; --import java.util.Collections; - import java.util.Map; - - public class HealthCheckModule extends Module { -@@ -80,6 +81,6 @@ public class HealthCheckModule extends Module { - @Override - public void setupModule(SetupContext context) { - context.addSerializers( -- new SimpleSerializers(Collections.singletonList(new HealthCheckResultSerializer()))); -+ new SimpleSerializers(ImmutableList.of(new HealthCheckResultSerializer()))); - } - } -diff --git a/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java b/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java -index 0f8c76b..fad833a 100644 ---- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java -+++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java -@@ -10,15 +10,14 @@ import java.util.LinkedHashMap; - import java.util.Map; - import org.junit.jupiter.api.Test; - --class HealthCheckModuleTest { -+final class HealthCheckModuleTest { - private final ObjectMapper mapper = new ObjectMapper().registerModule(new HealthCheckModule()); - - @Test - void serializesAHealthyResult() throws Exception { - HealthCheck.Result result = HealthCheck.Result.healthy(); - assertThat(mapper.writeValueAsString(result)) -- .isEqualTo( -- "{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); -+ .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"%s\"}", result.getTimestamp()); - } - - @Test -@@ -26,14 +25,8 @@ class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":true," -- + "\"message\":\"yay for me\"," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":true,\"message\":\"yay for me\",\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -41,14 +34,8 @@ class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":false," -- + "\"message\":\"boo\"," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":false,\"message\":\"boo\",\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -60,19 +47,8 @@ class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.unhealthy(e); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":false," -- + "\"message\":\"oh no\"," -- + "\"error\":{" -- + "\"type\":\"java.lang.RuntimeException\"," -- + "\"message\":\"oh no\"," -- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" -- + "}," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":false,\"message\":\"oh no\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]},\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -88,24 +64,8 @@ class HealthCheckModuleTest { - HealthCheck.Result result = HealthCheck.Result.unhealthy(b); - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":false," -- + "\"message\":\"oh well\"," -- + "\"error\":{" -- + "\"type\":\"java.lang.RuntimeException\"," -- + "\"message\":\"oh well\"," -- + "\"stack\":[\"Blah.blee(Blah.java:150)\"]," -- + "\"cause\":{" -- + "\"type\":\"java.lang.RuntimeException\"," -- + "\"message\":\"oh no\"," -- + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" -- + "}" -- + "}," -- + "\"duration\":0," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":false,\"message\":\"oh well\",\"error\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh well\",\"stack\":[\"Blah.blee(Blah.java:150)\"],\"cause\":{\"type\":\"java.lang.RuntimeException\",\"message\":\"oh no\",\"stack\":[\"Blah.bloo(Blah.java:100)\"]}},\"duration\":0,\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - - @Test -@@ -129,23 +89,7 @@ class HealthCheckModuleTest { - - assertThat(mapper.writeValueAsString(result)) - .isEqualTo( -- "{" -- + "\"healthy\":true," -- + "\"duration\":0," -- + "\"boolean\":true," -- + "\"integer\":1," -- + "\"long\":2," -- + "\"float\":3.546," -- + "\"double\":4.567," -- + "\"BigInteger\":12345," -- + "\"BigDecimal\":12345.56789," -- + "\"String\":\"string\"," -- + "\"complex\":{" -- + "\"field\":\"value\"" -- + "}," -- + "\"timestamp\":\"" -- + result.getTimestamp() -- + "\"" -- + "}"); -+ "{\"healthy\":true,\"duration\":0,\"boolean\":true,\"integer\":1,\"long\":2,\"float\":3.546,\"double\":4.567,\"BigInteger\":12345,\"BigDecimal\":12345.56789,\"String\":\"string\",\"complex\":{\"field\":\"value\"},\"timestamp\":\"%s\"}", -+ result.getTimestamp()); - } - } -diff --git a/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java b/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java -index 8fe2c7d..401a8f3 100644 ---- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java -+++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java -@@ -16,7 +16,7 @@ import io.dropwizard.metrics5.Timer; - import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; - --class MetricsModuleTest { -+final class MetricsModuleTest { - private final ObjectMapper mapper = - new ObjectMapper() - .registerModule( -@@ -42,7 +42,7 @@ class MetricsModuleTest { - - @Test - void serializesCounters() throws Exception { -- final Counter counter = mock(Counter.class); -+ final Counter counter = mock(); - when(counter.getCount()).thenReturn(100L); - - assertThat(mapper.writeValueAsString(counter)).isEqualTo("{\"count\":100}"); -@@ -50,10 +50,10 @@ class MetricsModuleTest { - - @Test - void serializesHistograms() throws Exception { -- final Histogram histogram = mock(Histogram.class); -+ final Histogram histogram = mock(); - when(histogram.getCount()).thenReturn(1L); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(2L); - when(snapshot.getMean()).thenReturn(3.0); - when(snapshot.getMin()).thenReturn(4L); -@@ -107,7 +107,7 @@ class MetricsModuleTest { - - @Test - void serializesMeters() throws Exception { -- final Meter meter = mock(Meter.class); -+ final Meter meter = mock(); - when(meter.getCount()).thenReturn(1L); - when(meter.getMeanRate()).thenReturn(2.0); - when(meter.getOneMinuteRate()).thenReturn(5.0); -@@ -127,14 +127,14 @@ class MetricsModuleTest { - - @Test - void serializesTimers() throws Exception { -- final Timer timer = mock(Timer.class); -+ final Timer timer = mock(); - when(timer.getCount()).thenReturn(1L); - when(timer.getMeanRate()).thenReturn(2.0); - when(timer.getOneMinuteRate()).thenReturn(3.0); - when(timer.getFiveMinuteRate()).thenReturn(4.0); - when(timer.getFifteenMinuteRate()).thenReturn(5.0); - -- final Snapshot snapshot = mock(Snapshot.class); -+ final Snapshot snapshot = mock(); - when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); - when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); - when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java -index d90d7d8..2bce9f4 100644 ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java -@@ -1,10 +1,11 @@ - package io.dropwizard.metrics5.jvm; - -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricRegistry; - import io.dropwizard.metrics5.MetricSet; --import java.util.Collections; - import java.util.HashMap; - import java.util.Map; - import javax.management.JMException; -@@ -19,7 +20,7 @@ import org.slf4j.LoggerFactory; - *

    These JMX objects are only available on Java 7 and above. - */ - public class BufferPoolMetricSet implements MetricSet { -- private static final Logger LOGGER = LoggerFactory.getLogger(BufferPoolMetricSet.class); -+ private static final Logger LOG = LoggerFactory.getLogger(BufferPoolMetricSet.class); - private static final String[] ATTRIBUTES = {"Count", "MemoryUsed", "TotalCapacity"}; - private static final String[] NAMES = {"count", "used", "capacity"}; - private static final String[] POOLS = {"direct", "mapped"}; -@@ -43,10 +44,10 @@ public class BufferPoolMetricSet implements MetricSet { - gauges.put( - MetricRegistry.name(pool, name), new JmxAttributeGauge(mBeanServer, on, attribute)); - } catch (JMException ignored) { -- LOGGER.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); -+ LOG.debug("Unable to load buffer pool MBeans, possibly running on Java 6"); - } - } - } -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } -diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java -index 35a031e..63792f9 100644 ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSet.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.jvm; - -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; -@@ -9,7 +11,6 @@ import java.lang.management.GarbageCollectorMXBean; - import java.lang.management.ManagementFactory; - import java.util.ArrayList; - import java.util.Collection; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -43,6 +44,6 @@ public class GarbageCollectorMetricSet implements MetricSet { - gauges.put(MetricRegistry.name(name, "count"), (Gauge) gc::getCollectionCount); - gauges.put(MetricRegistry.name(name, "time"), (Gauge) gc::getCollectionTime); - } -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } -diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java -index 3a19d83..67a16e9 100644 ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSet.java -@@ -1,12 +1,13 @@ - package io.dropwizard.metrics5.jvm; - -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; - import io.dropwizard.metrics5.MetricSet; - import java.lang.management.ManagementFactory; - import java.lang.management.RuntimeMXBean; --import java.util.Collections; - import java.util.HashMap; - import java.util.Locale; - import java.util.Map; -@@ -47,6 +48,6 @@ public class JvmAttributeGaugeSet implements MetricSet { - runtime.getSpecVersion())); - gauges.put(MetricName.build("uptime"), (Gauge) runtime::getUptime); - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } -diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java -index 60a2772..0c7ce49 100644 ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSet.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.jvm; - -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; -@@ -12,7 +14,6 @@ import java.lang.management.MemoryPoolMXBean; - import java.lang.management.MemoryUsage; - import java.util.ArrayList; - import java.util.Collection; --import java.util.Collections; - import java.util.HashMap; - import java.util.List; - import java.util.Map; -@@ -139,6 +140,6 @@ public class MemoryUsageGaugeSet implements MetricSet { - MetricRegistry.name(poolName, "init"), (Gauge) () -> pool.getUsage().getInit()); - } - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - } -diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java -index 40dc851..c973272 100644 ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetector.java -@@ -1,9 +1,11 @@ - package io.dropwizard.metrics5.jvm; - -+import static java.util.Collections.unmodifiableSet; -+ -+import com.google.common.collect.ImmutableSet; - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; --import java.util.Collections; - import java.util.HashSet; - import java.util.Set; - -@@ -40,19 +42,16 @@ public class ThreadDeadlockDetector { - for (ThreadInfo info : threads.getThreadInfo(ids, MAX_STACK_TRACE_DEPTH)) { - final StringBuilder stackTrace = new StringBuilder(); - for (StackTraceElement element : info.getStackTrace()) { -- stackTrace.append("\t at ").append(element.toString()).append(String.format("%n")); -+ stackTrace.append("\t at ").append(element).append(String.format("%n")); - } - - deadlocks.add( - String.format( - "%s locked on %s (owned by %s):%n%s", -- info.getThreadName(), -- info.getLockName(), -- info.getLockOwnerName(), -- stackTrace.toString())); -+ info.getThreadName(), info.getLockName(), info.getLockOwnerName(), stackTrace)); - } -- return Collections.unmodifiableSet(deadlocks); -+ return unmodifiableSet(deadlocks); - } -- return Collections.emptySet(); -+ return ImmutableSet.of(); - } - } -diff --git a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java -index 2d12960..1db9950 100644 ---- a/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java -+++ b/metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSet.java -@@ -1,5 +1,7 @@ - package io.dropwizard.metrics5.jvm; - -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.Metric; - import io.dropwizard.metrics5.MetricName; -@@ -8,7 +10,6 @@ import io.dropwizard.metrics5.MetricSet; - import java.lang.management.ManagementFactory; - import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; --import java.util.Collections; - import java.util.HashMap; - import java.util.Map; - import java.util.Set; -@@ -59,7 +60,7 @@ public class ThreadStatesGaugeSet implements MetricSet { - gauges.put( - MetricName.build("deadlocks"), (Gauge>) deadlockDetector::getDeadlockedThreads); - -- return Collections.unmodifiableMap(gauges); -+ return unmodifiableMap(gauges); - } - - private int getThreadCount(Thread.State state) { -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java -index f622832..c497fc3 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java -@@ -13,7 +13,7 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("rawtypes") --class BufferPoolMetricSetTest { -+final class BufferPoolMetricSetTest { - - private static final MetricName DIRECT = MetricName.build("direct"); - private static final MetricName MAPPED = MetricName.build("mapped"); -@@ -24,7 +24,7 @@ class BufferPoolMetricSetTest { - private static final MetricName MAPPED_CAPACITY = MAPPED.resolve("capacity"); - private static final MetricName MAPPED_USED = MAPPED.resolve("used"); - -- private final MBeanServer mBeanServer = mock(MBeanServer.class); -+ private final MBeanServer mBeanServer = mock(); - private final BufferPoolMetricSet buffers = new BufferPoolMetricSet(mBeanServer); - - private ObjectName mapped; -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java -index acefde0..24412e2 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java -@@ -11,9 +11,9 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("rawtypes") --class ClassLoadingGaugeSetTest { -+final class ClassLoadingGaugeSetTest { - -- private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); -+ private final ClassLoadingMXBean cl = mock(); - private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); - - @BeforeEach -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java -index db5d8f8..9b633ad 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java -@@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.offset; - import java.lang.management.ManagementFactory; - import org.junit.jupiter.api.Test; - --class CpuTimeClockTest { -+final class CpuTimeClockTest { - - @Test - void cpuTimeClock() { -@@ -14,10 +14,10 @@ class CpuTimeClockTest { - - final long clockTime = clock.getTime(); - final long systemTime = System.currentTimeMillis(); -- assertThat((double) clockTime).isEqualTo(systemTime, offset(200.0)); -+ assertThat((double) clockTime).isCloseTo(systemTime, offset(200.0)); - - final long clockTick = clock.getTick(); - final long systemTick = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime(); -- assertThat((double) clockTick).isEqualTo(systemTick, offset(1000000.0)); -+ assertThat((double) clockTick).isCloseTo(systemTick, offset(1000000.0)); - } - } -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java -index 5e9db15..019d29c 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5.jvm; - -+import static org.assertj.core.api.Assertions.assertThat; - import static org.junit.jupiter.api.Assumptions.assumeTrue; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; -@@ -12,8 +13,8 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("UnusedDeclaration") --class FileDescriptorRatioGaugeTest { -- private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); -+final class FileDescriptorRatioGaugeTest { -+ private final UnixOperatingSystemMXBean os = mock(); - - private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); - -@@ -25,7 +26,7 @@ class FileDescriptorRatioGaugeTest { - - @Test - void calculatesTheRatioOfUsedToTotalFileDescriptors() { -- Assertions.assertThat(gauge.getValue()).isEqualTo(0.1); -+ assertThat(gauge.getValue()).isEqualTo(0.1); - } - - @Test -@@ -34,14 +35,12 @@ class FileDescriptorRatioGaugeTest { - assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); - - Assertions.assertThat(new FileDescriptorRatioGauge().getValue()) -- .isGreaterThanOrEqualTo(0.0) -+ .isNotNegative() - .isLessThanOrEqualTo(1.0); - } - - @Test - void returnsNaNWhenTheInformationIsUnavailable() { -- Assertions.assertThat( -- new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()) -- .isNaN(); -+ assertThat(new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()).isNaN(); - } - } -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java -index 5e7f1bd..c32dccb 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java -@@ -4,18 +4,18 @@ import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.when; - -+import com.google.common.collect.ImmutableList; - import io.dropwizard.metrics5.Gauge; - import io.dropwizard.metrics5.MetricName; - import java.lang.management.GarbageCollectorMXBean; --import java.util.Collections; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("unchecked") --class GarbageCollectorMetricSetTest { -- private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); -+final class GarbageCollectorMetricSetTest { -+ private final GarbageCollectorMXBean gc = mock(); - private final GarbageCollectorMetricSet metrics = -- new GarbageCollectorMetricSet(Collections.singletonList(gc)); -+ new GarbageCollectorMetricSet(ImmutableList.of(gc)); - - private static final MetricName PS_OLDGEN_TIME = MetricName.build("PS-OldGen.time"); - private static final MetricName PS_OLDGEN_COUNT = MetricName.build("PS-OldGen.count"); -@@ -46,6 +46,6 @@ class GarbageCollectorMetricSetTest { - - @Test - void autoDiscoversGCs() { -- assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()).isNotEmpty(); -+ assertThat(new GarbageCollectorMetricSet().getMetrics()).isNotEmpty(); - } - } -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java -index 9e7e876..dec09ab 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java -@@ -13,7 +13,7 @@ import org.junit.jupiter.api.AfterAll; - import org.junit.jupiter.api.BeforeAll; - import org.junit.jupiter.api.Test; - --class JmxAttributeGaugeTest { -+final class JmxAttributeGaugeTest { - - private static MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); - -@@ -53,7 +53,7 @@ class JmxAttributeGaugeTest { - JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); - - assertThat(gauge.getValue()).isInstanceOf(Integer.class); -- assertThat((Integer) gauge.getValue()).isGreaterThan(0); -+ assertThat((Integer) gauge.getValue()).isPositive(); - } - - @Test -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java -index 3a50f92..d56cf8b 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java -@@ -11,8 +11,8 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("unchecked") --class JvmAttributeGaugeSetTest { -- private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); -+final class JvmAttributeGaugeSetTest { -+ private final RuntimeMXBean runtime = mock(); - private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); - - @BeforeEach -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java -index 9ebceed..96c5879 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java -@@ -14,15 +14,15 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("rawtypes") --class MemoryUsageGaugeSetTest { -- private final MemoryUsage heap = mock(MemoryUsage.class); -- private final MemoryUsage nonHeap = mock(MemoryUsage.class); -- private final MemoryUsage pool = mock(MemoryUsage.class); -- private final MemoryUsage weirdPool = mock(MemoryUsage.class); -- private final MemoryUsage weirdCollection = mock(MemoryUsage.class); -- private final MemoryMXBean mxBean = mock(MemoryMXBean.class); -- private final MemoryPoolMXBean memoryPool = mock(MemoryPoolMXBean.class); -- private final MemoryPoolMXBean weirdMemoryPool = mock(MemoryPoolMXBean.class); -+final class MemoryUsageGaugeSetTest { -+ private final MemoryUsage heap = mock(); -+ private final MemoryUsage nonHeap = mock(); -+ private final MemoryUsage pool = mock(); -+ private final MemoryUsage weirdPool = mock(); -+ private final MemoryUsage weirdCollection = mock(); -+ private final MemoryMXBean mxBean = mock(); -+ private final MemoryPoolMXBean memoryPool = mock(); -+ private final MemoryPoolMXBean weirdMemoryPool = mock(); - - private final MemoryUsageGaugeSet gauges = - new MemoryUsageGaugeSet(mxBean, Arrays.asList(memoryPool, weirdMemoryPool)); -@@ -159,7 +159,7 @@ class MemoryUsageGaugeSetTest { - } - - @Test -- public void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { -+ void hasAGaugeForTotalMaxWhenNonHeapMaxUndefined() { - when(nonHeap.getMax()).thenReturn(-1L); - - final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); -@@ -238,7 +238,7 @@ class MemoryUsageGaugeSetTest { - } - - @Test -- public void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { -+ void hasAGaugeForNonHeapUsageWhenNonHeapMaxUndefined() { - when(nonHeap.getMax()).thenReturn(-1L); - final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); - -@@ -296,6 +296,6 @@ class MemoryUsageGaugeSetTest { - - @Test - void autoDetectsMemoryUsageBeanAndMemoryPools() { -- assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()).isNotEmpty(); -+ assertThat(new MemoryUsageGaugeSet().getMetrics()).isNotEmpty(); - } - } -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java -index 98850d7..4367c03 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java -@@ -11,8 +11,8 @@ import java.lang.management.ThreadMXBean; - import java.util.Locale; - import org.junit.jupiter.api.Test; - --class ThreadDeadlockDetectorTest { -- private final ThreadMXBean threads = mock(ThreadMXBean.class); -+final class ThreadDeadlockDetectorTest { -+ private final ThreadMXBean threads = mock(); - private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); - - @Test -@@ -24,7 +24,7 @@ class ThreadDeadlockDetectorTest { - - @Test - void returnsASetOfThreadsIfAnyAreDeadlocked() { -- final ThreadInfo thread1 = mock(ThreadInfo.class); -+ final ThreadInfo thread1 = mock(); - when(thread1.getThreadName()).thenReturn("thread1"); - when(thread1.getLockName()).thenReturn("lock2"); - when(thread1.getLockOwnerName()).thenReturn("thread2"); -@@ -35,7 +35,7 @@ class ThreadDeadlockDetectorTest { - new StackTraceElement("Blah", "blee", "Blah.java", 100) - }); - -- final ThreadInfo thread2 = mock(ThreadInfo.class); -+ final ThreadInfo thread2 = mock(); - when(thread2.getThreadName()).thenReturn("thread2"); - when(thread2.getLockName()).thenReturn("lock1"); - when(thread2.getLockOwnerName()).thenReturn("thread1"); -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java -index c89c824..1eeac39 100755 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java -@@ -14,11 +14,11 @@ import org.junit.jupiter.api.Test; - - // TODO: 3/12/13 -- improve test coverage for ThreadDump - --class ThreadDumpTest { -- private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); -+final class ThreadDumpTest { -+ private final ThreadMXBean threadMXBean = mock(); - private final ThreadDump threadDump = new ThreadDump(threadMXBean); - -- private final ThreadInfo runnable = mock(ThreadInfo.class); -+ private final ThreadInfo runnable = mock(); - - @BeforeEach - void setUp() { -@@ -39,8 +39,8 @@ class ThreadDumpTest { - final ByteArrayOutputStream output = new ByteArrayOutputStream(); - threadDump.dump(output); - -- assertThat(output.toString()) -- .isEqualTo( -+ assertThat(output) -+ .hasToString( - String.format( - "\"runnable\" id=100 state=RUNNABLE%n" - + " at Blah.blee(Blah.java:100)%n" -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java -index d5896e7..8d20493 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java -@@ -10,22 +10,21 @@ import java.lang.management.ThreadInfo; - import java.lang.management.ThreadMXBean; - import java.util.HashSet; - import java.util.Set; --import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class ThreadStatesGaugeSetTest { -- private final ThreadMXBean threads = mock(ThreadMXBean.class); -- private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); -+final class ThreadStatesGaugeSetTest { -+ private final ThreadMXBean threads = mock(); -+ private final ThreadDeadlockDetector detector = mock(); - private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); - private final long[] ids = new long[] {1, 2, 3}; - -- private final ThreadInfo newThread = mock(ThreadInfo.class); -- private final ThreadInfo runnableThread = mock(ThreadInfo.class); -- private final ThreadInfo blockedThread = mock(ThreadInfo.class); -- private final ThreadInfo waitingThread = mock(ThreadInfo.class); -- private final ThreadInfo timedWaitingThread = mock(ThreadInfo.class); -- private final ThreadInfo terminatedThread = mock(ThreadInfo.class); -+ private final ThreadInfo newThread = mock(); -+ private final ThreadInfo runnableThread = mock(); -+ private final ThreadInfo blockedThread = mock(); -+ private final ThreadInfo waitingThread = mock(); -+ private final ThreadInfo timedWaitingThread = mock(); -+ private final ThreadInfo terminatedThread = mock(); - - private final Set deadlocks = new HashSet<>(); - -@@ -87,7 +86,7 @@ class ThreadStatesGaugeSetTest { - - @Test - void hasAGaugeForEachThreadState() { -- Assertions.assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1); -+ assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()).isEqualTo(1); - - assertThat(((Gauge) gauges.getMetrics().get(RUNNABLE_COUNT)).getValue()).isEqualTo(1); - -diff --git a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java -index b176fb3..3c16b02 100644 ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java -@@ -1,16 +1,16 @@ - package com.codahale.metrics; - -+import static java.util.Collections.unmodifiableSortedMap; - import static java.util.Collections.unmodifiableSortedSet; - import static java.util.Objects.requireNonNull; -+import static java.util.stream.Collectors.toCollection; - - import io.dropwizard.metrics5.MetricName; --import java.util.Collections; - import java.util.Map; - import java.util.SortedMap; - import java.util.SortedSet; - import java.util.TreeMap; - import java.util.TreeSet; --import java.util.stream.Collectors; - - @Deprecated - public class MetricRegistry implements MetricSet { -@@ -102,9 +102,7 @@ public class MetricRegistry implements MetricSet { - - public SortedSet getNames() { - return unmodifiableSortedSet( -- delegate.getNames().stream() -- .map(MetricName::getKey) -- .collect(Collectors.toCollection(TreeSet::new))); -+ delegate.getNames().stream().map(MetricName::getKey).collect(toCollection(TreeSet::new))); - } - - public SortedMap getGauges() { -@@ -160,7 +158,7 @@ public class MetricRegistry implements MetricSet { - metrics.entrySet()) { - items.put(entry.getKey().getKey(), (T) Metric.of(entry.getValue())); - } -- return Collections.unmodifiableSortedMap(items); -+ return unmodifiableSortedMap(items); - } - - @Override -diff --git a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java -index a3c8c09..913df5b 100644 ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricSet.java -@@ -1,7 +1,8 @@ - package com.codahale.metrics; - -+import static java.util.Collections.unmodifiableMap; -+ - import io.dropwizard.metrics5.MetricName; --import java.util.Collections; - import java.util.HashMap; - import java.util.Map; - -@@ -24,7 +25,7 @@ public interface MetricSet extends Metric { - original.getMetrics().entrySet()) { - items.put(entry.getKey().getKey(), Metric.of(entry.getValue())); - } -- return Collections.unmodifiableMap(items); -+ return unmodifiableMap(items); - } - - @Override -@@ -48,7 +49,7 @@ public interface MetricSet extends Metric { - for (Map.Entry entry : delegate.getMetrics().entrySet()) { - items.put(MetricName.build(entry.getKey()), entry.getValue().getDelegate()); - } -- return Collections.unmodifiableMap(items); -+ return unmodifiableMap(items); - } - } - } -diff --git a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java -index 498b258..6005e7e 100644 ---- a/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java -+++ b/metrics-legacy-adapter/src/main/java/com/codahale/metrics/ScheduledReporter.java -@@ -1,10 +1,10 @@ - package com.codahale.metrics; - -+import static java.util.Collections.unmodifiableSortedMap; - import static java.util.Objects.requireNonNull; - - import io.dropwizard.metrics5.MetricName; - import java.io.Closeable; --import java.util.Collections; - import java.util.Map; - import java.util.Set; - import java.util.SortedMap; -@@ -115,7 +115,7 @@ public abstract class ScheduledReporter implements Closeable, Reporter { - for (Map.Entry entry : metrics.entrySet()) { - items.put(MetricName.build(entry.getKey()), (T) entry.getValue().getDelegate()); - } -- return Collections.unmodifiableSortedMap(items); -+ return unmodifiableSortedMap(items); - } - - protected String getRateUnit() { -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java -index 223ecc1..8c49b13 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java -@@ -6,10 +6,10 @@ import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class CachedGaugeTest { -+final class CachedGaugeTest { - - @Test -- void testCreate() { -+ void create() { - CachedGauge cachedGauge = - new CachedGauge(100, TimeUnit.MILLISECONDS) { - @Override -@@ -21,7 +21,7 @@ class CachedGaugeTest { - } - - @Test -- void testCreateWothClock() { -+ void createWothClock() { - CachedGauge cachedGauge = - new CachedGauge(new Clock.UserTimeClock(), 100, TimeUnit.MILLISECONDS) { - @Override -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java -index 23f627f..392918b 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java -@@ -5,22 +5,22 @@ import static org.assertj.core.api.Assertions.assertThat; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class ClockTest { -+final class ClockTest { - - @Test -- void testDefaultClockCanBeUsed() { -+ void defaultClockCanBeUsed() { - Clock clock = Clock.defaultClock(); -- assertThat(clock.getTick()).isGreaterThan(0); -+ assertThat(clock.getTick()).isPositive(); - } - - @Test -- void testUserTimeClockCanBeUsed() { -+ void userTimeClockCanBeUsed() { - Clock clock = new Clock.UserTimeClock(); -- assertThat(clock.getTick()).isGreaterThan(0); -+ assertThat(clock.getTick()).isPositive(); - } - - @Test -- void testCustomTimeClockCanBeUsed() { -+ void customTimeClockCanBeUsed() { - Clock clock = - new Clock() { - @Override -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java -index e828f0a..bf94dc6 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java -@@ -1,10 +1,10 @@ - package com.codahale.metrics; - -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - - import java.io.ByteArrayOutputStream; - import java.io.PrintStream; --import java.nio.charset.StandardCharsets; - import java.util.EnumSet; - import java.util.Locale; - import java.util.TimeZone; -@@ -17,7 +17,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class ConsoleReporterTest { -+final class ConsoleReporterTest { - - private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - private final String dateHeader = -@@ -35,7 +35,7 @@ class ConsoleReporterTest { - } - - @Test -- void testCreateConsoleReporter() throws Exception { -+ void createConsoleReporter() throws Exception { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - - MetricRegistry metricRegistry = new MetricRegistry(); -@@ -72,7 +72,7 @@ class ConsoleReporterTest { - .build(); - consoleReporter.report(); - -- assertThat(new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8)) -+ assertThat(new String(byteArrayOutputStream.toByteArray(), UTF_8)) - .isEqualToNormalizingNewlines( - dateHeader - + "\n" -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java -index 2c6540e..a17564f 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java -@@ -6,33 +6,33 @@ import io.dropwizard.metrics5.Counter; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class CounterTest { -+final class CounterTest { - - private Counter counter = new Counter(); - - @Test -- void testIncrementCounter() { -+ void incrementCounter() { - counter.inc(); - - assertThat(counter.getCount()).isEqualTo(1); - } - - @Test -- void testIncrementCounterOnManyPoints() { -+ void incrementCounterOnManyPoints() { - counter.inc(5); - - assertThat(counter.getCount()).isEqualTo(5); - } - - @Test -- void testDecrementCounter() { -+ void decrementCounter() { - counter.dec(); - - assertThat(counter.getCount()).isEqualTo(-1); - } - - @Test -- void testDecrementCounterOnManyPoints() { -+ void decrementCounterOnManyPoints() { - counter.dec(5); - - assertThat(counter.getCount()).isEqualTo(-5); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java -index b3e7ad8..63bdd10 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java -@@ -5,10 +5,10 @@ import static org.assertj.core.api.Assertions.assertThat; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class DerivativeGaugeTest { -+final class DerivativeGaugeTest { - - @Test -- void testCalculate() { -+ void calculate() { - DerivativeGauge derivativeGauge = - new DerivativeGauge(() -> "23") { - @Override -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -index c598fe4..39c5242 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -@@ -6,10 +6,10 @@ import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class ExponentiallyDecayingReservoirTest { -+final class ExponentiallyDecayingReservoirTest { - - @Test -- void testCreateReservoir() { -+ void createReservoir() { - ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(); - reservoir.update(120); - reservoir.update(190); -@@ -22,7 +22,7 @@ class ExponentiallyDecayingReservoirTest { - assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); - assertThat(snapshot.getMin()).isEqualTo(120); - assertThat(snapshot.getMax()).isEqualTo(200); -- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); -+ assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1)); - assertThat(snapshot.get75thPercentile()).isEqualTo(190); - assertThat(snapshot.get95thPercentile()).isEqualTo(200); - assertThat(snapshot.get98thPercentile()).isEqualTo(200); -@@ -31,14 +31,14 @@ class ExponentiallyDecayingReservoirTest { - } - - @Test -- void testCreateReservoirWithCustomSizeAndAlpha() { -+ void createReservoirWithCustomSizeAndAlpha() { - ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01); - reservoir.update(100); - assertThat(reservoir.size()).isEqualTo(1); - } - - @Test -- void testCreateReservoirWithCustomSizeAlphaAndClock() { -+ void createReservoirWithCustomSizeAlphaAndClock() { - ExponentiallyDecayingReservoir reservoir = - new ExponentiallyDecayingReservoir( - 512, -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java -index 8696ad6..9dcbc16 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java -@@ -10,7 +10,7 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class FixedNameCsvFileProviderTest { -+final class FixedNameCsvFileProviderTest { - - private Path tempDirectory; - private FixedNameCsvFileProvider fixedNameCsvFileProvider = new FixedNameCsvFileProvider(); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java -index 22ad432..41a4073 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java -@@ -5,12 +5,12 @@ import static org.assertj.core.api.Assertions.assertThat; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class GaugeTest { -+final class GaugeTest { - - private Gauge gauge = () -> 83; - - @Test -- void testGetValue() { -+ void getValue() { - assertThat(gauge.getValue()).isEqualTo(83); - } - } -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java -index 86e24c7..a141c70 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java -@@ -6,10 +6,10 @@ import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class HistogramTest { -+final class HistogramTest { - - @Test -- void testCreate() { -+ void create() { - Histogram histogram = new Histogram(new ExponentiallyDecayingReservoir()); - histogram.update(120); - histogram.update(190); -@@ -23,7 +23,7 @@ class HistogramTest { - assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); - assertThat(snapshot.getMin()).isEqualTo(120); - assertThat(snapshot.getMax()).isEqualTo(200); -- assertThat(snapshot.getStdDev()).isEqualTo(32.62, Offset.offset(0.1)); -+ assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1)); - assertThat(snapshot.get75thPercentile()).isEqualTo(190); - assertThat(snapshot.get95thPercentile()).isEqualTo(200); - assertThat(snapshot.get98thPercentile()).isEqualTo(200); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java -index 2b18cb6..994061d 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java -@@ -9,10 +9,10 @@ import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class InstrumentedExecutorServiceTest { -+final class InstrumentedExecutorServiceTest { - - @Test -- void testCreate() throws Exception { -+ void create() throws Exception { - ExecutorService executorService = Executors.newSingleThreadExecutor(); - MetricRegistry registry = new MetricRegistry(); - InstrumentedExecutorService instrumentedExecutorService = -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java -index caf4bbb..d0e4130 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java -@@ -10,7 +10,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class InstrumentedScheduledExecutorServiceTest { -+final class InstrumentedScheduledExecutorServiceTest { - private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - - @AfterEach -@@ -19,7 +19,7 @@ class InstrumentedScheduledExecutorServiceTest { - } - - @Test -- void testCreate() throws Exception { -+ void create() throws Exception { - MetricRegistry registry = new MetricRegistry(); - InstrumentedScheduledExecutorService instrumentedExecutorService = - new InstrumentedScheduledExecutorService( -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java -index c947556..0355cfd 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java -@@ -7,11 +7,11 @@ import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class InstrumentedThreadFactoryTest { -+final class InstrumentedThreadFactoryTest { - -- @Test - @SuppressWarnings("DoNotCall") -- void testFactory() throws Exception { -+ @Test -+ void factory() throws Exception { - MetricRegistry registry = new MetricRegistry(); - InstrumentedThreadFactory threadFactory = - new InstrumentedThreadFactory(Thread::new, registry, "test-instrumented-thread-factory"); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java -index 0fee61f..a32fa5e 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java -@@ -6,16 +6,16 @@ import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class MeterTest { -+final class MeterTest { - - @Test -- void testCreateMeteer() { -+ void createMeteer() { - Meter meter = new Meter(); - assertThat(meter.getCount()).isEqualTo(0); - } - - @Test -- void testCreateMeterWithCustomClock() { -+ void createMeterWithCustomClock() { - Meter meter = - new Meter( - new Clock() { -@@ -28,7 +28,7 @@ class MeterTest { - } - - @Test -- void testMark() { -+ void mark() { - Meter meter = - new Meter( - new Clock() { -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java -index 7a5b056..80bd9f1 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java -@@ -11,19 +11,19 @@ import java.util.concurrent.TimeUnit; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class MetricRegistryTest { -+final class MetricRegistryTest { - - private MetricRegistry metricRegistry = new MetricRegistry(); - - @Test -- void testRegisterMetric() { -+ void registerMetric() { - Counter counter = metricRegistry.register("test-counter", new Counter()); - counter.inc(42); - assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); - } - - @Test -- void testRegisterAll() { -+ void registerAll() { - metricRegistry.registerAll( - () -> { - Map map = new HashMap<>(); -@@ -40,26 +40,26 @@ class MetricRegistryTest { - } - - @Test -- void testRegisterGauge() { -+ void registerGauge() { - metricRegistry.registerGauge("test-gauge", () -> 42); - assertThat(metricRegistry.getGauges().get("test-gauge").getValue()).isEqualTo(42); - } - - @Test -- void testCreateCustomGauge() { -+ void createCustomGauge() { - Gauge gauge = metricRegistry.gauge("test-gauge-supplier", () -> () -> 42); - assertThat(gauge.getValue()).isEqualTo(42); - } - - @Test -- void testCreateCounter() { -+ void createCounter() { - Counter counter = metricRegistry.counter("test-counter"); - counter.inc(42); - assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); - } - - @Test -- void testCreateCustomCounter() { -+ void createCustomCounter() { - Counter counter = - metricRegistry.counter( - "test-custom-counter", -@@ -73,7 +73,7 @@ class MetricRegistryTest { - } - - @Test -- void testCreateHistogram() { -+ void createHistogram() { - Histogram histogram = metricRegistry.histogram("test-histogram"); - histogram.update(100); - histogram.update(200); -@@ -83,7 +83,7 @@ class MetricRegistryTest { - } - - @Test -- void testCreateCustomHistogram() { -+ void createCustomHistogram() { - Histogram histogram = - metricRegistry.histogram( - "test-custom-histogram", () -> new Histogram(new SlidingWindowReservoir(2))); -@@ -95,7 +95,7 @@ class MetricRegistryTest { - } - - @Test -- void testCreateMeter() { -+ void createMeter() { - Meter meter = metricRegistry.meter("test-meter"); - meter.mark(); - meter.mark(2); -@@ -104,7 +104,7 @@ class MetricRegistryTest { - } - - @Test -- void testCreateCustomMeter() { -+ void createCustomMeter() { - Meter meter = - metricRegistry.meter( - "test-custom-meter", -@@ -119,7 +119,7 @@ class MetricRegistryTest { - } - - @Test -- void testCreateTimer() { -+ void createTimer() { - Timer timer = metricRegistry.timer("test-timer"); - timer.update(100, TimeUnit.MILLISECONDS); - timer.update(200, TimeUnit.MILLISECONDS); -@@ -129,7 +129,7 @@ class MetricRegistryTest { - } - - @Test -- void testCreateCustomTimer() { -+ void createCustomTimer() { - Timer timer = - metricRegistry.timer( - "custom-test-timer", -@@ -145,7 +145,7 @@ class MetricRegistryTest { - } - - @Test -- void testRemoveMetric() { -+ void removeMetric() { - metricRegistry.timer("test-timer"); - metricRegistry.counter("test-counter"); - metricRegistry.meter("test-meter"); -@@ -156,7 +156,7 @@ class MetricRegistryTest { - } - - @Test -- void testRemoveMatching() { -+ void removeMatching() { - metricRegistry.counter("test-counter"); - metricRegistry.timer("test-timer"); - metricRegistry.timer("test-custom-timer"); -@@ -168,7 +168,7 @@ class MetricRegistryTest { - } - - @Test -- void testAddListenerForGauge() throws Exception { -+ void addListenerForGauge() throws Exception { - CountDownLatch gaugeAddedLatch = new CountDownLatch(1); - CountDownLatch gaugeRemovedLatch = new CountDownLatch(1); - metricRegistry.addListener( -@@ -197,7 +197,7 @@ class MetricRegistryTest { - } - - @Test -- void testAddListenerForCounter() throws Exception { -+ void addListenerForCounter() throws Exception { - CountDownLatch counterAddedLatch = new CountDownLatch(1); - CountDownLatch counterRemovedLatch = new CountDownLatch(1); - metricRegistry.addListener( -@@ -225,7 +225,7 @@ class MetricRegistryTest { - } - - @Test -- void testAddListenerForHistogram() throws Exception { -+ void addListenerForHistogram() throws Exception { - CountDownLatch histogramAddedLatch = new CountDownLatch(1); - CountDownLatch histogramRemovedLatch = new CountDownLatch(1); - metricRegistry.addListener( -@@ -254,7 +254,7 @@ class MetricRegistryTest { - } - - @Test -- void testAddListenerForMeter() throws Exception { -+ void addListenerForMeter() throws Exception { - CountDownLatch meterAddedLatch = new CountDownLatch(1); - CountDownLatch meterRemovedLatch = new CountDownLatch(1); - metricRegistry.addListener( -@@ -283,7 +283,7 @@ class MetricRegistryTest { - } - - @Test -- void testAddListenerForTimer() throws Exception { -+ void addListenerForTimer() throws Exception { - CountDownLatch timerAddedLatch = new CountDownLatch(1); - CountDownLatch timerRemovedLatch = new CountDownLatch(1); - metricRegistry.addListener( -@@ -312,7 +312,7 @@ class MetricRegistryTest { - } - - @Test -- void testRemoveListener() throws Exception { -+ void removeListener() throws Exception { - CountDownLatch gaugeAddedLatch = new CountDownLatch(1); - MetricRegistryListener listener = - new MetricRegistryListener.Base() { -@@ -331,7 +331,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetNames() { -+ void getNames() { - metricRegistry.counter("test-counter"); - metricRegistry.timer("test-timer"); - metricRegistry.timer("test-custom-timer"); -@@ -342,7 +342,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetGauges() { -+ void getGauges() { - metricRegistry.counter("test-counter"); - metricRegistry.timer("test-timer"); - metricRegistry.meter("test-meter"); -@@ -369,7 +369,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetGaugesWithFilter() { -+ void getGaugesWithFilter() { - metricRegistry.counter("test-counter"); - metricRegistry.timer("test-timer"); - metricRegistry.meter("test-meter"); -@@ -398,7 +398,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetHistograms() { -+ void getHistograms() { - metricRegistry.counter("test-counter"); - metricRegistry.timer("test-timer"); - metricRegistry.meter("test-meter"); -@@ -411,7 +411,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetHistogramsWithFilter() { -+ void getHistogramsWithFilter() { - metricRegistry.counter("sw-counter"); - metricRegistry.timer("sw-timer"); - metricRegistry.meter("sw-meter"); -@@ -424,7 +424,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetCounters() { -+ void getCounters() { - metricRegistry.histogram("test-histogram"); - metricRegistry.timer("test-timer"); - metricRegistry.meter("test-meter"); -@@ -437,7 +437,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetCountersWithFilter() { -+ void getCountersWithFilter() { - metricRegistry.histogram("test-histogram"); - metricRegistry.timer("test-timer"); - metricRegistry.meter("test-meter"); -@@ -450,7 +450,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetMeters() { -+ void getMeters() { - metricRegistry.register("test-gauge", (Gauge) () -> 42); - metricRegistry.histogram("test-histogram"); - metricRegistry.timer("test-timer"); -@@ -464,7 +464,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetMetersWithFilter() { -+ void getMetersWithFilter() { - metricRegistry.register("sw-gauge", (Gauge) () -> 42); - metricRegistry.histogram("sw-histogram"); - metricRegistry.timer("sw-timer"); -@@ -478,7 +478,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetTimers() { -+ void getTimers() { - metricRegistry.histogram("test-histogram"); - metricRegistry.meter("test-meter"); - metricRegistry.counter("test-counter"); -@@ -491,7 +491,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetTimersWithFilter() { -+ void getTimersWithFilter() { - metricRegistry.histogram("test-histogram-2"); - metricRegistry.meter("test-meter-2"); - metricRegistry.counter("test-counter-2"); -@@ -504,7 +504,7 @@ class MetricRegistryTest { - } - - @Test -- void testGetMetrics() { -+ void getMetrics() { - metricRegistry.register( - "test-text-gauge-2", - new CachedGauge(1, TimeUnit.MINUTES) { -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java -index e593421..acd78e9 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java -@@ -1,12 +1,12 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; - --import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class RatioGaugeTest { -+final class RatioGaugeTest { - - private RatioGauge ratioGauge = - new RatioGauge() { -@@ -17,12 +17,12 @@ class RatioGaugeTest { - }; - - @Test -- void testViewRatin() { -- assertThat(ratioGauge.getRatio().toString()).isEqualTo("1.0:3.0"); -+ void viewRatin() { -+ assertThat(ratioGauge.getRatio()).hasToString("1.0:3.0"); - } - - @Test -- void testCalculateRatio() { -- assertThat(ratioGauge.getValue()).isCloseTo(0.33, Offset.offset(0.01)); -+ void calculateRatio() { -+ assertThat(ratioGauge.getValue()).isCloseTo(0.33, offset(0.01)); - } - } -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java -index b483a4c..8f6f103 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java -@@ -10,7 +10,7 @@ import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class ScheduledReporterTest { -+final class ScheduledReporterTest { - - private MetricRegistry metricRegistry = new MetricRegistry(); - private ScheduledReporter scheduledReporter; -@@ -51,7 +51,7 @@ class ScheduledReporterTest { - } - - @Test -- void testReport() throws Exception { -+ void report() throws Exception { - CountDownLatch latch = new CountDownLatch(1); - scheduledReporter = createScheduledReporter(latch); - scheduledReporter.report(); -@@ -61,7 +61,7 @@ class ScheduledReporterTest { - } - - @Test -- void testStart() throws Exception { -+ void start() throws Exception { - CountDownLatch latch = new CountDownLatch(2); - scheduledReporter = createScheduledReporter(latch); - scheduledReporter.start(10, TimeUnit.MILLISECONDS); -@@ -71,7 +71,7 @@ class ScheduledReporterTest { - } - - @Test -- void testStartWithoutDelay() throws Exception { -+ void startWithoutDelay() throws Exception { - CountDownLatch latch = new CountDownLatch(2); - scheduledReporter = createScheduledReporter(latch); - scheduledReporter.start(0, 10, TimeUnit.MILLISECONDS); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java -index c2340f2..232c473 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java -@@ -1,13 +1,13 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - - import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class SharedMetricRegistriesTest { -+final class SharedMetricRegistriesTest { - - @AfterEach - void tearDown() throws Exception { -@@ -15,7 +15,7 @@ class SharedMetricRegistriesTest { - } - - @Test -- void testGetOrCreateMetricRegistry() { -+ void getOrCreateMetricRegistry() { - SharedMetricRegistries.getOrCreate("get-or-create").counter("test-counter"); - - assertThat(SharedMetricRegistries.getOrCreate("get-or-create").getCounters()) -@@ -23,7 +23,7 @@ class SharedMetricRegistriesTest { - } - - @Test -- void testAddMetricRegistry() { -+ void addMetricRegistry() { - MetricRegistry metricRegistry = new MetricRegistry(); - metricRegistry.histogram("test-histogram"); - SharedMetricRegistries.add("add", metricRegistry); -@@ -33,7 +33,7 @@ class SharedMetricRegistriesTest { - } - - @Test -- void testNames() { -+ void names() { - SharedMetricRegistries.add("registry-1", new MetricRegistry()); - SharedMetricRegistries.add("registry-2", new MetricRegistry()); - SharedMetricRegistries.add("registry-3", new MetricRegistry()); -@@ -43,12 +43,13 @@ class SharedMetricRegistriesTest { - } - - @Test -- void testTryGetDefaultRegistry() { -+ void tryGetDefaultRegistry() { - assertThat(SharedMetricRegistries.tryGetDefault()).isNull(); - } - - @Test -- void testGetDefaultRegistry() { -- assertThatIllegalStateException().isThrownBy(SharedMetricRegistries::getDefault); -+ void getDefaultRegistry() { -+ assertThatThrownBy(SharedMetricRegistries::getDefault) -+ .isInstanceOf(IllegalStateException.class); - } - } -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java -index 55d05fe..984ceb1 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java -@@ -14,11 +14,11 @@ import org.slf4j.Logger; - import org.slf4j.Marker; - - @SuppressWarnings("deprecation") --class Slf4jReporterTest { -+final class Slf4jReporterTest { - - private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); -- private Logger logger = mock(Logger.class); -- private Marker marker = mock(Marker.class); -+ private Logger logger = mock(); -+ private Marker marker = mock(); - - @BeforeEach - void setUp() throws Exception { -@@ -31,7 +31,7 @@ class Slf4jReporterTest { - } - - @Test -- void testReport() throws Exception { -+ void report() throws Exception { - MetricRegistry metricRegistry = new MetricRegistry(); - metricRegistry.counter("test-counter").inc(100); - -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java -index 95228fa..9e48141 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java -@@ -1,16 +1,16 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; - - import java.util.concurrent.TimeUnit; --import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class SlidingTimeWindowArrayReservoirTest { -+final class SlidingTimeWindowArrayReservoirTest { - - @Test -- void testCreateWithWindow() { -+ void createWithWindow() { - SlidingTimeWindowArrayReservoir reservoir = - new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS); - reservoir.update(100); -@@ -18,17 +18,17 @@ class SlidingTimeWindowArrayReservoirTest { - reservoir.update(30); - - assertThat(reservoir.size()).isEqualTo(3); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); - } - - @Test -- void testCreateWithWindowAndClock() { -+ void createWithWindowAndClock() { - SlidingTimeWindowArrayReservoir reservoir = - new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); - reservoir.update(400); - reservoir.update(300); - - assertThat(reservoir.size()).isEqualTo(2); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); - } - } -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java -index c80dcee..dcd9b61 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java -@@ -1,33 +1,33 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; - - import java.util.concurrent.TimeUnit; --import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class SlidingTimeWindowReservoirTest { -+final class SlidingTimeWindowReservoirTest { - - @Test -- void testCreateWithWindow() { -+ void createWithWindow() { - SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS); - reservoir.update(100); - reservoir.update(200); - reservoir.update(30); - - assertThat(reservoir.size()).isEqualTo(3); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, Offset.offset(0.1)); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(110, offset(0.1)); - } - - @Test -- void testCreateWithWindowAndClock() { -+ void createWithWindowAndClock() { - SlidingTimeWindowReservoir reservoir = - new SlidingTimeWindowReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); - reservoir.update(400); - reservoir.update(300); - - assertThat(reservoir.size()).isEqualTo(2); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, Offset.offset(0.1)); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(350, offset(0.1)); - } - } -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java -index bebb55e..37cca6a 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java -@@ -1,26 +1,26 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; - --import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class SlidingWindowReservoirTest { -+final class SlidingWindowReservoirTest { - - @Test -- void testCreateWithBigWindow() { -+ void createWithBigWindow() { - SlidingWindowReservoir reservoir = new SlidingWindowReservoir(100); - reservoir.update(100); - reservoir.update(220); - reservoir.update(130); - - assertThat(reservoir.size()).isEqualTo(3); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, Offset.offset(0.1)); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(150, offset(0.1)); - } - - @Test -- void testCreateWithLowWindow() { -+ void createWithLowWindow() { - SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); - reservoir.update(500); - reservoir.update(220); -@@ -28,6 +28,6 @@ class SlidingWindowReservoirTest { - reservoir.update(40); - - assertThat(reservoir.size()).isEqualTo(3); -- assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, Offset.offset(0.1)); -+ assertThat(reservoir.getSnapshot().getMean()).isCloseTo(120, offset(0.1)); - } - } -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java -index 6c24eaa..24a6ae0 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java -@@ -8,23 +8,23 @@ import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class SnapshotTest { -+final class SnapshotTest { - - @Test -- void testCreateSnapshot() throws Exception { -+ void createSnapshot() throws Exception { - Snapshot snapshot = Snapshot.of(new UniformSnapshot(new long[] {5, 1, 2, 3, 4})); - - assertThat(snapshot.getValues()).isEqualTo(new long[] {1, 2, 3, 4, 5}); - assertThat(snapshot.size()).isEqualTo(5); - assertThat(snapshot.getMin()).isEqualTo(1); - assertThat(snapshot.getMax()).isEqualTo(5); -- assertThat(snapshot.getStdDev()).isEqualTo(1.58, Offset.offset(0.01)); -- assertThat(snapshot.getMedian()).isEqualTo(3, Offset.offset(0.01)); -- assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, Offset.offset(0.01)); -- assertThat(snapshot.get95thPercentile()).isEqualTo(5, Offset.offset(0.01)); -- assertThat(snapshot.get98thPercentile()).isEqualTo(5, Offset.offset(0.01)); -- assertThat(snapshot.get99thPercentile()).isEqualTo(5, Offset.offset(0.01)); -- assertThat(snapshot.get999thPercentile()).isEqualTo(5, Offset.offset(0.01)); -+ assertThat(snapshot.getStdDev()).isCloseTo(1.58, Offset.offset(0.01)); -+ assertThat(snapshot.getMedian()).isCloseTo(3, Offset.offset(0.01)); -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, Offset.offset(0.01)); -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5, Offset.offset(0.01)); -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5, Offset.offset(0.01)); -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5, Offset.offset(0.01)); -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5, Offset.offset(0.01)); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - snapshot.dump(baos); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java -index c2bd51c..d9764ee 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java -@@ -8,7 +8,7 @@ import java.util.concurrent.atomic.AtomicInteger; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class TimerTest { -+final class TimerTest { - - private static class ManualClock extends Clock { - -@@ -26,7 +26,7 @@ class TimerTest { - } - - @Test -- void testCreate() { -+ void create() { - Timer timer = new Timer(); - timer.update(100, TimeUnit.MILLISECONDS); - timer.update(200, TimeUnit.MILLISECONDS); -@@ -35,7 +35,7 @@ class TimerTest { - } - - @Test -- void testCreateWithCustomReservoir() { -+ void createWithCustomReservoir() { - Timer timer = new Timer(new SlidingWindowReservoir(100)); - timer.update(100, TimeUnit.MILLISECONDS); - timer.update(200, TimeUnit.MILLISECONDS); -@@ -44,7 +44,7 @@ class TimerTest { - } - - @Test -- void testCreateWithCustomReservoirAndClock() { -+ void createWithCustomReservoirAndClock() { - Timer timer = new Timer(new SlidingWindowReservoir(100), new Clock.UserTimeClock()); - timer.update(100, TimeUnit.MILLISECONDS); - timer.update(200, TimeUnit.MILLISECONDS); -@@ -53,7 +53,7 @@ class TimerTest { - } - - @Test -- void testTimerContext() { -+ void timerContext() { - Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); - timer.time().stop(); - -@@ -61,7 +61,7 @@ class TimerTest { - } - - @Test -- void testTimerRunnable() { -+ void timerRunnable() { - Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); - - AtomicInteger counter = new AtomicInteger(); -@@ -72,7 +72,7 @@ class TimerTest { - } - - @Test -- void testTimerCallable() throws Exception { -+ void timerCallable() throws Exception { - Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); - - String message = timer.time(() -> "SUCCESS"); -@@ -82,7 +82,7 @@ class TimerTest { - } - - @Test -- void testTimerSupplier() throws Exception { -+ void timerSupplier() throws Exception { - Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); - - Integer result = timer.timeSupplier(() -> 42); -@@ -92,7 +92,7 @@ class TimerTest { - } - - @Test -- void testUpdateDuration() { -+ void updateDuration() { - Timer timer = new Timer(); - timer.update(Duration.ofMillis(100)); - timer.update(Duration.ofMillis(200)); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java -index f125498..0668c1e 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java -@@ -6,10 +6,10 @@ import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") --class UniformReservoirTest { -+final class UniformReservoirTest { - - @Test -- void testCreateReservoir() { -+ void createReservoir() { - UniformReservoir reservoir = new UniformReservoir(); - reservoir.update(120); - reservoir.update(190); -@@ -22,7 +22,7 @@ class UniformReservoirTest { - assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); - assertThat(snapshot.getMin()).isEqualTo(120); - assertThat(snapshot.getMax()).isEqualTo(200); -- assertThat(snapshot.getStdDev()).isEqualTo(36.47, Offset.offset(0.1)); -+ assertThat(snapshot.getStdDev()).isCloseTo(36.47, Offset.offset(0.1)); - assertThat(snapshot.get75thPercentile()).isEqualTo(195); - assertThat(snapshot.get95thPercentile()).isEqualTo(200); - assertThat(snapshot.get98thPercentile()).isEqualTo(200); -@@ -31,7 +31,7 @@ class UniformReservoirTest { - } - - @Test -- void testCreateReservoirWithCustomSize() { -+ void createReservoirWithCustomSize() { - UniformReservoir reservoir = new UniformReservoir(128); - reservoir.update(440); - reservoir.update(250); -diff --git a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java -index a4e9cee..b93cf21 100644 ---- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java -+++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java -@@ -12,7 +12,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --public class InstrumentedAppenderConfigTest { -+final class InstrumentedAppenderConfigTest { - public static final String METRIC_NAME_PREFIX = "metrics"; - public static final String REGISTRY_NAME = "shared-metrics-registry"; - -diff --git a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java -index ce0bae1..ea2f261 100644 ---- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java -+++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java -@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --public class InstrumentedAppenderTest { -+final class InstrumentedAppenderTest { - - public static final String METRIC_NAME_PREFIX = "org.apache.logging.log4j.core.Appender"; - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final LogEvent event = mock(LogEvent.class); -+ private final LogEvent event = mock(); - - @BeforeEach - void setUp() { -diff --git a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java -index 81a0e1b..9adaef7 100644 ---- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java -+++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java -@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --public class InstrumentedAppenderTest { -+final class InstrumentedAppenderTest { - - public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ private final ILoggingEvent event = mock(); - - @BeforeEach - void setUp() { -diff --git a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java -index e29f84a..b83ae22 100644 ---- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java -+++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java -@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --public class InstrumentedAppenderTest { -+final class InstrumentedAppenderTest { - - public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ private final ILoggingEvent event = mock(); - - @BeforeEach - void setUp() { -diff --git a/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java b/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java -index 2891ce4..9f1e279 100644 ---- a/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java -+++ b/metrics-logback15/src/test/java/io/dropwizard/metrics5/logback15/InstrumentedAppenderTest.java -@@ -12,13 +12,13 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --public class InstrumentedAppenderTest { -+final class InstrumentedAppenderTest { - - public static final String METRIC_NAME_PREFIX = "ch.qos.logback.core.Appender"; - - private final MetricRegistry registry = new MetricRegistry(); - private final InstrumentedAppender appender = new InstrumentedAppender(registry); -- private final ILoggingEvent event = mock(ILoggingEvent.class); -+ private final ILoggingEvent event = mock(); - - @BeforeEach - void setUp() { -diff --git a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -index dcc19dd..84c04d4 100644 ---- a/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -+++ b/metrics-servlet/src/main/java/io/dropwizard/metrics5/servlet/AbstractInstrumentedFilter.java -@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.servlet; - - import static io.dropwizard.metrics5.MetricRegistry.name; - -+import com.google.common.base.Strings; - import io.dropwizard.metrics5.Counter; - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -64,7 +65,7 @@ public abstract class AbstractInstrumentedFilter implements Filter { - final MetricRegistry metricsRegistry = getMetricsFactory(filterConfig); - - String metricName = filterConfig.getInitParameter(METRIC_PREFIX); -- if (metricName == null || metricName.isEmpty()) { -+ if (Strings.isNullOrEmpty(metricName)) { - metricName = getClass().getName(); - } - -diff --git a/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java b/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -index 1a0bd8e..d7ceae8 100644 ---- a/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -+++ b/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java -@@ -9,8 +9,8 @@ import javax.servlet.ServletContext; - import javax.servlet.ServletContextEvent; - import org.junit.jupiter.api.Test; - --class InstrumentedFilterContextListenerTest { -- private final MetricRegistry registry = mock(MetricRegistry.class); -+final class InstrumentedFilterContextListenerTest { -+ private final MetricRegistry registry = mock(); - private final InstrumentedFilterContextListener listener = - new InstrumentedFilterContextListener() { - @Override -@@ -21,9 +21,9 @@ class InstrumentedFilterContextListenerTest { - - @Test - void injectsTheMetricRegistryIntoTheServletContext() { -- final ServletContext context = mock(ServletContext.class); -+ final ServletContext context = mock(); - -- final ServletContextEvent event = mock(ServletContextEvent.class); -+ final ServletContextEvent event = mock(); - when(event.getServletContext()).thenReturn(context); - - listener.contextInitialized(event); -diff --git a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -index 88cd1fa..8685484 100644 ---- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -+++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/HealthCheckServlet.java -@@ -99,7 +99,7 @@ public class HealthCheckServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY); - if (registryAttr instanceof HealthCheckRegistry) { - this.registry = (HealthCheckRegistry) registryAttr; -diff --git a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -index 3efdc27..cc16683 100644 ---- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -+++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -@@ -131,7 +131,7 @@ public class MetricsServlet extends HttpServlet { - super.init(config); - - final ServletContext context = config.getServletContext(); -- if (null == registry) { -+ if (registry == null) { - final Object registryAttr = context.getAttribute(METRICS_REGISTRY); - if (registryAttr instanceof MetricRegistry) { - this.registry = (MetricRegistry) registryAttr; -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java -index 8fcdf8a..77b50ba 100755 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java -@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class AdminServletTest extends AbstractServletTest { -+final class AdminServletTest extends AbstractServletTest { - private final MetricRegistry registry = new MetricRegistry(); - private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); - -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java -index ebe2c81..424a05e 100755 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java -@@ -9,7 +9,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class AdminServletUriTest extends AbstractServletTest { -+final class AdminServletUriTest extends AbstractServletTest { - private final MetricRegistry registry = new MetricRegistry(); - private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); - -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java -index 1c63a41..2df4050 100644 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java -@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class CpuProfileServletTest extends AbstractServletTest { -+final class CpuProfileServletTest extends AbstractServletTest { - - @Override - protected void setUp(ServletTester tester) { -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -index e7bc067..80b40f1 100644 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -@@ -1,10 +1,9 @@ - package io.dropwizard.metrics5.servlets; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -27,7 +26,7 @@ import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class HealthCheckServletTest extends AbstractServletTest { -+final class HealthCheckServletTest extends AbstractServletTest { - - private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); - -@@ -95,9 +94,8 @@ class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - } - - @Test -@@ -111,9 +109,8 @@ class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - assertThat(response.getContent()) - .isEqualTo( -- "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" -- + EXPECTED_TIMESTAMP -- + "\"}}"); -+ "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"%s\"}}", -+ EXPECTED_TIMESTAMP); - } - - @Test -@@ -168,15 +165,8 @@ class HealthCheckServletTest extends AbstractServletTest { - assertThat(response.getContent()) - .isEqualTo( - String.format( -- "{%n" -- + " \"fun\" : {%n" -- + " \"healthy\" : true,%n" -- + " \"message\" : \"foo bar 123\",%n" -- + " \"duration\" : 0,%n" -- + " \"timestamp\" : \"" -- + EXPECTED_TIMESTAMP -- + "\"" -- + "%n }%n}")); -+ "{%n \"fun\" : {%n \"healthy\" : true,%n \"message\" : \"foo bar 123\",%n \"duration\" : 0,%n \"timestamp\" : \"%s\"%n }%n}", -+ EXPECTED_TIMESTAMP)); - } - - private static HealthCheck.Result healthyResultWithMessage(String message) { -@@ -197,23 +187,23 @@ class HealthCheckServletTest extends AbstractServletTest { - - @Test - void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(healthCheckRegistry); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -+ verify(servletConfig).getServletContext(); - verify(servletContext, never()).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); - } - - @Test - void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final HealthCheckRegistry healthCheckRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn(healthCheckRegistry); -@@ -221,32 +211,32 @@ class HealthCheckServletTest extends AbstractServletTest { - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); - healthCheckServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); - } - - @Test - void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- assertThrows( -- ServletException.class, -- () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -- .thenReturn("IRELLEVANT_STRING"); -- -- final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -- healthCheckServlet.init(servletConfig); -- }); -+ assertThatThrownBy( -+ () -> { -+ final ServletContext servletContext = mock(ServletContext.class); -+ final ServletConfig servletConfig = mock(ServletConfig.class); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) -+ .thenReturn("IRELLEVANT_STRING"); -+ -+ final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); -+ healthCheckServlet.init(servletConfig); -+ }) -+ .isInstanceOf(ServletException.class); - } - - @Test - void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn(registry); -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java -index 5cd3578..101f79d 100644 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java -@@ -17,8 +17,8 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class MetricsServletContextListenerTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+final class MetricsServletContextListenerTest extends AbstractServletTest { -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private final String allowedOrigin = "some.other.origin"; - -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -index ee72291..78086f5 100644 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -@@ -1,11 +1,10 @@ - package io.dropwizard.metrics5.servlets; - - import static org.assertj.core.api.Assertions.assertThat; --import static org.junit.jupiter.api.Assertions.assertThrows; -+import static org.assertj.core.api.Assertions.assertThatThrownBy; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; --import static org.mockito.Mockito.times; - import static org.mockito.Mockito.verify; - import static org.mockito.Mockito.when; - -@@ -25,8 +24,8 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class MetricsServletTest extends AbstractServletTest { -- private final Clock clock = mock(Clock.class); -+final class MetricsServletTest extends AbstractServletTest { -+ private final Clock clock = mock(); - private final MetricRegistry registry = new MetricRegistry(); - private ServletTester tester; - -@@ -130,22 +129,8 @@ class MetricsServletTest extends AbstractServletTest { - assertThat(response.get("Access-Control-Allow-Origin")).isEqualTo("*"); - assertThat(response.getContent()) - .isEqualTo( -- callbackParamVal -- + "({" -- + "\"version\":\"5.0.0\"," -- + "\"gauges\":{" -- + "\"g1\":{\"value\":100}" -- + "}," -- + "\"counters\":{" -- + "\"c\":{\"count\":1}" -- + "}," -- + "\"histograms\":{" -- + "\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}" -- + "}," -- + "\"meters\":{" -- + "\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}" -- + "}" -- + "})"); -+ "%s({\"version\":\"5.0.0\",\"gauges\":{\"g1\":{\"value\":100}},\"counters\":{\"c\":{\"count\":1}},\"histograms\":{\"h\":{\"count\":1,\"max\":1,\"mean\":1.0,\"min\":1,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0}},\"meters\":{\"m\":{\"count\":1,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":3333333.3333333335,\"units\":\"events/second\"}},\"timers\":{\"t\":{\"count\":1,\"max\":1.0,\"mean\":1.0,\"min\":1.0,\"p50\":1.0,\"p75\":1.0,\"p95\":1.0,\"p98\":1.0,\"p99\":1.0,\"p999\":1.0,\"stddev\":0.0,\"m15_rate\":0.0,\"m1_rate\":0.0,\"m5_rate\":0.0,\"mean_rate\":1.0E7,\"duration_units\":\"seconds\",\"rate_units\":\"calls/second\"}}})", -+ callbackParamVal); - assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); - } - -@@ -224,48 +209,47 @@ class MetricsServletTest extends AbstractServletTest { - - @Test - void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - - final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext, never()).getAttribute(MetricsServlet.METRICS_REGISTRY); - } - - @Test - void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { -- final MetricRegistry metricRegistry = mock(MetricRegistry.class); -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final MetricRegistry metricRegistry = mock(); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn(metricRegistry); -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).thenReturn(metricRegistry); - - final MetricsServlet metricsServlet = new MetricsServlet(null); - metricsServlet.init(servletConfig); - -- verify(servletConfig, times(1)).getServletContext(); -- verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); -+ verify(servletConfig).getServletContext(); -+ verify(servletContext).getAttribute(MetricsServlet.METRICS_REGISTRY); - } - - @Test - void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() - throws Exception { -- assertThrows( -- ServletException.class, -- () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -- when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -- .thenReturn("IRELLEVANT_STRING"); -- -- final MetricsServlet metricsServlet = new MetricsServlet(null); -- metricsServlet.init(servletConfig); -- }); -+ assertThatThrownBy( -+ () -> { -+ final ServletContext servletContext = mock(ServletContext.class); -+ final ServletConfig servletConfig = mock(ServletConfig.class); -+ when(servletConfig.getServletContext()).thenReturn(servletContext); -+ when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -+ .thenReturn("IRELLEVANT_STRING"); -+ -+ final MetricsServlet metricsServlet = new MetricsServlet(null); -+ metricsServlet.init(servletConfig); -+ }) -+ .isInstanceOf(ServletException.class); - } - } -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java -index 72e4d9f..56bb1ee 100644 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java -@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class PingServletTest extends AbstractServletTest { -+final class PingServletTest extends AbstractServletTest { - @Override - protected void setUp(ServletTester tester) { - tester.addServlet(PingServlet.class, "/ping"); -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java -index 3b92675..5bbb7b1 100644 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java -@@ -7,7 +7,7 @@ import org.eclipse.jetty.servlet.ServletTester; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - --class ThreadDumpServletTest extends AbstractServletTest { -+final class ThreadDumpServletTest extends AbstractServletTest { - @Override - protected void setUp(ServletTester tester) { - tester.addServlet(ThreadDumpServlet.class, "/threads"); -[detached HEAD 05c4a97] minor: Apply patches - 235 files changed, 1678 insertions(+), 1820 deletions(-) -[INFO] Scanning for projects... -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Build Order: -[INFO] -[INFO] Metrics5 Parent [pom] -[INFO] Metrics5 Documentation [jar] -[INFO] Metrics5 BOM [pom] -[INFO] Annotations for Metrics5 [bundle] -[INFO] Metrics5 Core [bundle] -[INFO] Benchmarks for Metrics5 [jar] -[INFO] Metrics Integration for Caffeine 3.x [bundle] -[INFO] Metrics Integration for Collectd [bundle] -[INFO] Metrics Integration for Ehcache [bundle] -[INFO] Graphite Integration for Metrics5 [bundle] -[INFO] InfluxDB integration for Metrics5 [bundle] -[INFO] JVM Integration for Metrics5 [bundle] -[INFO] Metrics5 Health Checks [bundle] -[INFO] Metrics Integration for Apache HttpClient [bundle] -[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] -[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] -[INFO] Metrics Integration for Jakarta Servlets [bundle] -[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] -[INFO] Jackson Integration for Metrics5 [bundle] -[INFO] Metrics Integration for Jetty 11.x and higher [bundle] -[INFO] Metrics5 Utility Jakarta Servlets [bundle] -[INFO] Metrics Integration for JCache [bundle] -[INFO] Metrics Integration for JDBI3 [bundle] -[INFO] Metrics Integration for Jersey 2.x [bundle] -[INFO] Metrics Integration for Jersey 3.0.x [bundle] -[INFO] Metrics Integration for Jersey 3.1.x [bundle] -[INFO] Metrics Integration for Jetty 10.x and higher [bundle] -[INFO] Metrics Integration for Log4j 2.x [bundle] -[INFO] Metrics Integration for Logback 1.3.x [bundle] -[INFO] Metrics Integration for Logback 1.4.x [bundle] -[INFO] Metrics Integration for Logback 1.5.x [bundle] -[INFO] Metrics Integration for Servlets [bundle] -[INFO] Metrics5 Utility Servlets [bundle] -[INFO] Metrics5 JCStress tests [jar] -[INFO] Metrics Integration with JMX [bundle] -[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] -[INFO] Metrics Integration for Jetty 12.x and higher [bundle] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- -[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] -[INFO] from pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- -[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] -[INFO] from docs/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec -[INFO] -[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- -[INFO] -[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- -[INFO] Copying 72 resources from source to target/source -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- -[INFO] Copying 72 resources from source to target/classes -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ docs --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- -[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. -[info] Processed 0 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- -[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] -[INFO] from metrics-bom/pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- -[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] -[INFO] from metrics-annotation/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. -[info] Processed 9 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- -[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] -[INFO] from metrics-core/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- -[INFO] Compiling 10 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[56,27] [this-escape] possible 'this' escape before subclass is fully initialized -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java:[68,17] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"%s is not in [0..1]", quantile);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java:[240,19] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean 'value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: %s", value);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java:[51,17] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"%s is not in [0..1]", quantile);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- -[INFO] Compiling 16 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[124,54] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean 'assertThat(futures.get(i).get()).withFailMessage("Future %s failed", i).isTrue();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[93,56] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) - Did you mean 'assertThat(b).isLessThan(b.resolve("key"));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[101,56] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) - Did you mean 'assertThat(MetricName.EMPTY).isLessThan(a);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[102,56] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) - Did you mean 'assertThat(MetricName.EMPTY).isLessThan(b);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[92,56] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsGreaterThan: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsGreaterThan) - Did you mean 'assertThat(b.resolve("key")).isGreaterThan(b);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[90,41] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) - Did you mean 'assertThat(a).isLessThan(b);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[103,41] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsLessThan: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsLessThan) - Did you mean 'assertThat(a).isLessThan(b);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[91,41] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsGreaterThan: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsGreaterThan) - Did you mean 'assertThat(b).isGreaterThan(a);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java:[104,41] Note: [Refaster Rule] AssertJComparableRules.AssertThatIsGreaterThan: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/AssertJComparableRules#AssertThatIsGreaterThan) - Did you mean 'assertThat(b).isGreaterThan(a);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[508,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[508,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[529,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[529,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[555,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[555,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[585,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[585,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[611,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[611,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[640,41] [CollectorMutability] Avoid `Collectors.to{List,Map,Set}` in favor of collectors that emphasize (im)mutability - (see https://error-prone.picnic.tech/bugpatterns/CollectorMutability) - Did you mean '.collect(toImmutableSet()));' or '.collect(toCollection(HashSet::new)));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java:[640,35] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean '.collect(toSet()));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java:[109,16] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail("NullPointerException must be thrown !!!");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java:[22,17] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '"Mismatched lengths: %s vs %s", values.length, weights.length);'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- -[info] Processed 87 files (6 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- -[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] -[INFO] from metrics-benchmarks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_arrTime_jmhTest' already exists on the sourcepath or classpath -[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_jmhType_B1' already exists on the sourcepath or classpath -[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_jmhType_B2' already exists on the sourcepath or classpath -[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_jmhType_B3' already exists on the sourcepath or classpath -[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_jmhType' already exists on the sourcepath or classpath -[WARNING] A file for type 'io.dropwizard.metrics5.benchmarks.jmh_generated.SlidingTimeWindowReservoirsBenchmark_slidingTime_jmhTest' already exists on the sourcepath or classpath -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22.jar -[INFO] -[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. -[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- -[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] -[INFO] from metrics-caffeine3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- -[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] -[INFO] from metrics-collectd/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[152,21] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '!username.isEmpty(), "username is required for securityLevel: %s", securityLevel);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[154,21] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '!password.isEmpty(), "password is required for securityLevel: %s", securityLevel);'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[125,20] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean 'if (Strings.isNullOrEmpty(val)) {'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- -[info] Processed 12 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- -[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] -[INFO] from metrics-ehcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- -[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] -[INFO] from metrics-graphite/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[68,35] Note: [Refaster Rule] StringRules.StringIsNullOrEmpty: Refactoring opportunity - (see https://error-prone.picnic.tech/refasterrules/StringRules#StringIsNullOrEmpty) - Did you mean 'checkArgument(!Strings.isNullOrEmpty(hostname), "hostname must not be null or empty");'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- -[info] Processed 13 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- -[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] -[INFO] from metrics-influxdb/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- -[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] -[INFO] from metrics-jvm/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[74,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[83,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[92,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java:[37,14] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(new FileDescriptorRatioGauge().getValue())'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- -[info] Processed 23 files (1 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- -[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] -[INFO] from metrics-healthchecks/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[97,19] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) - Did you mean '!healthChecks.containsKey(name), "A health check named %s already exists", name);'? -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- -[info] Processed 14 files (0 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] -[INFO] from metrics-httpclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java:[69,16] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- -[info] Processed 8 files (1 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] -[INFO] from metrics-httpclient5/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[104,26] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[109,26] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[147,28] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[157,28] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[163,16] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[214,28] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java:[219,28] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[69,16] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail();'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- -[info] Processed 13 files (2 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- -[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] -[INFO] from metrics-httpasyncclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java:[121,16] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail("This should fail as the client should not be able to connect");'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- -[info] Processed 5 files (1 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] -[INFO] from metrics-jakarta-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] -[INFO] from metrics-jakarta-servlet6/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- -[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] -[INFO] from metrics-json/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- -[info] Processed 4 files (1 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- -[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] -[INFO] from metrics-jetty11/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- -[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] -[INFO] from metrics-jakarta-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[223,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[224,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[244,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[245,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[247,46] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- -[info] Processed 17 files (1 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- -[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] -[INFO] from metrics-jcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- -[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] -[INFO] from metrics-jdbi3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- -[info] Processed 15 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- -[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] -[INFO] from metrics-jersey2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- -[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[110,16] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail("expected RuntimeException");'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- -[info] Processed 24 files (1 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- -[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] -[INFO] from metrics-jersey3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- -[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[111,16] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail("expected RuntimeException");'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- -[info] Processed 24 files (1 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- -[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] -[INFO] from metrics-jersey31/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- -[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java:[111,16] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'fail("expected RuntimeException");'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- -[info] Processed 24 files (1 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- -[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] -[INFO] from metrics-jetty10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- -[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] -[INFO] from metrics-log4j2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- -[info] Processed 3 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- -[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] -[INFO] from metrics-logback13/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- -[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] -[INFO] from metrics-logback14/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- -[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] -[INFO] from metrics-logback15/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- -[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] -[INFO] from metrics-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- -[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] -[INFO] from metrics-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[223,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[224,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[244,56] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletContext servletContext = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[245,54] Note: [MockitoMockClassReference] Don't unnecessarily pass a type to Mockito's `mock(Class)` and `spy(Class)` methods - (see https://error-prone.picnic.tech/bugpatterns/MockitoMockClassReference) - Did you mean 'final ServletConfig servletConfig = mock();'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java:[247,46] Note: [MockitoStubbing] Don't unnecessarily use Mockito's `eq(...)` - (see https://error-prone.picnic.tech/bugpatterns/MockitoStubbing) - Did you mean 'when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY))'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- -[info] Processed 16 files (1 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- -[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] -[INFO] from metrics-jcstress/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- -[INFO] -[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. -[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. -[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: -[WARNING] - META-INF/AL2.0 -[WARNING] - META-INF/LGPL2.1 -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. -[info] Processed 3 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- -[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] -[INFO] from metrics-jmx/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ -[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] -[INFO] from metrics-legacy-adapter/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,49] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,9] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[108,27] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[112,27] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- -[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java:[25,60] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java:[26,60] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[21,59] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(1.58, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[22,56] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[23,66] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[24,64] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get95thPercentile()).isCloseTo(5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[25,64] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get98thPercentile()).isCloseTo(5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[26,64] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get99thPercentile()).isCloseTo(5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java:[27,65] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.get999thPercentile()).isCloseTo(5, offset(0.01));'? -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java:[25,60] Note: [StaticImport] Identifier should be statically imported - (see https://error-prone.picnic.tech/bugpatterns/StaticImport) - Did you mean 'assertThat(snapshot.getStdDev()).isCloseTo(36.47, offset(0.1));'? -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/metrics-legacy-adapter-5.0.0-rc22.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- -[info] Processed 60 files (4 reformatted). -[INFO] -[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- -[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] -[INFO] from metrics-legacy-adapter-healthchecks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] -[INFO] from metrics-jetty12/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] -[INFO] from metrics-jetty12-ee10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- -[info] Processed 2 files (0 reformatted). -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: -[INFO] -[INFO] Metrics5 Parent .................................... SUCCESS [ 0.391 s] -[INFO] Metrics5 Documentation ............................. SUCCESS [ 1.880 s] -[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.014 s] -[INFO] Annotations for Metrics5 ........................... SUCCESS [ 1.568 s] -[INFO] Metrics5 Core ...................................... SUCCESS [ 22.310 s] -[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 5.459 s] -[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 1.077 s] -[INFO] Metrics Integration for Collectd ................... SUCCESS [ 10.115 s] -[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 4.245 s] -[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 11.673 s] -[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 9.941 s] -[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 9.770 s] -[INFO] Metrics5 Health Checks ............................. SUCCESS [ 10.600 s] -[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 4.977 s] -[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 5.551 s] -[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 4.450 s] -[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 1.031 s] -[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 0.975 s] -[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 7.408 s] -[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 10.104 s] -[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 5.666 s] -[INFO] Metrics Integration for JCache ..................... SUCCESS [ 7.253 s] -[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 3.869 s] -[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 9.938 s] -[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 10.113 s] -[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 10.754 s] -[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 10.424 s] -[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 3.974 s] -[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 4.406 s] -[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 4.368 s] -[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 4.072 s] -[INFO] Metrics Integration for Servlets ................... SUCCESS [ 0.960 s] -[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 5.149 s] -[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 1.683 s] -[INFO] Metrics Integration with JMX ....................... SUCCESS [ 10.200 s] -[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 9.881 s] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 0.890 s] -[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 7.734 s] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 4.772 s] -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 04:00 min -[INFO] Finished at: 2024-11-18T12:55:25+01:00 -[INFO] ------------------------------------------------------------------------ -diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java -index 7b54d0b..b04d203 100644 ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java -@@ -150,9 +150,9 @@ public class CollectdReporter extends ScheduledReporter { - public CollectdReporter build(Sender sender) { - if (securityLevel != SecurityLevel.NONE) { - checkArgument( -- !username.isEmpty(), "username is required for securityLevel: " + securityLevel); -+ !username.isEmpty(), "username is required for securityLevel: %s", securityLevel); - checkArgument( -- !password.isEmpty(), "password is required for securityLevel: " + securityLevel); -+ !password.isEmpty(), "password is required for securityLevel: %s", securityLevel); - } - return new CollectdReporter( - registry, -diff --git a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java -index 764b5f8..8318562 100644 ---- a/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java -+++ b/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java -@@ -4,6 +4,7 @@ import static com.google.common.base.Preconditions.checkState; - import static java.nio.charset.StandardCharsets.US_ASCII; - import static java.nio.charset.StandardCharsets.UTF_8; - -+import com.google.common.base.Strings; - import java.io.IOException; - import java.nio.BufferOverflowException; - import java.nio.ByteBuffer; -@@ -122,7 +123,7 @@ class PacketWriter { - } - - private void writeString(ByteBuffer buffer, int type, String val) { -- if (val == null || val.isEmpty()) { -+ if (Strings.isNullOrEmpty(val)) { - return; - } - int len = HEADER_LEN + val.length() + 1; -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java -index 6e22c83..257a72b 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/ConsoleReporter.java -@@ -1,6 +1,5 @@ - package io.dropwizard.metrics5; - -- - import com.google.common.collect.ImmutableSet; - import java.io.PrintStream; - import java.text.DateFormat; -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java -index 43690af..bf4470b 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/LockFreeExponentiallyDecayingReservoir.java -@@ -238,7 +238,7 @@ public final class LockFreeExponentiallyDecayingReservoir implements Reservoir { - */ - public Builder size(int value) { - checkArgument( -- value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: " + value); -+ value > 0, "LockFreeExponentiallyDecayingReservoir size must be positive: %s", value); - this.size = value; - return this; - } -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java -index 28c6a60..8a478d9 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/UniformSnapshot.java -@@ -50,7 +50,8 @@ public class UniformSnapshot extends Snapshot { - public double getValue(double quantile) { - checkArgument( - quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), -- quantile + " is not in [0..1]"); -+ "%s is not in [0..1]", -+ quantile); - - if (values.length == 0) { - return 0.0; -diff --git a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java -index 156bd3c..3e5c339 100644 ---- a/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java -+++ b/metrics-core/src/main/java/io/dropwizard/metrics5/WeightedSnapshot.java -@@ -67,7 +67,8 @@ public class WeightedSnapshot extends Snapshot { - public double getValue(double quantile) { - checkArgument( - quantile >= 0.0 && quantile <= 1.0 && !Double.isNaN(quantile), -- quantile + " is not in [0..1]"); -+ "%s is not in [0..1]", -+ quantile); - - if (values.length == 0) { - return 0.0; -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java -index 356b1a5..8c2720a 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java -@@ -121,7 +121,7 @@ final class CachedGaugeTest { - } - - for (int i = 0; i < futures.size(); i++) { -- assertThat(futures.get(i).get()).withFailMessage("Future " + i + " failed").isTrue(); -+ assertThat(futures.get(i).get()).withFailMessage("Future %s failed", i).isTrue(); - } - - executor.shutdown(); -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java -index 35860d7..286e40f 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java -@@ -87,10 +87,10 @@ final class MetricNameTest { - final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); - final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); - -- assertThat(a.compareTo(b)).isNegative(); -- assertThat(b.compareTo(a)).isPositive(); -- assertThat(b.resolve("key").compareTo(b)).isPositive(); -- assertThat(b.compareTo(b.resolve("key"))).isNegative(); -+ assertThat(a).isLessThan(b); -+ assertThat(b).isGreaterThan(a); -+ assertThat(b.resolve("key")).isGreaterThan(b); -+ assertThat(b).isLessThan(b.resolve("key")); - } - - @Test -@@ -98,9 +98,9 @@ final class MetricNameTest { - final MetricName a = MetricName.EMPTY.tagged("a", "x"); - final MetricName b = MetricName.EMPTY.tagged("b", "x"); - -- assertThat(MetricName.EMPTY.compareTo(a)).isNegative(); -- assertThat(MetricName.EMPTY.compareTo(b)).isNegative(); -- assertThat(a.compareTo(b)).isNegative(); -- assertThat(b.compareTo(a)).isPositive(); -+ assertThat(MetricName.EMPTY).isLessThan(a); -+ assertThat(MetricName.EMPTY).isLessThan(b); -+ assertThat(a).isLessThan(b); -+ assertThat(b).isGreaterThan(a); - } - } -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java -index d79a191..dddda8d 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java -@@ -12,7 +12,6 @@ import static org.mockito.Mockito.verify; - import java.util.HashMap; - import java.util.Map; - import java.util.Set; --import java.util.stream.Collectors; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - -@@ -505,7 +504,7 @@ final class MetricRegistryTest { - .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) -- .collect(Collectors.toSet())); -+ .collect(toImmutableSet())); - } - - @Test -@@ -526,7 +525,7 @@ final class MetricRegistryTest { - .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) -- .collect(Collectors.toSet())); -+ .collect(toImmutableSet())); - } - - @Test -@@ -552,7 +551,7 @@ final class MetricRegistryTest { - .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) -- .collect(Collectors.toSet())); -+ .collect(toImmutableSet())); - - assertThat(childMetrics) - .containsAll( -@@ -582,7 +581,7 @@ final class MetricRegistryTest { - .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) -- .collect(Collectors.toSet())); -+ .collect(toImmutableSet())); - - assertThat(childMetrics).doesNotContain(MetricName.build("test-1")); - } -@@ -608,7 +607,7 @@ final class MetricRegistryTest { - .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) -- .collect(Collectors.toSet())); -+ .collect(toImmutableSet())); - - assertThat(childMetrics).doesNotContain(MetricName.build("test-1"), MetricName.build("test-3")); - } -@@ -637,7 +636,7 @@ final class MetricRegistryTest { - .hasSameElementsAs( - childMetrics.stream() - .map(m -> MetricName.build("child", m.getKey())) -- .collect(Collectors.toSet())); -+ .collect(toImmutableSet())); - - assertThat(childMetrics) - .containsAll( -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java -index a3e7329..59c187f 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java -@@ -2,6 +2,7 @@ package io.dropwizard.metrics5; - - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatThrownBy; -+import static org.assertj.core.api.Assertions.fail; - import static org.junit.jupiter.api.Assertions.assertEquals; - import static org.mockito.Mockito.any; - import static org.mockito.Mockito.eq; -@@ -19,7 +20,6 @@ import java.util.concurrent.ScheduledExecutorService; - import java.util.concurrent.TimeUnit; - import java.util.concurrent.TimeoutException; - import java.util.concurrent.atomic.AtomicInteger; --import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; -@@ -106,7 +106,7 @@ final class ScheduledReporterTest { - r = - new DummyReporter( - null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); -- Assertions.fail("NullPointerException must be thrown !!!"); -+ fail("NullPointerException must be thrown !!!"); - } catch (NullPointerException e) { - assertEquals("registry == null", e.getMessage()); - } finally { -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java -index 052948c..b059444 100644 ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java -@@ -21,7 +21,9 @@ final class WeightedSnapshotTest { - long[] values, double[] weights) { - checkArgument( - values.length == weights.length, -- "Mismatched lengths: " + values.length + " vs " + weights.length); -+ "Mismatched lengths: %s vs %s", -+ values.length, -+ weights.length); - - final List samples = new ArrayList<>(); - for (int i = 0; i < values.length; i++) { -diff --git a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java -index 8dfe5cf..36efd52 100644 ---- a/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java -+++ b/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java -@@ -5,6 +5,7 @@ import static com.google.common.base.Preconditions.checkState; - import static java.nio.charset.StandardCharsets.UTF_8; - import static java.util.Objects.requireNonNull; - -+import com.google.common.base.Strings; - import java.io.BufferedWriter; - import java.io.IOException; - import java.io.OutputStreamWriter; -@@ -65,7 +66,7 @@ public class Graphite implements GraphiteSender { - * @param charset the character set used by the server - */ - public Graphite(String hostname, int port, SocketFactory socketFactory, Charset charset) { -- checkArgument(hostname != null && !hostname.isEmpty(), "hostname must not be null or empty"); -+ checkArgument(!Strings.isNullOrEmpty(hostname), "hostname must not be null or empty"); - - checkArgument(port >= 0 && port <= 65535, "port must be a valid IP port (0-65535)"); - -diff --git a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java -index 77b1e1e..467fc76 100644 ---- a/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java -+++ b/metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java -@@ -95,7 +95,7 @@ public class HealthCheckRegistry { - HealthCheck registered; - synchronized (lock) { - checkArgument( -- !healthChecks.containsKey(name), "A health check named " + name + " already exists"); -+ !healthChecks.containsKey(name), "A health check named %s already exists", name); - registered = healthCheck; - if (healthCheck.getClass().isAnnotationPresent(Async.class)) { - registered = new AsyncHealthCheckDecorator(healthCheck, asyncExecutorService); -diff --git a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java -index 44f52fa..833855e 100644 ---- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java -+++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics5.httpasyncclient; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; -@@ -19,7 +20,6 @@ import org.apache.http.client.methods.HttpGet; - import org.apache.http.concurrent.FutureCallback; - import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; - import org.apache.http.nio.client.HttpAsyncClient; --import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Disabled; - import org.junit.jupiter.api.Test; -@@ -118,7 +118,7 @@ final class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { - - try { - responseFuture.get(20, TimeUnit.SECONDS); -- Assertions.fail("This should fail as the client should not be able to connect"); -+ fail("This should fail as the client should not be able to connect"); - } catch (Exception e) { - // Ignore - } -diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java -index e5c7259..905b1a5 100644 ---- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics5.httpclient; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; -@@ -18,7 +19,6 @@ import org.apache.http.HttpRequest; - import org.apache.http.NoHttpResponseException; - import org.apache.http.client.HttpClient; - import org.apache.http.client.methods.HttpGet; --import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - -@@ -66,7 +66,7 @@ final class InstrumentedHttpClientsTest { - - try { - client.execute(get); -- Assertions.fail(); -+ fail(); - } catch (NoHttpResponseException expected) { - assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); - } finally { -diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java -index b67225a..ee5ceb2 100644 ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java -@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.httpclient5; - - import static java.nio.charset.StandardCharsets.US_ASCII; - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; - import static org.awaitility.Awaitility.await; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; -@@ -30,7 +31,6 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; - import org.apache.hc.core5.concurrent.FutureCallback; - import org.apache.hc.core5.http.ConnectionClosedException; - import org.apache.hc.core5.http.HttpRequest; --import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.AfterEach; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; -@@ -101,12 +101,12 @@ final class InstrumentedHttpAsyncClientsTest { - - @Override - public void failed(Exception ex) { -- Assertions.fail(); -+ fail(); - } - - @Override - public void cancelled() { -- Assertions.fail(); -+ fail(); - } - }); - responseFuture.get(1L, TimeUnit.SECONDS); -@@ -144,7 +144,7 @@ final class InstrumentedHttpAsyncClientsTest { - new FutureCallback() { - @Override - public void completed(SimpleHttpResponse result) { -- Assertions.fail(); -+ fail(); - } - - @Override -@@ -154,13 +154,13 @@ final class InstrumentedHttpAsyncClientsTest { - - @Override - public void cancelled() { -- Assertions.fail(); -+ fail(); - } - }); - countDownLatch.await(5, TimeUnit.SECONDS); - responseFuture.get(5, TimeUnit.SECONDS); - -- Assertions.fail(); -+ fail(); - } catch (ExecutionException e) { - assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class); - await() -@@ -211,12 +211,12 @@ final class InstrumentedHttpAsyncClientsTest { - - @Override - public void failed(Exception ex) { -- Assertions.fail(); -+ fail(); - } - - @Override - public void cancelled() { -- Assertions.fail(); -+ fail(); - } - }); - responseFuture.get(1L, TimeUnit.SECONDS); -diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java -index 46cdc5e..c935e61 100644 ---- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java -+++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics5.httpclient5; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; - import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; -@@ -18,7 +19,6 @@ import org.apache.hc.client5.http.classic.HttpClient; - import org.apache.hc.client5.http.classic.methods.HttpGet; - import org.apache.hc.core5.http.HttpRequest; - import org.apache.hc.core5.http.NoHttpResponseException; --import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - -@@ -66,7 +66,7 @@ final class InstrumentedHttpClientsTest { - - try { - client.execute(get); -- Assertions.fail(); -+ fail(); - } catch (NoHttpResponseException expected) { - assertThat(metricRegistry.getMeters()).containsKey(MetricName.build("exception")); - } finally { -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -index e8208b0..df10b41 100644 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -@@ -220,8 +220,8 @@ final class HealthCheckServletTest extends AbstractServletTest { - throws Exception { - assertThatThrownBy( - () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); -diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -index d74900f..67d9741 100644 ---- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -+++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.servlets; - - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatThrownBy; --import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; - import static org.mockito.Mockito.verify; -@@ -241,10 +240,10 @@ final class MetricsServletTest extends AbstractServletTest { - throws Exception { - assertThatThrownBy( - () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); - - final MetricsServlet metricsServlet = new MetricsServlet(null); -diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -index eeec0da..01abf40 100644 ---- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -1,6 +1,7 @@ - package io.dropwizard.metrics5.jersey2; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; - - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -10,7 +11,6 @@ import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceResponseM - import java.util.logging.Level; - import java.util.logging.Logger; - import javax.ws.rs.core.Application; --import org.assertj.core.api.Assertions; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; -@@ -107,7 +107,7 @@ final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest - void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { - try { - target("responseMeteredRuntimeExceptionPerClass").request().get(); -- Assertions.fail("expected RuntimeException"); -+ fail("expected RuntimeException"); - } catch (Exception e) { - assertThat(e.getCause()).isInstanceOf(RuntimeException.class); - } -diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -index 00e401f..272caf0 100644 ---- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.jersey3; - - import static io.dropwizard.metrics5.MetricRegistry.name; - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; - - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -11,7 +12,6 @@ import io.dropwizard.metrics5.jersey3.resources.InstrumentedSubResourceResponseM - import jakarta.ws.rs.core.Application; - import java.util.logging.Level; - import java.util.logging.Logger; --import org.assertj.core.api.Assertions; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; -@@ -108,7 +108,7 @@ final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest - void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { - try { - target("responseMeteredRuntimeExceptionPerClass").request().get(); -- Assertions.fail("expected RuntimeException"); -+ fail("expected RuntimeException"); - } catch (Exception e) { - assertThat(e.getCause()).isInstanceOf(RuntimeException.class); - } -diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -index fdd0440..e7d6d3c 100644 ---- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -+++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java -@@ -2,6 +2,7 @@ package io.dropwizard.metrics5.jersey31; - - import static io.dropwizard.metrics5.MetricRegistry.name; - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.api.Assertions.fail; - - import io.dropwizard.metrics5.Meter; - import io.dropwizard.metrics5.MetricRegistry; -@@ -11,7 +12,6 @@ import io.dropwizard.metrics5.jersey31.resources.InstrumentedSubResourceResponse - import jakarta.ws.rs.core.Application; - import java.util.logging.Level; - import java.util.logging.Logger; --import org.assertj.core.api.Assertions; - import org.glassfish.jersey.server.ResourceConfig; - import org.glassfish.jersey.test.JerseyTest; - import org.junit.jupiter.api.Test; -@@ -108,7 +108,7 @@ final class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest - void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { - try { - target("responseMeteredRuntimeExceptionPerClass").request().get(); -- Assertions.fail("expected RuntimeException"); -+ fail("expected RuntimeException"); - } catch (Exception e) { - assertThat(e.getCause()).isInstanceOf(RuntimeException.class); - } -diff --git a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java -index 0c6cfcf..7db5876 100644 ---- a/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java -+++ b/metrics-json/src/main/java/io/dropwizard/metrics5/json/HealthCheckModule.java -@@ -1,6 +1,5 @@ - package io.dropwizard.metrics5.json; - -- - import com.fasterxml.jackson.core.JsonGenerator; - import com.fasterxml.jackson.core.Version; - import com.fasterxml.jackson.databind.Module; -diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java -index 019d29c..7f25d68 100644 ---- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java -+++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java -@@ -8,7 +8,6 @@ import static org.mockito.Mockito.when; - import com.sun.management.UnixOperatingSystemMXBean; - import java.lang.management.ManagementFactory; - import java.lang.management.OperatingSystemMXBean; --import org.assertj.core.api.Assertions; - import org.junit.jupiter.api.BeforeEach; - import org.junit.jupiter.api.Test; - -@@ -34,9 +33,7 @@ final class FileDescriptorRatioGaugeTest { - OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); - assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); - -- Assertions.assertThat(new FileDescriptorRatioGauge().getValue()) -- .isNotNegative() -- .isLessThanOrEqualTo(1.0); -+ assertThat(new FileDescriptorRatioGauge().getValue()).isNotNegative().isLessThanOrEqualTo(1.0); - } - - @Test -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -index 39c5242..b57f137 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java -@@ -1,8 +1,8 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; - --import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") -@@ -22,7 +22,7 @@ final class ExponentiallyDecayingReservoirTest { - assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); - assertThat(snapshot.getMin()).isEqualTo(120); - assertThat(snapshot.getMax()).isEqualTo(200); -- assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1)); -+ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); - assertThat(snapshot.get75thPercentile()).isEqualTo(190); - assertThat(snapshot.get95thPercentile()).isEqualTo(200); - assertThat(snapshot.get98thPercentile()).isEqualTo(200); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java -index a141c70..db5f29b 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java -@@ -1,8 +1,8 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; - --import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") -@@ -23,7 +23,7 @@ final class HistogramTest { - assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); - assertThat(snapshot.getMin()).isEqualTo(120); - assertThat(snapshot.getMax()).isEqualTo(200); -- assertThat(snapshot.getStdDev()).isCloseTo(32.62, Offset.offset(0.1)); -+ assertThat(snapshot.getStdDev()).isCloseTo(32.62, offset(0.1)); - assertThat(snapshot.get75thPercentile()).isEqualTo(190); - assertThat(snapshot.get95thPercentile()).isEqualTo(200); - assertThat(snapshot.get98thPercentile()).isEqualTo(200); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java -index 24a6ae0..77cbdf1 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java -@@ -1,10 +1,10 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; - - import io.dropwizard.metrics5.UniformSnapshot; - import java.io.ByteArrayOutputStream; --import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") -@@ -18,13 +18,13 @@ final class SnapshotTest { - assertThat(snapshot.size()).isEqualTo(5); - assertThat(snapshot.getMin()).isEqualTo(1); - assertThat(snapshot.getMax()).isEqualTo(5); -- assertThat(snapshot.getStdDev()).isCloseTo(1.58, Offset.offset(0.01)); -- assertThat(snapshot.getMedian()).isCloseTo(3, Offset.offset(0.01)); -- assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, Offset.offset(0.01)); -- assertThat(snapshot.get95thPercentile()).isCloseTo(5, Offset.offset(0.01)); -- assertThat(snapshot.get98thPercentile()).isCloseTo(5, Offset.offset(0.01)); -- assertThat(snapshot.get99thPercentile()).isCloseTo(5, Offset.offset(0.01)); -- assertThat(snapshot.get999thPercentile()).isCloseTo(5, Offset.offset(0.01)); -+ assertThat(snapshot.getStdDev()).isCloseTo(1.58, offset(0.01)); -+ assertThat(snapshot.getMedian()).isCloseTo(3, offset(0.01)); -+ assertThat(snapshot.get75thPercentile()).isCloseTo(4.5, offset(0.01)); -+ assertThat(snapshot.get95thPercentile()).isCloseTo(5, offset(0.01)); -+ assertThat(snapshot.get98thPercentile()).isCloseTo(5, offset(0.01)); -+ assertThat(snapshot.get99thPercentile()).isCloseTo(5, offset(0.01)); -+ assertThat(snapshot.get999thPercentile()).isCloseTo(5, offset(0.01)); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - snapshot.dump(baos); -diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java -index 0668c1e..01fb3d6 100644 ---- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java -+++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java -@@ -1,8 +1,8 @@ - package com.codahale.metrics; - - import static org.assertj.core.api.Assertions.assertThat; -+import static org.assertj.core.data.Offset.offset; - --import org.assertj.core.data.Offset; - import org.junit.jupiter.api.Test; - - @SuppressWarnings("deprecation") -@@ -22,7 +22,7 @@ final class UniformReservoirTest { - assertThat(snapshot.getValues()).contains(120, 130, 140, 190, 200); - assertThat(snapshot.getMin()).isEqualTo(120); - assertThat(snapshot.getMax()).isEqualTo(200); -- assertThat(snapshot.getStdDev()).isCloseTo(36.47, Offset.offset(0.1)); -+ assertThat(snapshot.getStdDev()).isCloseTo(36.47, offset(0.1)); - assertThat(snapshot.get75thPercentile()).isEqualTo(195); - assertThat(snapshot.get95thPercentile()).isEqualTo(200); - assertThat(snapshot.get98thPercentile()).isEqualTo(200); -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -index 80b40f1..5aa0027 100644 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java -@@ -220,8 +220,8 @@ final class HealthCheckServletTest extends AbstractServletTest { - throws Exception { - assertThatThrownBy( - () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); -diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -index 78086f5..39bdcf2 100644 ---- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -+++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java -@@ -2,7 +2,6 @@ package io.dropwizard.metrics5.servlets; - - import static org.assertj.core.api.Assertions.assertThat; - import static org.assertj.core.api.Assertions.assertThatThrownBy; --import static org.mockito.ArgumentMatchers.eq; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.never; - import static org.mockito.Mockito.verify; -@@ -241,10 +240,10 @@ final class MetricsServletTest extends AbstractServletTest { - throws Exception { - assertThatThrownBy( - () -> { -- final ServletContext servletContext = mock(ServletContext.class); -- final ServletConfig servletConfig = mock(ServletConfig.class); -+ final ServletContext servletContext = mock(); -+ final ServletConfig servletConfig = mock(); - when(servletConfig.getServletContext()).thenReturn(servletContext); -- when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) -+ when(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); - - final MetricsServlet metricsServlet = new MetricsServlet(null); -[detached HEAD 01cbee7] minor: Apply patches - 30 files changed, 77 insertions(+), 79 deletions(-) -[INFO] Scanning for projects... -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Build Order: -[INFO] -[INFO] Metrics5 Parent [pom] -[INFO] Metrics5 Documentation [jar] -[INFO] Metrics5 BOM [pom] -[INFO] Annotations for Metrics5 [bundle] -[INFO] Metrics5 Core [bundle] -[INFO] Benchmarks for Metrics5 [jar] -[INFO] Metrics Integration for Caffeine 3.x [bundle] -[INFO] Metrics Integration for Collectd [bundle] -[INFO] Metrics Integration for Ehcache [bundle] -[INFO] Graphite Integration for Metrics5 [bundle] -[INFO] InfluxDB integration for Metrics5 [bundle] -[INFO] JVM Integration for Metrics5 [bundle] -[INFO] Metrics5 Health Checks [bundle] -[INFO] Metrics Integration for Apache HttpClient [bundle] -[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] -[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] -[INFO] Metrics Integration for Jakarta Servlets [bundle] -[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] -[INFO] Jackson Integration for Metrics5 [bundle] -[INFO] Metrics Integration for Jetty 11.x and higher [bundle] -[INFO] Metrics5 Utility Jakarta Servlets [bundle] -[INFO] Metrics Integration for JCache [bundle] -[INFO] Metrics Integration for JDBI3 [bundle] -[INFO] Metrics Integration for Jersey 2.x [bundle] -[INFO] Metrics Integration for Jersey 3.0.x [bundle] -[INFO] Metrics Integration for Jersey 3.1.x [bundle] -[INFO] Metrics Integration for Jetty 10.x and higher [bundle] -[INFO] Metrics Integration for Log4j 2.x [bundle] -[INFO] Metrics Integration for Logback 1.3.x [bundle] -[INFO] Metrics Integration for Logback 1.4.x [bundle] -[INFO] Metrics Integration for Logback 1.5.x [bundle] -[INFO] Metrics Integration for Servlets [bundle] -[INFO] Metrics5 Utility Servlets [bundle] -[INFO] Metrics5 JCStress tests [jar] -[INFO] Metrics Integration with JMX [bundle] -[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] -[INFO] Metrics Integration for Jetty 12.x and higher [bundle] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- -[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] -[INFO] from pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- -[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] -[INFO] from docs/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec -[INFO] -[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- -[INFO] -[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- -[INFO] Copying 72 resources from source to target/source -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- -[INFO] Copying 72 resources from source to target/classes -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ docs --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- -[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. -[info] Processed 0 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- -[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] -[INFO] from metrics-bom/pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- -[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] -[INFO] from metrics-annotation/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. -[info] Processed 9 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- -[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] -[INFO] from metrics-core/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- -[info] Processed 87 files (0 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- -[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] -[INFO] from metrics-benchmarks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- -[INFO] -[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. -[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- -[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] -[INFO] from metrics-caffeine3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- -[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] -[INFO] from metrics-collectd/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- -[info] Processed 12 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- -[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] -[INFO] from metrics-ehcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- -[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] -[INFO] from metrics-graphite/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- -[info] Processed 13 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- -[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] -[INFO] from metrics-influxdb/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- -[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] -[INFO] from metrics-jvm/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- -[info] Processed 23 files (0 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- -[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] -[INFO] from metrics-healthchecks/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- -[info] Processed 14 files (0 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] -[INFO] from metrics-httpclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] -[INFO] from metrics-httpclient5/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- -[info] Processed 13 files (0 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- -[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] -[INFO] from metrics-httpasyncclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] -[INFO] from metrics-jakarta-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] -[INFO] from metrics-jakarta-servlet6/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- -[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] -[INFO] from metrics-json/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- -[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] -[INFO] from metrics-jetty11/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- -[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] -[INFO] from metrics-jakarta-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- -[info] Processed 17 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- -[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] -[INFO] from metrics-jcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- -[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] -[INFO] from metrics-jdbi3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- -[info] Processed 15 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- -[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] -[INFO] from metrics-jersey2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- -[info] Processed 24 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- -[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] -[INFO] from metrics-jersey3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- -[info] Processed 24 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- -[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] -[INFO] from metrics-jersey31/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- -[info] Processed 24 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- -[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] -[INFO] from metrics-jetty10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- -[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] -[INFO] from metrics-log4j2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- -[info] Processed 3 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- -[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] -[INFO] from metrics-logback13/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- -[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] -[INFO] from metrics-logback14/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- -[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] -[INFO] from metrics-logback15/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- -[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] -[INFO] from metrics-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- -[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] -[INFO] from metrics-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- -[info] Processed 16 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- -[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] -[INFO] from metrics-jcstress/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- -[INFO] -[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. -[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. -[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: -[WARNING] - META-INF/AL2.0 -[WARNING] - META-INF/LGPL2.1 -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. -[info] Processed 3 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- -[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] -[INFO] from metrics-jmx/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ -[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] -[INFO] from metrics-legacy-adapter/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- -[info] Processed 60 files (0 reformatted). -[INFO] -[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- -[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] -[INFO] from metrics-legacy-adapter-healthchecks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] -[INFO] from metrics-jetty12/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] -[INFO] from metrics-jetty12-ee10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- -[INFO] Nothing to compile - all classes are up to date. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- -[info] Processed 2 files (0 reformatted). -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: -[INFO] -[INFO] Metrics5 Parent .................................... SUCCESS [ 0.360 s] -[INFO] Metrics5 Documentation ............................. SUCCESS [ 1.633 s] -[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.010 s] -[INFO] Annotations for Metrics5 ........................... SUCCESS [ 1.490 s] -[INFO] Metrics5 Core ...................................... SUCCESS [ 11.952 s] -[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 1.680 s] -[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 1.138 s] -[INFO] Metrics Integration for Collectd ................... SUCCESS [ 1.143 s] -[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 1.143 s] -[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 4.578 s] -[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 1.134 s] -[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 4.038 s] -[INFO] Metrics5 Health Checks ............................. SUCCESS [ 1.171 s] -[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 3.962 s] -[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 5.074 s] -[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 4.234 s] -[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 1.043 s] -[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 0.974 s] -[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 4.146 s] -[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 1.212 s] -[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 4.821 s] -[INFO] Metrics Integration for JCache ..................... SUCCESS [ 1.155 s] -[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 1.069 s] -[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 4.570 s] -[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 4.438 s] -[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 4.365 s] -[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 1.063 s] -[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 1.018 s] -[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 1.002 s] -[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 1.031 s] -[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 0.990 s] -[INFO] Metrics Integration for Servlets ................... SUCCESS [ 0.951 s] -[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 4.621 s] -[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 1.508 s] -[INFO] Metrics Integration with JMX ....................... SUCCESS [ 1.102 s] -[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 4.456 s] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 0.861 s] -[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 1.028 s] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 1.186 s] -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 01:34 min -[INFO] Finished at: 2024-11-18T12:57:00+01:00 -[INFO] ------------------------------------------------------------------------ -[INFO] Scanning for projects... -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Build Order: -[INFO] -[INFO] Metrics5 Parent [pom] -[INFO] Metrics5 Documentation [jar] -[INFO] Metrics5 BOM [pom] -[INFO] Annotations for Metrics5 [bundle] -[INFO] Metrics5 Core [bundle] -[INFO] Benchmarks for Metrics5 [jar] -[INFO] Metrics Integration for Caffeine 3.x [bundle] -[INFO] Metrics Integration for Collectd [bundle] -[INFO] Metrics Integration for Ehcache [bundle] -[INFO] Graphite Integration for Metrics5 [bundle] -[INFO] InfluxDB integration for Metrics5 [bundle] -[INFO] JVM Integration for Metrics5 [bundle] -[INFO] Metrics5 Health Checks [bundle] -[INFO] Metrics Integration for Apache HttpClient [bundle] -[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] -[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] -[INFO] Metrics Integration for Jakarta Servlets [bundle] -[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] -[INFO] Jackson Integration for Metrics5 [bundle] -[INFO] Metrics Integration for Jetty 11.x and higher [bundle] -[INFO] Metrics5 Utility Jakarta Servlets [bundle] -[INFO] Metrics Integration for JCache [bundle] -[INFO] Metrics Integration for JDBI3 [bundle] -[INFO] Metrics Integration for Jersey 2.x [bundle] -[INFO] Metrics Integration for Jersey 3.0.x [bundle] -[INFO] Metrics Integration for Jersey 3.1.x [bundle] -[INFO] Metrics Integration for Jetty 10.x and higher [bundle] -[INFO] Metrics Integration for Log4j 2.x [bundle] -[INFO] Metrics Integration for Logback 1.3.x [bundle] -[INFO] Metrics Integration for Logback 1.4.x [bundle] -[INFO] Metrics Integration for Logback 1.5.x [bundle] -[INFO] Metrics Integration for Servlets [bundle] -[INFO] Metrics5 Utility Servlets [bundle] -[INFO] Metrics5 JCStress tests [jar] -[INFO] Metrics Integration with JMX [bundle] -[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] -[INFO] Metrics Integration for Jetty 12.x and higher [bundle] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- -[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] -[INFO] from pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-parent --- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-parent --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- -[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] -[INFO] from docs/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ docs --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec -[INFO] -[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- -[INFO] -[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- -[INFO] Copying 72 resources from source to target/source -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- -[INFO] Copying 72 resources from source to target/classes -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ docs --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/docs-5.0.0-rc22.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ docs --- -[WARNING] Source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/main/java' does not exist, ignoring. -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/java' does not exist, ignoring. -[info] Processed 0 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- -[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] -[INFO] from metrics-bom/pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-bom --- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-bom --- -[INFO] Skipping format check: project uses 'pom' packaging -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- -[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] -[INFO] from metrics-annotation/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-annotation --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- -[INFO] Recompiling the module because of changed source code. -[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-annotation --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/java' does not exist, ignoring. -[info] Processed 9 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- -[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] -[INFO] from metrics-core/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-core --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- -[INFO] Recompiling the module because of changed source code. -[INFO] Compiling 49 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[56,27] [this-escape] possible 'this' escape before subclass is fully initialized -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 38 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-core --- -[info] Processed 87 files (0 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- -[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] -[INFO] from metrics-benchmarks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-benchmarks --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22.jar -[INFO] -[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. -[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-benchmarks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/java' does not exist, ignoring. -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- -[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] -[INFO] from metrics-caffeine3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-caffeine3 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-caffeine3 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- -[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] -[INFO] from metrics-collectd/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-collectd --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-collectd --- -[info] Processed 12 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- -[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] -[INFO] from metrics-ehcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-ehcache --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-ehcache --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- -[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] -[INFO] from metrics-graphite/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-graphite --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-graphite --- -[info] Processed 13 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- -[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] -[INFO] from metrics-influxdb/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-influxdb --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-influxdb --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- -[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] -[INFO] from metrics-jvm/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jvm --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 12 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[74,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[83,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[92,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jvm --- -[info] Processed 23 files (0 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- -[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] -[INFO] from metrics-healthchecks/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-healthchecks --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-healthchecks --- -[info] Processed 14 files (0 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] -[INFO] from metrics-httpclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpclient --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java:[114,8] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] -[INFO] from metrics-httpclient5/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpclient5 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[14,40] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[15,40] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[16,37] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[30,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[31,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[32,37] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[33,38] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[96,21] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[160,12] [deprecation] DefaultHttpClientConnectionOperator(Lookup,SchemePortResolver,DnsResolver) in DefaultHttpClientConnectionOperator has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java:[49,4] [deprecation] HttpRequestExecutor(Timeout,ConnectionReuseStrategy,Http1StreamListener) in HttpRequestExecutor has been deprecated -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpclient5 --- -[info] Processed 13 files (0 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- -[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] -[INFO] from metrics-httpasyncclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpasyncclient --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java:[40,8] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-httpasyncclient --- -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] -[INFO] from metrics-jakarta-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlet --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] -[INFO] from metrics-jakarta-servlet6/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlet6 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlet6 --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- -[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] -[INFO] from metrics-json/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-json --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java:[189,31] [serial] non-transient instance field of a serializable class declared with a non-serializable type -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-json --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- -[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] -[INFO] from metrics-jetty11/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty11 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty11 --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- -[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] -[INFO] from metrics-jakarta-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlets --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jakarta-servlets --- -[info] Processed 17 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- -[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] -[INFO] from metrics-jcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jcache --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcache --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- -[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] -[INFO] from metrics-jdbi3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jdbi3 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jdbi3 --- -[info] Processed 15 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- -[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] -[INFO] from metrics-jersey2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey2 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey2 --- -[info] Processed 24 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- -[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] -[INFO] from metrics-jersey3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey3 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey3 --- -[info] Processed 24 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- -[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] -[INFO] from metrics-jersey31/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey31 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jersey31 --- -[info] Processed 24 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- -[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] -[INFO] from metrics-jetty10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty10 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty10 --- -[info] Processed 8 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- -[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] -[INFO] from metrics-log4j2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-log4j2 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-log4j2 --- -[info] Processed 3 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- -[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] -[INFO] from metrics-logback13/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback13 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback13 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- -[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] -[INFO] from metrics-logback14/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback14 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback14 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- -[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] -[INFO] from metrics-logback15/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback15 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-logback15 --- -[info] Processed 2 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- -[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] -[INFO] from metrics-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-servlet --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlet --- -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- -[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] -[INFO] from metrics-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-servlets --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 10 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-servlets --- -[info] Processed 16 files (0 reformatted). -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- -[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] -[INFO] from metrics-jcstress/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jcstress --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22.jar -[INFO] -[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. -[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. -[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: -[WARNING] - META-INF/AL2.0 -[WARNING] - META-INF/LGPL2.1 -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jcstress --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/java' does not exist, ignoring. -[info] Processed 3 files (0 reformatted). -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- -[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] -[INFO] from metrics-jmx/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jmx --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jmx --- -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ -[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] -[INFO] from metrics-legacy-adapter/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-legacy-adapter --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 36 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,49] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,9] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[108,27] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[112,27] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 24 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[50,4] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[367,22] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/metrics-legacy-adapter-5.0.0-rc22.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter --- -[info] Processed 60 files (0 reformatted). -[INFO] -[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- -[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] -[INFO] from metrics-legacy-adapter-healthchecks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-legacy-adapter-healthchecks --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/metrics-legacy-adapter-healthchecks-5.0.0-rc22.jar -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-legacy-adapter-healthchecks --- -[WARNING] Test source directory '/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/java' does not exist, ignoring. -[info] Processed 4 files (0 reformatted). -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] -[INFO] from metrics-jetty12/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty12 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12 --- -[info] Processed 5 files (0 reformatted). -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] -[INFO] from metrics-jetty12-ee10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty12-ee10 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- -[INFO] Tests are skipped. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --- fmt:2.21.1:format (default-cli) @ metrics-jetty12-ee10 --- -[info] Processed 2 files (0 reformatted). -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: -[INFO] -[INFO] Metrics5 Parent .................................... SUCCESS [ 0.418 s] -[INFO] Metrics5 Documentation ............................. SUCCESS [ 1.391 s] -[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.011 s] -[INFO] Annotations for Metrics5 ........................... SUCCESS [ 4.821 s] -[INFO] Metrics5 Core ...................................... SUCCESS [ 28.095 s] -[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 6.099 s] -[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 8.141 s] -[INFO] Metrics Integration for Collectd ................... SUCCESS [ 11.672 s] -[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 8.411 s] -[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 13.436 s] -[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 11.847 s] -[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 11.927 s] -[INFO] Metrics5 Health Checks ............................. SUCCESS [ 12.779 s] -[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 8.383 s] -[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 9.257 s] -[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 7.406 s] -[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 6.872 s] -[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 6.500 s] -[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 7.977 s] -[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 9.592 s] -[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 10.249 s] -[INFO] Metrics Integration for JCache ..................... SUCCESS [ 6.698 s] -[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 8.201 s] -[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 10.156 s] -[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 9.897 s] -[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 10.378 s] -[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 10.002 s] -[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 6.949 s] -[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 6.816 s] -[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 6.705 s] -[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 6.484 s] -[INFO] Metrics Integration for Servlets ................... SUCCESS [ 6.860 s] -[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 9.801 s] -[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 4.324 s] -[INFO] Metrics Integration with JMX ....................... SUCCESS [ 8.759 s] -[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 13.046 s] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 4.518 s] -[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 8.373 s] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 7.795 s] -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 05:31 min -[INFO] Finished at: 2024-11-18T13:02:34+01:00 -[INFO] ------------------------------------------------------------------------ -[INFO] Scanning for projects... -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Build Order: -[INFO] -[INFO] Metrics5 Parent [pom] -[INFO] Metrics5 Documentation [jar] -[INFO] Metrics5 BOM [pom] -[INFO] Annotations for Metrics5 [bundle] -[INFO] Metrics5 Core [bundle] -[INFO] Benchmarks for Metrics5 [jar] -[INFO] Metrics Integration for Caffeine 3.x [bundle] -[INFO] Metrics Integration for Collectd [bundle] -[INFO] Metrics Integration for Ehcache [bundle] -[INFO] Graphite Integration for Metrics5 [bundle] -[INFO] InfluxDB integration for Metrics5 [bundle] -[INFO] JVM Integration for Metrics5 [bundle] -[INFO] Metrics5 Health Checks [bundle] -[INFO] Metrics Integration for Apache HttpClient [bundle] -[INFO] Metrics Integration for Apache HttpClient 5.x [bundle] -[INFO] Metrics Integration for Apache HttpAsyncClient [bundle] -[INFO] Metrics Integration for Jakarta Servlets [bundle] -[INFO] Metrics Integration for Jakarta Servlets 6.x [bundle] -[INFO] Jackson Integration for Metrics5 [bundle] -[INFO] Metrics Integration for Jetty 11.x and higher [bundle] -[INFO] Metrics5 Utility Jakarta Servlets [bundle] -[INFO] Metrics Integration for JCache [bundle] -[INFO] Metrics Integration for JDBI3 [bundle] -[INFO] Metrics Integration for Jersey 2.x [bundle] -[INFO] Metrics Integration for Jersey 3.0.x [bundle] -[INFO] Metrics Integration for Jersey 3.1.x [bundle] -[INFO] Metrics Integration for Jetty 10.x and higher [bundle] -[INFO] Metrics Integration for Log4j 2.x [bundle] -[INFO] Metrics Integration for Logback 1.3.x [bundle] -[INFO] Metrics Integration for Logback 1.4.x [bundle] -[INFO] Metrics Integration for Logback 1.5.x [bundle] -[INFO] Metrics Integration for Servlets [bundle] -[INFO] Metrics5 Utility Servlets [bundle] -[INFO] Metrics5 JCStress tests [jar] -[INFO] Metrics Integration with JMX [bundle] -[INFO] Metrics5 Adapter to Metrics 3/4 API [jar] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API [jar] -[INFO] Metrics Integration for Jetty 12.x and higher [bundle] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 [bundle] -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-parent >---------------- -[INFO] Building Metrics5 Parent 5.0.0-rc22 [1/39] -[INFO] from pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-parent --- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-parent --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-parent --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/target/jacoco.exec -[INFO] -[INFO] --------------------< io.dropwizard.metrics5:docs >--------------------- -[INFO] Building Metrics5 Documentation 5.0.0-rc22 [2/39] -[INFO] from docs/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ docs --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ docs --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ docs --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/jacoco.exec -[INFO] -[INFO] --- build-helper:3.6.0:parse-version (parse-version) @ docs --- -[INFO] -[INFO] --- resources:3.3.1:resources (process-resources) @ docs --- -[INFO] Copying 72 resources from source to target/source -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ docs --- -[INFO] Copying 72 resources from source to target/classes -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ docs --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ docs --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ docs --- -[INFO] No tests to run. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ docs --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/docs/target/docs-5.0.0-rc22.jar -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-bom >----------------- -[INFO] Building Metrics5 BOM 5.0.0-rc22 [3/39] -[INFO] from metrics-bom/pom.xml -[INFO] --------------------------------[ pom ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-bom --- -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-bom --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-bom --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-bom/target/jacoco.exec -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-annotation >-------------- -[INFO] Building Annotations for Metrics5 5.0.0-rc22 [4/39] -[INFO] from metrics-annotation/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-resources-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-resources-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-resources-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-resources-plugin:3.3.1 -[WARNING] Ignoring incompatible plugin version 4.0.0-beta-1: The plugin org.apache.maven.plugins:maven-install-plugin:4.0.0-beta-1 requires Maven version 4.0.0-beta-3 -[INFO] Latest version of plugin org.apache.maven.plugins:maven-install-plugin failed compatibility check -[INFO] Looking for compatible RELEASE version of plugin org.apache.maven.plugins:maven-install-plugin -[INFO] Selected plugin org.apache.maven.plugins:maven-install-plugin:3.1.3 -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-annotation --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-annotation --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-annotation --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-annotation --- -[INFO] Recompiling the module because of changed source code. -[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-annotation --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-annotation --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-annotation --- -[INFO] No tests to run. -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-annotation --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-annotation:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/metrics-annotation-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-annotation/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-core >----------------- -[INFO] Building Metrics5 Core 5.0.0-rc22 [5/39] -[INFO] from metrics-core/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-core --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-core --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-core --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-core --- -[INFO] Recompiling the module because of changed source code. -[INFO] Compiling 49 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[56,27] [this-escape] possible 'this' escape before subclass is fully initialized -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method - (see https://error-prone.picnic.tech/bugpatterns/FormatStringConcatenation) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-core --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-core --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 38 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-core --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.ExponentialMovingAveragesTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.311 s -- in io.dropwizard.metrics5.ExponentialMovingAveragesTest -[INFO] Running io.dropwizard.metrics5.SlidingWindowReservoirTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.219 s -- in io.dropwizard.metrics5.SlidingWindowReservoirTest -[INFO] Running io.dropwizard.metrics5.InstrumentedScheduledExecutorServiceTest -[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.762 s -- in io.dropwizard.metrics5.InstrumentedScheduledExecutorServiceTest -[INFO] Running io.dropwizard.metrics5.ExponentiallyDecayingReservoirTest -[INFO] Tests run: 24, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.212 s -- in io.dropwizard.metrics5.ExponentiallyDecayingReservoirTest -[INFO] Running io.dropwizard.metrics5.HistogramTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.113 s -- in io.dropwizard.metrics5.HistogramTest -[INFO] Running io.dropwizard.metrics5.ScheduledReporterTest -[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.402 s -- in io.dropwizard.metrics5.ScheduledReporterTest -[INFO] Running io.dropwizard.metrics5.ConsoleReporterTest -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.200 s -- in io.dropwizard.metrics5.ConsoleReporterTest -[INFO] Running io.dropwizard.metrics5.RatioGaugeTest -[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in io.dropwizard.metrics5.RatioGaugeTest -[INFO] Running io.dropwizard.metrics5.SimpleSettableGaugeTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 s -- in io.dropwizard.metrics5.SimpleSettableGaugeTest -[INFO] Running io.dropwizard.metrics5.UniformSnapshotTest -[INFO] Tests run: 25, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 s -- in io.dropwizard.metrics5.UniformSnapshotTest -[INFO] Running io.dropwizard.metrics5.ChunkedAssociativeLongArrayTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in io.dropwizard.metrics5.ChunkedAssociativeLongArrayTest -[INFO] Running io.dropwizard.metrics5.MetricNameTest -[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 s -- in io.dropwizard.metrics5.MetricNameTest -[INFO] Running io.dropwizard.metrics5.MetricFilterTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 s -- in io.dropwizard.metrics5.MetricFilterTest -[INFO] Running io.dropwizard.metrics5.ClockTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 s -- in io.dropwizard.metrics5.ClockTest -[INFO] Running io.dropwizard.metrics5.SlidingTimeWindowReservoirTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.363 s -- in io.dropwizard.metrics5.SlidingTimeWindowReservoirTest -[INFO] Running io.dropwizard.metrics5.DefaultSettableGaugeTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in io.dropwizard.metrics5.DefaultSettableGaugeTest -[INFO] Running io.dropwizard.metrics5.TimerTest -[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.012 s -- in io.dropwizard.metrics5.TimerTest -[INFO] Running io.dropwizard.metrics5.Slf4jReporterTest -[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.189 s -- in io.dropwizard.metrics5.Slf4jReporterTest -[INFO] Running io.dropwizard.metrics5.SharedMetricRegistriesTest -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.022 s -- in io.dropwizard.metrics5.SharedMetricRegistriesTest -[INFO] Running io.dropwizard.metrics5.MetricRegistryListenerTest -[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.012 s -- in io.dropwizard.metrics5.MetricRegistryListenerTest -[INFO] Running io.dropwizard.metrics5.UniformReservoirTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in io.dropwizard.metrics5.UniformReservoirTest -[INFO] Running io.dropwizard.metrics5.InstrumentedThreadFactoryTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in io.dropwizard.metrics5.InstrumentedThreadFactoryTest -[INFO] Running io.dropwizard.metrics5.WeightedSnapshotTest -[INFO] Tests run: 27, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.230 s -- in io.dropwizard.metrics5.WeightedSnapshotTest -[INFO] Running io.dropwizard.metrics5.CounterTest -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s -- in io.dropwizard.metrics5.CounterTest -[INFO] Running io.dropwizard.metrics5.SlidingTimeWindowMovingAveragesTest -[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 s -- in io.dropwizard.metrics5.SlidingTimeWindowMovingAveragesTest -[INFO] Running io.dropwizard.metrics5.CsvReporterTest -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.083 s -- in io.dropwizard.metrics5.CsvReporterTest -[INFO] Running io.dropwizard.metrics5.MeterTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 s -- in io.dropwizard.metrics5.MeterTest -[INFO] Running io.dropwizard.metrics5.NoopMetricRegistryTest -[INFO] Tests run: 40, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.130 s -- in io.dropwizard.metrics5.NoopMetricRegistryTest -[INFO] Running io.dropwizard.metrics5.EWMATest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 s -- in io.dropwizard.metrics5.EWMATest -[INFO] Running io.dropwizard.metrics5.DerivativeGaugeTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 s -- in io.dropwizard.metrics5.DerivativeGaugeTest -[INFO] Running io.dropwizard.metrics5.MeterApproximationTest -[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.107 s -- in io.dropwizard.metrics5.MeterApproximationTest -[INFO] Running io.dropwizard.metrics5.InstrumentedExecutorServiceTest -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.018 s -- in io.dropwizard.metrics5.InstrumentedExecutorServiceTest -[INFO] Running io.dropwizard.metrics5.FixedNameCsvFileProviderTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.011 s -- in io.dropwizard.metrics5.FixedNameCsvFileProviderTest -[INFO] Running io.dropwizard.metrics5.SlidingTimeWindowArrayReservoirTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.209 s -- in io.dropwizard.metrics5.SlidingTimeWindowArrayReservoirTest -[INFO] Running io.dropwizard.metrics5.ClassMetadataTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.021 s -- in io.dropwizard.metrics5.ClassMetadataTest -[INFO] Running io.dropwizard.metrics5.CachedGaugeTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 10.16 s -- in io.dropwizard.metrics5.CachedGaugeTest -[INFO] Running io.dropwizard.metrics5.MetricRegistryTest -[INFO] Tests run: 53, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.079 s -- in io.dropwizard.metrics5.MetricRegistryTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 338, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-core --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-core:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/metrics-core-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-core/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-benchmarks >-------------- -[INFO] Building Benchmarks for Metrics5 5.0.0-rc22 [6/39] -[INFO] from metrics-benchmarks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-benchmarks --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-benchmarks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-benchmarks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-benchmarks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-benchmarks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-benchmarks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-benchmarks --- -[INFO] No tests to run. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-benchmarks --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22.jar -[INFO] -[INFO] --- shade:3.6.0:shade (default) @ metrics-benchmarks --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jmh:jmh-core:jar:1.37 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:5.0.4 in the shaded jar. -[INFO] Including org.apache.commons:commons-math3:jar:3.6.1 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jmh-core-1.37.jar, jopt-simple-5.0.4.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-benchmarks-5.0.0-rc22.jar, metrics-core-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] checker-qual-3.43.0.jar, commons-math3-3.6.1.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/benchmarks.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-benchmarks/target/metrics-benchmarks-5.0.0-rc22-shaded.jar -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-caffeine3 >-------------- -[INFO] Building Metrics Integration for Caffeine 3.x 5.0.0-rc22 [7/39] -[INFO] from metrics-caffeine3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-caffeine3 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-caffeine3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-caffeine3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-caffeine3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-caffeine3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-caffeine3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-caffeine3 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.caffeine3.MetricsStatsCounterTest -[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.281 s -- in io.dropwizard.metrics5.caffeine3.MetricsStatsCounterTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-caffeine3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-caffeine3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/metrics-caffeine3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-caffeine3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-collectd >--------------- -[INFO] Building Metrics Integration for Collectd 5.0.0-rc22 [8/39] -[INFO] from metrics-collectd/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-collectd --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-collectd --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-collectd --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-collectd --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-collectd --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-collectd --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-collectd --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.collectd.CollectdReporterSecurityTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.224 s -- in io.dropwizard.metrics5.collectd.CollectdReporterSecurityTest -[INFO] Running io.dropwizard.metrics5.collectd.PacketWriterTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.102 s -- in io.dropwizard.metrics5.collectd.PacketWriterTest -[INFO] Running io.dropwizard.metrics5.collectd.CollectdReporterTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 17, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.770 s -- in io.dropwizard.metrics5.collectd.CollectdReporterTest -[INFO] Running io.dropwizard.metrics5.collectd.SanitizeTest -[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.014 s -- in io.dropwizard.metrics5.collectd.SanitizeTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 26, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-collectd --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-collectd:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/metrics-collectd-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-collectd/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-ehcache >--------------- -[INFO] Building Metrics Integration for Ehcache 5.0.0-rc22 [9/39] -[INFO] from metrics-ehcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-ehcache --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-ehcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-ehcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-ehcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-ehcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-ehcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-ehcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-ehcache --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.ehcache.InstrumentedCacheDecoratorFactoryTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.325 s -- in io.dropwizard.metrics5.ehcache.InstrumentedCacheDecoratorFactoryTest -[INFO] Running io.dropwizard.metrics5.ehcache.InstrumentedEhcacheTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.029 s -- in io.dropwizard.metrics5.ehcache.InstrumentedEhcacheTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-ehcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-ehcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/metrics-ehcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-ehcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-graphite >--------------- -[INFO] Building Graphite Integration for Metrics5 5.0.0-rc22 [10/39] -[INFO] from metrics-graphite/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-graphite --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-graphite --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-graphite --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-graphite --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-graphite --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 7 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-graphite --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-graphite --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-graphite --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.graphite.GraphiteRabbitMQTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.020 s -- in io.dropwizard.metrics5.graphite.GraphiteRabbitMQTest -[INFO] Running io.dropwizard.metrics5.graphite.GraphiteTest -[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.297 s -- in io.dropwizard.metrics5.graphite.GraphiteTest -[INFO] Running io.dropwizard.metrics5.graphite.GraphiteUDPTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.108 s -- in io.dropwizard.metrics5.graphite.GraphiteUDPTest -[INFO] Running io.dropwizard.metrics5.graphite.PickledGraphiteTest -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 9.740 s -- in io.dropwizard.metrics5.graphite.PickledGraphiteTest -[INFO] Running io.dropwizard.metrics5.graphite.GraphiteSanitizeTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.351 s -- in io.dropwizard.metrics5.graphite.GraphiteSanitizeTest -[INFO] Running io.dropwizard.metrics5.graphite.GraphiteReporterTest -[INFO] Tests run: 19, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.429 s -- in io.dropwizard.metrics5.graphite.GraphiteReporterTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 45, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-graphite --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-graphite:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/metrics-graphite-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-graphite/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-influxdb >--------------- -[INFO] Building InfluxDB integration for Metrics5 5.0.0-rc22 [11/39] -[INFO] from metrics-influxdb/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-influxdb --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-influxdb --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-influxdb --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-influxdb --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) - (see https://error-prone.picnic.tech/bugpatterns/Slf4jLogStatement) -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-influxdb --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-influxdb --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-influxdb --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.influxdb.InfluxDbReporterTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.312 s -- in io.dropwizard.metrics5.influxdb.InfluxDbReporterTest -[INFO] Running io.dropwizard.metrics5.influxdb.InfluxDbLineBuilderAssumptionsTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.009 s -- in io.dropwizard.metrics5.influxdb.InfluxDbLineBuilderAssumptionsTest -[INFO] Running io.dropwizard.metrics5.influxdb.InfluxDbUdpTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.144 s -- in io.dropwizard.metrics5.influxdb.InfluxDbUdpTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 20, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-influxdb --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-influxdb:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/metrics-influxdb-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-influxdb/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jvm >----------------- -[INFO] Building JVM Integration for Metrics5 5.0.0-rc22 [12/39] -[INFO] from metrics-jvm/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jvm --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jvm --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jvm --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jvm --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 12 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jvm --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jvm --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[74,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[83,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[92,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast - required: Gauge - found: Metric -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jvm --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.jvm.ThreadStatesGaugeSetTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.806 s -- in io.dropwizard.metrics5.jvm.ThreadStatesGaugeSetTest -[INFO] Running io.dropwizard.metrics5.jvm.MemoryUsageGaugeSetTest -[INFO] Tests run: 25, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.315 s -- in io.dropwizard.metrics5.jvm.MemoryUsageGaugeSetTest -[INFO] Running io.dropwizard.metrics5.jvm.CpuTimeClockTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.010 s -- in io.dropwizard.metrics5.jvm.CpuTimeClockTest -[INFO] Running io.dropwizard.metrics5.jvm.JmxAttributeGaugeTest -[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.113 s -- in io.dropwizard.metrics5.jvm.JmxAttributeGaugeTest -[INFO] Running io.dropwizard.metrics5.jvm.FileDescriptorRatioGaugeTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.091 s -- in io.dropwizard.metrics5.jvm.FileDescriptorRatioGaugeTest -[INFO] Running io.dropwizard.metrics5.jvm.JvmAttributeGaugeSetTest -[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.072 s -- in io.dropwizard.metrics5.jvm.JvmAttributeGaugeSetTest -[INFO] Running io.dropwizard.metrics5.jvm.ThreadDeadlockDetectorTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.009 s -- in io.dropwizard.metrics5.jvm.ThreadDeadlockDetectorTest -[INFO] Running io.dropwizard.metrics5.jvm.BufferPoolMetricSetTest -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.162 s -- in io.dropwizard.metrics5.jvm.BufferPoolMetricSetTest -[INFO] Running io.dropwizard.metrics5.jvm.ThreadDumpTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.010 s -- in io.dropwizard.metrics5.jvm.ThreadDumpTest -[INFO] Running io.dropwizard.metrics5.jvm.GarbageCollectorMetricSetTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.061 s -- in io.dropwizard.metrics5.jvm.GarbageCollectorMetricSetTest -[INFO] Running io.dropwizard.metrics5.jvm.ClassLoadingGaugeSetTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.043 s -- in io.dropwizard.metrics5.jvm.ClassLoadingGaugeSetTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 66, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jvm --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jvm:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/metrics-jvm-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jvm/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-healthchecks >------------- -[INFO] Building Metrics5 Health Checks 5.0.0-rc22 [13/39] -[INFO] from metrics-healthchecks/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-healthchecks --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-healthchecks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-healthchecks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-healthchecks --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.health.AsyncHealthCheckDecoratorTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 15, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.608 s -- in io.dropwizard.metrics5.health.AsyncHealthCheckDecoratorTest -[INFO] Running io.dropwizard.metrics5.health.HealthCheckFilterTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 s -- in io.dropwizard.metrics5.health.HealthCheckFilterTest -[INFO] Running io.dropwizard.metrics5.health.SharedHealthCheckRegistriesTest -[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.065 s -- in io.dropwizard.metrics5.health.SharedHealthCheckRegistriesTest -[INFO] Running io.dropwizard.metrics5.health.HealthCheckTest -[INFO] Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.271 s -- in io.dropwizard.metrics5.health.HealthCheckTest -[INFO] Running io.dropwizard.metrics5.health.HealthCheckRegistryTest -[INFO] Tests run: 17, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.108 s -- in io.dropwizard.metrics5.health.HealthCheckRegistryTest -[INFO] Running io.dropwizard.metrics5.health.jvm.ThreadDeadlockHealthCheckTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.048 s -- in io.dropwizard.metrics5.health.jvm.ThreadDeadlockHealthCheckTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 59, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-healthchecks --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-healthchecks:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/metrics-healthchecks-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-healthchecks/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient >-------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.0.0-rc22 [14/39] -[INFO] from metrics-httpclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpclient --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java:[114,8] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.httpclient.InstrumentedHttpClientsTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.183 s -- in io.dropwizard.metrics5.httpclient.InstrumentedHttpClientsTest -[INFO] Running io.dropwizard.metrics5.httpclient.InstrumentedHttpClientConnectionManagerTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.187 s -- in io.dropwizard.metrics5.httpclient.InstrumentedHttpClientConnectionManagerTest -[INFO] Running io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategiesTest -[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 s -- in io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategiesTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/metrics-httpclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] -------------< io.dropwizard.metrics5:metrics-httpclient5 >------------- -[INFO] Building Metrics Integration for Apache HttpClient 5.x 5.0.0-rc22 [15/39] -[INFO] from metrics-httpclient5/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpclient5 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpclient5 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpclient5 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpclient5 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 8 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[14,40] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[15,40] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[16,37] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[30,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[31,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[32,37] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[33,38] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[96,21] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[160,12] [deprecation] DefaultHttpClientConnectionOperator(Lookup,SchemePortResolver,DnsResolver) in DefaultHttpClientConnectionOperator has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java:[49,4] [deprecation] HttpRequestExecutor(Timeout,ConnectionReuseStrategy,Http1StreamListener) in HttpRequestExecutor has been deprecated -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpclient5 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpclient5 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 5 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpclient5 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.httpclient5.InstrumentedHttpClientsTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.411 s -- in io.dropwizard.metrics5.httpclient5.InstrumentedHttpClientsTest -[INFO] Running io.dropwizard.metrics5.httpclient5.InstrumentedHttpClientConnectionManagerTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.206 s -- in io.dropwizard.metrics5.httpclient5.InstrumentedHttpClientConnectionManagerTest -[INFO] Running io.dropwizard.metrics5.httpclient5.InstrumentedHttpAsyncClientsTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.550 s -- in io.dropwizard.metrics5.httpclient5.InstrumentedHttpAsyncClientsTest -[INFO] Running io.dropwizard.metrics5.httpclient5.InstrumentedAsyncClientConnectionManagerTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in io.dropwizard.metrics5.httpclient5.InstrumentedAsyncClientConnectionManagerTest -[INFO] Running io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategiesTest -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 s -- in io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategiesTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 17, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpclient5 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpclient5:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/metrics-httpclient5-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpclient5/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-httpasyncclient >----------- -[INFO] Building Metrics Integration for Apache HttpAsyncClient 5.0.0-rc22 [16/39] -[INFO] from metrics-httpasyncclient/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-httpasyncclient --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-httpasyncclient --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-httpasyncclient --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-httpasyncclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java:[40,8] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-httpasyncclient --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-httpasyncclient --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-httpasyncclient --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.httpasyncclient.InstrumentedHttpClientsTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.927 s -- in io.dropwizard.metrics5.httpasyncclient.InstrumentedHttpClientsTest -[INFO] Running io.dropwizard.metrics5.httpasyncclient.InstrumentedHttpClientsTimerTest -[WARNING] Tests run: 3, Failures: 0, Errors: 0, Skipped: 3, Time elapsed: 0.001 s -- in io.dropwizard.metrics5.httpasyncclient.InstrumentedHttpClientsTimerTest -[INFO] -[INFO] Results: -[INFO] -[WARNING] Tests run: 4, Failures: 0, Errors: 0, Skipped: 3 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-httpasyncclient --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-httpasyncclient:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/metrics-httpasyncclient-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-httpasyncclient/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-jakarta-servlet >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 5.0.0-rc22 [17/39] -[INFO] from metrics-jakarta-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlet --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.servlet.InstrumentedFilterContextListenerTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.523 s -- in io.dropwizard.metrics5.servlet.InstrumentedFilterContextListenerTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/metrics-jakarta-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlet6 >----------- -[INFO] Building Metrics Integration for Jakarta Servlets 6.x 5.0.0-rc22 [18/39] -[INFO] from metrics-jakarta-servlet6/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlet6 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlet6 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlet6 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlet6 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlet6 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlet6 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlet6 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.servlet6.InstrumentedFilterContextListenerTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.522 s -- in io.dropwizard.metrics5.servlet6.InstrumentedFilterContextListenerTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlet6 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlet6:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/metrics-jakarta-servlet6-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlet6/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-json >----------------- -[INFO] Building Jackson Integration for Metrics5 5.0.0-rc22 [19/39] -[INFO] from metrics-json/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-json --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-json --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-json --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-json --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java:[189,31] [serial] non-transient instance field of a serializable class declared with a non-serializable type -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-json --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-json --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-json --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.json.MetricsModuleTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.168 s -- in io.dropwizard.metrics5.json.MetricsModuleTest -[INFO] Running io.dropwizard.metrics5.json.HealthCheckModuleTest -[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.069 s -- in io.dropwizard.metrics5.json.HealthCheckModuleTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 13, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-json --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-json:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/metrics-json-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-json/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty11 >--------------- -[INFO] Building Metrics Integration for Jetty 11.x and higher 5.0.0-rc22 [20/39] -[INFO] from metrics-jetty11/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty11 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty11 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty11 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty11 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/11.0.24/jetty-util-11.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/11.0.24/jetty-server-11.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/main/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty11 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty11 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty11 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.jetty11.InstrumentedConnectionFactoryTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.029 s -- in io.dropwizard.metrics5.jetty11.InstrumentedConnectionFactoryTest -[INFO] Running io.dropwizard.metrics5.jetty11.InstrumentedHandlerTest -[WARNING] Tests run: 7, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.252 s -- in io.dropwizard.metrics5.jetty11.InstrumentedHandlerTest -[INFO] Running io.dropwizard.metrics5.jetty11.InstrumentedQueuedThreadPoolTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.014 s -- in io.dropwizard.metrics5.jetty11.InstrumentedQueuedThreadPoolTest -[INFO] Running io.dropwizard.metrics5.jetty11.InstrumentedHttpChannelListenerTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.454 s -- in io.dropwizard.metrics5.jetty11.InstrumentedHttpChannelListenerTest -[INFO] -[INFO] Results: -[INFO] -[WARNING] Tests run: 14, Failures: 0, Errors: 0, Skipped: 1 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty11 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty11:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/metrics-jetty11-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty11/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ----------< io.dropwizard.metrics5:metrics-jakarta-servlets >----------- -[INFO] Building Metrics5 Utility Jakarta Servlets 5.0.0-rc22 [21/39] -[INFO] from metrics-jakarta-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jakarta-servlets --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jakarta-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jakarta-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jakarta-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jakarta-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jakarta-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 11 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/jakarta/servlet/jakarta.servlet-api/6.1.0/jakarta.servlet-api-6.1.0.jar(/jakarta/servlet/http/HttpServlet.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jakarta-servlets --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.servlets.MetricsServletContextListenerTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.667 s -- in io.dropwizard.metrics5.servlets.MetricsServletContextListenerTest -[INFO] Running io.dropwizard.metrics5.servlets.HealthCheckServletTest -[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.359 s -- in io.dropwizard.metrics5.servlets.HealthCheckServletTest -[INFO] Running io.dropwizard.metrics5.servlets.ThreadDumpServletTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.072 s -- in io.dropwizard.metrics5.servlets.ThreadDumpServletTest -[INFO] Running io.dropwizard.metrics5.servlets.CpuProfileServletTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.032 s -- in io.dropwizard.metrics5.servlets.CpuProfileServletTest -[INFO] Running io.dropwizard.metrics5.servlets.AdminServletExclusionTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 s -- in io.dropwizard.metrics5.servlets.AdminServletExclusionTest -[INFO] Running io.dropwizard.metrics5.servlets.MetricsServletTest -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.150 s -- in io.dropwizard.metrics5.servlets.MetricsServletTest -[INFO] Running io.dropwizard.metrics5.servlets.PingServletTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 s -- in io.dropwizard.metrics5.servlets.PingServletTest -[INFO] Running io.dropwizard.metrics5.servlets.AdminServletTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in io.dropwizard.metrics5.servlets.AdminServletTest -[INFO] Running io.dropwizard.metrics5.servlets.AdminServletUriTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in io.dropwizard.metrics5.servlets.AdminServletUriTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 33, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jakarta-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jakarta-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/metrics-jakarta-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jakarta-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jcache >---------------- -[INFO] Building Metrics Integration for JCache 5.0.0-rc22 [22/39] -[INFO] from metrics-jcache/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jcache --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcache --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcache --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcache --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcache --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcache --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcache --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running JCacheGaugeSetTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.112 s -- in JCacheGaugeSetTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jcache --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jcache:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/metrics-jcache-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcache/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ----------------< io.dropwizard.metrics5:metrics-jdbi3 >---------------- -[INFO] Building Metrics Integration for JDBI3 5.0.0-rc22 [23/39] -[INFO] from metrics-jdbi3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jdbi3 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jdbi3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jdbi3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jdbi3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 9 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jdbi3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jdbi3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jdbi3 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.525 s -- in io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest -[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.BasicSqlNameStrategyTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in io.dropwizard.metrics5.jdbi3.strategies.BasicSqlNameStrategyTest -[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.NaiveNameStrategyTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.012 s -- in io.dropwizard.metrics5.jdbi3.strategies.NaiveNameStrategyTest -[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.SmartNameStrategyTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.062 s -- in io.dropwizard.metrics5.jdbi3.strategies.SmartNameStrategyTest -[INFO] Running io.dropwizard.metrics5.jdbi3.strategies.InstrumentedSqlLoggerTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.306 s -- in io.dropwizard.metrics5.jdbi3.strategies.InstrumentedSqlLoggerTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 15, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jdbi3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jdbi3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/metrics-jdbi3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jdbi3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey2 >--------------- -[INFO] Building Metrics Integration for Jersey 2.x 5.0.0-rc22 [24/39] -[INFO] from metrics-jersey2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey2 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey2 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsJerseyTest -[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.543 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsTimedPerClassJerseyTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.108 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsTimedPerClassJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey2.SingletonFilterMetricsJerseyTest -[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.417 s -- in io.dropwizard.metrics5.jersey2.SingletonFilterMetricsJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsMeteredPerClassJerseyTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.074 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsMeteredPerClassJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsExceptionMeteredPerClassJerseyTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.081 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsExceptionMeteredPerClassJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey2.CustomReservoirImplementationTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 s -- in io.dropwizard.metrics5.jersey2.CustomReservoirImplementationTest -[INFO] Running io.dropwizard.metrics5.jersey2.SingletonMetricsResponseMeteredPerClassJerseyTest -[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.242 s -- in io.dropwizard.metrics5.jersey2.SingletonMetricsResponseMeteredPerClassJerseyTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 28, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/metrics-jersey2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jersey3 >--------------- -[INFO] Building Metrics Integration for Jersey 3.0.x 5.0.0-rc22 [25/39] -[INFO] from metrics-jersey3/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey3 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey3 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey3 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey3 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey3 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey3 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsJerseyTest -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.630 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsTimedPerClassJerseyTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.094 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsTimedPerClassJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey3.SingletonFilterMetricsJerseyTest -[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.367 s -- in io.dropwizard.metrics5.jersey3.SingletonFilterMetricsJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsMeteredPerClassJerseyTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.078 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsMeteredPerClassJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsExceptionMeteredPerClassJerseyTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.074 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsExceptionMeteredPerClassJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey3.CustomReservoirImplementationTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.049 s -- in io.dropwizard.metrics5.jersey3.CustomReservoirImplementationTest -[INFO] Running io.dropwizard.metrics5.jersey3.SingletonMetricsResponseMeteredPerClassJerseyTest -[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.216 s -- in io.dropwizard.metrics5.jersey3.SingletonMetricsResponseMeteredPerClassJerseyTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 30, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey3 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey3:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/metrics-jersey3-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey3/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jersey31 >--------------- -[INFO] Building Metrics Integration for Jersey 3.1.x 5.0.0-rc22 [26/39] -[INFO] from metrics-jersey31/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jersey31 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jersey31 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jersey31 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jersey31 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jersey31 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jersey31 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 22 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jersey31 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsJerseyTest -[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.924 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsTimedPerClassJerseyTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.103 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsTimedPerClassJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey31.SingletonFilterMetricsJerseyTest -[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.376 s -- in io.dropwizard.metrics5.jersey31.SingletonFilterMetricsJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsMeteredPerClassJerseyTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.069 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsMeteredPerClassJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsExceptionMeteredPerClassJerseyTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.077 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsExceptionMeteredPerClassJerseyTest -[INFO] Running io.dropwizard.metrics5.jersey31.CustomReservoirImplementationTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.044 s -- in io.dropwizard.metrics5.jersey31.CustomReservoirImplementationTest -[INFO] Running io.dropwizard.metrics5.jersey31.SingletonMetricsResponseMeteredPerClassJerseyTest -[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.215 s -- in io.dropwizard.metrics5.jersey31.SingletonMetricsResponseMeteredPerClassJerseyTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 31, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jersey31 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jersey31:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/metrics-jersey31-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jersey31/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty10 >--------------- -[INFO] Building Metrics Integration for Jetty 10.x and higher 5.0.0-rc22 [27/39] -[INFO] from metrics-jetty10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty10 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Request.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/10.0.24/jetty-util-10.0.24.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-server/10.0.24/jetty-server-10.0.24.jar(/org/eclipse/jetty/server/Response.class): warning: Cannot find annotation method 'since()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/main/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty10 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.jetty10.InstrumentedConnectionFactoryTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.053 s -- in io.dropwizard.metrics5.jetty10.InstrumentedConnectionFactoryTest -[INFO] Running io.dropwizard.metrics5.jetty10.InstrumentedHandlerTest -[WARNING] Tests run: 7, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.255 s -- in io.dropwizard.metrics5.jetty10.InstrumentedHandlerTest -[INFO] Running io.dropwizard.metrics5.jetty10.InstrumentedQueuedThreadPoolTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.016 s -- in io.dropwizard.metrics5.jetty10.InstrumentedQueuedThreadPoolTest -[INFO] Running io.dropwizard.metrics5.jetty10.InstrumentedHttpChannelListenerTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.468 s -- in io.dropwizard.metrics5.jetty10.InstrumentedHttpChannelListenerTest -[INFO] -[INFO] Results: -[INFO] -[WARNING] Tests run: 14, Failures: 0, Errors: 0, Skipped: 1 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/metrics-jetty10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty10/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-log4j2 >---------------- -[INFO] Building Metrics Integration for Log4j 2.x 5.0.0-rc22 [28/39] -[INFO] from metrics-log4j2/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-log4j2 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-log4j2 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-log4j2 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-log4j2 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-log4j2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-log4j2 --- -[INFO] Copying 1 resource from src/test/resources to target/test-classes -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-log4j2 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-log4j2 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.log4j2.InstrumentedAppenderTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.721 s -- in io.dropwizard.metrics5.log4j2.InstrumentedAppenderTest -[INFO] Running io.dropwizard.metrics5.log4j2.InstrumentedAppenderConfigTest -2024-11-18T12:07:39.193984674Z main INFO Starting LoggerContext[name=18b4aac2] with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... -2024-11-18T12:07:39.200922446Z main WARN The use of package scanning to locate Log4j plugins is deprecated. -Please remove the `packages` attribute from your configuration file. -See https://logging.apache.org/log4j/2.x/faq.html#package-scanning for details. -2024-11-18T12:07:39.207876369Z main WARN Some custom `Core` Log4j plugins are not properly registered: - io.dropwizard.metrics5.log4j2.InstrumentedAppender -Please consider reporting this to the maintainers of these plugins. -See https://logging.apache.org/log4j/2.x/manual/plugins.html#plugin-registry for details. -2024-11-18T12:07:39.252201564Z main INFO Starting configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... -2024-11-18T12:07:39.252463966Z main INFO Start watching for changes to stream (376 bytes, unknown location) every 0 seconds -2024-11-18T12:07:39.253074854Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] started. -2024-11-18T12:07:39.254125924Z main INFO Stopping configuration org.apache.logging.log4j.core.config.DefaultConfiguration@ac4915e... -2024-11-18T12:07:39.254564734Z main INFO Configuration org.apache.logging.log4j.core.config.DefaultConfiguration@ac4915e stopped. -2024-11-18T12:07:39.258930312Z main INFO LoggerContext[name=18b4aac2] started with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]. -2024-11-18T12:07:39.273527830Z main INFO Stopping configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... -2024-11-18T12:07:39.273749982Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] stopped. -2024-11-18T12:07:39.281549911Z main INFO Starting LoggerContext[name=18b4aac2] with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... -2024-11-18T12:07:39.281853632Z main WARN The use of package scanning to locate Log4j plugins is deprecated. -Please remove the `packages` attribute from your configuration file. -See https://logging.apache.org/log4j/2.x/faq.html#package-scanning for details. -2024-11-18T12:07:39.282118934Z main WARN Some custom `Core` Log4j plugins are not properly registered: - io.dropwizard.metrics5.log4j2.InstrumentedAppender -Please consider reporting this to the maintainers of these plugins. -See https://logging.apache.org/log4j/2.x/manual/plugins.html#plugin-registry for details. -2024-11-18T12:07:39.283482926Z main INFO Starting configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... -2024-11-18T12:07:39.283620004Z main INFO Start watching for changes to stream (376 bytes, unknown location) every 0 seconds -2024-11-18T12:07:39.283897571Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] started. -2024-11-18T12:07:39.284115452Z main INFO Stopping configuration org.apache.logging.log4j.core.config.DefaultConfiguration@5086623f... -2024-11-18T12:07:39.284280232Z main INFO Configuration org.apache.logging.log4j.core.config.DefaultConfiguration@5086623f stopped. -2024-11-18T12:07:39.284468124Z main INFO LoggerContext[name=18b4aac2] started with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]. -2024-11-18T12:07:39.285252313Z main INFO Stopping configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... -2024-11-18T12:07:39.285427352Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] stopped. -2024-11-18T12:07:39.292498164Z main INFO Starting LoggerContext[name=18b4aac2] with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... -2024-11-18T12:07:39.292822040Z main WARN The use of package scanning to locate Log4j plugins is deprecated. -Please remove the `packages` attribute from your configuration file. -See https://logging.apache.org/log4j/2.x/faq.html#package-scanning for details. -2024-11-18T12:07:39.293143105Z main WARN Some custom `Core` Log4j plugins are not properly registered: - io.dropwizard.metrics5.log4j2.InstrumentedAppender -Please consider reporting this to the maintainers of these plugins. -See https://logging.apache.org/log4j/2.x/manual/plugins.html#plugin-registry for details. -2024-11-18T12:07:39.294793189Z main INFO Starting configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... -2024-11-18T12:07:39.294953661Z main INFO Start watching for changes to stream (376 bytes, unknown location) every 0 seconds -2024-11-18T12:07:39.295337107Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] started. -2024-11-18T12:07:39.295497681Z main INFO Stopping configuration org.apache.logging.log4j.core.config.DefaultConfiguration@7eae55... -2024-11-18T12:07:39.295668975Z main INFO Configuration org.apache.logging.log4j.core.config.DefaultConfiguration@7eae55 stopped. -2024-11-18T12:07:39.295909868Z main INFO LoggerContext[name=18b4aac2] started with configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]. -2024-11-18T12:07:39.296699991Z main INFO Stopping configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z]... -2024-11-18T12:07:39.296886682Z main INFO Configuration XmlConfiguration[location=stream (376 bytes, unknown location), lastModified=1970-01-01T00:00:00Z] stopped. -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.633 s -- in io.dropwizard.metrics5.log4j2.InstrumentedAppenderConfigTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-log4j2 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-log4j2:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/metrics-log4j2-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-log4j2/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback13 >-------------- -[INFO] Building Metrics Integration for Logback 1.3.x 5.0.0-rc22 [29/39] -[INFO] from metrics-logback13/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback13 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback13 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback13 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback13 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback13 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback13 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback13 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics.logback13.InstrumentedAppenderTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.881 s -- in io.dropwizard.metrics.logback13.InstrumentedAppenderTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback13 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback13:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/metrics-logback13-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback13/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback14 >-------------- -[INFO] Building Metrics Integration for Logback 1.4.x 5.0.0-rc22 [30/39] -[INFO] from metrics-logback14/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback14 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback14 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback14 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback14 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback14 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback14 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback14 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics.logback14.InstrumentedAppenderTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.666 s -- in io.dropwizard.metrics.logback14.InstrumentedAppenderTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback14 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback14:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/metrics-logback14-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback14/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-logback15 >-------------- -[INFO] Building Metrics Integration for Logback 1.5.x 5.0.0-rc22 [31/39] -[INFO] from metrics-logback15/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-logback15 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-logback15 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-logback15 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-logback15 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-logback15 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-logback15 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-logback15 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.logback15.InstrumentedAppenderTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.605 s -- in io.dropwizard.metrics5.logback15.InstrumentedAppenderTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-logback15 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-logback15:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/metrics-logback15-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-logback15/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-servlet >--------------- -[INFO] Building Metrics Integration for Servlets 5.0.0-rc22 [32/39] -[INFO] from metrics-servlet/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-servlet --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlet --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlet --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlet --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlet --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlet --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.servlet.InstrumentedFilterContextListenerTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.546 s -- in io.dropwizard.metrics5.servlet.InstrumentedFilterContextListenerTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlet --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlet:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/metrics-servlet-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlet/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-servlets >--------------- -[INFO] Building Metrics5 Utility Servlets 5.0.0-rc22 [33/39] -[INFO] from metrics-servlets/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-servlets --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-servlets --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-servlets --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 6 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-servlets --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-servlets --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 10 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone - (see https://error-prone.picnic.tech/bugpatterns/TimeZoneUsage) -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-servlets --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.servlets.MetricsServletContextListenerTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.524 s -- in io.dropwizard.metrics5.servlets.MetricsServletContextListenerTest -[INFO] Running io.dropwizard.metrics5.servlets.HealthCheckServletTest -[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.360 s -- in io.dropwizard.metrics5.servlets.HealthCheckServletTest -[INFO] Running io.dropwizard.metrics5.servlets.ThreadDumpServletTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.064 s -- in io.dropwizard.metrics5.servlets.ThreadDumpServletTest -[INFO] Running io.dropwizard.metrics5.servlets.CpuProfileServletTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.050 s -- in io.dropwizard.metrics5.servlets.CpuProfileServletTest -[INFO] Running io.dropwizard.metrics5.servlets.MetricsServletTest -[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.159 s -- in io.dropwizard.metrics5.servlets.MetricsServletTest -[INFO] Running io.dropwizard.metrics5.servlets.PingServletTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.024 s -- in io.dropwizard.metrics5.servlets.PingServletTest -[INFO] Running io.dropwizard.metrics5.servlets.AdminServletTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.009 s -- in io.dropwizard.metrics5.servlets.AdminServletTest -[INFO] Running io.dropwizard.metrics5.servlets.AdminServletUriTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s -- in io.dropwizard.metrics5.servlets.AdminServletUriTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 32, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-servlets --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-servlets:bundle:5.0.0-rc22 : Unused Import-Package instructions: [org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/metrics-servlets-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-servlets/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] --------------< io.dropwizard.metrics5:metrics-jcstress >--------------- -[INFO] Building Metrics5 JCStress tests 5.0.0-rc22 [34/39] -[INFO] from metrics-jcstress/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jcstress --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jcstress --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jcstress --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jcstress --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jcstress --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jcstress --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jcstress --- -[INFO] No tests to run. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-jcstress --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22.jar -[INFO] -[INFO] --- shade:3.6.0:shade (main) @ metrics-jcstress --- -[INFO] Including io.dropwizard.metrics5:metrics-core:jar:5.0.0-rc22 in the shaded jar. -[INFO] Including org.slf4j:slf4j-api:jar:2.0.16 in the shaded jar. -[INFO] Including org.openjdk.jcstress:jcstress-core:jar:0.16 in the shaded jar. -[INFO] Including net.sf.jopt-simple:jopt-simple:jar:4.6 in the shaded jar. -[INFO] Including net.java.dev.jna:jna:jar:5.8.0 in the shaded jar. -[INFO] Including net.java.dev.jna:jna-platform:jar:5.8.0 in the shaded jar. -[INFO] Including com.google.guava:guava:jar:33.3.1-jre in the shaded jar. -[INFO] Including com.google.guava:failureaccess:jar:1.0.2 in the shaded jar. -[INFO] Including com.google.guava:listenablefuture:jar:9999.0-empty-to-avoid-conflict-with-guava in the shaded jar. -[INFO] Including com.google.code.findbugs:jsr305:jar:3.0.2 in the shaded jar. -[INFO] Including org.checkerframework:checker-qual:jar:3.43.0 in the shaded jar. -[INFO] Including com.google.j2objc:j2objc-annotations:jar:3.0.0 in the shaded jar. -[INFO] Including com.google.errorprone:error_prone_annotations:jar:2.35.1 in the shaded jar. -[INFO] Dependency-reduced POM written at: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/dependency-reduced-pom.xml -[WARNING] Discovered module-info.class. Shading will break its strong encapsulation. -[WARNING] guava-33.3.1-jre.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE -[WARNING] error_prone_annotations-2.35.1.jar, j2objc-annotations-3.0.0.jar, slf4j-api-2.0.16.jar define 1 overlapping classes: -[WARNING] - META-INF.versions.9.module-info -[WARNING] checker-qual-3.43.0.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/LICENSE.txt -[WARNING] checker-qual-3.43.0.jar, error_prone_annotations-2.35.1.jar, failureaccess-1.0.2.jar, guava-33.3.1-jre.jar, j2objc-annotations-3.0.0.jar, jcstress-core-0.16.jar, jna-5.8.0.jar, jna-platform-5.8.0.jar, jopt-simple-4.6.jar, jsr305-3.0.2.jar, listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar, metrics-core-5.0.0-rc22.jar, metrics-jcstress-5.0.0-rc22.jar, slf4j-api-2.0.16.jar define 1 overlapping resource: -[WARNING] - META-INF/MANIFEST.MF -[WARNING] jna-5.8.0.jar, jna-platform-5.8.0.jar define 2 overlapping resources: -[WARNING] - META-INF/AL2.0 -[WARNING] - META-INF/LGPL2.1 -[WARNING] maven-shade-plugin has detected that some files are -[WARNING] present in two or more JARs. When this happens, only one -[WARNING] single version of the file is copied to the uber jar. -[WARNING] Usually this is not harmful and you can skip these warnings, -[WARNING] otherwise try to manually exclude artifacts based on -[WARNING] mvn dependency:tree -Ddetail=true and the above output. -[WARNING] See https://maven.apache.org/plugins/maven-shade-plugin/ -[INFO] Replacing /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/jcstress.jar with /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jcstress/target/metrics-jcstress-5.0.0-rc22-shaded.jar -[INFO] -[INFO] -----------------< io.dropwizard.metrics5:metrics-jmx >----------------- -[INFO] Building Metrics Integration with JMX 5.0.0-rc22 [35/39] -[INFO] from metrics-jmx/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jmx --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jmx --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jmx --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jmx --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jmx --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jmx --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jmx --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics5.jmx.DefaultObjectNameFactoryTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.231 s -- in io.dropwizard.metrics5.jmx.DefaultObjectNameFactoryTest -[INFO] Running io.dropwizard.metrics5.jmx.JmxReporterTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.994 s -- in io.dropwizard.metrics5.jmx.JmxReporterTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jmx --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jmx:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/metrics-jmx-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jmx/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] -----------< io.dropwizard.metrics5:metrics-legacy-adapter >------------ -[INFO] Building Metrics5 Adapter to Metrics 3/4 API 5.0.0-rc22 [36/39] -[INFO] from metrics-legacy-adapter/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-legacy-adapter --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 36 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,49] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[51,9] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[108,27] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/main/java/com/codahale/metrics/MetricRegistry.java:[112,27] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 24 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[50,4] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[WARNING] /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[367,22] [rawtypes] found raw type: Gauge - missing type arguments for generic class Gauge - where T is a type-variable: - T extends Object declared in interface Gauge -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running com.codahale.metrics.GaugeTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.162 s -- in com.codahale.metrics.GaugeTest -[INFO] Running com.codahale.metrics.SlidingWindowReservoirTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.010 s -- in com.codahale.metrics.SlidingWindowReservoirTest -[INFO] Running com.codahale.metrics.InstrumentedScheduledExecutorServiceTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.169 s -- in com.codahale.metrics.InstrumentedScheduledExecutorServiceTest -[INFO] Running com.codahale.metrics.ExponentiallyDecayingReservoirTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.015 s -- in com.codahale.metrics.ExponentiallyDecayingReservoirTest -[INFO] Running com.codahale.metrics.HistogramTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 s -- in com.codahale.metrics.HistogramTest -[INFO] Running com.codahale.metrics.ScheduledReporterTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.059 s -- in com.codahale.metrics.ScheduledReporterTest -[INFO] Running com.codahale.metrics.ConsoleReporterTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.059 s -- in com.codahale.metrics.ConsoleReporterTest -[INFO] Running com.codahale.metrics.RatioGaugeTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in com.codahale.metrics.RatioGaugeTest -[INFO] Running com.codahale.metrics.SnapshotTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 s -- in com.codahale.metrics.SnapshotTest -[INFO] Running com.codahale.metrics.ClockTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in com.codahale.metrics.ClockTest -[INFO] Running com.codahale.metrics.SlidingTimeWindowReservoirTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 s -- in com.codahale.metrics.SlidingTimeWindowReservoirTest -[INFO] Running com.codahale.metrics.TimerTest -[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.013 s -- in com.codahale.metrics.TimerTest -[INFO] Running com.codahale.metrics.Slf4jReporterTest -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK. Please add Mockito as an agent to your build what is described in Mockito's documentation: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#0.3 -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.432 s -- in com.codahale.metrics.Slf4jReporterTest -[INFO] Running com.codahale.metrics.SharedMetricRegistriesTest -[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.033 s -- in com.codahale.metrics.SharedMetricRegistriesTest -[INFO] Running com.codahale.metrics.UniformReservoirTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in com.codahale.metrics.UniformReservoirTest -[INFO] Running com.codahale.metrics.InstrumentedThreadFactoryTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 s -- in com.codahale.metrics.InstrumentedThreadFactoryTest -[INFO] Running com.codahale.metrics.CounterTest -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in com.codahale.metrics.CounterTest -[INFO] Running com.codahale.metrics.MeterTest -[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s -- in com.codahale.metrics.MeterTest -[INFO] Running com.codahale.metrics.DerivativeGaugeTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 s -- in com.codahale.metrics.DerivativeGaugeTest -[INFO] Running com.codahale.metrics.InstrumentedExecutorServiceTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 s -- in com.codahale.metrics.InstrumentedExecutorServiceTest -[INFO] Running com.codahale.metrics.FixedNameCsvFileProviderTest -[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in com.codahale.metrics.FixedNameCsvFileProviderTest -[INFO] Running com.codahale.metrics.SlidingTimeWindowArrayReservoirTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.006 s -- in com.codahale.metrics.SlidingTimeWindowArrayReservoirTest -[INFO] Running com.codahale.metrics.CachedGaugeTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in com.codahale.metrics.CachedGaugeTest -[INFO] Running com.codahale.metrics.MetricRegistryTest -[INFO] Tests run: 32, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.160 s -- in com.codahale.metrics.MetricRegistryTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 83, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter/target/metrics-legacy-adapter-5.0.0-rc22.jar -[INFO] -[INFO] -----< io.dropwizard.metrics5:metrics-legacy-adapter-healthchecks >----- -[INFO] Building Metrics5 Health Checks Adapter to Metrics 3/4 API 5.0.0-rc22 [37/39] -[INFO] from metrics-legacy-adapter-healthchecks/pom.xml -[INFO] --------------------------------[ jar ]--------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-legacy-adapter-healthchecks --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-legacy-adapter-healthchecks --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-legacy-adapter-healthchecks --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-legacy-adapter-healthchecks --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 4 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-legacy-adapter-healthchecks --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-legacy-adapter-healthchecks --- -[INFO] No sources to compile -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-legacy-adapter-healthchecks --- -[INFO] No tests to run. -[INFO] -[INFO] --- jar:3.4.2:jar (default-jar) @ metrics-legacy-adapter-healthchecks --- -[INFO] Building jar: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-legacy-adapter-healthchecks/target/metrics-legacy-adapter-healthchecks-5.0.0-rc22.jar -[INFO] -[INFO] ---------------< io.dropwizard.metrics5:metrics-jetty12 >--------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher 5.0.0-rc22 [38/39] -[INFO] from metrics-jetty12/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty12 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 3 source files with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[WARNING] /home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/.m2/repository/org/eclipse/jetty/jetty-util/12.0.14/jetty-util-12.0.14.jar(/org/eclipse/jetty/util/VirtualThreads$Configurable.class): warning: Cannot find annotation method 'forRemoval()' in type 'Deprecated' -/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/main/java/io/dropwizard/metrics/jetty12/InstrumentedConnectionFactory.java:[26,11] [this-escape] possible 'this' escape before subclass is fully initialized -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 2 source files with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics.jetty12.InstrumentedConnectionFactoryTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.040 s -- in io.dropwizard.metrics.jetty12.InstrumentedConnectionFactoryTest -[INFO] Running io.dropwizard.metrics.jetty12.InstrumentedQueuedThreadPoolTest -[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.045 s -- in io.dropwizard.metrics.jetty12.InstrumentedQueuedThreadPoolTest -[INFO] -[INFO] Results: -[INFO] -[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/metrics-jetty12-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12/target/classes/META-INF/MANIFEST.MF -[INFO] -[INFO] ------------< io.dropwizard.metrics5:metrics-jetty12-ee10 >------------- -[INFO] Building Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 5.0.0-rc22 [39/39] -[INFO] from metrics-jetty12-ee10/pom.xml -[INFO] -------------------------------[ bundle ]------------------------------- -[INFO] -[INFO] --- clean:3.2.0:clean (default-clean) @ metrics-jetty12-ee10 --- -[INFO] Deleting /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target -[INFO] -[INFO] --- enforcer:3.5.0:enforce (enforce) @ metrics-jetty12-ee10 --- -[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence passed -[INFO] -[INFO] --- jacoco:0.8.12:prepare-agent (prepare-agent) @ metrics-jetty12-ee10 --- -[INFO] argLine set to -javaagent:/home/rick/.m2/repository/org/jacoco/org.jacoco.agent/0.8.12/org.jacoco.agent-0.8.12-runtime.jar=destfile=/home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/jacoco.exec -[INFO] -[INFO] --- resources:3.3.1:resources (default-resources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/main/resources -[INFO] -[INFO] --- compiler:3.13.0:compile (default-compile) @ metrics-jetty12-ee10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- resources:3.3.1:testResources (default-testResources) @ metrics-jetty12-ee10 --- -[INFO] skip non existing resourceDirectory /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/src/test/resources -[INFO] -[INFO] --- compiler:3.13.0:testCompile (default-testCompile) @ metrics-jetty12-ee10 --- -[INFO] Recompiling the module because of changed dependency. -[INFO] Compiling 1 source file with javac [forked debug parameters release 8] to target/test-classes -[WARNING] [options] source value 8 is obsolete and will be removed in a future release -[WARNING] [options] target value 8 is obsolete and will be removed in a future release -[WARNING] [options] To suppress warnings about obsolete options, use -Xlint:-options. -[INFO] -[INFO] --- surefire:3.5.0:test (default-test) @ metrics-jetty12-ee10 --- -[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider -[INFO] -[INFO] ------------------------------------------------------- -[INFO] T E S T S -[INFO] ------------------------------------------------------- -[INFO] Running io.dropwizard.metrics.jetty12.ee10.InstrumentedEE10HandlerTest -[WARNING] Tests run: 7, Failures: 0, Errors: 0, Skipped: 2, Time elapsed: 1.101 s -- in io.dropwizard.metrics.jetty12.ee10.InstrumentedEE10HandlerTest -[INFO] -[INFO] Results: -[INFO] -[WARNING] Tests run: 7, Failures: 0, Errors: 0, Skipped: 2 -[INFO] -[INFO] -[INFO] --- bundle:5.1.9:bundle (default-bundle) @ metrics-jetty12-ee10 --- -[WARNING] Bundle io.dropwizard.metrics5:metrics-jetty12-ee10:bundle:5.0.0-rc22 : Unused Import-Package instructions: [javax.servlet*, org.slf4j*, sun.misc.*, com.sun.management.*] -[INFO] Building bundle: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/metrics-jetty12-ee10-5.0.0-rc22.jar -[INFO] Writing manifest: /home/rick/repos/error-prone-support/integration-tests/.repos/metrics/metrics-jetty12-ee10/target/classes/META-INF/MANIFEST.MF -[INFO] ------------------------------------------------------------------------ -[INFO] Reactor Summary for Metrics5 Parent 5.0.0-rc22: -[INFO] -[INFO] Metrics5 Parent .................................... SUCCESS [ 0.301 s] -[INFO] Metrics5 Documentation ............................. SUCCESS [ 0.858 s] -[INFO] Metrics5 BOM ....................................... SUCCESS [ 0.010 s] -[INFO] Annotations for Metrics5 ........................... SUCCESS [ 3.433 s] -[INFO] Metrics5 Core ...................................... SUCCESS [ 43.065 s] -[INFO] Benchmarks for Metrics5 ............................ SUCCESS [ 4.517 s] -[INFO] Metrics Integration for Caffeine 3.x ............... SUCCESS [ 6.998 s] -[INFO] Metrics Integration for Collectd ................... SUCCESS [ 13.792 s] -[INFO] Metrics Integration for Ehcache .................... SUCCESS [ 8.234 s] -[INFO] Graphite Integration for Metrics5 .................. SUCCESS [ 23.915 s] -[INFO] InfluxDB integration for Metrics5 .................. SUCCESS [ 11.740 s] -[INFO] JVM Integration for Metrics5 ....................... SUCCESS [ 12.421 s] -[INFO] Metrics5 Health Checks ............................. SUCCESS [ 12.220 s] -[INFO] Metrics Integration for Apache HttpClient .......... SUCCESS [ 10.439 s] -[INFO] Metrics Integration for Apache HttpClient 5.x ...... SUCCESS [ 11.712 s] -[INFO] Metrics Integration for Apache HttpAsyncClient ..... SUCCESS [ 9.507 s] -[INFO] Metrics Integration for Jakarta Servlets ........... SUCCESS [ 8.534 s] -[INFO] Metrics Integration for Jakarta Servlets 6.x ....... SUCCESS [ 8.044 s] -[INFO] Jackson Integration for Metrics5 ................... SUCCESS [ 10.017 s] -[INFO] Metrics Integration for Jetty 11.x and higher ...... SUCCESS [ 11.538 s] -[INFO] Metrics5 Utility Jakarta Servlets .................. SUCCESS [ 15.820 s] -[INFO] Metrics Integration for JCache ..................... SUCCESS [ 7.572 s] -[INFO] Metrics Integration for JDBI3 ...................... SUCCESS [ 9.939 s] -[INFO] Metrics Integration for Jersey 2.x ................. SUCCESS [ 12.822 s] -[INFO] Metrics Integration for Jersey 3.0.x ............... SUCCESS [ 12.505 s] -[INFO] Metrics Integration for Jersey 3.1.x ............... SUCCESS [ 12.638 s] -[INFO] Metrics Integration for Jetty 10.x and higher ...... SUCCESS [ 11.402 s] -[INFO] Metrics Integration for Log4j 2.x .................. SUCCESS [ 9.544 s] -[INFO] Metrics Integration for Logback 1.3.x .............. SUCCESS [ 8.491 s] -[INFO] Metrics Integration for Logback 1.4.x .............. SUCCESS [ 8.182 s] -[INFO] Metrics Integration for Logback 1.5.x .............. SUCCESS [ 8.366 s] -[INFO] Metrics Integration for Servlets ................... SUCCESS [ 7.982 s] -[INFO] Metrics5 Utility Servlets .......................... SUCCESS [ 16.075 s] -[INFO] Metrics5 JCStress tests ............................ SUCCESS [ 3.657 s] -[INFO] Metrics Integration with JMX ....................... SUCCESS [ 11.060 s] -[INFO] Metrics5 Adapter to Metrics 3/4 API ................ SUCCESS [ 15.265 s] -[INFO] Metrics5 Health Checks Adapter to Metrics 3/4 API .. SUCCESS [ 3.360 s] -[INFO] Metrics Integration for Jetty 12.x and higher ...... SUCCESS [ 9.505 s] -[INFO] Metrics Integration for Jetty 12.x and higher with Jakarta EE 10 SUCCESS [ 8.916 s] -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 06:45 min -[INFO] Finished at: 2024-11-18T13:09:20+01:00 -[INFO] ------------------------------------------------------------------------ -Inspecting changes... -Inspecting emitted warnings... From 4c2363c274397aeffc9e623d63094e21d1ee70af Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 19 Nov 2024 09:27:36 +0100 Subject: [PATCH 41/59] Improve init patch --- integration-tests/metrics-init.patch | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index 101ed67b7b..8dbb3003fe 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -1,11 +1,12 @@ diff --git a/metrics-caffeine3/pom.xml b/metrics-caffeine3/pom.xml -index 1e7c155..fd441a4 100644 +index 1e7c155..fd5a6e3 100644 --- a/metrics-caffeine3/pom.xml +++ b/metrics-caffeine3/pom.xml -@@ -35,6 +35,12 @@ +@@ -35,6 +35,13 @@ com.github.ben-manes.caffeine caffeine 3.1.8 ++ + + + com.google.errorprone @@ -28,31 +29,33 @@ index a9d5984..dd9ecd5 100644 return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); } diff --git a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -index 195619b..5584f91 100644 +index 195619b..76b31e1 100644 --- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -@@ -188,6 +188,7 @@ public class MetricsServlet extends HttpServlet { +@@ -188,6 +188,8 @@ public class MetricsServlet extends HttpServlet { return mapper.writer(); } ++ // XXX: Can't drop identity conversion as `value` can be `null`. + @SuppressWarnings("IdentityConversion") protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { try { return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); diff --git a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -index fdce054..b2475d7 100644 +index fdce054..b1cc73f 100644 --- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -@@ -188,6 +188,7 @@ public class MetricsServlet extends HttpServlet { +@@ -188,6 +188,8 @@ public class MetricsServlet extends HttpServlet { return mapper.writer(); } ++ // XXX: Can't drop identity conversion as `value` can be `null`. + @SuppressWarnings("IdentityConversion") protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { try { return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); diff --git a/pom.xml b/pom.xml -index 5318dac..8d678ea 100644 +index 5318dac..3f27500 100644 --- a/pom.xml +++ b/pom.xml @@ -66,8 +66,12 @@ @@ -73,7 +76,7 @@ index 5318dac..8d678ea 100644 -+ ++ + + + com.google.guava @@ -86,7 +89,7 @@ index 5318dac..8d678ea 100644 + + + -+ ++ + + com.google.errorprone + error_prone_annotations From 6697858dfea772163b4e92161e23f5eeddcaad8b Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 19 Nov 2024 10:16:47 +0100 Subject: [PATCH 42/59] Try to test the IT setup --- .github/workflows/run-integration-tests.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 37e6a0aa55..34e7bc4e6c 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -7,8 +7,12 @@ # https://docs.github.com/en/actions/learn-github-actions/expressions#example-returning-a-json-object name: "Integration tests" on: + workflow_dispatch: issue_comment: types: [ created ] + push: + branches: + - rossendrijver/metrics_integration_test permissions: contents: read jobs: From d7bf1a77a6d0a9ec54a19ad0d6a3317194dfe83e Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 19 Nov 2024 10:26:01 +0100 Subject: [PATCH 43/59] Test trigger? --- .github/workflows/run-integration-tests.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 34e7bc4e6c..7818435f9b 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -7,7 +7,6 @@ # https://docs.github.com/en/actions/learn-github-actions/expressions#example-returning-a-json-object name: "Integration tests" on: - workflow_dispatch: issue_comment: types: [ created ] push: From 9429021d90cfeaaa89e54111b07339388f171f44 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 19 Nov 2024 11:11:26 +0100 Subject: [PATCH 44/59] Revert commit to test GHA --- .github/workflows/run-integration-tests.yml | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 7818435f9b..d9be2ec3b5 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -7,18 +7,12 @@ # https://docs.github.com/en/actions/learn-github-actions/expressions#example-returning-a-json-object name: "Integration tests" on: - issue_comment: - types: [ created ] - push: - branches: - - rossendrijver/metrics_integration_test + pull_request: permissions: contents: read jobs: run-integration-tests: name: On-demand integration test - if: | - github.event.issue.pull_request && contains(github.event.comment.body, '/integration-tests') runs-on: ubuntu-24.04 strategy: matrix: @@ -41,7 +35,6 @@ jobs: - name: Check out code and set up JDK and Maven uses: s4u/setup-maven-action@382542f77617f34e56bf83868920a4d45b7451e7 # v1.16.0 with: - checkout-ref: "refs/pull/${{ github.event.issue.number }}/head" java-version: 17.0.13 java-distribution: temurin maven-version: 3.9.9 From eb43a776f1eb85d45e2dcee8c3bdcda3081bb2ec Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Wed, 20 Nov 2024 13:17:19 +0100 Subject: [PATCH 45/59] Try to see if we can make it pass without --- integration-tests/metrics.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 225f4f3140..04b1090023 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -12,7 +12,7 @@ shared_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' # XXX: These don't work... patch_error_prone_flags='-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*' validation_error_prone_flags='' -validation_build_flags='' +validation_build_flags='-Dtest=!InstrumentedHttpClientsTest#registersExpectedMetricsGivenNameStrategy' if [ "${#}" -gt 2 ] || ([ "${#}" = 2 ] && [ "${1:---sync}" != '--sync' ]); then echo "Usage: ${0} [--sync] []" From 3d7a390fdcb2bd0a8e59d34767870efb2c793092 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Fri, 22 Nov 2024 11:05:41 +0100 Subject: [PATCH 46/59] This works locally, well the test passes, but FileRule still seems ignore --- integration-tests/metrics.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 04b1090023..f76b732089 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -10,9 +10,10 @@ additional_build_flags='' additional_source_directories='' shared_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' # XXX: These don't work... -patch_error_prone_flags='-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern=^(?!FileRules\$).*' +patch_error_prone_flags='-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern="^(?!FileRules\$).*"' validation_error_prone_flags='' -validation_build_flags='-Dtest=!InstrumentedHttpClientsTest#registersExpectedMetricsGivenNameStrategy' +#validation_build_flags='-Dtest=!InstrumentedHttpClientsTest#registersExpectedMetricsGivenNameStrategy' +validation_build_flags="" if [ "${#}" -gt 2 ] || ([ "${#}" = 2 ] && [ "${1:---sync}" != '--sync' ]); then echo "Usage: ${0} [--sync] []" From 6f5ae5b26810165cc163b447d2c50f95b79024f7 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Fri, 22 Nov 2024 11:23:28 +0100 Subject: [PATCH 47/59] This also doesnt work --- integration-tests/metrics.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index f76b732089..63d425ebf3 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -10,7 +10,7 @@ additional_build_flags='' additional_source_directories='' shared_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' # XXX: These don't work... -patch_error_prone_flags='-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern="^(?!FileRules\$).*"' +patch_error_prone_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern='^(?!FileRules\$).*'" validation_error_prone_flags='' #validation_build_flags='-Dtest=!InstrumentedHttpClientsTest#registersExpectedMetricsGivenNameStrategy' validation_build_flags="" From acf14a1dc1efbc6483efed996aa77d4f44b51baf Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Sat, 23 Nov 2024 15:12:51 +0100 Subject: [PATCH 48/59] Sync --- integration-tests/metrics-init.patch | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index 8dbb3003fe..51d7ee5f3c 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -1,5 +1,3 @@ -diff --git a/metrics-caffeine3/pom.xml b/metrics-caffeine3/pom.xml -index 1e7c155..fd5a6e3 100644 --- a/metrics-caffeine3/pom.xml +++ b/metrics-caffeine3/pom.xml @@ -35,6 +35,13 @@ @@ -16,8 +14,6 @@ index 1e7c155..fd5a6e3 100644 org.checkerframework -diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java -index a9d5984..dd9ecd5 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java @@ -231,6 +231,7 @@ public class CsvReporterTest { @@ -28,8 +24,6 @@ index a9d5984..dd9ecd5 100644 private String fileContents(String filename) throws IOException { return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); } -diff --git a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -index 195619b..76b31e1 100644 --- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java @@ -188,6 +188,8 @@ public class MetricsServlet extends HttpServlet { @@ -41,8 +35,6 @@ index 195619b..76b31e1 100644 protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { try { return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); -diff --git a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -index fdce054..b1cc73f 100644 --- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java @@ -188,6 +188,8 @@ public class MetricsServlet extends HttpServlet { @@ -54,8 +46,6 @@ index fdce054..b1cc73f 100644 protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { try { return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); -diff --git a/pom.xml b/pom.xml -index 5318dac..3f27500 100644 --- a/pom.xml +++ b/pom.xml @@ -66,8 +66,12 @@ From 998ded91f042a9adddb37aca6a46563bf24fc08b Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Sat, 23 Nov 2024 18:01:55 +0100 Subject: [PATCH 49/59] Whitelist example.com:80 --- .github/workflows/run-integration-tests.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index d9be2ec3b5..e01ebf6381 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -26,6 +26,7 @@ jobs: allowed-endpoints: > api.adoptium.net:443 checkstyle.org:443 + example.com:80 github.com:443 objects.githubusercontent.com:443 oss.sonatype.org:443 From b31689f52de749c1a8f47c5e594244b954e69aa2 Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Sat, 23 Nov 2024 18:24:34 +0100 Subject: [PATCH 50/59] Suggestions (WIP) --- .github/workflows/run-integration-tests.yml | 4 +- .../metrics-expected-warnings.txt | 8 --- integration-tests/metrics-init.patch | 63 +++++++------------ integration-tests/metrics.sh | 4 +- 4 files changed, 26 insertions(+), 53 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index e01ebf6381..66cb7adc64 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -16,7 +16,9 @@ jobs: runs-on: ubuntu-24.04 strategy: matrix: - integration-test: [ "checkstyle", "metrics" ] + integration-test: [ "metrics" ] + # XXX: Enable. + # integration-test: [ "checkstyle", "metrics" ] steps: - name: Install Harden-Runner uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1 diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index 57884f7984..7f3d379d02 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -2,14 +2,11 @@ metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter. metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement -metrics-core/src/main/java/io/dropwizard/metrics5/MetricRegistry.java:[56,27] [this-escape] possible 'this' escape before subclass is fully initialized metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone -metrics-httpasyncclient/src/main/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedNClientConnManager.java:[40,8] [this-escape] possible 'this' escape before subclass is fully initialized -metrics-httpclient/src/main/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManager.java:[114,8] [this-escape] possible 'this' escape before subclass is fully initialized metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated @@ -31,7 +28,6 @@ metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingColle metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -metrics-json/src/main/java/io/dropwizard/metrics5/json/MetricsModule.java:[189,31] [serial] non-transient instance field of a serializable class declared with a non-serializable type metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast @@ -46,8 +42,4 @@ metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.jav metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java:[50,4] [rawtypes] found raw type: Gauge metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[85,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated metrics-log4j2/src/main/java/io/dropwizard/metrics5/log4j2/InstrumentedAppender.java:[96,4] [deprecation] AbstractAppender(String,Filter,Layout,boolean) in AbstractAppender has been deprecated -metrics-logback13/src/main/java/io/dropwizard/metrics/logback13/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -metrics-logback14/src/main/java/io/dropwizard/metrics/logback14/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -metrics-logback15/src/main/java/io/dropwizard/metrics5/logback15/InstrumentedAppender.java:[51,11] [this-escape] possible 'this' escape before subclass is fully initialized -metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/CpuProfileServlet.java:[23,21] [serial] non-transient instance field of a serializable class declared with a non-serializable type metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index 51d7ee5f3c..19b2734a66 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -1,19 +1,3 @@ ---- a/metrics-caffeine3/pom.xml -+++ b/metrics-caffeine3/pom.xml -@@ -35,6 +35,13 @@ - com.github.ben-manes.caffeine - caffeine - 3.1.8 -+ -+ -+ -+ com.google.errorprone -+ error_prone_annotations -+ -+ - - - org.checkerframework --- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java @@ -231,6 +231,7 @@ public class CsvReporterTest { @@ -26,22 +10,24 @@ } --- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -@@ -188,6 +188,8 @@ public class MetricsServlet extends HttpServlet { +@@ -188,6 +188,9 @@ public class MetricsServlet extends HttpServlet { return mapper.writer(); } -+ // XXX: Can't drop identity conversion as `value` can be `null`. ++ // Here `value` may be `null`, while `TimeUnit#valueOf` requires a non-`null` argument. ++ // XXX: Investigate better nullness handling by `IdentityConversion`. + @SuppressWarnings("IdentityConversion") protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { try { return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); --- a/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +++ b/metrics-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java -@@ -188,6 +188,8 @@ public class MetricsServlet extends HttpServlet { +@@ -188,6 +188,9 @@ public class MetricsServlet extends HttpServlet { return mapper.writer(); } -+ // XXX: Can't drop identity conversion as `value` can be `null`. ++ // Here `value` may be `null`, while `TimeUnit#valueOf` requires a non-`null` argument. ++ // XXX: Investigate better nullness handling by `IdentityConversion`. + @SuppressWarnings("IdentityConversion") protected TimeUnit parseTimeUnit(String value, TimeUnit defaultValue) { try { @@ -66,24 +52,24 @@ -+ ++ ++ ++ ++ com.google.errorprone ++ error_prone_annotations ++ ${errorprone.version} ++ ++ ++ com.google.guava ++ guava ++ 33.3.1-jre ++ ++ ++ + + + com.google.guava + guava -+ 33.3.1-jre -+ -+ -+ com.google.errorprone -+ error_prone_annotations -+ -+ -+ -+ -+ -+ com.google.errorprone -+ error_prone_annotations -+ ${errorprone.version} + + + @@ -99,14 +85,7 @@ -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED -@@ -230,12 +255,22 @@ - -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED - -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED - -- -+ - - com.google.errorprone +@@ -236,6 +261,16 @@ error_prone_core ${errorprone.version} diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 63d425ebf3..75de5cc9ad 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -9,8 +9,8 @@ revision='v5.0.0-rc22' additional_build_flags='' additional_source_directories='' shared_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' -# XXX: These don't work... -patch_error_prone_flags="-Xep:CollectorMutability:OFF -XepOpt:Refaster:NamePattern='^(?!FileRules\$).*'" +# XXX: Custom logger name isn't picked up. +patch_error_prone_flags="-XepOpt:Slf4jLogDeclaration:CanonicalStaticLoggerName=LOGGER" validation_error_prone_flags='' #validation_build_flags='-Dtest=!InstrumentedHttpClientsTest#registersExpectedMetricsGivenNameStrategy' validation_build_flags="" From 561275a9daa710a1d20436c5c8ac931e9d52477f Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Sat, 23 Nov 2024 20:04:06 +0100 Subject: [PATCH 51/59] Suggestions (WIP) --- .../bugpatterns/Slf4jLoggerDeclaration.java | 2 +- .../Slf4jLoggerDeclarationTest.java | 2 +- .../metrics-expected-warnings.txt | 15 ++++++++++++ integration-tests/metrics-init.patch | 24 ++++--------------- integration-tests/metrics.sh | 14 +++++------ 5 files changed, 28 insertions(+), 29 deletions(-) diff --git a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclaration.java b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclaration.java index 8435860751..66fb716729 100644 --- a/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclaration.java +++ b/error-prone-contrib/src/main/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclaration.java @@ -53,7 +53,7 @@ public final class Slf4jLoggerDeclaration extends BugChecker implements Variable private static final Matcher IS_GET_LOGGER = staticMethod().onDescendantOf("org.slf4j.LoggerFactory").named("getLogger"); private static final String CANONICAL_STATIC_LOGGER_NAME_FLAG = - "Slf4jLogDeclaration:CanonicalStaticLoggerName"; + "Slf4jLoggerDeclaration:CanonicalStaticLoggerName"; private static final String DEFAULT_CANONICAL_LOGGER_NAME = "LOG"; private static final Matcher IS_STATIC_ENCLOSING_CLASS_REFERENCE = classLiteral(Slf4jLoggerDeclaration::isEnclosingClassReference); diff --git a/error-prone-contrib/src/test/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclarationTest.java b/error-prone-contrib/src/test/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclarationTest.java index ada419cc4c..456d40d84f 100644 --- a/error-prone-contrib/src/test/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclarationTest.java +++ b/error-prone-contrib/src/test/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclarationTest.java @@ -189,7 +189,7 @@ void replacement() { @Test void replacementWithCustomLoggerName() { BugCheckerRefactoringTestHelper.newInstance(Slf4jLoggerDeclaration.class, getClass()) - .setArgs(ImmutableList.of("-XepOpt:Slf4jLogDeclaration:CanonicalStaticLoggerName=FOO_BAR")) + .setArgs(ImmutableList.of("-XepOpt:Slf4jLoggerDeclaration:CanonicalStaticLoggerName=FOO_BAR")) .addInputLines( "A.java", "import org.slf4j.Logger;", diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index 7f3d379d02..937f98eff6 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -1,10 +1,20 @@ +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[175,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge +metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[182,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement +metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[30,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices +metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[18,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices +metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[24,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices +metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[17,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices +metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[35,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices +metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[250,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java:[52,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices +metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[32,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated @@ -22,12 +32,17 @@ metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/Instrumente metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java:[49,4] [deprecation] HttpRequestExecutor(Timeout,ConnectionReuseStrategy,Http1StreamListener) in HttpRequestExecutor has been deprecated metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated +metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[199,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) +metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java:[36,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated +metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java:[13,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices +metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[163,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices +metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java:[23,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index 19b2734a66..982ea85616 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -34,21 +34,16 @@ return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); --- a/pom.xml +++ b/pom.xml -@@ -66,8 +66,12 @@ +@@ -66,7 +66,7 @@ 5.14.1 3.17.0 3.13.0 - 2.31.0 + ${error-prone.version} 9+181-r4173-1 -+ -Xplugin:ErrorProne \ -+ -XepDisableWarningsInGeneratedCode \ -+ ${error-prone.configuration-args} -+ dropwizard_metrics - dropwizard -@@ -136,6 +140,27 @@ +@@ -136,6 +136,27 @@ @@ -76,16 +71,16 @@ jdk8 -@@ -218,7 +243,7 @@ +@@ -218,7 +239,7 @@ -Xlint:all -XDcompilePolicy=simple - -Xplugin:ErrorProne -XepExcludedPaths:.*/target/generated-sources/.* -+ ${error-prone-support.flags} ++ -Xplugin:ErrorProne ${error-prone.configuration-args} -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED -@@ -236,6 +261,16 @@ +@@ -236,6 +257,16 @@ error_prone_core ${errorprone.version} @@ -102,12 +97,3 @@ -@@ -371,7 +406,7 @@ - - -Xlint:all - -XDcompilePolicy=simple -- -Xplugin:ErrorProne -XepExcludedPaths:.*/target/generated-sources/.* -+ ${error-prone-support.flags} - - - diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 75de5cc9ad..b4b490c274 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -8,19 +8,17 @@ repository='https://github.com/dropwizard/metrics.git' revision='v5.0.0-rc22' additional_build_flags='' additional_source_directories='' -shared_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' -# XXX: Custom logger name isn't picked up. -patch_error_prone_flags="-XepOpt:Slf4jLogDeclaration:CanonicalStaticLoggerName=LOGGER" +shared_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.* -XepOpt:Slf4jLoggerDeclaration:CanonicalStaticLoggerName=LOGGER' +patch_error_prone_flags='' validation_error_prone_flags='' -#validation_build_flags='-Dtest=!InstrumentedHttpClientsTest#registersExpectedMetricsGivenNameStrategy' -validation_build_flags="" +validation_build_flags='' if [ "${#}" -gt 2 ] || ([ "${#}" = 2 ] && [ "${1:---sync}" != '--sync' ]); then - echo "Usage: ${0} [--sync] []" + >&2 echo "Usage: ${0} [--sync] []" exit 1 fi -"$(dirname "${0}")"/run-integration-test.sh \ +"$(dirname "${0}")/run-integration-test.sh" \ "${test_name}" \ "${project}" \ "${repository}" \ @@ -31,4 +29,4 @@ fi "${patch_error_prone_flags}" \ "${validation_error_prone_flags}" \ "${validation_build_flags}" \ - $@ + ${@} From e441bc3a488eeec2ca79f0395c81eac6c69a248a Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Sat, 23 Nov 2024 22:20:29 +0100 Subject: [PATCH 52/59] Doh --- .../errorprone/bugpatterns/Slf4jLoggerDeclarationTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/error-prone-contrib/src/test/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclarationTest.java b/error-prone-contrib/src/test/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclarationTest.java index 456d40d84f..3bf864548e 100644 --- a/error-prone-contrib/src/test/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclarationTest.java +++ b/error-prone-contrib/src/test/java/tech/picnic/errorprone/bugpatterns/Slf4jLoggerDeclarationTest.java @@ -1,6 +1,5 @@ package tech.picnic.errorprone.bugpatterns; -import com.google.common.collect.ImmutableList; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; @@ -189,7 +188,7 @@ void replacement() { @Test void replacementWithCustomLoggerName() { BugCheckerRefactoringTestHelper.newInstance(Slf4jLoggerDeclaration.class, getClass()) - .setArgs(ImmutableList.of("-XepOpt:Slf4jLoggerDeclaration:CanonicalStaticLoggerName=FOO_BAR")) + .setArgs("-XepOpt:Slf4jLoggerDeclaration:CanonicalStaticLoggerName=FOO_BAR") .addInputLines( "A.java", "import org.slf4j.Logger;", From 331cea62a8d7f13d98d06bec5b089374bea5ef35 Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Sun, 24 Nov 2024 15:14:27 +0100 Subject: [PATCH 53/59] Suggestions (WIP) --- integration-tests/metrics-expected-warnings.txt | 15 --------------- integration-tests/metrics.sh | 6 +++++- 2 files changed, 5 insertions(+), 16 deletions(-) diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index 937f98eff6..7f3d379d02 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -1,20 +1,10 @@ -metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[175,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge -metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[182,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement -metrics-core/src/main/java/io/dropwizard/metrics5/ScheduledReporter.java:[30,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices -metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java:[18,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices -metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java:[24,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices -metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java:[17,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices -metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/Graphite.java:[35,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices -metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[250,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[431,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[436,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/GraphiteReporter.java:[449,17] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-graphite/src/main/java/io/dropwizard/metrics5/graphite/PickledGraphite.java:[52,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices -metrics-healthchecks/src/main/java/io/dropwizard/metrics5/health/HealthCheckRegistry.java:[32,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[189,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java:[203,46] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated @@ -32,17 +22,12 @@ metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/Instrumente metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpRequestExecutor.java:[49,4] [deprecation] HttpRequestExecutor(Timeout,ConnectionReuseStrategy,Http1StreamListener) in HttpRequestExecutor has been deprecated metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[46,10] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated -metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[199,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-jcache/src/main/java/io/dropwizard/metrics5/jcache/JCacheGaugeSet.java:[36,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactory.java:[13,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices -metrics-jmx/src/main/java/io/dropwizard/metrics5/jmx/JmxReporter.java:[163,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices -metrics-jvm/src/main/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSet.java:[23,30] [Slf4jLoggerDeclaration] SLF4J logger declarations should follow established best-practices metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index b4b490c274..379801e274 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -8,7 +8,11 @@ repository='https://github.com/dropwizard/metrics.git' revision='v5.0.0-rc22' additional_build_flags='' additional_source_directories='' -shared_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.* -XepOpt:Slf4jLoggerDeclaration:CanonicalStaticLoggerName=LOGGER' +# XXX: Minimize the diff by including +# `-XepOpt:Slf4jLoggerDeclaration:CanonicalStaticLoggerName=LOGGER` once such +# flags are supported in patch mode. See +# https://github.com/google/error-prone/pull/4699. +shared_error_prone_flags='-XepExcludedPaths:.*/target/generated-sources/.*' patch_error_prone_flags='' validation_error_prone_flags='' validation_build_flags='' From 18890ff39089146b948a246b575cf67f3cdfd76a Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Sun, 24 Nov 2024 15:40:05 +0100 Subject: [PATCH 54/59] Suggestions (WIP) --- integration-tests/metrics-init.patch | 30 ++++++++++++++-------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index 982ea85616..91b3d71e73 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -34,15 +34,6 @@ return TimeUnit.valueOf(String.valueOf(value).toUpperCase(Locale.US)); --- a/pom.xml +++ b/pom.xml -@@ -66,7 +66,7 @@ - 5.14.1 - 3.17.0 - 3.13.0 -- 2.31.0 -+ ${error-prone.version} - 9+181-r4173-1 - - dropwizard_metrics @@ -136,6 +136,27 @@ @@ -52,7 +43,7 @@ + + com.google.errorprone + error_prone_annotations -+ ${errorprone.version} ++ ${error-prone.version} + + + com.google.guava @@ -80,10 +71,20 @@ -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED -@@ -236,6 +257,16 @@ +@@ -229,12 +250,24 @@ + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED ++ -Xmaxwarns ++ 1000000 + + + + com.google.errorprone error_prone_core - ${errorprone.version} - +- ${errorprone.version} ++ ${error-prone.version} ++ + + tech.picnic.error-prone-support + error-prone-contrib @@ -93,7 +94,6 @@ + tech.picnic.error-prone-support + refaster-runner + ${error-prone-support.version} -+ + - From 10a84d004695abf8cc06fa20f577238f469bfded Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Tue, 26 Nov 2024 10:18:02 +0100 Subject: [PATCH 55/59] Suggestions and improvements --- integration-tests/checkstyle.sh | 2 +- .../metrics-expected-changes.patch | 29 +++++++------------ .../metrics-expected-warnings.txt | 13 +++++---- integration-tests/metrics-init.patch | 28 +++++++++++------- integration-tests/metrics.sh | 2 +- 5 files changed, 39 insertions(+), 35 deletions(-) diff --git a/integration-tests/checkstyle.sh b/integration-tests/checkstyle.sh index 332f53da67..6a587049a2 100755 --- a/integration-tests/checkstyle.sh +++ b/integration-tests/checkstyle.sh @@ -34,4 +34,4 @@ fi "${patch_error_prone_flags}" \ "${validation_error_prone_flags}" \ "${validation_build_flags}" \ - ${@} + $@ diff --git a/integration-tests/metrics-expected-changes.patch b/integration-tests/metrics-expected-changes.patch index f2c74a2d04..4f4a74558c 100644 --- a/integration-tests/metrics-expected-changes.patch +++ b/integration-tests/metrics-expected-changes.patch @@ -1413,14 +1413,7 @@ @Test --- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java -@@ -1,5 +1,6 @@ - package io.dropwizard.metrics5; - -+import static java.nio.charset.StandardCharsets.UTF_8; - import static org.assertj.core.api.Assertions.assertThat; - import static org.mockito.Mockito.mock; - import static org.mockito.Mockito.verify; -@@ -7,7 +8,6 @@ import static org.mockito.Mockito.when; +@@ -7,7 +7,6 @@ import static org.mockito.Mockito.when; import java.io.File; import java.io.IOException; @@ -1428,7 +1421,7 @@ import java.nio.file.Files; import java.util.Locale; import java.util.SortedMap; -@@ -17,11 +17,11 @@ import org.junit.jupiter.api.BeforeEach; +@@ -17,11 +16,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -1443,7 +1436,7 @@ private File dataDirectory; private CsvReporter reporter; -@@ -53,7 +53,7 @@ public class CsvReporterTest { +@@ -53,7 +52,7 @@ public class CsvReporterTest { @Test void reportsCounterValues() throws Exception { @@ -1452,7 +1445,7 @@ when(counter.getCount()).thenReturn(100L); reporter.report(map(), map(MetricName.build("test.counter"), counter), map(), map(), map()); -@@ -63,11 +63,11 @@ public class CsvReporterTest { +@@ -63,11 +62,11 @@ public class CsvReporterTest { @Test void reportsHistogramValues() throws Exception { @@ -1466,7 +1459,7 @@ when(snapshot.getMax()).thenReturn(2L); when(snapshot.getMean()).thenReturn(3.0); when(snapshot.getMin()).thenReturn(4L); -@@ -105,7 +105,7 @@ public class CsvReporterTest { +@@ -105,7 +104,7 @@ public class CsvReporterTest { @Test void reportsTimerValues() throws Exception { @@ -1475,7 +1468,7 @@ when(timer.getCount()).thenReturn(1L); when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); when(timer.getMeanRate()).thenReturn(2.0); -@@ -113,7 +113,7 @@ public class CsvReporterTest { +@@ -113,7 +112,7 @@ public class CsvReporterTest { when(timer.getFiveMinuteRate()).thenReturn(4.0); when(timer.getFifteenMinuteRate()).thenReturn(5.0); @@ -1484,7 +1477,7 @@ when(snapshot.getMax()).thenReturn(TimeUnit.MILLISECONDS.toNanos(100)); when(snapshot.getMean()).thenReturn((double) TimeUnit.MILLISECONDS.toNanos(200)); when(snapshot.getMin()).thenReturn(TimeUnit.MILLISECONDS.toNanos(300)); -@@ -137,8 +137,8 @@ public class CsvReporterTest { +@@ -137,8 +136,8 @@ public class CsvReporterTest { } @Test @@ -1495,7 +1488,7 @@ when(fileProvider.getFile(dataDirectory, "gauge")) .thenReturn(new File(dataDirectory, "guage.csv")); -@@ -177,7 +177,7 @@ public class CsvReporterTest { +@@ -177,7 +176,7 @@ public class CsvReporterTest { } private Meter mockMeter() { @@ -1504,13 +1497,13 @@ when(meter.getCount()).thenReturn(1L); when(meter.getSum()).thenReturn(6L); when(meter.getMeanRate()).thenReturn(2.0); -@@ -198,8 +198,7 @@ public class CsvReporterTest { +@@ -197,8 +196,7 @@ public class CsvReporterTest { + } - @SuppressWarnings("FilesReadStringWithCharset") private String fileContents(String filename) throws IOException { - return new String( - Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); -+ return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), UTF_8); ++ return Files.readString(new File(dataDirectory, filename).toPath()); } private SortedMap map() { diff --git a/integration-tests/metrics-expected-warnings.txt b/integration-tests/metrics-expected-warnings.txt index 7f3d379d02..401c709fc1 100644 --- a/integration-tests/metrics-expected-warnings.txt +++ b/integration-tests/metrics-expected-warnings.txt @@ -1,4 +1,11 @@ metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/CollectdReporter.java:[306,57] [rawtypes] found raw type: Gauge +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[164,12] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[169,11] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[175,17] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[200,8] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[203,21] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[206,11] [cast] redundant cast to ByteBuffer +metrics-collectd/src/main/java/io/dropwizard/metrics5/collectd/PacketWriter.java:[250,36] [cast] redundant cast to ByteBuffer metrics-core/src/main/java/io/dropwizard/metrics5/CsvReporter.java:[390,35] [FormatStringConcatenation] Defer string concatenation to the invoked method metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[244,25] [try] auto-closeable resource durationContext is never referenced in body of corresponding try statement metrics-core/src/main/java/io/dropwizard/metrics5/InstrumentedExecutorService.java:[266,25] [try] auto-closeable resource context is never referenced in body of corresponding try statement @@ -10,9 +17,6 @@ metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java:[124,22] [deprecation] rewriteURI(URI,HttpHost,boolean) in URIUtils has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManager.java:[29,62] [deprecation] getDefault() in DefaultClientTlsStrategy has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[116,50] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[14,40] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[15,40] [deprecation] PlainConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated -metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[16,37] [deprecation] SSLConnectionSocketFactory in org.apache.hc.client5.http.ssl has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[160,12] [deprecation] DefaultHttpClientConnectionOperator(Lookup,SchemePortResolver,DnsResolver) in DefaultHttpClientConnectionOperator has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[30,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated metrics-httpclient5/src/main/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManager.java:[31,28] [deprecation] ConnectionSocketFactory in org.apache.hc.client5.http.socket has been deprecated @@ -24,10 +28,9 @@ metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/Instrumente metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java:[68,12] [deprecation] execute(ClassicHttpRequest) in HttpClient has been deprecated metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[282,14] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) metrics-influxdb/src/main/java/io/dropwizard/metrics5/influxdb/InfluxDbReporter.java:[287,16] [Slf4jLogStatement] Log statement contains 0 placeholders, but specifies 1 matching argument(s) -metrics-jdbi3/src/main/java/io/dropwizard/metrics5/jdbi3/InstrumentedTimingCollector.java:[10,33] [deprecation] TimingCollector in org.jdbi.v3.core.statement has been deprecated +metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java:[31,67] [TimeZoneUsage] Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[18,10] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[24,20] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated -metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java:[9,35] [deprecation] InstrumentedTimingCollector in io.dropwizard.metrics5.jdbi3 has been deprecated metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[101,74] [unchecked] unchecked cast metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[56,74] [unchecked] unchecked cast metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java:[65,74] [unchecked] unchecked cast diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index 91b3d71e73..8300f95497 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -1,13 +1,3 @@ ---- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java -+++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java -@@ -231,6 +231,7 @@ public class CsvReporterTest { - return builder.toString(); - } - -+ @SuppressWarnings("FilesReadStringWithCharset") - private String fileContents(String filename) throws IOException { - return new String(Files.readAllBytes(new File(dataDirectory, filename).toPath()), StandardCharsets.UTF_8); - } --- a/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java +++ b/metrics-jakarta-servlets/src/main/java/io/dropwizard/metrics5/servlets/MetricsServlet.java @@ -188,6 +188,9 @@ public class MetricsServlet extends HttpServlet { @@ -97,3 +87,21 @@ +@@ -350,7 +383,7 @@ + maven-javadoc-plugin + 3.10.1 + +- 8 ++ 11 + none + true + true +@@ -364,7 +397,7 @@ + org.apache.maven.plugins + maven-compiler-plugin + +- 8 ++ 11 + true + true + true diff --git a/integration-tests/metrics.sh b/integration-tests/metrics.sh index 379801e274..812a4a12e6 100755 --- a/integration-tests/metrics.sh +++ b/integration-tests/metrics.sh @@ -33,4 +33,4 @@ fi "${patch_error_prone_flags}" \ "${validation_error_prone_flags}" \ "${validation_build_flags}" \ - ${@} + $@ From 296f9ee1ea2b99c3d9cf357fba6d7740e7bbdc79 Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Tue, 26 Nov 2024 21:54:18 +0100 Subject: [PATCH 56/59] Tweak --- integration-tests/metrics-init.patch | 9 --------- 1 file changed, 9 deletions(-) diff --git a/integration-tests/metrics-init.patch b/integration-tests/metrics-init.patch index 8300f95497..5254829a29 100644 --- a/integration-tests/metrics-init.patch +++ b/integration-tests/metrics-init.patch @@ -87,15 +87,6 @@ -@@ -350,7 +383,7 @@ - maven-javadoc-plugin - 3.10.1 - -- 8 -+ 11 - none - true - true @@ -364,7 +397,7 @@ org.apache.maven.plugins maven-compiler-plugin From d27ae54dcfe98d9e8bde768c8c93ad0cb6c6dd2f Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Tue, 26 Nov 2024 22:02:43 +0100 Subject: [PATCH 57/59] Run Checkstyle test again --- .github/workflows/run-integration-tests.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index 66cb7adc64..e01ebf6381 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -16,9 +16,7 @@ jobs: runs-on: ubuntu-24.04 strategy: matrix: - integration-test: [ "metrics" ] - # XXX: Enable. - # integration-test: [ "checkstyle", "metrics" ] + integration-test: [ "checkstyle", "metrics" ] steps: - name: Install Harden-Runner uses: step-security/harden-runner@91182cccc01eb5e619899d80e4e971d6181294a7 # v2.10.1 From 3734ec61991a281c54a9ef7edbf17182fc19cf41 Mon Sep 17 00:00:00 2001 From: Rick Ossendrijver Date: Thu, 28 Nov 2024 09:01:18 +0100 Subject: [PATCH 58/59] Revert changes in `run-integration-tests` --- .github/workflows/run-integration-tests.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index e01ebf6381..cccf8188a2 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -7,12 +7,15 @@ # https://docs.github.com/en/actions/learn-github-actions/expressions#example-returning-a-json-object name: "Integration tests" on: - pull_request: + issue_comment: + types: [ created ] permissions: contents: read jobs: run-integration-tests: name: On-demand integration test + if: | + github.event.issue.pull_request && contains(github.event.comment.body, '/integration-test') runs-on: ubuntu-24.04 strategy: matrix: @@ -36,6 +39,7 @@ jobs: - name: Check out code and set up JDK and Maven uses: s4u/setup-maven-action@382542f77617f34e56bf83868920a4d45b7451e7 # v1.16.0 with: + checkout-ref: "refs/pull/${{ github.event.issue.number }}/head" java-version: 17.0.13 java-distribution: temurin maven-version: 3.9.9 From a6bd840cd02cc4ea9b45baed3a1691988da2c4f7 Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Thu, 28 Nov 2024 14:27:31 +0100 Subject: [PATCH 59/59] Polish --- .github/workflows/run-integration-tests.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/run-integration-tests.yml b/.github/workflows/run-integration-tests.yml index cccf8188a2..db02108e00 100644 --- a/.github/workflows/run-integration-tests.yml +++ b/.github/workflows/run-integration-tests.yml @@ -1,8 +1,8 @@ # If requested by means of a pull request comment, runs integration tests # against the project, using the code found on the pull request branch. -# XXX: Generalize this to a matrix build of multiple integration tests, -# possibly using multiple JDK or OS versions. -# XXX: Investigate whether the comment can specify which integration tests run. +# XXX: Review whether then build matrix should also vary JDK or OS versions. +# XXX: Support `/integration-test [name...]` comment syntax to specify the +# subset of integration tests to run. # See this example of a dynamic build matrix: # https://docs.github.com/en/actions/learn-github-actions/expressions#example-returning-a-json-object name: "Integration tests"